blob: a88d75b6897e5593fbc977c1d17998e806a93a8d [file] [log] [blame]
Jim Fultonfafd8742004-08-28 15:22:12 +00001"""Test script for unittest.
2
Guido van Rossumd8faa362007-04-27 19:54:29 +00003By Collin Winter <collinw at gmail.com>
4
5Still need testing:
6 TestCase.{assert,fail}* methods (some are tested implicitly)
Jim Fultonfafd8742004-08-28 15:22:12 +00007"""
8
Benjamin Petersonbed7d042009-07-19 21:01:52 +00009import builtins
Benjamin Petersond2397752009-06-27 23:45:02 +000010import os
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000011import re
Benjamin Petersond2397752009-06-27 23:45:02 +000012import sys
Benjamin Peterson6bcbad52009-06-30 23:45:41 +000013import warnings
Benjamin Petersonee8712c2008-05-20 21:35:26 +000014from test import support
Jim Fultonfafd8742004-08-28 15:22:12 +000015import unittest
Benjamin Peterson25c95f12009-05-08 20:42:26 +000016from unittest import TestCase, TestProgram
Christian Heimes45f9af32007-11-27 21:50:00 +000017import types
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000018from copy import deepcopy
Benjamin Peterson25c95f12009-05-08 20:42:26 +000019import io
Antoine Pitrouc63ecee2009-11-10 21:34:48 +000020import pickle
Benjamin Peterson847a4112010-03-14 15:04:17 +000021import warnings
22
Jim Fultonfafd8742004-08-28 15:22:12 +000023
Guido van Rossumd8faa362007-04-27 19:54:29 +000024### Support code
25################################################################
Jim Fultonfafd8742004-08-28 15:22:12 +000026
Benjamin Peterson847a4112010-03-14 15:04:17 +000027def resultFactory(*_):
28 return unittest.TestResult()
29
Guido van Rossumd8faa362007-04-27 19:54:29 +000030class LoggingResult(unittest.TestResult):
31 def __init__(self, log):
32 self._events = log
Guido van Rossumcd16bf62007-06-13 18:07:49 +000033 super().__init__()
Guido van Rossumd8faa362007-04-27 19:54:29 +000034
35 def startTest(self, test):
36 self._events.append('startTest')
Guido van Rossumcd16bf62007-06-13 18:07:49 +000037 super().startTest(test)
Guido van Rossumd8faa362007-04-27 19:54:29 +000038
Benjamin Peterson25c95f12009-05-08 20:42:26 +000039 def startTestRun(self):
40 self._events.append('startTestRun')
41 super(LoggingResult, self).startTestRun()
42
Guido van Rossumd8faa362007-04-27 19:54:29 +000043 def stopTest(self, test):
44 self._events.append('stopTest')
Guido van Rossumcd16bf62007-06-13 18:07:49 +000045 super().stopTest(test)
Guido van Rossumd8faa362007-04-27 19:54:29 +000046
Benjamin Peterson25c95f12009-05-08 20:42:26 +000047 def stopTestRun(self):
48 self._events.append('stopTestRun')
49 super(LoggingResult, self).stopTestRun()
50
Guido van Rossumd8faa362007-04-27 19:54:29 +000051 def addFailure(self, *args):
52 self._events.append('addFailure')
Guido van Rossumcd16bf62007-06-13 18:07:49 +000053 super().addFailure(*args)
Guido van Rossumd8faa362007-04-27 19:54:29 +000054
Benjamin Peterson5254c042009-03-23 22:25:03 +000055 def addSuccess(self, *args):
56 self._events.append('addSuccess')
57 super(LoggingResult, self).addSuccess(*args)
58
Guido van Rossumd8faa362007-04-27 19:54:29 +000059 def addError(self, *args):
60 self._events.append('addError')
Guido van Rossumcd16bf62007-06-13 18:07:49 +000061 super().addError(*args)
Guido van Rossumd8faa362007-04-27 19:54:29 +000062
Benjamin Peterson5254c042009-03-23 22:25:03 +000063 def addSkip(self, *args):
64 self._events.append('addSkip')
65 super(LoggingResult, self).addSkip(*args)
66
67 def addExpectedFailure(self, *args):
68 self._events.append('addExpectedFailure')
69 super(LoggingResult, self).addExpectedFailure(*args)
70
71 def addUnexpectedSuccess(self, *args):
72 self._events.append('addUnexpectedSuccess')
73 super(LoggingResult, self).addUnexpectedSuccess(*args)
74
75
Guido van Rossumd8faa362007-04-27 19:54:29 +000076class TestEquality(object):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000077 """Used as a mixin for TestCase"""
78
Guido van Rossumd8faa362007-04-27 19:54:29 +000079 # Check for a valid __eq__ implementation
80 def test_eq(self):
81 for obj_1, obj_2 in self.eq_pairs:
82 self.assertEqual(obj_1, obj_2)
83 self.assertEqual(obj_2, obj_1)
84
85 # Check for a valid __ne__ implementation
86 def test_ne(self):
87 for obj_1, obj_2 in self.ne_pairs:
Benjamin Petersone1759f82009-06-30 23:35:19 +000088 self.assertNotEqual(obj_1, obj_2)
89 self.assertNotEqual(obj_2, obj_1)
Guido van Rossumd8faa362007-04-27 19:54:29 +000090
91class TestHashing(object):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000092 """Used as a mixin for TestCase"""
93
Guido van Rossumd8faa362007-04-27 19:54:29 +000094 # Check for a valid __hash__ implementation
95 def test_hash(self):
96 for obj_1, obj_2 in self.eq_pairs:
97 try:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000098 if not hash(obj_1) == hash(obj_2):
99 self.fail("%r and %r do not hash equal" % (obj_1, obj_2))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000100 except KeyboardInterrupt:
101 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +0000102 except Exception as e:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000103 self.fail("Problem hashing %r and %r: %s" % (obj_1, obj_2, e))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000104
105 for obj_1, obj_2 in self.ne_pairs:
106 try:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000107 if hash(obj_1) == hash(obj_2):
108 self.fail("%s and %s hash equal, but shouldn't" %
109 (obj_1, obj_2))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000110 except KeyboardInterrupt:
111 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +0000112 except Exception as e:
113 self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e))
114
115
Benjamin Peterson5254c042009-03-23 22:25:03 +0000116# List subclass we can add attributes to.
117class MyClassSuite(list):
118
Benjamin Peterson14a3dd72009-05-25 00:51:58 +0000119 def __init__(self, tests):
Benjamin Peterson5254c042009-03-23 22:25:03 +0000120 super(MyClassSuite, self).__init__(tests)
121
122
Guido van Rossumd8faa362007-04-27 19:54:29 +0000123################################################################
124### /Support code
125
126class Test_TestLoader(TestCase):
127
128 ### Tests for TestLoader.loadTestsFromTestCase
129 ################################################################
130
131 # "Return a suite of all tests cases contained in the TestCase-derived
132 # class testCaseClass"
133 def test_loadTestsFromTestCase(self):
134 class Foo(unittest.TestCase):
135 def test_1(self): pass
136 def test_2(self): pass
137 def foo_bar(self): pass
138
139 tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
140
141 loader = unittest.TestLoader()
142 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
143
144 # "Return a suite of all tests cases contained in the TestCase-derived
145 # class testCaseClass"
146 #
147 # Make sure it does the right thing even if no tests were found
148 def test_loadTestsFromTestCase__no_matches(self):
149 class Foo(unittest.TestCase):
150 def foo_bar(self): pass
151
152 empty_suite = unittest.TestSuite()
153
154 loader = unittest.TestLoader()
155 self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite)
156
157 # "Return a suite of all tests cases contained in the TestCase-derived
158 # class testCaseClass"
159 #
160 # What happens if loadTestsFromTestCase() is given an object
161 # that isn't a subclass of TestCase? Specifically, what happens
162 # if testCaseClass is a subclass of TestSuite?
163 #
164 # This is checked for specifically in the code, so we better add a
165 # test for it.
166 def test_loadTestsFromTestCase__TestSuite_subclass(self):
167 class NotATestCase(unittest.TestSuite):
168 pass
169
170 loader = unittest.TestLoader()
171 try:
172 loader.loadTestsFromTestCase(NotATestCase)
173 except TypeError:
174 pass
175 else:
176 self.fail('Should raise TypeError')
177
178 # "Return a suite of all tests cases contained in the TestCase-derived
179 # class testCaseClass"
180 #
181 # Make sure loadTestsFromTestCase() picks up the default test method
182 # name (as specified by TestCase), even though the method name does
183 # not match the default TestLoader.testMethodPrefix string
184 def test_loadTestsFromTestCase__default_method_name(self):
185 class Foo(unittest.TestCase):
186 def runTest(self):
187 pass
188
189 loader = unittest.TestLoader()
190 # This has to be false for the test to succeed
Benjamin Petersone1759f82009-06-30 23:35:19 +0000191 self.assertFalse('runTest'.startswith(loader.testMethodPrefix))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000192
193 suite = loader.loadTestsFromTestCase(Foo)
Ezio Melottie9615932010-01-24 19:26:24 +0000194 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000195 self.assertEqual(list(suite), [Foo('runTest')])
196
197 ################################################################
198 ### /Tests for TestLoader.loadTestsFromTestCase
199
200 ### Tests for TestLoader.loadTestsFromModule
201 ################################################################
202
203 # "This method searches `module` for classes derived from TestCase"
204 def test_loadTestsFromModule__TestCase_subclass(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000205 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000206 class MyTestCase(unittest.TestCase):
207 def test(self):
208 pass
209 m.testcase_1 = MyTestCase
210
211 loader = unittest.TestLoader()
212 suite = loader.loadTestsFromModule(m)
Ezio Melottie9615932010-01-24 19:26:24 +0000213 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000214
215 expected = [loader.suiteClass([MyTestCase('test')])]
216 self.assertEqual(list(suite), expected)
217
218 # "This method searches `module` for classes derived from TestCase"
219 #
220 # What happens if no tests are found (no TestCase instances)?
221 def test_loadTestsFromModule__no_TestCase_instances(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000222 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000223
224 loader = unittest.TestLoader()
225 suite = loader.loadTestsFromModule(m)
Ezio Melottie9615932010-01-24 19:26:24 +0000226 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000227 self.assertEqual(list(suite), [])
228
229 # "This method searches `module` for classes derived from TestCase"
230 #
231 # What happens if no tests are found (TestCases instances, but no tests)?
232 def test_loadTestsFromModule__no_TestCase_tests(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000233 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000234 class MyTestCase(unittest.TestCase):
235 pass
236 m.testcase_1 = MyTestCase
237
238 loader = unittest.TestLoader()
239 suite = loader.loadTestsFromModule(m)
Ezio Melottie9615932010-01-24 19:26:24 +0000240 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000241
242 self.assertEqual(list(suite), [loader.suiteClass()])
243
244 # "This method searches `module` for classes derived from TestCase"s
245 #
246 # What happens if loadTestsFromModule() is given something other
247 # than a module?
248 #
249 # XXX Currently, it succeeds anyway. This flexibility
250 # should either be documented or loadTestsFromModule() should
251 # raise a TypeError
252 #
253 # XXX Certain people are using this behaviour. We'll add a test for it
254 def test_loadTestsFromModule__not_a_module(self):
255 class MyTestCase(unittest.TestCase):
256 def test(self):
257 pass
258
259 class NotAModule(object):
260 test_2 = MyTestCase
261
262 loader = unittest.TestLoader()
263 suite = loader.loadTestsFromModule(NotAModule)
264
265 reference = [unittest.TestSuite([MyTestCase('test')])]
266 self.assertEqual(list(suite), reference)
267
Benjamin Petersond2397752009-06-27 23:45:02 +0000268
269 # Check that loadTestsFromModule honors (or not) a module
270 # with a load_tests function.
271 def test_loadTestsFromModule__load_tests(self):
272 m = types.ModuleType('m')
273 class MyTestCase(unittest.TestCase):
274 def test(self):
275 pass
276 m.testcase_1 = MyTestCase
277
278 load_tests_args = []
279 def load_tests(loader, tests, pattern):
Michael Foord41647d62010-02-06 00:26:13 +0000280 self.assertIsInstance(tests, unittest.TestSuite)
Benjamin Petersond2397752009-06-27 23:45:02 +0000281 load_tests_args.extend((loader, tests, pattern))
282 return tests
283 m.load_tests = load_tests
284
285 loader = unittest.TestLoader()
286 suite = loader.loadTestsFromModule(m)
Michael Foord41647d62010-02-06 00:26:13 +0000287 self.assertIsInstance(suite, unittest.TestSuite)
Benjamin Petersond2397752009-06-27 23:45:02 +0000288 self.assertEquals(load_tests_args, [loader, suite, None])
289
290 load_tests_args = []
291 suite = loader.loadTestsFromModule(m, use_load_tests=False)
292 self.assertEquals(load_tests_args, [])
293
Benjamin Peterson886af962010-03-21 23:13:07 +0000294 def test_loadTestsFromModule__faulty_load_tests(self):
295 m = types.ModuleType('m')
296
297 def load_tests(loader, tests, pattern):
298 raise TypeError('some failure')
299 m.load_tests = load_tests
300
301 loader = unittest.TestLoader()
302 suite = loader.loadTestsFromModule(m)
303 self.assertIsInstance(suite, unittest.TestSuite)
304 self.assertEqual(suite.countTestCases(), 1)
305 test = list(suite)[0]
306
307 self.assertRaisesRegexp(TypeError, "some failure", test.m)
308
Guido van Rossumd8faa362007-04-27 19:54:29 +0000309 ################################################################
310 ### /Tests for TestLoader.loadTestsFromModule()
311
312 ### Tests for TestLoader.loadTestsFromName()
313 ################################################################
314
315 # "The specifier name is a ``dotted name'' that may resolve either to
316 # a module, a test case class, a TestSuite instance, a test method
317 # within a test case class, or a callable object which returns a
318 # TestCase or TestSuite instance."
319 #
320 # Is ValueError raised in response to an empty name?
321 def test_loadTestsFromName__empty_name(self):
322 loader = unittest.TestLoader()
323
324 try:
325 loader.loadTestsFromName('')
326 except ValueError as e:
327 self.assertEqual(str(e), "Empty module name")
328 else:
329 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
330
331 # "The specifier name is a ``dotted name'' that may resolve either to
332 # a module, a test case class, a TestSuite instance, a test method
333 # within a test case class, or a callable object which returns a
334 # TestCase or TestSuite instance."
335 #
336 # What happens when the name contains invalid characters?
337 def test_loadTestsFromName__malformed_name(self):
338 loader = unittest.TestLoader()
339
340 # XXX Should this raise ValueError or ImportError?
341 try:
342 loader.loadTestsFromName('abc () //')
343 except ValueError:
344 pass
345 except ImportError:
346 pass
347 else:
348 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
349
350 # "The specifier name is a ``dotted name'' that may resolve ... to a
351 # module"
352 #
353 # What happens when a module by that name can't be found?
354 def test_loadTestsFromName__unknown_module_name(self):
355 loader = unittest.TestLoader()
356
357 try:
358 loader.loadTestsFromName('sdasfasfasdf')
359 except ImportError as e:
360 self.assertEqual(str(e), "No module named sdasfasfasdf")
361 else:
362 self.fail("TestLoader.loadTestsFromName failed to raise ImportError")
363
364 # "The specifier name is a ``dotted name'' that may resolve either to
365 # a module, a test case class, a TestSuite instance, a test method
366 # within a test case class, or a callable object which returns a
367 # TestCase or TestSuite instance."
368 #
369 # What happens when the module is found, but the attribute can't?
370 def test_loadTestsFromName__unknown_attr_name(self):
371 loader = unittest.TestLoader()
372
373 try:
374 loader.loadTestsFromName('unittest.sdasfasfasdf')
375 except AttributeError as e:
376 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
377 else:
378 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
379
380 # "The specifier name is a ``dotted name'' that may resolve either to
381 # a module, a test case class, a TestSuite instance, a test method
382 # within a test case class, or a callable object which returns a
383 # TestCase or TestSuite instance."
384 #
385 # What happens when we provide the module, but the attribute can't be
386 # found?
387 def test_loadTestsFromName__relative_unknown_name(self):
388 loader = unittest.TestLoader()
389
390 try:
391 loader.loadTestsFromName('sdasfasfasdf', unittest)
392 except AttributeError as e:
393 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
394 else:
395 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
396
397 # "The specifier name is a ``dotted name'' that may resolve either to
398 # a module, a test case class, a TestSuite instance, a test method
399 # within a test case class, or a callable object which returns a
400 # TestCase or TestSuite instance."
401 # ...
402 # "The method optionally resolves name relative to the given module"
403 #
404 # Does loadTestsFromName raise ValueError when passed an empty
405 # name relative to a provided module?
406 #
407 # XXX Should probably raise a ValueError instead of an AttributeError
408 def test_loadTestsFromName__relative_empty_name(self):
409 loader = unittest.TestLoader()
410
411 try:
412 loader.loadTestsFromName('', unittest)
413 except AttributeError as e:
414 pass
415 else:
416 self.fail("Failed to raise AttributeError")
417
418 # "The specifier name is a ``dotted name'' that may resolve either to
419 # a module, a test case class, a TestSuite instance, a test method
420 # within a test case class, or a callable object which returns a
421 # TestCase or TestSuite instance."
422 # ...
423 # "The method optionally resolves name relative to the given module"
424 #
425 # What happens when an impossible name is given, relative to the provided
426 # `module`?
427 def test_loadTestsFromName__relative_malformed_name(self):
428 loader = unittest.TestLoader()
429
430 # XXX Should this raise AttributeError or ValueError?
431 try:
432 loader.loadTestsFromName('abc () //', unittest)
433 except ValueError:
434 pass
435 except AttributeError:
436 pass
437 else:
438 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
439
440 # "The method optionally resolves name relative to the given module"
441 #
442 # Does loadTestsFromName raise TypeError when the `module` argument
443 # isn't a module object?
444 #
445 # XXX Accepts the not-a-module object, ignorning the object's type
446 # This should raise an exception or the method name should be changed
447 #
448 # XXX Some people are relying on this, so keep it for now
449 def test_loadTestsFromName__relative_not_a_module(self):
450 class MyTestCase(unittest.TestCase):
451 def test(self):
452 pass
453
454 class NotAModule(object):
455 test_2 = MyTestCase
456
457 loader = unittest.TestLoader()
458 suite = loader.loadTestsFromName('test_2', NotAModule)
459
460 reference = [MyTestCase('test')]
461 self.assertEqual(list(suite), reference)
462
463 # "The specifier name is a ``dotted name'' that may resolve either to
464 # a module, a test case class, a TestSuite instance, a test method
465 # within a test case class, or a callable object which returns a
466 # TestCase or TestSuite instance."
467 #
468 # Does it raise an exception if the name resolves to an invalid
469 # object?
470 def test_loadTestsFromName__relative_bad_object(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000471 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000472 m.testcase_1 = object()
473
474 loader = unittest.TestLoader()
475 try:
476 loader.loadTestsFromName('testcase_1', m)
477 except TypeError:
478 pass
479 else:
480 self.fail("Should have raised TypeError")
481
482 # "The specifier name is a ``dotted name'' that may
483 # resolve either to ... a test case class"
484 def test_loadTestsFromName__relative_TestCase_subclass(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000485 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000486 class MyTestCase(unittest.TestCase):
487 def test(self):
488 pass
489 m.testcase_1 = MyTestCase
490
491 loader = unittest.TestLoader()
492 suite = loader.loadTestsFromName('testcase_1', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000493 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000494 self.assertEqual(list(suite), [MyTestCase('test')])
495
496 # "The specifier name is a ``dotted name'' that may resolve either to
497 # a module, a test case class, a TestSuite instance, a test method
498 # within a test case class, or a callable object which returns a
499 # TestCase or TestSuite instance."
500 def test_loadTestsFromName__relative_TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000501 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000502 class MyTestCase(unittest.TestCase):
503 def test(self):
504 pass
505 m.testsuite = unittest.TestSuite([MyTestCase('test')])
506
507 loader = unittest.TestLoader()
508 suite = loader.loadTestsFromName('testsuite', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000509 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000510
511 self.assertEqual(list(suite), [MyTestCase('test')])
512
513 # "The specifier name is a ``dotted name'' that may resolve ... to
514 # ... a test method within a test case class"
515 def test_loadTestsFromName__relative_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000516 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000517 class MyTestCase(unittest.TestCase):
518 def test(self):
519 pass
520 m.testcase_1 = MyTestCase
521
522 loader = unittest.TestLoader()
523 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000524 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000525
526 self.assertEqual(list(suite), [MyTestCase('test')])
527
528 # "The specifier name is a ``dotted name'' that may resolve either to
529 # a module, a test case class, a TestSuite instance, a test method
530 # within a test case class, or a callable object which returns a
531 # TestCase or TestSuite instance."
532 #
533 # Does loadTestsFromName() raise the proper exception when trying to
534 # resolve "a test method within a test case class" that doesn't exist
535 # for the given name (relative to a provided module)?
536 def test_loadTestsFromName__relative_invalid_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000537 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000538 class MyTestCase(unittest.TestCase):
539 def test(self):
540 pass
541 m.testcase_1 = MyTestCase
542
543 loader = unittest.TestLoader()
544 try:
545 loader.loadTestsFromName('testcase_1.testfoo', m)
546 except AttributeError as e:
547 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
548 else:
549 self.fail("Failed to raise AttributeError")
550
551 # "The specifier name is a ``dotted name'' that may resolve ... to
552 # ... a callable object which returns a ... TestSuite instance"
553 def test_loadTestsFromName__callable__TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000554 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000555 testcase_1 = unittest.FunctionTestCase(lambda: None)
556 testcase_2 = unittest.FunctionTestCase(lambda: None)
557 def return_TestSuite():
558 return unittest.TestSuite([testcase_1, testcase_2])
559 m.return_TestSuite = return_TestSuite
560
561 loader = unittest.TestLoader()
562 suite = loader.loadTestsFromName('return_TestSuite', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000563 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000564 self.assertEqual(list(suite), [testcase_1, testcase_2])
565
566 # "The specifier name is a ``dotted name'' that may resolve ... to
567 # ... a callable object which returns a TestCase ... instance"
568 def test_loadTestsFromName__callable__TestCase_instance(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000569 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000570 testcase_1 = unittest.FunctionTestCase(lambda: None)
571 def return_TestCase():
572 return testcase_1
573 m.return_TestCase = return_TestCase
574
575 loader = unittest.TestLoader()
576 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000577 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000578 self.assertEqual(list(suite), [testcase_1])
579
580 # "The specifier name is a ``dotted name'' that may resolve ... to
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000581 # ... a callable object which returns a TestCase ... instance"
582 #*****************************************************************
583 #Override the suiteClass attribute to ensure that the suiteClass
584 #attribute is used
585 def test_loadTestsFromName__callable__TestCase_instance_ProperSuiteClass(self):
586 class SubTestSuite(unittest.TestSuite):
587 pass
588 m = types.ModuleType('m')
589 testcase_1 = unittest.FunctionTestCase(lambda: None)
590 def return_TestCase():
591 return testcase_1
592 m.return_TestCase = return_TestCase
593
594 loader = unittest.TestLoader()
595 loader.suiteClass = SubTestSuite
596 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000597 self.assertIsInstance(suite, loader.suiteClass)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000598 self.assertEqual(list(suite), [testcase_1])
599
600 # "The specifier name is a ``dotted name'' that may resolve ... to
601 # ... a test method within a test case class"
602 #*****************************************************************
603 #Override the suiteClass attribute to ensure that the suiteClass
604 #attribute is used
605 def test_loadTestsFromName__relative_testmethod_ProperSuiteClass(self):
606 class SubTestSuite(unittest.TestSuite):
607 pass
608 m = types.ModuleType('m')
609 class MyTestCase(unittest.TestCase):
610 def test(self):
611 pass
612 m.testcase_1 = MyTestCase
613
614 loader = unittest.TestLoader()
615 loader.suiteClass=SubTestSuite
616 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000617 self.assertIsInstance(suite, loader.suiteClass)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000618
619 self.assertEqual(list(suite), [MyTestCase('test')])
620
621 # "The specifier name is a ``dotted name'' that may resolve ... to
Guido van Rossumd8faa362007-04-27 19:54:29 +0000622 # ... a callable object which returns a TestCase or TestSuite instance"
623 #
624 # What happens if the callable returns something else?
625 def test_loadTestsFromName__callable__wrong_type(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000626 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000627 def return_wrong():
628 return 6
629 m.return_wrong = return_wrong
630
631 loader = unittest.TestLoader()
632 try:
633 suite = loader.loadTestsFromName('return_wrong', m)
634 except TypeError:
635 pass
636 else:
637 self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
638
639 # "The specifier can refer to modules and packages which have not been
640 # imported; they will be imported as a side-effect"
641 def test_loadTestsFromName__module_not_loaded(self):
642 # We're going to try to load this module as a side-effect, so it
643 # better not be loaded before we try.
644 #
645 # Why pick audioop? Google shows it isn't used very often, so there's
646 # a good chance that it won't be imported when this test is run
647 module_name = 'audioop'
648
Guido van Rossumd8faa362007-04-27 19:54:29 +0000649 if module_name in sys.modules:
650 del sys.modules[module_name]
651
652 loader = unittest.TestLoader()
653 try:
654 suite = loader.loadTestsFromName(module_name)
655
Ezio Melottie9615932010-01-24 19:26:24 +0000656 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000657 self.assertEqual(list(suite), [])
658
659 # audioop should now be loaded, thanks to loadTestsFromName()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000660 self.assertIn(module_name, sys.modules)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000661 finally:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000662 if module_name in sys.modules:
663 del sys.modules[module_name]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000664
665 ################################################################
666 ### Tests for TestLoader.loadTestsFromName()
667
668 ### Tests for TestLoader.loadTestsFromNames()
669 ################################################################
670
671 # "Similar to loadTestsFromName(), but takes a sequence of names rather
672 # than a single name."
673 #
674 # What happens if that sequence of names is empty?
675 def test_loadTestsFromNames__empty_name_list(self):
676 loader = unittest.TestLoader()
677
678 suite = loader.loadTestsFromNames([])
Ezio Melottie9615932010-01-24 19:26:24 +0000679 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000680 self.assertEqual(list(suite), [])
681
682 # "Similar to loadTestsFromName(), but takes a sequence of names rather
683 # than a single name."
684 # ...
685 # "The method optionally resolves name relative to the given module"
686 #
687 # What happens if that sequence of names is empty?
688 #
689 # XXX Should this raise a ValueError or just return an empty TestSuite?
690 def test_loadTestsFromNames__relative_empty_name_list(self):
691 loader = unittest.TestLoader()
692
693 suite = loader.loadTestsFromNames([], unittest)
Ezio Melottie9615932010-01-24 19:26:24 +0000694 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000695 self.assertEqual(list(suite), [])
696
697 # "The specifier name is a ``dotted name'' that may resolve either to
698 # a module, a test case class, a TestSuite instance, a test method
699 # within a test case class, or a callable object which returns a
700 # TestCase or TestSuite instance."
701 #
702 # Is ValueError raised in response to an empty name?
703 def test_loadTestsFromNames__empty_name(self):
704 loader = unittest.TestLoader()
705
706 try:
707 loader.loadTestsFromNames([''])
708 except ValueError as e:
709 self.assertEqual(str(e), "Empty module name")
710 else:
711 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
712
713 # "The specifier name is a ``dotted name'' that may resolve either to
714 # a module, a test case class, a TestSuite instance, a test method
715 # within a test case class, or a callable object which returns a
716 # TestCase or TestSuite instance."
717 #
718 # What happens when presented with an impossible module name?
719 def test_loadTestsFromNames__malformed_name(self):
720 loader = unittest.TestLoader()
721
722 # XXX Should this raise ValueError or ImportError?
723 try:
724 loader.loadTestsFromNames(['abc () //'])
725 except ValueError:
726 pass
727 except ImportError:
728 pass
729 else:
730 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
731
732 # "The specifier name is a ``dotted name'' that may resolve either to
733 # a module, a test case class, a TestSuite instance, a test method
734 # within a test case class, or a callable object which returns a
735 # TestCase or TestSuite instance."
736 #
737 # What happens when no module can be found for the given name?
738 def test_loadTestsFromNames__unknown_module_name(self):
739 loader = unittest.TestLoader()
740
741 try:
742 loader.loadTestsFromNames(['sdasfasfasdf'])
743 except ImportError as e:
744 self.assertEqual(str(e), "No module named sdasfasfasdf")
745 else:
746 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
747
748 # "The specifier name is a ``dotted name'' that may resolve either to
749 # a module, a test case class, a TestSuite instance, a test method
750 # within a test case class, or a callable object which returns a
751 # TestCase or TestSuite instance."
752 #
753 # What happens when the module can be found, but not the attribute?
754 def test_loadTestsFromNames__unknown_attr_name(self):
755 loader = unittest.TestLoader()
756
757 try:
758 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
759 except AttributeError as e:
760 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
761 else:
762 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
763
764 # "The specifier name is a ``dotted name'' that may resolve either to
765 # a module, a test case class, a TestSuite instance, a test method
766 # within a test case class, or a callable object which returns a
767 # TestCase or TestSuite instance."
768 # ...
769 # "The method optionally resolves name relative to the given module"
770 #
771 # What happens when given an unknown attribute on a specified `module`
772 # argument?
773 def test_loadTestsFromNames__unknown_name_relative_1(self):
774 loader = unittest.TestLoader()
775
776 try:
777 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
778 except AttributeError as e:
779 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
780 else:
781 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
782
783 # "The specifier name is a ``dotted name'' that may resolve either to
784 # a module, a test case class, a TestSuite instance, a test method
785 # within a test case class, or a callable object which returns a
786 # TestCase or TestSuite instance."
787 # ...
788 # "The method optionally resolves name relative to the given module"
789 #
790 # Do unknown attributes (relative to a provided module) still raise an
791 # exception even in the presence of valid attribute names?
792 def test_loadTestsFromNames__unknown_name_relative_2(self):
793 loader = unittest.TestLoader()
794
795 try:
796 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
797 except AttributeError as e:
798 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
799 else:
800 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
801
802 # "The specifier name is a ``dotted name'' that may resolve either to
803 # a module, a test case class, a TestSuite instance, a test method
804 # within a test case class, or a callable object which returns a
805 # TestCase or TestSuite instance."
806 # ...
807 # "The method optionally resolves name relative to the given module"
808 #
809 # What happens when faced with the empty string?
810 #
811 # XXX This currently raises AttributeError, though ValueError is probably
812 # more appropriate
813 def test_loadTestsFromNames__relative_empty_name(self):
814 loader = unittest.TestLoader()
815
816 try:
817 loader.loadTestsFromNames([''], unittest)
818 except AttributeError:
819 pass
820 else:
821 self.fail("Failed to raise ValueError")
822
823 # "The specifier name is a ``dotted name'' that may resolve either to
824 # a module, a test case class, a TestSuite instance, a test method
825 # within a test case class, or a callable object which returns a
826 # TestCase or TestSuite instance."
827 # ...
828 # "The method optionally resolves name relative to the given module"
829 #
830 # What happens when presented with an impossible attribute name?
831 def test_loadTestsFromNames__relative_malformed_name(self):
832 loader = unittest.TestLoader()
833
834 # XXX Should this raise AttributeError or ValueError?
835 try:
836 loader.loadTestsFromNames(['abc () //'], unittest)
837 except AttributeError:
838 pass
839 except ValueError:
840 pass
841 else:
842 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
843
844 # "The method optionally resolves name relative to the given module"
845 #
846 # Does loadTestsFromNames() make sure the provided `module` is in fact
847 # a module?
848 #
849 # XXX This validation is currently not done. This flexibility should
850 # either be documented or a TypeError should be raised.
851 def test_loadTestsFromNames__relative_not_a_module(self):
852 class MyTestCase(unittest.TestCase):
853 def test(self):
854 pass
855
856 class NotAModule(object):
857 test_2 = MyTestCase
858
859 loader = unittest.TestLoader()
860 suite = loader.loadTestsFromNames(['test_2'], NotAModule)
861
862 reference = [unittest.TestSuite([MyTestCase('test')])]
863 self.assertEqual(list(suite), reference)
864
865 # "The specifier name is a ``dotted name'' that may resolve either to
866 # a module, a test case class, a TestSuite instance, a test method
867 # within a test case class, or a callable object which returns a
868 # TestCase or TestSuite instance."
869 #
870 # Does it raise an exception if the name resolves to an invalid
871 # object?
872 def test_loadTestsFromNames__relative_bad_object(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000873 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000874 m.testcase_1 = object()
875
876 loader = unittest.TestLoader()
877 try:
878 loader.loadTestsFromNames(['testcase_1'], m)
879 except TypeError:
880 pass
881 else:
882 self.fail("Should have raised TypeError")
883
884 # "The specifier name is a ``dotted name'' that may resolve ... to
885 # ... a test case class"
886 def test_loadTestsFromNames__relative_TestCase_subclass(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000887 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000888 class MyTestCase(unittest.TestCase):
889 def test(self):
890 pass
891 m.testcase_1 = MyTestCase
892
893 loader = unittest.TestLoader()
894 suite = loader.loadTestsFromNames(['testcase_1'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000895 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000896
897 expected = loader.suiteClass([MyTestCase('test')])
898 self.assertEqual(list(suite), [expected])
899
900 # "The specifier name is a ``dotted name'' that may resolve ... to
901 # ... a TestSuite instance"
902 def test_loadTestsFromNames__relative_TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000903 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000904 class MyTestCase(unittest.TestCase):
905 def test(self):
906 pass
907 m.testsuite = unittest.TestSuite([MyTestCase('test')])
908
909 loader = unittest.TestLoader()
910 suite = loader.loadTestsFromNames(['testsuite'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000911 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000912
913 self.assertEqual(list(suite), [m.testsuite])
914
915 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
916 # test method within a test case class"
917 def test_loadTestsFromNames__relative_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000918 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000919 class MyTestCase(unittest.TestCase):
920 def test(self):
921 pass
922 m.testcase_1 = MyTestCase
923
924 loader = unittest.TestLoader()
925 suite = loader.loadTestsFromNames(['testcase_1.test'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000926 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000927
928 ref_suite = unittest.TestSuite([MyTestCase('test')])
929 self.assertEqual(list(suite), [ref_suite])
930
931 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
932 # test method within a test case class"
933 #
934 # Does the method gracefully handle names that initially look like they
935 # resolve to "a test method within a test case class" but don't?
936 def test_loadTestsFromNames__relative_invalid_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000937 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000938 class MyTestCase(unittest.TestCase):
939 def test(self):
940 pass
941 m.testcase_1 = MyTestCase
942
943 loader = unittest.TestLoader()
944 try:
945 loader.loadTestsFromNames(['testcase_1.testfoo'], m)
946 except AttributeError as e:
947 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
948 else:
949 self.fail("Failed to raise AttributeError")
950
951 # "The specifier name is a ``dotted name'' that may resolve ... to
952 # ... a callable object which returns a ... TestSuite instance"
953 def test_loadTestsFromNames__callable__TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000954 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000955 testcase_1 = unittest.FunctionTestCase(lambda: None)
956 testcase_2 = unittest.FunctionTestCase(lambda: None)
957 def return_TestSuite():
958 return unittest.TestSuite([testcase_1, testcase_2])
959 m.return_TestSuite = return_TestSuite
960
961 loader = unittest.TestLoader()
962 suite = loader.loadTestsFromNames(['return_TestSuite'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000963 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000964
965 expected = unittest.TestSuite([testcase_1, testcase_2])
966 self.assertEqual(list(suite), [expected])
967
968 # "The specifier name is a ``dotted name'' that may resolve ... to
969 # ... a callable object which returns a TestCase ... instance"
970 def test_loadTestsFromNames__callable__TestCase_instance(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000971 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000972 testcase_1 = unittest.FunctionTestCase(lambda: None)
973 def return_TestCase():
974 return testcase_1
975 m.return_TestCase = return_TestCase
976
977 loader = unittest.TestLoader()
978 suite = loader.loadTestsFromNames(['return_TestCase'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000979 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000980
981 ref_suite = unittest.TestSuite([testcase_1])
982 self.assertEqual(list(suite), [ref_suite])
983
984 # "The specifier name is a ``dotted name'' that may resolve ... to
985 # ... a callable object which returns a TestCase or TestSuite instance"
986 #
987 # Are staticmethods handled correctly?
988 def test_loadTestsFromNames__callable__call_staticmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000989 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000990 class Test1(unittest.TestCase):
991 def test(self):
992 pass
993
994 testcase_1 = Test1('test')
995 class Foo(unittest.TestCase):
996 @staticmethod
997 def foo():
998 return testcase_1
999 m.Foo = Foo
1000
1001 loader = unittest.TestLoader()
1002 suite = loader.loadTestsFromNames(['Foo.foo'], m)
Ezio Melottie9615932010-01-24 19:26:24 +00001003 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001004
1005 ref_suite = unittest.TestSuite([testcase_1])
1006 self.assertEqual(list(suite), [ref_suite])
1007
1008 # "The specifier name is a ``dotted name'' that may resolve ... to
1009 # ... a callable object which returns a TestCase or TestSuite instance"
1010 #
1011 # What happens when the callable returns something else?
1012 def test_loadTestsFromNames__callable__wrong_type(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001013 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001014 def return_wrong():
1015 return 6
1016 m.return_wrong = return_wrong
1017
1018 loader = unittest.TestLoader()
1019 try:
1020 suite = loader.loadTestsFromNames(['return_wrong'], m)
1021 except TypeError:
1022 pass
1023 else:
1024 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
1025
1026 # "The specifier can refer to modules and packages which have not been
1027 # imported; they will be imported as a side-effect"
1028 def test_loadTestsFromNames__module_not_loaded(self):
1029 # We're going to try to load this module as a side-effect, so it
1030 # better not be loaded before we try.
1031 #
1032 # Why pick audioop? Google shows it isn't used very often, so there's
1033 # a good chance that it won't be imported when this test is run
1034 module_name = 'audioop'
1035
Guido van Rossumd8faa362007-04-27 19:54:29 +00001036 if module_name in sys.modules:
1037 del sys.modules[module_name]
1038
1039 loader = unittest.TestLoader()
1040 try:
1041 suite = loader.loadTestsFromNames([module_name])
1042
Ezio Melottie9615932010-01-24 19:26:24 +00001043 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001044 self.assertEqual(list(suite), [unittest.TestSuite()])
1045
1046 # audioop should now be loaded, thanks to loadTestsFromName()
Benjamin Peterson577473f2010-01-19 00:09:57 +00001047 self.assertIn(module_name, sys.modules)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001048 finally:
Guido van Rossum360e4b82007-05-14 22:51:27 +00001049 if module_name in sys.modules:
1050 del sys.modules[module_name]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001051
1052 ################################################################
1053 ### /Tests for TestLoader.loadTestsFromNames()
1054
1055 ### Tests for TestLoader.getTestCaseNames()
1056 ################################################################
1057
1058 # "Return a sorted sequence of method names found within testCaseClass"
1059 #
1060 # Test.foobar is defined to make sure getTestCaseNames() respects
1061 # loader.testMethodPrefix
1062 def test_getTestCaseNames(self):
1063 class Test(unittest.TestCase):
1064 def test_1(self): pass
1065 def test_2(self): pass
1066 def foobar(self): pass
1067
1068 loader = unittest.TestLoader()
1069
1070 self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])
1071
1072 # "Return a sorted sequence of method names found within testCaseClass"
1073 #
1074 # Does getTestCaseNames() behave appropriately if no tests are found?
1075 def test_getTestCaseNames__no_tests(self):
1076 class Test(unittest.TestCase):
1077 def foobar(self): pass
1078
1079 loader = unittest.TestLoader()
1080
1081 self.assertEqual(loader.getTestCaseNames(Test), [])
1082
1083 # "Return a sorted sequence of method names found within testCaseClass"
1084 #
1085 # Are not-TestCases handled gracefully?
1086 #
1087 # XXX This should raise a TypeError, not return a list
1088 #
1089 # XXX It's too late in the 2.5 release cycle to fix this, but it should
1090 # probably be revisited for 2.6
1091 def test_getTestCaseNames__not_a_TestCase(self):
1092 class BadCase(int):
1093 def test_foo(self):
1094 pass
1095
1096 loader = unittest.TestLoader()
1097 names = loader.getTestCaseNames(BadCase)
1098
1099 self.assertEqual(names, ['test_foo'])
1100
1101 # "Return a sorted sequence of method names found within testCaseClass"
1102 #
1103 # Make sure inherited names are handled.
1104 #
1105 # TestP.foobar is defined to make sure getTestCaseNames() respects
1106 # loader.testMethodPrefix
1107 def test_getTestCaseNames__inheritance(self):
1108 class TestP(unittest.TestCase):
1109 def test_1(self): pass
1110 def test_2(self): pass
1111 def foobar(self): pass
1112
1113 class TestC(TestP):
1114 def test_1(self): pass
1115 def test_3(self): pass
1116
1117 loader = unittest.TestLoader()
1118
1119 names = ['test_1', 'test_2', 'test_3']
1120 self.assertEqual(loader.getTestCaseNames(TestC), names)
1121
1122 ################################################################
1123 ### /Tests for TestLoader.getTestCaseNames()
1124
1125 ### Tests for TestLoader.testMethodPrefix
1126 ################################################################
1127
1128 # "String giving the prefix of method names which will be interpreted as
1129 # test methods"
1130 #
1131 # Implicit in the documentation is that testMethodPrefix is respected by
1132 # all loadTestsFrom* methods.
1133 def test_testMethodPrefix__loadTestsFromTestCase(self):
1134 class Foo(unittest.TestCase):
1135 def test_1(self): pass
1136 def test_2(self): pass
1137 def foo_bar(self): pass
1138
1139 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1140 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1141
1142 loader = unittest.TestLoader()
1143 loader.testMethodPrefix = 'foo'
1144 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
1145
1146 loader.testMethodPrefix = 'test'
1147 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
1148
1149 # "String giving the prefix of method names which will be interpreted as
1150 # test methods"
1151 #
1152 # Implicit in the documentation is that testMethodPrefix is respected by
1153 # all loadTestsFrom* methods.
1154 def test_testMethodPrefix__loadTestsFromModule(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001155 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001156 class Foo(unittest.TestCase):
1157 def test_1(self): pass
1158 def test_2(self): pass
1159 def foo_bar(self): pass
1160 m.Foo = Foo
1161
1162 tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
1163 tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]
1164
1165 loader = unittest.TestLoader()
1166 loader.testMethodPrefix = 'foo'
1167 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
1168
1169 loader.testMethodPrefix = 'test'
1170 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
1171
1172 # "String giving the prefix of method names which will be interpreted as
1173 # test methods"
1174 #
1175 # Implicit in the documentation is that testMethodPrefix is respected by
1176 # all loadTestsFrom* methods.
1177 def test_testMethodPrefix__loadTestsFromName(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001178 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001179 class Foo(unittest.TestCase):
1180 def test_1(self): pass
1181 def test_2(self): pass
1182 def foo_bar(self): pass
1183 m.Foo = Foo
1184
1185 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1186 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1187
1188 loader = unittest.TestLoader()
1189 loader.testMethodPrefix = 'foo'
1190 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
1191
1192 loader.testMethodPrefix = 'test'
1193 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
1194
1195 # "String giving the prefix of method names which will be interpreted as
1196 # test methods"
1197 #
1198 # Implicit in the documentation is that testMethodPrefix is respected by
1199 # all loadTestsFrom* methods.
1200 def test_testMethodPrefix__loadTestsFromNames(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001201 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001202 class Foo(unittest.TestCase):
1203 def test_1(self): pass
1204 def test_2(self): pass
1205 def foo_bar(self): pass
1206 m.Foo = Foo
1207
1208 tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
1209 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1210 tests_2 = unittest.TestSuite([tests_2])
1211
1212 loader = unittest.TestLoader()
1213 loader.testMethodPrefix = 'foo'
1214 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)
1215
1216 loader.testMethodPrefix = 'test'
1217 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)
1218
1219 # "The default value is 'test'"
1220 def test_testMethodPrefix__default_value(self):
1221 loader = unittest.TestLoader()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001222 self.assertEqual(loader.testMethodPrefix, 'test')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001223
1224 ################################################################
1225 ### /Tests for TestLoader.testMethodPrefix
1226
1227 ### Tests for TestLoader.sortTestMethodsUsing
1228 ################################################################
1229
1230 # "Function to be used to compare method names when sorting them in
1231 # getTestCaseNames() and all the loadTestsFromX() methods"
1232 def test_sortTestMethodsUsing__loadTestsFromTestCase(self):
1233 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001234 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001235
1236 class Foo(unittest.TestCase):
1237 def test_1(self): pass
1238 def test_2(self): pass
1239
1240 loader = unittest.TestLoader()
1241 loader.sortTestMethodsUsing = reversed_cmp
1242
1243 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1244 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
1245
1246 # "Function to be used to compare method names when sorting them in
1247 # getTestCaseNames() and all the loadTestsFromX() methods"
1248 def test_sortTestMethodsUsing__loadTestsFromModule(self):
1249 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001250 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001251
Christian Heimes45f9af32007-11-27 21:50:00 +00001252 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001253 class Foo(unittest.TestCase):
1254 def test_1(self): pass
1255 def test_2(self): pass
1256 m.Foo = Foo
1257
1258 loader = unittest.TestLoader()
1259 loader.sortTestMethodsUsing = reversed_cmp
1260
1261 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1262 self.assertEqual(list(loader.loadTestsFromModule(m)), tests)
1263
1264 # "Function to be used to compare method names when sorting them in
1265 # getTestCaseNames() and all the loadTestsFromX() methods"
1266 def test_sortTestMethodsUsing__loadTestsFromName(self):
1267 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001268 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001269
Christian Heimes45f9af32007-11-27 21:50:00 +00001270 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001271 class Foo(unittest.TestCase):
1272 def test_1(self): pass
1273 def test_2(self): pass
1274 m.Foo = Foo
1275
1276 loader = unittest.TestLoader()
1277 loader.sortTestMethodsUsing = reversed_cmp
1278
1279 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1280 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
1281
1282 # "Function to be used to compare method names when sorting them in
1283 # getTestCaseNames() and all the loadTestsFromX() methods"
1284 def test_sortTestMethodsUsing__loadTestsFromNames(self):
1285 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001286 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001287
Christian Heimes45f9af32007-11-27 21:50:00 +00001288 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001289 class Foo(unittest.TestCase):
1290 def test_1(self): pass
1291 def test_2(self): pass
1292 m.Foo = Foo
1293
1294 loader = unittest.TestLoader()
1295 loader.sortTestMethodsUsing = reversed_cmp
1296
1297 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1298 self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)
1299
1300 # "Function to be used to compare method names when sorting them in
1301 # getTestCaseNames()"
1302 #
1303 # Does it actually affect getTestCaseNames()?
1304 def test_sortTestMethodsUsing__getTestCaseNames(self):
1305 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001306 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001307
1308 class Foo(unittest.TestCase):
1309 def test_1(self): pass
1310 def test_2(self): pass
1311
1312 loader = unittest.TestLoader()
1313 loader.sortTestMethodsUsing = reversed_cmp
1314
1315 test_names = ['test_2', 'test_1']
1316 self.assertEqual(loader.getTestCaseNames(Foo), test_names)
1317
1318 # "The default value is the built-in cmp() function"
Mark Dickinsona56c4672009-01-27 18:17:45 +00001319 # Since cmp is now defunct, we simply verify that the results
1320 # occur in the same order as they would with the default sort.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001321 def test_sortTestMethodsUsing__default_value(self):
1322 loader = unittest.TestLoader()
Mark Dickinsona56c4672009-01-27 18:17:45 +00001323
1324 class Foo(unittest.TestCase):
1325 def test_2(self): pass
1326 def test_3(self): pass
1327 def test_1(self): pass
1328
1329 test_names = ['test_2', 'test_3', 'test_1']
1330 self.assertEqual(loader.getTestCaseNames(Foo), sorted(test_names))
1331
Guido van Rossumd8faa362007-04-27 19:54:29 +00001332
1333 # "it can be set to None to disable the sort."
1334 #
1335 # XXX How is this different from reassigning cmp? Are the tests returned
1336 # in a random order or something? This behaviour should die
1337 def test_sortTestMethodsUsing__None(self):
1338 class Foo(unittest.TestCase):
1339 def test_1(self): pass
1340 def test_2(self): pass
1341
1342 loader = unittest.TestLoader()
1343 loader.sortTestMethodsUsing = None
1344
1345 test_names = ['test_2', 'test_1']
1346 self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))
1347
1348 ################################################################
1349 ### /Tests for TestLoader.sortTestMethodsUsing
1350
1351 ### Tests for TestLoader.suiteClass
1352 ################################################################
1353
1354 # "Callable object that constructs a test suite from a list of tests."
1355 def test_suiteClass__loadTestsFromTestCase(self):
1356 class Foo(unittest.TestCase):
1357 def test_1(self): pass
1358 def test_2(self): pass
1359 def foo_bar(self): pass
1360
1361 tests = [Foo('test_1'), Foo('test_2')]
1362
1363 loader = unittest.TestLoader()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001364 loader.suiteClass = list
Guido van Rossumd8faa362007-04-27 19:54:29 +00001365 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
1366
1367 # It is implicit in the documentation for TestLoader.suiteClass that
1368 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
1369 def test_suiteClass__loadTestsFromModule(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001370 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001371 class Foo(unittest.TestCase):
1372 def test_1(self): pass
1373 def test_2(self): pass
1374 def foo_bar(self): pass
1375 m.Foo = Foo
1376
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001377 tests = [[Foo('test_1'), Foo('test_2')]]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001378
1379 loader = unittest.TestLoader()
1380 loader.suiteClass = list
1381 self.assertEqual(loader.loadTestsFromModule(m), tests)
1382
1383 # It is implicit in the documentation for TestLoader.suiteClass that
1384 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
1385 def test_suiteClass__loadTestsFromName(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001386 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001387 class Foo(unittest.TestCase):
1388 def test_1(self): pass
1389 def test_2(self): pass
1390 def foo_bar(self): pass
1391 m.Foo = Foo
1392
1393 tests = [Foo('test_1'), Foo('test_2')]
1394
1395 loader = unittest.TestLoader()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001396 loader.suiteClass = list
Guido van Rossumd8faa362007-04-27 19:54:29 +00001397 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
1398
1399 # It is implicit in the documentation for TestLoader.suiteClass that
1400 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
1401 def test_suiteClass__loadTestsFromNames(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001402 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001403 class Foo(unittest.TestCase):
1404 def test_1(self): pass
1405 def test_2(self): pass
1406 def foo_bar(self): pass
1407 m.Foo = Foo
1408
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001409 tests = [[Foo('test_1'), Foo('test_2')]]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001410
1411 loader = unittest.TestLoader()
1412 loader.suiteClass = list
1413 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)
1414
1415 # "The default value is the TestSuite class"
1416 def test_suiteClass__default_value(self):
1417 loader = unittest.TestLoader()
Benjamin Petersone1759f82009-06-30 23:35:19 +00001418 self.assertTrue(loader.suiteClass is unittest.TestSuite)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001419
1420 ################################################################
1421 ### /Tests for TestLoader.suiteClass
1422
1423### Support code for Test_TestSuite
1424################################################################
1425
1426class Foo(unittest.TestCase):
1427 def test_1(self): pass
1428 def test_2(self): pass
1429 def test_3(self): pass
1430 def runTest(self): pass
1431
1432def _mk_TestSuite(*names):
1433 return unittest.TestSuite(Foo(n) for n in names)
1434
1435################################################################
1436### /Support code for Test_TestSuite
1437
1438class Test_TestSuite(TestCase, TestEquality):
1439
1440 ### Set up attributes needed by inherited tests
1441 ################################################################
1442
1443 # Used by TestEquality.test_eq
1444 eq_pairs = [(unittest.TestSuite(), unittest.TestSuite())
1445 ,(unittest.TestSuite(), unittest.TestSuite([]))
1446 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]
1447
1448 # Used by TestEquality.test_ne
1449 ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1'))
1450 ,(unittest.TestSuite([]), _mk_TestSuite('test_1'))
1451 ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3'))
1452 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]
1453
1454 ################################################################
1455 ### /Set up attributes needed by inherited tests
1456
1457 ### Tests for TestSuite.__init__
1458 ################################################################
1459
1460 # "class TestSuite([tests])"
1461 #
1462 # The tests iterable should be optional
1463 def test_init__tests_optional(self):
1464 suite = unittest.TestSuite()
1465
1466 self.assertEqual(suite.countTestCases(), 0)
1467
1468 # "class TestSuite([tests])"
1469 # ...
1470 # "If tests is given, it must be an iterable of individual test cases
1471 # or other test suites that will be used to build the suite initially"
1472 #
1473 # TestSuite should deal with empty tests iterables by allowing the
1474 # creation of an empty suite
1475 def test_init__empty_tests(self):
1476 suite = unittest.TestSuite([])
1477
1478 self.assertEqual(suite.countTestCases(), 0)
1479
1480 # "class TestSuite([tests])"
1481 # ...
1482 # "If tests is given, it must be an iterable of individual test cases
1483 # or other test suites that will be used to build the suite initially"
1484 #
1485 # TestSuite should allow any iterable to provide tests
1486 def test_init__tests_from_any_iterable(self):
1487 def tests():
1488 yield unittest.FunctionTestCase(lambda: None)
1489 yield unittest.FunctionTestCase(lambda: None)
1490
1491 suite_1 = unittest.TestSuite(tests())
1492 self.assertEqual(suite_1.countTestCases(), 2)
1493
1494 suite_2 = unittest.TestSuite(suite_1)
1495 self.assertEqual(suite_2.countTestCases(), 2)
1496
1497 suite_3 = unittest.TestSuite(set(suite_1))
1498 self.assertEqual(suite_3.countTestCases(), 2)
1499
1500 # "class TestSuite([tests])"
1501 # ...
1502 # "If tests is given, it must be an iterable of individual test cases
1503 # or other test suites that will be used to build the suite initially"
1504 #
1505 # Does TestSuite() also allow other TestSuite() instances to be present
1506 # in the tests iterable?
1507 def test_init__TestSuite_instances_in_tests(self):
1508 def tests():
1509 ftc = unittest.FunctionTestCase(lambda: None)
1510 yield unittest.TestSuite([ftc])
1511 yield unittest.FunctionTestCase(lambda: None)
1512
1513 suite = unittest.TestSuite(tests())
1514 self.assertEqual(suite.countTestCases(), 2)
1515
1516 ################################################################
1517 ### /Tests for TestSuite.__init__
1518
1519 # Container types should support the iter protocol
1520 def test_iter(self):
1521 test1 = unittest.FunctionTestCase(lambda: None)
1522 test2 = unittest.FunctionTestCase(lambda: None)
1523 suite = unittest.TestSuite((test1, test2))
1524
1525 self.assertEqual(list(suite), [test1, test2])
1526
1527 # "Return the number of tests represented by the this test object.
1528 # ...this method is also implemented by the TestSuite class, which can
1529 # return larger [greater than 1] values"
1530 #
1531 # Presumably an empty TestSuite returns 0?
1532 def test_countTestCases_zero_simple(self):
1533 suite = unittest.TestSuite()
1534
1535 self.assertEqual(suite.countTestCases(), 0)
1536
1537 # "Return the number of tests represented by the this test object.
1538 # ...this method is also implemented by the TestSuite class, which can
1539 # return larger [greater than 1] values"
1540 #
1541 # Presumably an empty TestSuite (even if it contains other empty
1542 # TestSuite instances) returns 0?
1543 def test_countTestCases_zero_nested(self):
1544 class Test1(unittest.TestCase):
1545 def test(self):
1546 pass
1547
1548 suite = unittest.TestSuite([unittest.TestSuite()])
1549
1550 self.assertEqual(suite.countTestCases(), 0)
1551
1552 # "Return the number of tests represented by the this test object.
1553 # ...this method is also implemented by the TestSuite class, which can
1554 # return larger [greater than 1] values"
1555 def test_countTestCases_simple(self):
1556 test1 = unittest.FunctionTestCase(lambda: None)
1557 test2 = unittest.FunctionTestCase(lambda: None)
1558 suite = unittest.TestSuite((test1, test2))
1559
1560 self.assertEqual(suite.countTestCases(), 2)
1561
1562 # "Return the number of tests represented by the this test object.
1563 # ...this method is also implemented by the TestSuite class, which can
1564 # return larger [greater than 1] values"
1565 #
1566 # Make sure this holds for nested TestSuite instances, too
1567 def test_countTestCases_nested(self):
1568 class Test1(unittest.TestCase):
1569 def test1(self): pass
1570 def test2(self): pass
1571
1572 test2 = unittest.FunctionTestCase(lambda: None)
1573 test3 = unittest.FunctionTestCase(lambda: None)
1574 child = unittest.TestSuite((Test1('test2'), test2))
1575 parent = unittest.TestSuite((test3, child, Test1('test1')))
1576
1577 self.assertEqual(parent.countTestCases(), 4)
1578
1579 # "Run the tests associated with this suite, collecting the result into
1580 # the test result object passed as result."
1581 #
1582 # And if there are no tests? What then?
1583 def test_run__empty_suite(self):
1584 events = []
1585 result = LoggingResult(events)
1586
1587 suite = unittest.TestSuite()
1588
1589 suite.run(result)
1590
1591 self.assertEqual(events, [])
1592
1593 # "Note that unlike TestCase.run(), TestSuite.run() requires the
1594 # "result object to be passed in."
1595 def test_run__requires_result(self):
1596 suite = unittest.TestSuite()
1597
1598 try:
1599 suite.run()
1600 except TypeError:
1601 pass
1602 else:
1603 self.fail("Failed to raise TypeError")
1604
1605 # "Run the tests associated with this suite, collecting the result into
1606 # the test result object passed as result."
1607 def test_run(self):
1608 events = []
1609 result = LoggingResult(events)
1610
1611 class LoggingCase(unittest.TestCase):
1612 def run(self, result):
1613 events.append('run %s' % self._testMethodName)
1614
1615 def test1(self): pass
1616 def test2(self): pass
1617
1618 tests = [LoggingCase('test1'), LoggingCase('test2')]
1619
1620 unittest.TestSuite(tests).run(result)
1621
1622 self.assertEqual(events, ['run test1', 'run test2'])
1623
1624 # "Add a TestCase ... to the suite"
1625 def test_addTest__TestCase(self):
1626 class Foo(unittest.TestCase):
1627 def test(self): pass
1628
1629 test = Foo('test')
1630 suite = unittest.TestSuite()
1631
1632 suite.addTest(test)
1633
1634 self.assertEqual(suite.countTestCases(), 1)
1635 self.assertEqual(list(suite), [test])
1636
1637 # "Add a ... TestSuite to the suite"
1638 def test_addTest__TestSuite(self):
1639 class Foo(unittest.TestCase):
1640 def test(self): pass
1641
1642 suite_2 = unittest.TestSuite([Foo('test')])
1643
1644 suite = unittest.TestSuite()
1645 suite.addTest(suite_2)
1646
1647 self.assertEqual(suite.countTestCases(), 1)
1648 self.assertEqual(list(suite), [suite_2])
1649
1650 # "Add all the tests from an iterable of TestCase and TestSuite
1651 # instances to this test suite."
1652 #
1653 # "This is equivalent to iterating over tests, calling addTest() for
1654 # each element"
1655 def test_addTests(self):
1656 class Foo(unittest.TestCase):
1657 def test_1(self): pass
1658 def test_2(self): pass
1659
1660 test_1 = Foo('test_1')
1661 test_2 = Foo('test_2')
1662 inner_suite = unittest.TestSuite([test_2])
1663
1664 def gen():
1665 yield test_1
1666 yield test_2
1667 yield inner_suite
1668
1669 suite_1 = unittest.TestSuite()
1670 suite_1.addTests(gen())
1671
1672 self.assertEqual(list(suite_1), list(gen()))
1673
1674 # "This is equivalent to iterating over tests, calling addTest() for
1675 # each element"
1676 suite_2 = unittest.TestSuite()
1677 for t in gen():
1678 suite_2.addTest(t)
1679
1680 self.assertEqual(suite_1, suite_2)
1681
1682 # "Add all the tests from an iterable of TestCase and TestSuite
1683 # instances to this test suite."
1684 #
1685 # What happens if it doesn't get an iterable?
1686 def test_addTest__noniterable(self):
1687 suite = unittest.TestSuite()
1688
1689 try:
1690 suite.addTests(5)
1691 except TypeError:
1692 pass
1693 else:
1694 self.fail("Failed to raise TypeError")
1695
1696 def test_addTest__noncallable(self):
1697 suite = unittest.TestSuite()
1698 self.assertRaises(TypeError, suite.addTest, 5)
1699
1700 def test_addTest__casesuiteclass(self):
1701 suite = unittest.TestSuite()
1702 self.assertRaises(TypeError, suite.addTest, Test_TestSuite)
1703 self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)
1704
1705 def test_addTests__string(self):
1706 suite = unittest.TestSuite()
1707 self.assertRaises(TypeError, suite.addTests, "foo")
1708
1709
1710class Test_FunctionTestCase(TestCase):
1711
1712 # "Return the number of tests represented by the this test object. For
1713 # TestCase instances, this will always be 1"
1714 def test_countTestCases(self):
1715 test = unittest.FunctionTestCase(lambda: None)
1716
1717 self.assertEqual(test.countTestCases(), 1)
1718
1719 # "When a setUp() method is defined, the test runner will run that method
1720 # prior to each test. Likewise, if a tearDown() method is defined, the
1721 # test runner will invoke that method after each test. In the example,
1722 # setUp() was used to create a fresh sequence for each test."
1723 #
1724 # Make sure the proper call order is maintained, even if setUp() raises
1725 # an exception.
1726 def test_run_call_order__error_in_setUp(self):
1727 events = []
1728 result = LoggingResult(events)
1729
1730 def setUp():
1731 events.append('setUp')
1732 raise RuntimeError('raised by setUp')
1733
1734 def test():
1735 events.append('test')
1736
1737 def tearDown():
1738 events.append('tearDown')
1739
1740 expected = ['startTest', 'setUp', 'addError', 'stopTest']
1741 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1742 self.assertEqual(events, expected)
1743
1744 # "When a setUp() method is defined, the test runner will run that method
1745 # prior to each test. Likewise, if a tearDown() method is defined, the
1746 # test runner will invoke that method after each test. In the example,
1747 # setUp() was used to create a fresh sequence for each test."
1748 #
1749 # Make sure the proper call order is maintained, even if the test raises
1750 # an error (as opposed to a failure).
1751 def test_run_call_order__error_in_test(self):
1752 events = []
1753 result = LoggingResult(events)
1754
1755 def setUp():
1756 events.append('setUp')
1757
1758 def test():
1759 events.append('test')
1760 raise RuntimeError('raised by test')
1761
1762 def tearDown():
1763 events.append('tearDown')
1764
1765 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
1766 'stopTest']
1767 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1768 self.assertEqual(events, expected)
1769
1770 # "When a setUp() method is defined, the test runner will run that method
1771 # prior to each test. Likewise, if a tearDown() method is defined, the
1772 # test runner will invoke that method after each test. In the example,
1773 # setUp() was used to create a fresh sequence for each test."
1774 #
1775 # Make sure the proper call order is maintained, even if the test signals
1776 # a failure (as opposed to an error).
1777 def test_run_call_order__failure_in_test(self):
1778 events = []
1779 result = LoggingResult(events)
1780
1781 def setUp():
1782 events.append('setUp')
1783
1784 def test():
1785 events.append('test')
1786 self.fail('raised by test')
1787
1788 def tearDown():
1789 events.append('tearDown')
1790
1791 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
1792 'stopTest']
1793 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1794 self.assertEqual(events, expected)
1795
1796 # "When a setUp() method is defined, the test runner will run that method
1797 # prior to each test. Likewise, if a tearDown() method is defined, the
1798 # test runner will invoke that method after each test. In the example,
1799 # setUp() was used to create a fresh sequence for each test."
1800 #
1801 # Make sure the proper call order is maintained, even if tearDown() raises
1802 # an exception.
1803 def test_run_call_order__error_in_tearDown(self):
1804 events = []
1805 result = LoggingResult(events)
1806
1807 def setUp():
1808 events.append('setUp')
1809
1810 def test():
1811 events.append('test')
1812
1813 def tearDown():
1814 events.append('tearDown')
1815 raise RuntimeError('raised by tearDown')
1816
1817 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
1818 'stopTest']
1819 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1820 self.assertEqual(events, expected)
1821
1822 # "Return a string identifying the specific test case."
1823 #
1824 # Because of the vague nature of the docs, I'm not going to lock this
1825 # test down too much. Really all that can be asserted is that the id()
1826 # will be a string (either 8-byte or unicode -- again, because the docs
1827 # just say "string")
1828 def test_id(self):
1829 test = unittest.FunctionTestCase(lambda: None)
1830
Ezio Melottie9615932010-01-24 19:26:24 +00001831 self.assertIsInstance(test.id(), str)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001832
1833 # "Returns a one-line description of the test, or None if no description
1834 # has been provided. The default implementation of this method returns
1835 # the first line of the test method's docstring, if available, or None."
1836 def test_shortDescription__no_docstring(self):
1837 test = unittest.FunctionTestCase(lambda: None)
1838
1839 self.assertEqual(test.shortDescription(), None)
1840
1841 # "Returns a one-line description of the test, or None if no description
1842 # has been provided. The default implementation of this method returns
1843 # the first line of the test method's docstring, if available, or None."
1844 def test_shortDescription__singleline_docstring(self):
1845 desc = "this tests foo"
1846 test = unittest.FunctionTestCase(lambda: None, description=desc)
1847
1848 self.assertEqual(test.shortDescription(), "this tests foo")
1849
1850class Test_TestResult(TestCase):
1851 # Note: there are not separate tests for TestResult.wasSuccessful(),
1852 # TestResult.errors, TestResult.failures, TestResult.testsRun or
1853 # TestResult.shouldStop because these only have meaning in terms of
1854 # other TestResult methods.
1855 #
1856 # Accordingly, tests for the aforenamed attributes are incorporated
1857 # in with the tests for the defining methods.
1858 ################################################################
1859
1860 def test_init(self):
1861 result = unittest.TestResult()
1862
Benjamin Petersone1759f82009-06-30 23:35:19 +00001863 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001864 self.assertEqual(len(result.errors), 0)
1865 self.assertEqual(len(result.failures), 0)
1866 self.assertEqual(result.testsRun, 0)
1867 self.assertEqual(result.shouldStop, False)
1868
1869 # "This method can be called to signal that the set of tests being
1870 # run should be aborted by setting the TestResult's shouldStop
1871 # attribute to True."
1872 def test_stop(self):
1873 result = unittest.TestResult()
1874
1875 result.stop()
1876
1877 self.assertEqual(result.shouldStop, True)
1878
1879 # "Called when the test case test is about to be run. The default
1880 # implementation simply increments the instance's testsRun counter."
1881 def test_startTest(self):
1882 class Foo(unittest.TestCase):
1883 def test_1(self):
1884 pass
1885
1886 test = Foo('test_1')
1887
1888 result = unittest.TestResult()
1889
1890 result.startTest(test)
1891
Benjamin Petersone1759f82009-06-30 23:35:19 +00001892 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001893 self.assertEqual(len(result.errors), 0)
1894 self.assertEqual(len(result.failures), 0)
1895 self.assertEqual(result.testsRun, 1)
1896 self.assertEqual(result.shouldStop, False)
1897
1898 result.stopTest(test)
1899
1900 # "Called after the test case test has been executed, regardless of
1901 # the outcome. The default implementation does nothing."
1902 def test_stopTest(self):
1903 class Foo(unittest.TestCase):
1904 def test_1(self):
1905 pass
1906
1907 test = Foo('test_1')
1908
1909 result = unittest.TestResult()
1910
1911 result.startTest(test)
1912
Benjamin Petersone1759f82009-06-30 23:35:19 +00001913 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001914 self.assertEqual(len(result.errors), 0)
1915 self.assertEqual(len(result.failures), 0)
1916 self.assertEqual(result.testsRun, 1)
1917 self.assertEqual(result.shouldStop, False)
1918
1919 result.stopTest(test)
1920
1921 # Same tests as above; make sure nothing has changed
Benjamin Petersone1759f82009-06-30 23:35:19 +00001922 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001923 self.assertEqual(len(result.errors), 0)
1924 self.assertEqual(len(result.failures), 0)
1925 self.assertEqual(result.testsRun, 1)
1926 self.assertEqual(result.shouldStop, False)
1927
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001928 # "Called before and after tests are run. The default implementation does nothing."
1929 def test_startTestRun_stopTestRun(self):
1930 result = unittest.TestResult()
1931 result.startTestRun()
1932 result.stopTestRun()
1933
Guido van Rossumd8faa362007-04-27 19:54:29 +00001934 # "addSuccess(test)"
1935 # ...
1936 # "Called when the test case test succeeds"
1937 # ...
1938 # "wasSuccessful() - Returns True if all tests run so far have passed,
1939 # otherwise returns False"
1940 # ...
1941 # "testsRun - The total number of tests run so far."
1942 # ...
1943 # "errors - A list containing 2-tuples of TestCase instances and
1944 # formatted tracebacks. Each tuple represents a test which raised an
1945 # unexpected exception. Contains formatted
1946 # tracebacks instead of sys.exc_info() results."
1947 # ...
1948 # "failures - A list containing 2-tuples of TestCase instances and
1949 # formatted tracebacks. Each tuple represents a test where a failure was
1950 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1951 # methods. Contains formatted tracebacks instead
1952 # of sys.exc_info() results."
1953 def test_addSuccess(self):
1954 class Foo(unittest.TestCase):
1955 def test_1(self):
1956 pass
1957
1958 test = Foo('test_1')
1959
1960 result = unittest.TestResult()
1961
1962 result.startTest(test)
1963 result.addSuccess(test)
1964 result.stopTest(test)
1965
Benjamin Petersone1759f82009-06-30 23:35:19 +00001966 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001967 self.assertEqual(len(result.errors), 0)
1968 self.assertEqual(len(result.failures), 0)
1969 self.assertEqual(result.testsRun, 1)
1970 self.assertEqual(result.shouldStop, False)
1971
1972 # "addFailure(test, err)"
1973 # ...
1974 # "Called when the test case test signals a failure. err is a tuple of
1975 # the form returned by sys.exc_info(): (type, value, traceback)"
1976 # ...
1977 # "wasSuccessful() - Returns True if all tests run so far have passed,
1978 # otherwise returns False"
1979 # ...
1980 # "testsRun - The total number of tests run so far."
1981 # ...
1982 # "errors - A list containing 2-tuples of TestCase instances and
1983 # formatted tracebacks. Each tuple represents a test which raised an
1984 # unexpected exception. Contains formatted
1985 # tracebacks instead of sys.exc_info() results."
1986 # ...
1987 # "failures - A list containing 2-tuples of TestCase instances and
1988 # formatted tracebacks. Each tuple represents a test where a failure was
1989 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1990 # methods. Contains formatted tracebacks instead
1991 # of sys.exc_info() results."
1992 def test_addFailure(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001993 class Foo(unittest.TestCase):
1994 def test_1(self):
1995 pass
1996
1997 test = Foo('test_1')
1998 try:
1999 test.fail("foo")
2000 except:
2001 exc_info_tuple = sys.exc_info()
2002
2003 result = unittest.TestResult()
2004
2005 result.startTest(test)
2006 result.addFailure(test, exc_info_tuple)
2007 result.stopTest(test)
2008
Benjamin Petersone1759f82009-06-30 23:35:19 +00002009 self.assertFalse(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00002010 self.assertEqual(len(result.errors), 0)
2011 self.assertEqual(len(result.failures), 1)
2012 self.assertEqual(result.testsRun, 1)
2013 self.assertEqual(result.shouldStop, False)
2014
2015 test_case, formatted_exc = result.failures[0]
Benjamin Petersone1759f82009-06-30 23:35:19 +00002016 self.assertTrue(test_case is test)
Ezio Melottie9615932010-01-24 19:26:24 +00002017 self.assertIsInstance(formatted_exc, str)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002018
2019 # "addError(test, err)"
2020 # ...
2021 # "Called when the test case test raises an unexpected exception err
2022 # is a tuple of the form returned by sys.exc_info():
2023 # (type, value, traceback)"
2024 # ...
2025 # "wasSuccessful() - Returns True if all tests run so far have passed,
2026 # otherwise returns False"
2027 # ...
2028 # "testsRun - The total number of tests run so far."
2029 # ...
2030 # "errors - A list containing 2-tuples of TestCase instances and
2031 # formatted tracebacks. Each tuple represents a test which raised an
2032 # unexpected exception. Contains formatted
2033 # tracebacks instead of sys.exc_info() results."
2034 # ...
2035 # "failures - A list containing 2-tuples of TestCase instances and
2036 # formatted tracebacks. Each tuple represents a test where a failure was
2037 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
2038 # methods. Contains formatted tracebacks instead
2039 # of sys.exc_info() results."
2040 def test_addError(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002041 class Foo(unittest.TestCase):
2042 def test_1(self):
2043 pass
2044
2045 test = Foo('test_1')
2046 try:
2047 raise TypeError()
2048 except:
2049 exc_info_tuple = sys.exc_info()
2050
2051 result = unittest.TestResult()
2052
2053 result.startTest(test)
2054 result.addError(test, exc_info_tuple)
2055 result.stopTest(test)
2056
Benjamin Petersone1759f82009-06-30 23:35:19 +00002057 self.assertFalse(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00002058 self.assertEqual(len(result.errors), 1)
2059 self.assertEqual(len(result.failures), 0)
2060 self.assertEqual(result.testsRun, 1)
2061 self.assertEqual(result.shouldStop, False)
2062
2063 test_case, formatted_exc = result.errors[0]
Benjamin Petersone1759f82009-06-30 23:35:19 +00002064 self.assertTrue(test_case is test)
Ezio Melottie9615932010-01-24 19:26:24 +00002065 self.assertIsInstance(formatted_exc, str)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002066
Michael Foord34c94622010-02-10 15:51:42 +00002067 def testGetDescriptionWithoutDocstring(self):
Michael Foord0b581e52010-02-10 15:53:19 +00002068 result = unittest.TextTestResult(None, True, 1)
Michael Foord34c94622010-02-10 15:51:42 +00002069 self.assertEqual(
2070 result.getDescription(self),
2071 'testGetDescriptionWithoutDocstring (' + __name__ +
2072 '.Test_TestResult)')
2073
R. David Murray378c0cf2010-02-24 01:46:21 +00002074 @unittest.skipIf(sys.flags.optimize >= 2,
2075 "Docstrings are omitted with -O2 and above")
Michael Foord34c94622010-02-10 15:51:42 +00002076 def testGetDescriptionWithOneLineDocstring(self):
2077 """Tests getDescription() for a method with a docstring."""
Michael Foord0b581e52010-02-10 15:53:19 +00002078 result = unittest.TextTestResult(None, True, 1)
Michael Foord34c94622010-02-10 15:51:42 +00002079 self.assertEqual(
2080 result.getDescription(self),
2081 ('testGetDescriptionWithOneLineDocstring '
2082 '(' + __name__ + '.Test_TestResult)\n'
2083 'Tests getDescription() for a method with a docstring.'))
2084
R. David Murray378c0cf2010-02-24 01:46:21 +00002085 @unittest.skipIf(sys.flags.optimize >= 2,
2086 "Docstrings are omitted with -O2 and above")
Michael Foord34c94622010-02-10 15:51:42 +00002087 def testGetDescriptionWithMultiLineDocstring(self):
2088 """Tests getDescription() for a method with a longer docstring.
2089 The second line of the docstring.
2090 """
Michael Foord0b581e52010-02-10 15:53:19 +00002091 result = unittest.TextTestResult(None, True, 1)
Michael Foord34c94622010-02-10 15:51:42 +00002092 self.assertEqual(
2093 result.getDescription(self),
2094 ('testGetDescriptionWithMultiLineDocstring '
2095 '(' + __name__ + '.Test_TestResult)\n'
2096 'Tests getDescription() for a method with a longer '
2097 'docstring.'))
2098
Benjamin Petersondccc1fc2010-03-22 00:15:53 +00002099 def testStackFrameTrimming(self):
2100 class Frame(object):
2101 class tb_frame(object):
2102 f_globals = {}
2103 result = unittest.TestResult()
2104 self.assertFalse(result._is_relevant_tb_level(Frame))
2105
2106 Frame.tb_frame.f_globals['__unittest'] = True
2107 self.assertTrue(result._is_relevant_tb_level(Frame))
2108
Benjamin Peterson8769fd82010-03-22 01:13:48 +00002109 def testFailFast(self):
2110 result = unittest.TestResult()
2111 result._exc_info_to_string = lambda *_: ''
2112 result.failfast = True
2113 result.addError(None, None)
2114 self.assertTrue(result.shouldStop)
2115
2116 result = unittest.TestResult()
2117 result._exc_info_to_string = lambda *_: ''
2118 result.failfast = True
2119 result.addFailure(None, None)
2120 self.assertTrue(result.shouldStop)
2121
2122 result = unittest.TestResult()
2123 result._exc_info_to_string = lambda *_: ''
2124 result.failfast = True
2125 result.addUnexpectedSuccess(None)
2126 self.assertTrue(result.shouldStop)
2127
2128 result = unittest.TestResult()
2129 result._exc_info_to_string = lambda *_: ''
2130 result.failfast = True
2131 result.addExpectedFailure(None, None)
2132 self.assertTrue(result.shouldStop)
2133
2134 def testFailFastSetByRunner(self):
2135 runner = unittest.TextTestRunner(stream=io.StringIO(), failfast=True)
2136 def test(result):
2137 self.assertTrue(result.failfast)
2138 result = runner.run(test)
2139
2140
Benjamin Peterson847a4112010-03-14 15:04:17 +00002141classDict = dict(unittest.TestResult.__dict__)
2142for m in ('addSkip', 'addExpectedFailure', 'addUnexpectedSuccess',
2143 '__init__'):
2144 del classDict[m]
2145
2146def __init__(self, stream=None, descriptions=None, verbosity=None):
2147 self.failures = []
2148 self.errors = []
2149 self.testsRun = 0
2150 self.shouldStop = False
2151classDict['__init__'] = __init__
2152OldResult = type('OldResult', (object,), classDict)
2153
2154class Test_OldTestResult(unittest.TestCase):
2155
2156 def assertOldResultWarning(self, test, failures):
2157 with warnings.catch_warnings(record=True) as log:
2158 result = OldResult()
2159 test.run(result)
2160 self.assertEqual(len(result.failures), failures)
2161 warning, = log
2162 self.assertIs(warning.category, RuntimeWarning)
2163
2164 def testOldTestResult(self):
2165 class Test(unittest.TestCase):
2166 def testSkip(self):
2167 self.skipTest('foobar')
2168 @unittest.expectedFailure
2169 def testExpectedFail(self):
2170 raise TypeError
2171 @unittest.expectedFailure
2172 def testUnexpectedSuccess(self):
2173 pass
2174
2175 for test_name, should_pass in (('testSkip', True),
2176 ('testExpectedFail', True),
2177 ('testUnexpectedSuccess', False)):
2178 test = Test(test_name)
2179 self.assertOldResultWarning(test, int(not should_pass))
2180
2181 def testOldTestTesultSetup(self):
2182 class Test(unittest.TestCase):
2183 def setUp(self):
2184 self.skipTest('no reason')
2185 def testFoo(self):
2186 pass
2187 self.assertOldResultWarning(Test('testFoo'), 0)
2188
2189 def testOldTestResultClass(self):
2190 @unittest.skip('no reason')
2191 class Test(unittest.TestCase):
2192 def testFoo(self):
2193 pass
2194 self.assertOldResultWarning(Test('testFoo'), 0)
2195
2196 def testOldResultWithRunner(self):
2197 class Test(unittest.TestCase):
2198 def testFoo(self):
2199 pass
2200 runner = unittest.TextTestRunner(resultclass=OldResult,
2201 stream=io.StringIO())
2202 # This will raise an exception if TextTestRunner can't handle old
2203 # test result objects
2204 runner.run(Test('testFoo'))
Michael Foord34c94622010-02-10 15:51:42 +00002205
Guido van Rossumd8faa362007-04-27 19:54:29 +00002206### Support code for Test_TestCase
2207################################################################
2208
2209class Foo(unittest.TestCase):
2210 def runTest(self): pass
2211 def test1(self): pass
2212
2213class Bar(Foo):
2214 def test2(self): pass
2215
Benjamin Peterson8769fd82010-03-22 01:13:48 +00002216def getLoggingTestCase():
2217 class LoggingTestCase(unittest.TestCase):
2218 """A test case which logs its calls."""
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002219
Benjamin Peterson8769fd82010-03-22 01:13:48 +00002220 def __init__(self, events):
2221 super(LoggingTestCase, self).__init__('test')
2222 self.events = events
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002223
Benjamin Peterson8769fd82010-03-22 01:13:48 +00002224 def setUp(self):
2225 self.events.append('setUp')
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002226
Benjamin Peterson8769fd82010-03-22 01:13:48 +00002227 def test(self):
2228 self.events.append('test')
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002229
Benjamin Peterson8769fd82010-03-22 01:13:48 +00002230 def tearDown(self):
2231 self.events.append('tearDown')
2232 return LoggingTestCase
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002233
2234class ResultWithNoStartTestRunStopTestRun(object):
2235 """An object honouring TestResult before startTestRun/stopTestRun."""
2236
2237 def __init__(self):
2238 self.failures = []
2239 self.errors = []
2240 self.testsRun = 0
2241 self.skipped = []
2242 self.expectedFailures = []
2243 self.unexpectedSuccesses = []
2244 self.shouldStop = False
2245
2246 def startTest(self, test):
2247 pass
2248
2249 def stopTest(self, test):
2250 pass
2251
2252 def addError(self, test):
2253 pass
2254
2255 def addFailure(self, test):
2256 pass
2257
2258 def addSuccess(self, test):
2259 pass
2260
2261 def wasSuccessful(self):
2262 return True
2263
2264
Guido van Rossumd8faa362007-04-27 19:54:29 +00002265################################################################
2266### /Support code for Test_TestCase
2267
2268class Test_TestCase(TestCase, TestEquality, TestHashing):
2269
2270 ### Set up attributes used by inherited tests
2271 ################################################################
2272
2273 # Used by TestHashing.test_hash and TestEquality.test_eq
2274 eq_pairs = [(Foo('test1'), Foo('test1'))]
2275
2276 # Used by TestEquality.test_ne
2277 ne_pairs = [(Foo('test1'), Foo('runTest'))
2278 ,(Foo('test1'), Bar('test1'))
2279 ,(Foo('test1'), Bar('test2'))]
2280
2281 ################################################################
2282 ### /Set up attributes used by inherited tests
2283
2284
2285 # "class TestCase([methodName])"
2286 # ...
2287 # "Each instance of TestCase will run a single test method: the
2288 # method named methodName."
2289 # ...
2290 # "methodName defaults to "runTest"."
2291 #
2292 # Make sure it really is optional, and that it defaults to the proper
2293 # thing.
2294 def test_init__no_test_name(self):
2295 class Test(unittest.TestCase):
2296 def runTest(self): raise MyException()
2297 def test(self): pass
2298
2299 self.assertEqual(Test().id()[-13:], '.Test.runTest')
2300
2301 # "class TestCase([methodName])"
2302 # ...
2303 # "Each instance of TestCase will run a single test method: the
2304 # method named methodName."
2305 def test_init__test_name__valid(self):
2306 class Test(unittest.TestCase):
2307 def runTest(self): raise MyException()
2308 def test(self): pass
2309
2310 self.assertEqual(Test('test').id()[-10:], '.Test.test')
2311
2312 # "class TestCase([methodName])"
2313 # ...
2314 # "Each instance of TestCase will run a single test method: the
2315 # method named methodName."
2316 def test_init__test_name__invalid(self):
2317 class Test(unittest.TestCase):
2318 def runTest(self): raise MyException()
2319 def test(self): pass
2320
2321 try:
2322 Test('testfoo')
2323 except ValueError:
2324 pass
2325 else:
2326 self.fail("Failed to raise ValueError")
2327
2328 # "Return the number of tests represented by the this test object. For
2329 # TestCase instances, this will always be 1"
2330 def test_countTestCases(self):
2331 class Foo(unittest.TestCase):
2332 def test(self): pass
2333
2334 self.assertEqual(Foo('test').countTestCases(), 1)
2335
2336 # "Return the default type of test result object to be used to run this
2337 # test. For TestCase instances, this will always be
2338 # unittest.TestResult; subclasses of TestCase should
2339 # override this as necessary."
2340 def test_defaultTestResult(self):
2341 class Foo(unittest.TestCase):
2342 def runTest(self):
2343 pass
2344
2345 result = Foo().defaultTestResult()
2346 self.assertEqual(type(result), unittest.TestResult)
2347
2348 # "When a setUp() method is defined, the test runner will run that method
2349 # prior to each test. Likewise, if a tearDown() method is defined, the
2350 # test runner will invoke that method after each test. In the example,
2351 # setUp() was used to create a fresh sequence for each test."
2352 #
2353 # Make sure the proper call order is maintained, even if setUp() raises
2354 # an exception.
2355 def test_run_call_order__error_in_setUp(self):
2356 events = []
2357 result = LoggingResult(events)
2358
Benjamin Peterson8769fd82010-03-22 01:13:48 +00002359 class Foo(getLoggingTestCase()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002360 def setUp(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002361 super(Foo, self).setUp()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002362 raise RuntimeError('raised by Foo.setUp')
2363
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002364 Foo(events).run(result)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002365 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2366 self.assertEqual(events, expected)
2367
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002368 # "With a temporary result stopTestRun is called when setUp errors.
2369 def test_run_call_order__error_in_setUp_default_result(self):
2370 events = []
2371
Benjamin Peterson8769fd82010-03-22 01:13:48 +00002372 class Foo(getLoggingTestCase()):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002373 def defaultTestResult(self):
2374 return LoggingResult(self.events)
2375
2376 def setUp(self):
2377 super(Foo, self).setUp()
2378 raise RuntimeError('raised by Foo.setUp')
2379
2380 Foo(events).run()
2381 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2382 'stopTest', 'stopTestRun']
2383 self.assertEqual(events, expected)
2384
Guido van Rossumd8faa362007-04-27 19:54:29 +00002385 # "When a setUp() method is defined, the test runner will run that method
2386 # prior to each test. Likewise, if a tearDown() method is defined, the
2387 # test runner will invoke that method after each test. In the example,
2388 # setUp() was used to create a fresh sequence for each test."
2389 #
2390 # Make sure the proper call order is maintained, even if the test raises
2391 # an error (as opposed to a failure).
2392 def test_run_call_order__error_in_test(self):
2393 events = []
2394 result = LoggingResult(events)
2395
Benjamin Peterson8769fd82010-03-22 01:13:48 +00002396 class Foo(getLoggingTestCase()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002397 def test(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002398 super(Foo, self).test()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002399 raise RuntimeError('raised by Foo.test')
2400
Guido van Rossumd8faa362007-04-27 19:54:29 +00002401 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2402 'stopTest']
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002403 Foo(events).run(result)
2404 self.assertEqual(events, expected)
2405
2406 # "With a default result, an error in the test still results in stopTestRun
2407 # being called."
2408 def test_run_call_order__error_in_test_default_result(self):
2409 events = []
2410
Benjamin Peterson8769fd82010-03-22 01:13:48 +00002411 class Foo(getLoggingTestCase()):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002412 def defaultTestResult(self):
2413 return LoggingResult(self.events)
2414
2415 def test(self):
2416 super(Foo, self).test()
2417 raise RuntimeError('raised by Foo.test')
2418
2419 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2420 'tearDown', 'stopTest', 'stopTestRun']
2421 Foo(events).run()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002422 self.assertEqual(events, expected)
2423
2424 # "When a setUp() method is defined, the test runner will run that method
2425 # prior to each test. Likewise, if a tearDown() method is defined, the
2426 # test runner will invoke that method after each test. In the example,
2427 # setUp() was used to create a fresh sequence for each test."
2428 #
2429 # Make sure the proper call order is maintained, even if the test signals
2430 # a failure (as opposed to an error).
2431 def test_run_call_order__failure_in_test(self):
2432 events = []
2433 result = LoggingResult(events)
2434
Benjamin Peterson8769fd82010-03-22 01:13:48 +00002435 class Foo(getLoggingTestCase()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002436 def test(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002437 super(Foo, self).test()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002438 self.fail('raised by Foo.test')
2439
Guido van Rossumd8faa362007-04-27 19:54:29 +00002440 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2441 'stopTest']
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002442 Foo(events).run(result)
2443 self.assertEqual(events, expected)
2444
2445 # "When a test fails with a default result stopTestRun is still called."
2446 def test_run_call_order__failure_in_test_default_result(self):
2447
Benjamin Peterson8769fd82010-03-22 01:13:48 +00002448 class Foo(getLoggingTestCase()):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002449 def defaultTestResult(self):
2450 return LoggingResult(self.events)
2451 def test(self):
2452 super(Foo, self).test()
2453 self.fail('raised by Foo.test')
2454
2455 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2456 'tearDown', 'stopTest', 'stopTestRun']
2457 events = []
2458 Foo(events).run()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002459 self.assertEqual(events, expected)
2460
2461 # "When a setUp() method is defined, the test runner will run that method
2462 # prior to each test. Likewise, if a tearDown() method is defined, the
2463 # test runner will invoke that method after each test. In the example,
2464 # setUp() was used to create a fresh sequence for each test."
2465 #
2466 # Make sure the proper call order is maintained, even if tearDown() raises
2467 # an exception.
2468 def test_run_call_order__error_in_tearDown(self):
2469 events = []
2470 result = LoggingResult(events)
2471
Benjamin Peterson8769fd82010-03-22 01:13:48 +00002472 class Foo(getLoggingTestCase()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002473 def tearDown(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002474 super(Foo, self).tearDown()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002475 raise RuntimeError('raised by Foo.tearDown')
2476
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002477 Foo(events).run(result)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002478 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2479 'stopTest']
2480 self.assertEqual(events, expected)
2481
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002482 # "When tearDown errors with a default result stopTestRun is still called."
2483 def test_run_call_order__error_in_tearDown_default_result(self):
2484
Benjamin Peterson8769fd82010-03-22 01:13:48 +00002485 class Foo(getLoggingTestCase()):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002486 def defaultTestResult(self):
2487 return LoggingResult(self.events)
2488 def tearDown(self):
2489 super(Foo, self).tearDown()
2490 raise RuntimeError('raised by Foo.tearDown')
2491
2492 events = []
2493 Foo(events).run()
2494 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2495 'addError', 'stopTest', 'stopTestRun']
2496 self.assertEqual(events, expected)
2497
2498 # "TestCase.run() still works when the defaultTestResult is a TestResult
2499 # that does not support startTestRun and stopTestRun.
2500 def test_run_call_order_default_result(self):
2501
2502 class Foo(unittest.TestCase):
2503 def defaultTestResult(self):
2504 return ResultWithNoStartTestRunStopTestRun()
2505 def test(self):
2506 pass
2507
2508 Foo('test').run()
2509
Guido van Rossumd8faa362007-04-27 19:54:29 +00002510 # "This class attribute gives the exception raised by the test() method.
2511 # If a test framework needs to use a specialized exception, possibly to
2512 # carry additional information, it must subclass this exception in
2513 # order to ``play fair'' with the framework. The initial value of this
2514 # attribute is AssertionError"
2515 def test_failureException__default(self):
2516 class Foo(unittest.TestCase):
2517 def test(self):
2518 pass
2519
Benjamin Petersone1759f82009-06-30 23:35:19 +00002520 self.assertTrue(Foo('test').failureException is AssertionError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002521
2522 # "This class attribute gives the exception raised by the test() method.
2523 # If a test framework needs to use a specialized exception, possibly to
2524 # carry additional information, it must subclass this exception in
2525 # order to ``play fair'' with the framework."
2526 #
2527 # Make sure TestCase.run() respects the designated failureException
2528 def test_failureException__subclassing__explicit_raise(self):
2529 events = []
2530 result = LoggingResult(events)
2531
2532 class Foo(unittest.TestCase):
2533 def test(self):
2534 raise RuntimeError()
2535
2536 failureException = RuntimeError
2537
Benjamin Petersone1759f82009-06-30 23:35:19 +00002538 self.assertTrue(Foo('test').failureException is RuntimeError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002539
2540
2541 Foo('test').run(result)
2542 expected = ['startTest', 'addFailure', 'stopTest']
2543 self.assertEqual(events, expected)
2544
2545 # "This class attribute gives the exception raised by the test() method.
2546 # If a test framework needs to use a specialized exception, possibly to
2547 # carry additional information, it must subclass this exception in
2548 # order to ``play fair'' with the framework."
2549 #
2550 # Make sure TestCase.run() respects the designated failureException
2551 def test_failureException__subclassing__implicit_raise(self):
2552 events = []
2553 result = LoggingResult(events)
2554
2555 class Foo(unittest.TestCase):
2556 def test(self):
2557 self.fail("foo")
2558
2559 failureException = RuntimeError
2560
Benjamin Petersone1759f82009-06-30 23:35:19 +00002561 self.assertTrue(Foo('test').failureException is RuntimeError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002562
2563
2564 Foo('test').run(result)
2565 expected = ['startTest', 'addFailure', 'stopTest']
2566 self.assertEqual(events, expected)
2567
2568 # "The default implementation does nothing."
2569 def test_setUp(self):
2570 class Foo(unittest.TestCase):
2571 def runTest(self):
2572 pass
2573
2574 # ... and nothing should happen
2575 Foo().setUp()
2576
2577 # "The default implementation does nothing."
2578 def test_tearDown(self):
2579 class Foo(unittest.TestCase):
2580 def runTest(self):
2581 pass
2582
2583 # ... and nothing should happen
2584 Foo().tearDown()
2585
2586 # "Return a string identifying the specific test case."
2587 #
2588 # Because of the vague nature of the docs, I'm not going to lock this
2589 # test down too much. Really all that can be asserted is that the id()
2590 # will be a string (either 8-byte or unicode -- again, because the docs
2591 # just say "string")
2592 def test_id(self):
2593 class Foo(unittest.TestCase):
2594 def runTest(self):
2595 pass
2596
Ezio Melottie9615932010-01-24 19:26:24 +00002597 self.assertIsInstance(Foo().id(), str)
2598
Guido van Rossumd8faa362007-04-27 19:54:29 +00002599
Guido van Rossumd8faa362007-04-27 19:54:29 +00002600 # "If result is omitted or None, a temporary result object is created
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002601 # and used, but is not made available to the caller. As TestCase owns the
2602 # temporary result startTestRun and stopTestRun are called.
2603
Guido van Rossumd8faa362007-04-27 19:54:29 +00002604 def test_run__uses_defaultTestResult(self):
2605 events = []
2606
2607 class Foo(unittest.TestCase):
2608 def test(self):
2609 events.append('test')
2610
2611 def defaultTestResult(self):
2612 return LoggingResult(events)
2613
2614 # Make run() find a result object on its own
2615 Foo('test').run()
2616
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002617 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2618 'stopTest', 'stopTestRun']
Guido van Rossumd8faa362007-04-27 19:54:29 +00002619 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002620
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002621 def testShortDescriptionWithoutDocstring(self):
Michael Foord34c94622010-02-10 15:51:42 +00002622 self.assertIsNone(self.shortDescription())
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002623
R. David Murray378c0cf2010-02-24 01:46:21 +00002624 @unittest.skipIf(sys.flags.optimize >= 2,
2625 "Docstrings are omitted with -O2 and above")
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002626 def testShortDescriptionWithOneLineDocstring(self):
2627 """Tests shortDescription() for a method with a docstring."""
2628 self.assertEqual(
2629 self.shortDescription(),
Michael Foord34c94622010-02-10 15:51:42 +00002630 'Tests shortDescription() for a method with a docstring.')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002631
R. David Murray378c0cf2010-02-24 01:46:21 +00002632 @unittest.skipIf(sys.flags.optimize >= 2,
2633 "Docstrings are omitted with -O2 and above")
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002634 def testShortDescriptionWithMultiLineDocstring(self):
2635 """Tests shortDescription() for a method with a longer docstring.
2636
2637 This method ensures that only the first line of a docstring is
2638 returned used in the short description, no matter how long the
2639 whole thing is.
2640 """
2641 self.assertEqual(
2642 self.shortDescription(),
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002643 'Tests shortDescription() for a method with a longer '
Michael Foord34c94622010-02-10 15:51:42 +00002644 'docstring.')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002645
2646 def testAddTypeEqualityFunc(self):
2647 class SadSnake(object):
2648 """Dummy class for test_addTypeEqualityFunc."""
2649 s1, s2 = SadSnake(), SadSnake()
2650 self.assertFalse(s1 == s2)
2651 def AllSnakesCreatedEqual(a, b, msg=None):
2652 return type(a) == type(b) == SadSnake
2653 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2654 self.assertEqual(s1, s2)
2655 # No this doesn't clean up and remove the SadSnake equality func
2656 # from this TestCase instance but since its a local nothing else
2657 # will ever notice that.
2658
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00002659 def testAssertIs(self):
2660 thing = object()
2661 self.assertIs(thing, thing)
2662 self.assertRaises(self.failureException, self.assertIs, thing, object())
2663
2664 def testAssertIsNot(self):
2665 thing = object()
2666 self.assertIsNot(thing, object())
2667 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2668
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00002669 def testAssertIsInstance(self):
2670 thing = []
2671 self.assertIsInstance(thing, list)
2672 self.assertRaises(self.failureException, self.assertIsInstance,
2673 thing, dict)
2674
2675 def testAssertNotIsInstance(self):
2676 thing = []
2677 self.assertNotIsInstance(thing, dict)
2678 self.assertRaises(self.failureException, self.assertNotIsInstance,
2679 thing, list)
2680
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002681 def testAssertIn(self):
2682 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2683
2684 self.assertIn('a', 'abc')
2685 self.assertIn(2, [1, 2, 3])
2686 self.assertIn('monkey', animals)
2687
2688 self.assertNotIn('d', 'abc')
2689 self.assertNotIn(0, [1, 2, 3])
2690 self.assertNotIn('otter', animals)
2691
2692 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2693 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2694 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2695 animals)
2696
2697 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2698 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2699 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2700 animals)
2701
2702 def testAssertDictContainsSubset(self):
2703 self.assertDictContainsSubset({}, {})
2704 self.assertDictContainsSubset({}, {'a': 1})
2705 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2706 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2707 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2708
Benjamin Peterson847a4112010-03-14 15:04:17 +00002709 with self.assertRaises(self.failureException):
2710 self.assertDictContainsSubset({1: "one"}, {})
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002711
Benjamin Peterson847a4112010-03-14 15:04:17 +00002712 with self.assertRaises(self.failureException):
2713 self.assertDictContainsSubset({'a': 2}, {'a': 1})
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002714
Benjamin Peterson847a4112010-03-14 15:04:17 +00002715 with self.assertRaises(self.failureException):
2716 self.assertDictContainsSubset({'c': 1}, {'a': 1})
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002717
Benjamin Peterson847a4112010-03-14 15:04:17 +00002718 with self.assertRaises(self.failureException):
2719 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2720
2721 with self.assertRaises(self.failureException):
2722 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2723
2724 with warnings.catch_warnings(record=True):
2725 # silence the UnicodeWarning
2726 one = ''.join(chr(i) for i in range(255))
2727 # this used to cause a UnicodeDecodeError constructing the failure msg
2728 with self.assertRaises(self.failureException):
2729 self.assertDictContainsSubset({'foo': one}, {'foo': '\uFFFD'})
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002730
2731 def testAssertEqual(self):
2732 equal_pairs = [
2733 ((), ()),
2734 ({}, {}),
2735 ([], []),
2736 (set(), set()),
2737 (frozenset(), frozenset())]
2738 for a, b in equal_pairs:
2739 # This mess of try excepts is to test the assertEqual behavior
2740 # itself.
2741 try:
2742 self.assertEqual(a, b)
2743 except self.failureException:
2744 self.fail('assertEqual(%r, %r) failed' % (a, b))
2745 try:
2746 self.assertEqual(a, b, msg='foo')
2747 except self.failureException:
2748 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2749 try:
2750 self.assertEqual(a, b, 'foo')
2751 except self.failureException:
2752 self.fail('assertEqual(%r, %r) with third parameter failed' %
2753 (a, b))
2754
2755 unequal_pairs = [
2756 ((), []),
2757 ({}, set()),
2758 (set([4,1]), frozenset([4,2])),
2759 (frozenset([4,5]), set([2,3])),
2760 (set([3,4]), set([5,4]))]
2761 for a, b in unequal_pairs:
2762 self.assertRaises(self.failureException, self.assertEqual, a, b)
2763 self.assertRaises(self.failureException, self.assertEqual, a, b,
2764 'foo')
2765 self.assertRaises(self.failureException, self.assertEqual, a, b,
2766 msg='foo')
2767
2768 def testEquality(self):
2769 self.assertListEqual([], [])
2770 self.assertTupleEqual((), ())
2771 self.assertSequenceEqual([], ())
2772
2773 a = [0, 'a', []]
2774 b = []
2775 self.assertRaises(unittest.TestCase.failureException,
2776 self.assertListEqual, a, b)
2777 self.assertRaises(unittest.TestCase.failureException,
2778 self.assertListEqual, tuple(a), tuple(b))
2779 self.assertRaises(unittest.TestCase.failureException,
2780 self.assertSequenceEqual, a, tuple(b))
2781
2782 b.extend(a)
2783 self.assertListEqual(a, b)
2784 self.assertTupleEqual(tuple(a), tuple(b))
2785 self.assertSequenceEqual(a, tuple(b))
2786 self.assertSequenceEqual(tuple(a), b)
2787
2788 self.assertRaises(self.failureException, self.assertListEqual,
2789 a, tuple(b))
2790 self.assertRaises(self.failureException, self.assertTupleEqual,
2791 tuple(a), b)
2792 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2793 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2794 tuple(b))
2795 self.assertRaises(self.failureException, self.assertSequenceEqual,
2796 None, tuple(b))
2797 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2798 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2799 self.assertRaises(self.failureException, self.assertSequenceEqual,
2800 1, 1)
2801
2802 self.assertDictEqual({}, {})
2803
2804 c = { 'x': 1 }
2805 d = {}
2806 self.assertRaises(unittest.TestCase.failureException,
2807 self.assertDictEqual, c, d)
2808
2809 d.update(c)
2810 self.assertDictEqual(c, d)
2811
2812 d['x'] = 0
2813 self.assertRaises(unittest.TestCase.failureException,
2814 self.assertDictEqual, c, d, 'These are unequal')
2815
2816 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2817 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2818 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2819
Michael Foord8442a602010-03-20 16:58:04 +00002820 def testAssertItemsEqual(self):
2821 a = object()
2822 self.assertItemsEqual([1, 2, 3], [3, 2, 1])
2823 self.assertItemsEqual(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2824 self.assertItemsEqual([a, a, 2, 2, 3], (a, 2, 3, a, 2))
2825 self.assertItemsEqual([1, "2", "a", "a"], ["a", "2", True, "a"])
2826 self.assertRaises(self.failureException, self.assertItemsEqual,
2827 [1, 2] + [3] * 100, [1] * 100 + [2, 3])
2828 self.assertRaises(self.failureException, self.assertItemsEqual,
2829 [1, "2", "a", "a"], ["a", "2", True, 1])
2830 self.assertRaises(self.failureException, self.assertItemsEqual,
2831 [10], [10, 11])
2832 self.assertRaises(self.failureException, self.assertItemsEqual,
2833 [10, 11], [10])
2834 self.assertRaises(self.failureException, self.assertItemsEqual,
2835 [10, 11, 10], [10, 11])
2836
2837 # Test that sequences of unhashable objects can be tested for sameness:
2838 self.assertItemsEqual([[1, 2], [3, 4], 0], [False, [3, 4], [1, 2]])
2839
2840 # hashable types, but not orderable
2841 self.assertRaises(self.failureException, self.assertItemsEqual,
2842 [], [divmod, 'x', 1, 5j, 2j, frozenset()])
2843 # comparing dicts raises a py3k warning
2844 self.assertItemsEqual([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2845 # comparing heterogenous non-hashable sequences raises a py3k warning
2846 self.assertItemsEqual([1, 'x', divmod, []], [divmod, [], 'x', 1])
2847 self.assertRaises(self.failureException, self.assertItemsEqual,
2848 [], [divmod, [], 'x', 1, 5j, 2j, set()])
2849 self.assertRaises(self.failureException, self.assertItemsEqual,
2850 [[1]], [[2]])
2851
2852 # Same elements, but not same sequence length
2853 self.assertRaises(self.failureException, self.assertItemsEqual,
2854 [1, 1, 2], [2, 1])
2855 self.assertRaises(self.failureException, self.assertItemsEqual,
2856 [1, 1, "2", "a", "a"], ["2", "2", True, "a"])
2857 self.assertRaises(self.failureException, self.assertItemsEqual,
2858 [1, {'b': 2}, None, True], [{'b': 2}, True, None])
2859
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002860 def testAssertSetEqual(self):
2861 set1 = set()
2862 set2 = set()
2863 self.assertSetEqual(set1, set2)
2864
2865 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2866 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2867 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2868 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2869
2870 set1 = set(['a'])
2871 set2 = set()
2872 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2873
2874 set1 = set(['a'])
2875 set2 = set(['a'])
2876 self.assertSetEqual(set1, set2)
2877
2878 set1 = set(['a'])
2879 set2 = set(['a', 'b'])
2880 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2881
2882 set1 = set(['a'])
2883 set2 = frozenset(['a', 'b'])
2884 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2885
2886 set1 = set(['a', 'b'])
2887 set2 = frozenset(['a', 'b'])
2888 self.assertSetEqual(set1, set2)
2889
2890 set1 = set()
2891 set2 = "foo"
2892 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2893 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2894
2895 # make sure any string formatting is tuple-safe
2896 set1 = set([(0, 1), (2, 3)])
2897 set2 = set([(4, 5)])
2898 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2899
2900 def testInequality(self):
2901 # Try ints
2902 self.assertGreater(2, 1)
2903 self.assertGreaterEqual(2, 1)
2904 self.assertGreaterEqual(1, 1)
2905 self.assertLess(1, 2)
2906 self.assertLessEqual(1, 2)
2907 self.assertLessEqual(1, 1)
2908 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2909 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2910 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2911 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2912 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2913 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2914
2915 # Try Floats
2916 self.assertGreater(1.1, 1.0)
2917 self.assertGreaterEqual(1.1, 1.0)
2918 self.assertGreaterEqual(1.0, 1.0)
2919 self.assertLess(1.0, 1.1)
2920 self.assertLessEqual(1.0, 1.1)
2921 self.assertLessEqual(1.0, 1.0)
2922 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2923 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2924 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2925 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2926 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2927 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2928
2929 # Try Strings
2930 self.assertGreater('bug', 'ant')
2931 self.assertGreaterEqual('bug', 'ant')
2932 self.assertGreaterEqual('ant', 'ant')
2933 self.assertLess('ant', 'bug')
2934 self.assertLessEqual('ant', 'bug')
2935 self.assertLessEqual('ant', 'ant')
2936 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2937 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2938 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2939 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2940 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2941 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2942
2943 # Try bytes
2944 self.assertGreater(b'bug', b'ant')
2945 self.assertGreaterEqual(b'bug', b'ant')
2946 self.assertGreaterEqual(b'ant', b'ant')
2947 self.assertLess(b'ant', b'bug')
2948 self.assertLessEqual(b'ant', b'bug')
2949 self.assertLessEqual(b'ant', b'ant')
2950 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'bug')
2951 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'ant')
2952 self.assertRaises(self.failureException, self.assertGreaterEqual, b'ant',
2953 b'bug')
2954 self.assertRaises(self.failureException, self.assertLess, b'bug', b'ant')
2955 self.assertRaises(self.failureException, self.assertLess, b'ant', b'ant')
2956 self.assertRaises(self.failureException, self.assertLessEqual, b'bug', b'ant')
2957
2958 def testAssertMultiLineEqual(self):
2959 sample_text = """\
2960http://www.python.org/doc/2.3/lib/module-unittest.html
2961test case
2962 A test case is the smallest unit of testing. [...]
2963"""
2964 revised_sample_text = """\
2965http://www.python.org/doc/2.4.1/lib/module-unittest.html
2966test case
2967 A test case is the smallest unit of testing. [...] You may provide your
2968 own implementation that does not subclass from TestCase, of course.
2969"""
2970 sample_text_error = """
2971- http://www.python.org/doc/2.3/lib/module-unittest.html
2972? ^
2973+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2974? ^^^
2975 test case
2976- A test case is the smallest unit of testing. [...]
2977+ A test case is the smallest unit of testing. [...] You may provide your
2978? +++++++++++++++++++++
2979+ own implementation that does not subclass from TestCase, of course.
2980"""
2981
2982 try:
2983 self.assertMultiLineEqual(sample_text, revised_sample_text)
2984 except self.failureException as e:
Michael Foord02834952010-02-08 23:10:39 +00002985 # no fair testing ourself with ourself, and assertEqual is used for strings
2986 # so can't use assertEqual either. Just use assertTrue.
2987 self.assertTrue(sample_text_error == str(e))
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002988
2989 def testAssertIsNone(self):
2990 self.assertIsNone(None)
2991 self.assertRaises(self.failureException, self.assertIsNone, False)
2992 self.assertIsNotNone('DjZoPloGears on Rails')
2993 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2994
2995 def testAssertRegexpMatches(self):
2996 self.assertRegexpMatches('asdfabasdf', r'ab+')
2997 self.assertRaises(self.failureException, self.assertRegexpMatches,
2998 'saaas', r'aaaa')
2999
3000 def testAssertRaisesRegexp(self):
3001 class ExceptionMock(Exception):
3002 pass
3003
3004 def Stub():
3005 raise ExceptionMock('We expect')
3006
3007 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
3008 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
3009
3010 def testAssertNotRaisesRegexp(self):
3011 self.assertRaisesRegexp(
Benjamin Peterson4f75b642009-04-04 16:39:09 +00003012 self.failureException, '^Exception not raised by <lambda>$',
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003013 self.assertRaisesRegexp, Exception, re.compile('x'),
3014 lambda: None)
3015 self.assertRaisesRegexp(
Benjamin Peterson4f75b642009-04-04 16:39:09 +00003016 self.failureException, '^Exception not raised by <lambda>$',
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003017 self.assertRaisesRegexp, Exception, 'x',
3018 lambda: None)
3019
3020 def testAssertRaisesRegexpMismatch(self):
3021 def Stub():
3022 raise Exception('Unexpected')
3023
3024 self.assertRaisesRegexp(
3025 self.failureException,
3026 r'"\^Expected\$" does not match "Unexpected"',
3027 self.assertRaisesRegexp, Exception, '^Expected$',
3028 Stub)
3029 self.assertRaisesRegexp(
3030 self.failureException,
3031 r'"\^Expected\$" does not match "Unexpected"',
3032 self.assertRaisesRegexp, Exception,
3033 re.compile('^Expected$'), Stub)
3034
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +00003035 def testAssertRaisesExcValue(self):
3036 class ExceptionMock(Exception):
3037 pass
3038
3039 def Stub(foo):
3040 raise ExceptionMock(foo)
3041 v = "particular value"
3042
3043 ctx = self.assertRaises(ExceptionMock)
3044 with ctx:
3045 Stub(v)
Ezio Melotti49008232010-02-08 21:57:48 +00003046 e = ctx.exception
Ezio Melottie9615932010-01-24 19:26:24 +00003047 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +00003048 self.assertEqual(e.args[0], v)
3049
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003050 def testSynonymAssertMethodNames(self):
3051 """Test undocumented method name synonyms.
3052
3053 Please do not use these methods names in your own code.
3054
3055 This test confirms their continued existence and functionality
3056 in order to avoid breaking existing code.
3057 """
3058 self.assertNotEquals(3, 5)
3059 self.assertEquals(3, 3)
3060 self.assertAlmostEquals(2.0, 2.0)
3061 self.assertNotAlmostEquals(3.0, 5.0)
3062 self.assert_(True)
3063
3064 def testPendingDeprecationMethodNames(self):
3065 """Test fail* methods pending deprecation, they will warn in 3.2.
3066
3067 Do not use these methods. They will go away in 3.3.
3068 """
Benjamin Peterson6bcbad52009-06-30 23:45:41 +00003069 old = (
3070 (self.failIfEqual, (3, 5)),
3071 (self.failUnlessEqual, (3, 3)),
3072 (self.failUnlessAlmostEqual, (2.0, 2.0)),
3073 (self.failIfAlmostEqual, (3.0, 5.0)),
3074 (self.failUnless, (True,)),
3075 (self.failUnlessRaises, (TypeError, lambda _: 3.14 + 'spam')),
Michael Foord91c9da32010-03-20 17:21:27 +00003076 (self.failIf, (False,)),
3077 (self.assertSameElements, ([1, 1, 2, 3], [1, 2, 3]))
Benjamin Peterson6bcbad52009-06-30 23:45:41 +00003078 )
3079 for meth, args in old:
3080 with warnings.catch_warnings(record=True) as w:
3081 meth(*args)
3082 self.assertEqual(len(w), 1)
3083 self.assertIs(w[0].category, DeprecationWarning)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003084
3085 def testDeepcopy(self):
3086 # Issue: 5660
3087 class TestableTest(TestCase):
3088 def testNothing(self):
3089 pass
3090
3091 test = TestableTest('testNothing')
3092
3093 # This shouldn't blow up
3094 deepcopy(test)
3095
Benjamin Peterson5254c042009-03-23 22:25:03 +00003096
3097class Test_TestSkipping(TestCase):
3098
3099 def test_skipping(self):
3100 class Foo(unittest.TestCase):
3101 def test_skip_me(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00003102 self.skipTest("skip")
Benjamin Peterson5254c042009-03-23 22:25:03 +00003103 events = []
3104 result = LoggingResult(events)
3105 test = Foo("test_skip_me")
3106 test.run(result)
3107 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3108 self.assertEqual(result.skipped, [(test, "skip")])
3109
3110 # Try letting setUp skip the test now.
3111 class Foo(unittest.TestCase):
3112 def setUp(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00003113 self.skipTest("testing")
Benjamin Peterson5254c042009-03-23 22:25:03 +00003114 def test_nothing(self): pass
3115 events = []
3116 result = LoggingResult(events)
3117 test = Foo("test_nothing")
3118 test.run(result)
3119 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3120 self.assertEqual(result.skipped, [(test, "testing")])
3121 self.assertEqual(result.testsRun, 1)
3122
3123 def test_skipping_decorators(self):
3124 op_table = ((unittest.skipUnless, False, True),
3125 (unittest.skipIf, True, False))
3126 for deco, do_skip, dont_skip in op_table:
3127 class Foo(unittest.TestCase):
3128 @deco(do_skip, "testing")
3129 def test_skip(self): pass
3130
3131 @deco(dont_skip, "testing")
3132 def test_dont_skip(self): pass
3133 test_do_skip = Foo("test_skip")
3134 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00003135 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003136 events = []
3137 result = LoggingResult(events)
3138 suite.run(result)
3139 self.assertEqual(len(result.skipped), 1)
3140 expected = ['startTest', 'addSkip', 'stopTest',
3141 'startTest', 'addSuccess', 'stopTest']
3142 self.assertEqual(events, expected)
3143 self.assertEqual(result.testsRun, 2)
3144 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
3145 self.assertTrue(result.wasSuccessful())
3146
3147 def test_skip_class(self):
3148 @unittest.skip("testing")
3149 class Foo(unittest.TestCase):
3150 def test_1(self):
3151 record.append(1)
3152 record = []
3153 result = unittest.TestResult()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00003154 test = Foo("test_1")
3155 suite = unittest.TestSuite([test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003156 suite.run(result)
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00003157 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003158 self.assertEqual(record, [])
3159
3160 def test_expected_failure(self):
3161 class Foo(unittest.TestCase):
3162 @unittest.expectedFailure
3163 def test_die(self):
3164 self.fail("help me!")
3165 events = []
3166 result = LoggingResult(events)
3167 test = Foo("test_die")
3168 test.run(result)
3169 self.assertEqual(events,
3170 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Peterson52baa292009-03-24 00:56:30 +00003171 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson5254c042009-03-23 22:25:03 +00003172 self.assertTrue(result.wasSuccessful())
3173
3174 def test_unexpected_success(self):
3175 class Foo(unittest.TestCase):
3176 @unittest.expectedFailure
3177 def test_die(self):
3178 pass
3179 events = []
3180 result = LoggingResult(events)
3181 test = Foo("test_die")
3182 test.run(result)
3183 self.assertEqual(events,
3184 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3185 self.assertFalse(result.failures)
Benjamin Peterson52baa292009-03-24 00:56:30 +00003186 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003187 self.assertTrue(result.wasSuccessful())
3188
Benjamin Peterson847a4112010-03-14 15:04:17 +00003189 def test_skip_doesnt_run_setup(self):
3190 class Foo(unittest.TestCase):
3191 wasSetUp = False
3192 wasTornDown = False
3193 def setUp(self):
3194 Foo.wasSetUp = True
3195 def tornDown(self):
3196 Foo.wasTornDown = True
3197 @unittest.skip('testing')
3198 def test_1(self):
3199 pass
3200
3201 result = unittest.TestResult()
3202 test = Foo("test_1")
3203 suite = unittest.TestSuite([test])
3204 suite.run(result)
3205 self.assertEqual(result.skipped, [(test, "testing")])
3206 self.assertFalse(Foo.wasSetUp)
3207 self.assertFalse(Foo.wasTornDown)
3208
3209 def test_decorated_skip(self):
3210 def decorator(func):
3211 def inner(*a):
3212 return func(*a)
3213 return inner
3214
3215 class Foo(unittest.TestCase):
3216 @decorator
3217 @unittest.skip('testing')
3218 def test_1(self):
3219 pass
3220
3221 result = unittest.TestResult()
3222 test = Foo("test_1")
3223 suite = unittest.TestSuite([test])
3224 suite.run(result)
3225 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003226
3227
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003228class Test_Assertions(TestCase):
3229 def test_AlmostEqual(self):
Benjamin Petersone1759f82009-06-30 23:35:19 +00003230 self.assertAlmostEqual(1.00000001, 1.0)
3231 self.assertNotAlmostEqual(1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003232 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003233 self.assertAlmostEqual, 1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003234 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003235 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003236
Benjamin Petersone1759f82009-06-30 23:35:19 +00003237 self.assertAlmostEqual(1.1, 1.0, places=0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003238 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003239 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003240
Benjamin Petersone1759f82009-06-30 23:35:19 +00003241 self.assertAlmostEqual(0, .1+.1j, places=0)
3242 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003243 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003244 self.assertAlmostEqual, 0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003245 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003246 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003247
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003248 self.assertAlmostEqual(float('inf'), float('inf'))
3249 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3250 float('inf'), float('inf'))
3251
3252
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003253 def test_assertRaises(self):
3254 def _raise(e):
3255 raise e
3256 self.assertRaises(KeyError, _raise, KeyError)
3257 self.assertRaises(KeyError, _raise, KeyError("key"))
3258 try:
3259 self.assertRaises(KeyError, lambda: None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003260 except self.failureException as e:
Ezio Melottib58e0bd2010-01-23 15:40:09 +00003261 self.assertIn("KeyError not raised", str(e))
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003262 else:
3263 self.fail("assertRaises() didn't fail")
3264 try:
3265 self.assertRaises(KeyError, _raise, ValueError)
3266 except ValueError:
3267 pass
3268 else:
3269 self.fail("assertRaises() didn't let exception pass through")
Ezio Melotti49008232010-02-08 21:57:48 +00003270 with self.assertRaises(KeyError) as cm:
3271 try:
3272 raise KeyError
3273 except Exception as e:
3274 exc = e
3275 raise
3276 self.assertIs(cm.exception, exc)
3277
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003278 with self.assertRaises(KeyError):
3279 raise KeyError("key")
3280 try:
3281 with self.assertRaises(KeyError):
3282 pass
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003283 except self.failureException as e:
Ezio Melottib58e0bd2010-01-23 15:40:09 +00003284 self.assertIn("KeyError not raised", str(e))
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003285 else:
3286 self.fail("assertRaises() didn't fail")
3287 try:
3288 with self.assertRaises(KeyError):
3289 raise ValueError
3290 except ValueError:
3291 pass
3292 else:
3293 self.fail("assertRaises() didn't let exception pass through")
3294
3295
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003296class TestLongMessage(TestCase):
3297 """Test that the individual asserts honour longMessage.
3298 This actually tests all the message behaviour for
3299 asserts that use longMessage."""
3300
3301 def setUp(self):
3302 class TestableTestFalse(TestCase):
3303 longMessage = False
3304 failureException = self.failureException
3305
3306 def testTest(self):
3307 pass
3308
3309 class TestableTestTrue(TestCase):
3310 longMessage = True
3311 failureException = self.failureException
3312
3313 def testTest(self):
3314 pass
3315
3316 self.testableTrue = TestableTestTrue('testTest')
3317 self.testableFalse = TestableTestFalse('testTest')
3318
3319 def testDefault(self):
3320 self.assertFalse(TestCase.longMessage)
3321
3322 def test_formatMsg(self):
3323 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3324 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3325
3326 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3327 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3328
Benjamin Peterson847a4112010-03-14 15:04:17 +00003329 # This blows up if _formatMessage uses string concatenation
3330 self.testableTrue._formatMessage(object(), 'foo')
3331
3332 def test_formatMessage_unicode_error(self):
3333 with warnings.catch_warnings(record=True):
3334 # This causes a UnicodeWarning due to its craziness
3335 one = ''.join(chr(i) for i in range(255))
3336 # this used to cause a UnicodeDecodeError constructing msg
3337 self.testableTrue._formatMessage(one, '\uFFFD')
3338
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003339 def assertMessages(self, methodName, args, errors):
3340 def getMethod(i):
3341 useTestableFalse = i < 2
3342 if useTestableFalse:
3343 test = self.testableFalse
3344 else:
3345 test = self.testableTrue
3346 return getattr(test, methodName)
3347
3348 for i, expected_regexp in enumerate(errors):
3349 testMethod = getMethod(i)
3350 kwargs = {}
3351 withMsg = i % 2
3352 if withMsg:
3353 kwargs = {"msg": "oops"}
3354
3355 with self.assertRaisesRegexp(self.failureException,
3356 expected_regexp=expected_regexp):
3357 testMethod(*args, **kwargs)
3358
3359 def testAssertTrue(self):
3360 self.assertMessages('assertTrue', (False,),
3361 ["^False is not True$", "^oops$", "^False is not True$",
3362 "^False is not True : oops$"])
3363
3364 def testAssertFalse(self):
3365 self.assertMessages('assertFalse', (True,),
3366 ["^True is not False$", "^oops$", "^True is not False$",
3367 "^True is not False : oops$"])
3368
3369 def testNotEqual(self):
3370 self.assertMessages('assertNotEqual', (1, 1),
3371 ["^1 == 1$", "^oops$", "^1 == 1$",
3372 "^1 == 1 : oops$"])
3373
3374 def testAlmostEqual(self):
3375 self.assertMessages('assertAlmostEqual', (1, 2),
3376 ["^1 != 2 within 7 places$", "^oops$",
3377 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3378
3379 def testNotAlmostEqual(self):
3380 self.assertMessages('assertNotAlmostEqual', (1, 1),
3381 ["^1 == 1 within 7 places$", "^oops$",
3382 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3383
3384 def test_baseAssertEqual(self):
3385 self.assertMessages('_baseAssertEqual', (1, 2),
3386 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3387
3388 def testAssertSequenceEqual(self):
3389 # Error messages are multiline so not testing on full message
3390 # assertTupleEqual and assertListEqual delegate to this method
3391 self.assertMessages('assertSequenceEqual', ([], [None]),
3392 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3393 r"\+ \[None\] : oops$"])
3394
3395 def testAssertSetEqual(self):
3396 self.assertMessages('assertSetEqual', (set(), set([None])),
3397 ["None$", "^oops$", "None$",
3398 "None : oops$"])
3399
3400 def testAssertIn(self):
3401 self.assertMessages('assertIn', (None, []),
3402 ['^None not found in \[\]$', "^oops$",
3403 '^None not found in \[\]$',
3404 '^None not found in \[\] : oops$'])
3405
3406 def testAssertNotIn(self):
3407 self.assertMessages('assertNotIn', (None, [None]),
3408 ['^None unexpectedly found in \[None\]$', "^oops$",
3409 '^None unexpectedly found in \[None\]$',
3410 '^None unexpectedly found in \[None\] : oops$'])
3411
3412 def testAssertDictEqual(self):
3413 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3414 [r"\+ \{'key': 'value'\}$", "^oops$",
3415 "\+ \{'key': 'value'\}$",
3416 "\+ \{'key': 'value'\} : oops$"])
3417
3418 def testAssertDictContainsSubset(self):
3419 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3420 ["^Missing: 'key'$", "^oops$",
3421 "^Missing: 'key'$",
3422 "^Missing: 'key' : oops$"])
3423
Michael Foord8442a602010-03-20 16:58:04 +00003424 def testAssertItemsEqual(self):
3425 self.assertMessages('assertItemsEqual', ([], [None]),
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003426 [r"\[None\]$", "^oops$",
3427 r"\[None\]$",
3428 r"\[None\] : oops$"])
3429
3430 def testAssertMultiLineEqual(self):
3431 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3432 [r"\+ foo$", "^oops$",
3433 r"\+ foo$",
3434 r"\+ foo : oops$"])
3435
3436 def testAssertLess(self):
3437 self.assertMessages('assertLess', (2, 1),
3438 ["^2 not less than 1$", "^oops$",
3439 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3440
3441 def testAssertLessEqual(self):
3442 self.assertMessages('assertLessEqual', (2, 1),
3443 ["^2 not less than or equal to 1$", "^oops$",
3444 "^2 not less than or equal to 1$",
3445 "^2 not less than or equal to 1 : oops$"])
3446
3447 def testAssertGreater(self):
3448 self.assertMessages('assertGreater', (1, 2),
3449 ["^1 not greater than 2$", "^oops$",
3450 "^1 not greater than 2$",
3451 "^1 not greater than 2 : oops$"])
3452
3453 def testAssertGreaterEqual(self):
3454 self.assertMessages('assertGreaterEqual', (1, 2),
3455 ["^1 not greater than or equal to 2$", "^oops$",
3456 "^1 not greater than or equal to 2$",
3457 "^1 not greater than or equal to 2 : oops$"])
3458
3459 def testAssertIsNone(self):
3460 self.assertMessages('assertIsNone', ('not None',),
3461 ["^'not None' is not None$", "^oops$",
3462 "^'not None' is not None$",
3463 "^'not None' is not None : oops$"])
3464
3465 def testAssertIsNotNone(self):
3466 self.assertMessages('assertIsNotNone', (None,),
3467 ["^unexpectedly None$", "^oops$",
3468 "^unexpectedly None$",
3469 "^unexpectedly None : oops$"])
3470
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00003471 def testAssertIs(self):
3472 self.assertMessages('assertIs', (None, 'foo'),
3473 ["^None is not 'foo'$", "^oops$",
3474 "^None is not 'foo'$",
3475 "^None is not 'foo' : oops$"])
3476
3477 def testAssertIsNot(self):
3478 self.assertMessages('assertIsNot', (None, None),
3479 ["^unexpectedly identical: None$", "^oops$",
3480 "^unexpectedly identical: None$",
3481 "^unexpectedly identical: None : oops$"])
3482
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003483
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003484class TestCleanUp(TestCase):
3485
3486 def testCleanUp(self):
3487 class TestableTest(TestCase):
3488 def testNothing(self):
3489 pass
3490
3491 test = TestableTest('testNothing')
3492 self.assertEqual(test._cleanups, [])
3493
3494 cleanups = []
3495
3496 def cleanup1(*args, **kwargs):
3497 cleanups.append((1, args, kwargs))
3498
3499 def cleanup2(*args, **kwargs):
3500 cleanups.append((2, args, kwargs))
3501
3502 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3503 test.addCleanup(cleanup2)
3504
3505 self.assertEqual(test._cleanups,
3506 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3507 (cleanup2, (), {})])
3508
3509 result = test.doCleanups()
3510 self.assertTrue(result)
3511
3512 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3513
3514 def testCleanUpWithErrors(self):
3515 class TestableTest(TestCase):
3516 def testNothing(self):
3517 pass
3518
3519 class MockResult(object):
3520 errors = []
3521 def addError(self, test, exc_info):
3522 self.errors.append((test, exc_info))
3523
3524 result = MockResult()
3525 test = TestableTest('testNothing')
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00003526 test._resultForDoCleanups = result
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003527
3528 exc1 = Exception('foo')
3529 exc2 = Exception('bar')
3530 def cleanup1():
3531 raise exc1
3532
3533 def cleanup2():
3534 raise exc2
3535
3536 test.addCleanup(cleanup1)
3537 test.addCleanup(cleanup2)
3538
3539 self.assertFalse(test.doCleanups())
3540
3541 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3542 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3543 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3544
3545 def testCleanupInRun(self):
3546 blowUp = False
3547 ordering = []
3548
3549 class TestableTest(TestCase):
3550 def setUp(self):
3551 ordering.append('setUp')
3552 if blowUp:
3553 raise Exception('foo')
3554
3555 def testNothing(self):
3556 ordering.append('test')
3557
3558 def tearDown(self):
3559 ordering.append('tearDown')
3560
3561 test = TestableTest('testNothing')
3562
3563 def cleanup1():
3564 ordering.append('cleanup1')
3565 def cleanup2():
3566 ordering.append('cleanup2')
3567 test.addCleanup(cleanup1)
3568 test.addCleanup(cleanup2)
3569
3570 def success(some_test):
3571 self.assertEqual(some_test, test)
3572 ordering.append('success')
3573
3574 result = unittest.TestResult()
3575 result.addSuccess = success
3576
3577 test.run(result)
3578 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3579 'cleanup2', 'cleanup1', 'success'])
3580
3581 blowUp = True
3582 ordering = []
3583 test = TestableTest('testNothing')
3584 test.addCleanup(cleanup1)
3585 test.run(result)
3586 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3587
3588
3589class Test_TestProgram(TestCase):
3590
3591 # Horrible white box test
3592 def testNoExit(self):
3593 result = object()
3594 test = object()
3595
3596 class FakeRunner(object):
3597 def run(self, test):
3598 self.test = test
3599 return result
3600
3601 runner = FakeRunner()
3602
Benjamin Petersond2397752009-06-27 23:45:02 +00003603 oldParseArgs = TestProgram.parseArgs
3604 def restoreParseArgs():
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003605 TestProgram.parseArgs = oldParseArgs
Benjamin Petersond2397752009-06-27 23:45:02 +00003606 TestProgram.parseArgs = lambda *args: None
3607 self.addCleanup(restoreParseArgs)
3608
3609 def removeTest():
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003610 del TestProgram.test
Benjamin Petersond2397752009-06-27 23:45:02 +00003611 TestProgram.test = test
3612 self.addCleanup(removeTest)
3613
3614 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3615
3616 self.assertEqual(program.result, result)
3617 self.assertEqual(runner.test, test)
3618 self.assertEqual(program.verbosity, 2)
3619
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003620 class FooBar(unittest.TestCase):
3621 def testPass(self):
3622 assert True
3623 def testFail(self):
3624 assert False
3625
3626 class FooBarLoader(unittest.TestLoader):
3627 """Test loader that returns a suite containing FooBar."""
3628 def loadTestsFromModule(self, module):
3629 return self.suiteClass(
3630 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3631
3632
3633 def test_NonExit(self):
3634 program = unittest.main(exit=False,
3635 argv=["foobar"],
3636 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3637 testLoader=self.FooBarLoader())
3638 self.assertTrue(hasattr(program, 'result'))
3639
3640
3641 def test_Exit(self):
3642 self.assertRaises(
3643 SystemExit,
3644 unittest.main,
3645 argv=["foobar"],
3646 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3647 exit=True,
3648 testLoader=self.FooBarLoader())
3649
3650
3651 def test_ExitAsDefault(self):
3652 self.assertRaises(
3653 SystemExit,
3654 unittest.main,
3655 argv=["foobar"],
3656 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3657 testLoader=self.FooBarLoader())
3658
3659
3660class Test_TextTestRunner(TestCase):
3661 """Tests for TextTestRunner."""
3662
3663 def test_works_with_result_without_startTestRun_stopTestRun(self):
3664 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3665 separator2 = ''
3666 def printErrors(self):
3667 pass
3668
3669 class Runner(unittest.TextTestRunner):
3670 def __init__(self):
3671 super(Runner, self).__init__(io.StringIO())
3672
3673 def _makeResult(self):
3674 return OldTextResult()
3675
3676 runner = Runner()
3677 runner.run(unittest.TestSuite())
3678
3679 def test_startTestRun_stopTestRun_called(self):
3680 class LoggingTextResult(LoggingResult):
3681 separator2 = ''
3682 def printErrors(self):
3683 pass
3684
3685 class LoggingRunner(unittest.TextTestRunner):
3686 def __init__(self, events):
3687 super(LoggingRunner, self).__init__(io.StringIO())
3688 self._events = events
3689
3690 def _makeResult(self):
3691 return LoggingTextResult(self._events)
3692
3693 events = []
3694 runner = LoggingRunner(events)
3695 runner.run(unittest.TestSuite())
3696 expected = ['startTestRun', 'stopTestRun']
3697 self.assertEqual(events, expected)
3698
Antoine Pitrouc63ecee2009-11-10 21:34:48 +00003699 def test_pickle_unpickle(self):
3700 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3701 # required by test_multiprocessing under Windows (in verbose mode).
3702 stream = io.StringIO("foo")
3703 runner = unittest.TextTestRunner(stream)
3704 for protocol in range(2, pickle.HIGHEST_PROTOCOL + 1):
3705 s = pickle.dumps(runner, protocol)
3706 obj = pickle.loads(s)
3707 # StringIO objects never compare equal, a cheap test instead.
3708 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3709
Michael Foord34c94622010-02-10 15:51:42 +00003710 def test_resultclass(self):
3711 def MockResultClass(*args):
3712 return args
3713 STREAM = object()
3714 DESCRIPTIONS = object()
3715 VERBOSITY = object()
3716 runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY,
3717 resultclass=MockResultClass)
3718 self.assertEqual(runner.resultclass, MockResultClass)
3719
3720 expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY)
3721 self.assertEqual(runner._makeResult(), expectedresult)
3722
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003723
Benjamin Petersond2397752009-06-27 23:45:02 +00003724class TestDiscovery(TestCase):
3725
3726 # Heavily mocked tests so I can avoid hitting the filesystem
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003727 def test_get_name_from_path(self):
Benjamin Petersond2397752009-06-27 23:45:02 +00003728 loader = unittest.TestLoader()
Benjamin Petersond2397752009-06-27 23:45:02 +00003729 loader._top_level_dir = '/foo'
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003730 name = loader._get_name_from_path('/foo/bar/baz.py')
3731 self.assertEqual(name, 'bar.baz')
Benjamin Petersond2397752009-06-27 23:45:02 +00003732
3733 if not __debug__:
3734 # asserts are off
3735 return
3736
3737 with self.assertRaises(AssertionError):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003738 loader._get_name_from_path('/bar/baz.py')
Benjamin Petersond2397752009-06-27 23:45:02 +00003739
3740 def test_find_tests(self):
3741 loader = unittest.TestLoader()
3742
3743 original_listdir = os.listdir
3744 def restore_listdir():
3745 os.listdir = original_listdir
3746 original_isfile = os.path.isfile
3747 def restore_isfile():
3748 os.path.isfile = original_isfile
3749 original_isdir = os.path.isdir
3750 def restore_isdir():
3751 os.path.isdir = original_isdir
3752
3753 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003754 'test.foo', 'test-not-a-module.py', 'another_dir'],
Benjamin Petersond2397752009-06-27 23:45:02 +00003755 ['test3.py', 'test4.py', ]]
3756 os.listdir = lambda path: path_lists.pop(0)
3757 self.addCleanup(restore_listdir)
3758
3759 def isdir(path):
3760 return path.endswith('dir')
3761 os.path.isdir = isdir
3762 self.addCleanup(restore_isdir)
3763
3764 def isfile(path):
3765 # another_dir is not a package and so shouldn't be recursed into
3766 return not path.endswith('dir') and not 'another_dir' in path
3767 os.path.isfile = isfile
3768 self.addCleanup(restore_isfile)
3769
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003770 loader._get_module_from_name = lambda path: path + ' module'
Benjamin Petersond2397752009-06-27 23:45:02 +00003771 loader.loadTestsFromModule = lambda module: module + ' tests'
3772
3773 loader._top_level_dir = '/foo'
3774 suite = list(loader._find_tests('/foo', 'test*.py'))
3775
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003776 expected = [name + ' module tests' for name in
3777 ('test1', 'test2')]
3778 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3779 ('test3', 'test4')])
Benjamin Petersond2397752009-06-27 23:45:02 +00003780 self.assertEqual(suite, expected)
3781
3782 def test_find_tests_with_package(self):
3783 loader = unittest.TestLoader()
3784
3785 original_listdir = os.listdir
3786 def restore_listdir():
3787 os.listdir = original_listdir
3788 original_isfile = os.path.isfile
3789 def restore_isfile():
3790 os.path.isfile = original_isfile
3791 original_isdir = os.path.isdir
3792 def restore_isdir():
3793 os.path.isdir = original_isdir
3794
3795 directories = ['a_directory', 'test_directory', 'test_directory2']
3796 path_lists = [directories, [], [], []]
3797 os.listdir = lambda path: path_lists.pop(0)
3798 self.addCleanup(restore_listdir)
3799
3800 os.path.isdir = lambda path: True
3801 self.addCleanup(restore_isdir)
3802
3803 os.path.isfile = lambda path: os.path.basename(path) not in directories
3804 self.addCleanup(restore_isfile)
3805
3806 class Module(object):
3807 paths = []
3808 load_tests_args = []
3809
3810 def __init__(self, path):
3811 self.path = path
3812 self.paths.append(path)
3813 if os.path.basename(path) == 'test_directory':
3814 def load_tests(loader, tests, pattern):
3815 self.load_tests_args.append((loader, tests, pattern))
3816 return 'load_tests'
3817 self.load_tests = load_tests
3818
3819 def __eq__(self, other):
3820 return self.path == other.path
3821
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003822 loader._get_module_from_name = lambda name: Module(name)
Benjamin Petersond2397752009-06-27 23:45:02 +00003823 def loadTestsFromModule(module, use_load_tests):
3824 if use_load_tests:
3825 raise self.failureException('use_load_tests should be False for packages')
3826 return module.path + ' module tests'
3827 loader.loadTestsFromModule = loadTestsFromModule
3828
3829 loader._top_level_dir = '/foo'
3830 # this time no '.py' on the pattern so that it can match
3831 # a test package
3832 suite = list(loader._find_tests('/foo', 'test*'))
3833
3834 # We should have loaded tests from the test_directory package by calling load_tests
3835 # and directly from the test_directory2 package
3836 self.assertEqual(suite,
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003837 ['load_tests', 'test_directory2' + ' module tests'])
3838 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Benjamin Petersond2397752009-06-27 23:45:02 +00003839
3840 # load_tests should have been called once with loader, tests and pattern
3841 self.assertEqual(Module.load_tests_args,
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003842 [(loader, 'test_directory' + ' module tests', 'test*')])
Benjamin Petersond2397752009-06-27 23:45:02 +00003843
3844 def test_discover(self):
3845 loader = unittest.TestLoader()
3846
3847 original_isfile = os.path.isfile
3848 def restore_isfile():
3849 os.path.isfile = original_isfile
3850
3851 os.path.isfile = lambda path: False
3852 self.addCleanup(restore_isfile)
3853
Nick Coghlan6ead5522009-10-18 13:19:33 +00003854 orig_sys_path = sys.path[:]
3855 def restore_path():
3856 sys.path[:] = orig_sys_path
3857 self.addCleanup(restore_path)
Benjamin Petersond2397752009-06-27 23:45:02 +00003858
Nick Coghlan6ead5522009-10-18 13:19:33 +00003859 full_path = os.path.abspath(os.path.normpath('/foo'))
Benjamin Petersond2397752009-06-27 23:45:02 +00003860 with self.assertRaises(ImportError):
3861 loader.discover('/foo/bar', top_level_dir='/foo')
3862
3863 self.assertEqual(loader._top_level_dir, full_path)
3864 self.assertIn(full_path, sys.path)
3865
3866 os.path.isfile = lambda path: True
3867 _find_tests_args = []
3868 def _find_tests(start_dir, pattern):
3869 _find_tests_args.append((start_dir, pattern))
3870 return ['tests']
3871 loader._find_tests = _find_tests
3872 loader.suiteClass = str
3873
3874 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3875
3876 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3877 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3878 self.assertEqual(suite, "['tests']")
3879 self.assertEqual(loader._top_level_dir, top_level_dir)
3880 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlan6ead5522009-10-18 13:19:33 +00003881 self.assertIn(top_level_dir, sys.path)
Benjamin Petersond2397752009-06-27 23:45:02 +00003882
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003883 def test_discover_with_modules_that_fail_to_import(self):
3884 loader = unittest.TestLoader()
3885
3886 listdir = os.listdir
3887 os.listdir = lambda _: ['test_this_does_not_exist.py']
3888 isfile = os.path.isfile
3889 os.path.isfile = lambda _: True
Nick Coghlan6ead5522009-10-18 13:19:33 +00003890 orig_sys_path = sys.path[:]
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003891 def restore():
3892 os.path.isfile = isfile
3893 os.listdir = listdir
Nick Coghlan6ead5522009-10-18 13:19:33 +00003894 sys.path[:] = orig_sys_path
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003895 self.addCleanup(restore)
3896
3897 suite = loader.discover('.')
Nick Coghlan6ead5522009-10-18 13:19:33 +00003898 self.assertIn(os.getcwd(), sys.path)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003899 self.assertEqual(suite.countTestCases(), 1)
3900 test = list(list(suite)[0])[0] # extract test from suite
3901
3902 with self.assertRaises(ImportError):
3903 test.test_this_does_not_exist()
3904
Benjamin Petersond2397752009-06-27 23:45:02 +00003905 def test_command_line_handling_parseArgs(self):
3906 # Haha - take that uninstantiable class
3907 program = object.__new__(TestProgram)
3908
3909 args = []
3910 def do_discovery(argv):
3911 args.extend(argv)
3912 program._do_discovery = do_discovery
3913 program.parseArgs(['something', 'discover'])
3914 self.assertEqual(args, [])
3915
3916 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3917 self.assertEqual(args, ['foo', 'bar'])
3918
3919 def test_command_line_handling_do_discovery_too_many_arguments(self):
3920 class Stop(Exception):
3921 pass
3922 def usageExit():
3923 raise Stop
3924
3925 program = object.__new__(TestProgram)
3926 program.usageExit = usageExit
3927
3928 with self.assertRaises(Stop):
3929 # too many args
3930 program._do_discovery(['one', 'two', 'three', 'four'])
3931
3932
3933 def test_command_line_handling_do_discovery_calls_loader(self):
3934 program = object.__new__(TestProgram)
3935
3936 class Loader(object):
3937 args = []
3938 def discover(self, start_dir, pattern, top_level_dir):
3939 self.args.append((start_dir, pattern, top_level_dir))
3940 return 'tests'
3941
3942 program._do_discovery(['-v'], Loader=Loader)
3943 self.assertEqual(program.verbosity, 2)
3944 self.assertEqual(program.test, 'tests')
3945 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3946
3947 Loader.args = []
3948 program = object.__new__(TestProgram)
3949 program._do_discovery(['--verbose'], Loader=Loader)
3950 self.assertEqual(program.test, 'tests')
3951 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3952
3953 Loader.args = []
3954 program = object.__new__(TestProgram)
3955 program._do_discovery([], Loader=Loader)
3956 self.assertEqual(program.test, 'tests')
3957 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3958
3959 Loader.args = []
3960 program = object.__new__(TestProgram)
3961 program._do_discovery(['fish'], Loader=Loader)
3962 self.assertEqual(program.test, 'tests')
3963 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3964
3965 Loader.args = []
3966 program = object.__new__(TestProgram)
3967 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3968 self.assertEqual(program.test, 'tests')
3969 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3970
3971 Loader.args = []
3972 program = object.__new__(TestProgram)
3973 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3974 self.assertEqual(program.test, 'tests')
3975 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3976
3977 Loader.args = []
3978 program = object.__new__(TestProgram)
3979 program._do_discovery(['-s', 'fish'], Loader=Loader)
3980 self.assertEqual(program.test, 'tests')
3981 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3982
3983 Loader.args = []
3984 program = object.__new__(TestProgram)
3985 program._do_discovery(['-t', 'fish'], Loader=Loader)
3986 self.assertEqual(program.test, 'tests')
3987 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3988
3989 Loader.args = []
3990 program = object.__new__(TestProgram)
3991 program._do_discovery(['-p', 'fish'], Loader=Loader)
3992 self.assertEqual(program.test, 'tests')
3993 self.assertEqual(Loader.args, [('.', 'fish', None)])
Benjamin Peterson434ae772010-03-22 01:46:47 +00003994 self.assertFalse(program.failfast)
Benjamin Petersond2397752009-06-27 23:45:02 +00003995
3996 Loader.args = []
3997 program = object.__new__(TestProgram)
Benjamin Peterson434ae772010-03-22 01:46:47 +00003998 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v', '-f'], Loader=Loader)
Benjamin Petersond2397752009-06-27 23:45:02 +00003999 self.assertEqual(program.test, 'tests')
4000 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
4001 self.assertEqual(program.verbosity, 2)
Benjamin Peterson434ae772010-03-22 01:46:47 +00004002 self.assertTrue(program.failfast)
Benjamin Petersond2397752009-06-27 23:45:02 +00004003
4004
Benjamin Peterson847a4112010-03-14 15:04:17 +00004005class TestSetups(unittest.TestCase):
4006
4007 def getRunner(self):
4008 return unittest.TextTestRunner(resultclass=resultFactory,
4009 stream=io.StringIO())
4010 def runTests(self, *cases):
4011 suite = unittest.TestSuite()
4012 for case in cases:
4013 tests = unittest.defaultTestLoader.loadTestsFromTestCase(case)
4014 suite.addTests(tests)
4015
4016 runner = self.getRunner()
4017
4018 # creating a nested suite exposes some potential bugs
4019 realSuite = unittest.TestSuite()
4020 realSuite.addTest(suite)
4021 # adding empty suites to the end exposes potential bugs
4022 suite.addTest(unittest.TestSuite())
4023 realSuite.addTest(unittest.TestSuite())
4024 return runner.run(realSuite)
4025
4026 def test_setup_class(self):
4027 class Test(unittest.TestCase):
4028 setUpCalled = 0
4029 @classmethod
4030 def setUpClass(cls):
4031 Test.setUpCalled += 1
4032 unittest.TestCase.setUpClass()
4033 def test_one(self):
4034 pass
4035 def test_two(self):
4036 pass
4037
4038 result = self.runTests(Test)
4039
4040 self.assertEqual(Test.setUpCalled, 1)
4041 self.assertEqual(result.testsRun, 2)
4042 self.assertEqual(len(result.errors), 0)
4043
4044 def test_teardown_class(self):
4045 class Test(unittest.TestCase):
4046 tearDownCalled = 0
4047 @classmethod
4048 def tearDownClass(cls):
4049 Test.tearDownCalled += 1
4050 unittest.TestCase.tearDownClass()
4051 def test_one(self):
4052 pass
4053 def test_two(self):
4054 pass
4055
4056 result = self.runTests(Test)
4057
4058 self.assertEqual(Test.tearDownCalled, 1)
4059 self.assertEqual(result.testsRun, 2)
4060 self.assertEqual(len(result.errors), 0)
4061
4062 def test_teardown_class_two_classes(self):
4063 class Test(unittest.TestCase):
4064 tearDownCalled = 0
4065 @classmethod
4066 def tearDownClass(cls):
4067 Test.tearDownCalled += 1
4068 unittest.TestCase.tearDownClass()
4069 def test_one(self):
4070 pass
4071 def test_two(self):
4072 pass
4073
4074 class Test2(unittest.TestCase):
4075 tearDownCalled = 0
4076 @classmethod
4077 def tearDownClass(cls):
4078 Test2.tearDownCalled += 1
4079 unittest.TestCase.tearDownClass()
4080 def test_one(self):
4081 pass
4082 def test_two(self):
4083 pass
4084
4085 result = self.runTests(Test, Test2)
4086
4087 self.assertEqual(Test.tearDownCalled, 1)
4088 self.assertEqual(Test2.tearDownCalled, 1)
4089 self.assertEqual(result.testsRun, 4)
4090 self.assertEqual(len(result.errors), 0)
4091
4092 def test_error_in_setupclass(self):
4093 class BrokenTest(unittest.TestCase):
4094 @classmethod
4095 def setUpClass(cls):
4096 raise TypeError('foo')
4097 def test_one(self):
4098 pass
4099 def test_two(self):
4100 pass
4101
4102 result = self.runTests(BrokenTest)
4103
4104 self.assertEqual(result.testsRun, 0)
4105 self.assertEqual(len(result.errors), 1)
4106 error, _ = result.errors[0]
4107 self.assertEqual(str(error),
4108 'classSetUp (%s.BrokenTest)' % __name__)
4109
4110 def test_error_in_teardown_class(self):
4111 class Test(unittest.TestCase):
4112 tornDown = 0
4113 @classmethod
4114 def tearDownClass(cls):
4115 Test.tornDown += 1
4116 raise TypeError('foo')
4117 def test_one(self):
4118 pass
4119 def test_two(self):
4120 pass
4121
4122 class Test2(unittest.TestCase):
4123 tornDown = 0
4124 @classmethod
4125 def tearDownClass(cls):
4126 Test2.tornDown += 1
4127 raise TypeError('foo')
4128 def test_one(self):
4129 pass
4130 def test_two(self):
4131 pass
4132
4133 result = self.runTests(Test, Test2)
4134 self.assertEqual(result.testsRun, 4)
4135 self.assertEqual(len(result.errors), 2)
4136 self.assertEqual(Test.tornDown, 1)
4137 self.assertEqual(Test2.tornDown, 1)
4138
4139 error, _ = result.errors[0]
4140 self.assertEqual(str(error),
4141 'classTearDown (%s.Test)' % __name__)
4142
4143 def test_class_not_torndown_when_setup_fails(self):
4144 class Test(unittest.TestCase):
4145 tornDown = False
4146 @classmethod
4147 def setUpClass(cls):
4148 raise TypeError
4149 @classmethod
4150 def tearDownClass(cls):
4151 Test.tornDown = True
4152 raise TypeError('foo')
4153 def test_one(self):
4154 pass
4155
4156 self.runTests(Test)
4157 self.assertFalse(Test.tornDown)
4158
4159 def test_class_not_setup_or_torndown_when_skipped(self):
4160 class Test(unittest.TestCase):
4161 classSetUp = False
4162 tornDown = False
4163 @classmethod
4164 def setUpClass(cls):
4165 Test.classSetUp = True
4166 @classmethod
4167 def tearDownClass(cls):
4168 Test.tornDown = True
4169 def test_one(self):
4170 pass
4171
4172 Test = unittest.skip("hop")(Test)
4173 self.runTests(Test)
4174 self.assertFalse(Test.classSetUp)
4175 self.assertFalse(Test.tornDown)
4176
4177 def test_setup_teardown_order_with_pathological_suite(self):
4178 results = []
4179
4180 class Module1(object):
4181 @staticmethod
4182 def setUpModule():
4183 results.append('Module1.setUpModule')
4184 @staticmethod
4185 def tearDownModule():
4186 results.append('Module1.tearDownModule')
4187
4188 class Module2(object):
4189 @staticmethod
4190 def setUpModule():
4191 results.append('Module2.setUpModule')
4192 @staticmethod
4193 def tearDownModule():
4194 results.append('Module2.tearDownModule')
4195
4196 class Test1(unittest.TestCase):
4197 @classmethod
4198 def setUpClass(cls):
4199 results.append('setup 1')
4200 @classmethod
4201 def tearDownClass(cls):
4202 results.append('teardown 1')
4203 def testOne(self):
4204 results.append('Test1.testOne')
4205 def testTwo(self):
4206 results.append('Test1.testTwo')
4207
4208 class Test2(unittest.TestCase):
4209 @classmethod
4210 def setUpClass(cls):
4211 results.append('setup 2')
4212 @classmethod
4213 def tearDownClass(cls):
4214 results.append('teardown 2')
4215 def testOne(self):
4216 results.append('Test2.testOne')
4217 def testTwo(self):
4218 results.append('Test2.testTwo')
4219
4220 class Test3(unittest.TestCase):
4221 @classmethod
4222 def setUpClass(cls):
4223 results.append('setup 3')
4224 @classmethod
4225 def tearDownClass(cls):
4226 results.append('teardown 3')
4227 def testOne(self):
4228 results.append('Test3.testOne')
4229 def testTwo(self):
4230 results.append('Test3.testTwo')
4231
4232 Test1.__module__ = Test2.__module__ = 'Module'
4233 Test3.__module__ = 'Module2'
4234 sys.modules['Module'] = Module1
4235 sys.modules['Module2'] = Module2
4236
4237 first = unittest.TestSuite((Test1('testOne'),))
4238 second = unittest.TestSuite((Test1('testTwo'),))
4239 third = unittest.TestSuite((Test2('testOne'),))
4240 fourth = unittest.TestSuite((Test2('testTwo'),))
4241 fifth = unittest.TestSuite((Test3('testOne'),))
4242 sixth = unittest.TestSuite((Test3('testTwo'),))
4243 suite = unittest.TestSuite((first, second, third, fourth, fifth, sixth))
4244
4245 runner = self.getRunner()
4246 result = runner.run(suite)
4247 self.assertEqual(result.testsRun, 6)
4248 self.assertEqual(len(result.errors), 0)
4249
4250 self.assertEqual(results,
4251 ['Module1.setUpModule', 'setup 1',
4252 'Test1.testOne', 'Test1.testTwo', 'teardown 1',
4253 'setup 2', 'Test2.testOne', 'Test2.testTwo',
4254 'teardown 2', 'Module1.tearDownModule',
4255 'Module2.setUpModule', 'setup 3',
4256 'Test3.testOne', 'Test3.testTwo',
4257 'teardown 3', 'Module2.tearDownModule'])
4258
4259 def test_setup_module(self):
4260 class Module(object):
4261 moduleSetup = 0
4262 @staticmethod
4263 def setUpModule():
4264 Module.moduleSetup += 1
4265
4266 class Test(unittest.TestCase):
4267 def test_one(self):
4268 pass
4269 def test_two(self):
4270 pass
4271 Test.__module__ = 'Module'
4272 sys.modules['Module'] = Module
4273
4274 result = self.runTests(Test)
4275 self.assertEqual(Module.moduleSetup, 1)
4276 self.assertEqual(result.testsRun, 2)
4277 self.assertEqual(len(result.errors), 0)
4278
4279 def test_error_in_setup_module(self):
4280 class Module(object):
4281 moduleSetup = 0
4282 moduleTornDown = 0
4283 @staticmethod
4284 def setUpModule():
4285 Module.moduleSetup += 1
4286 raise TypeError('foo')
4287 @staticmethod
4288 def tearDownModule():
4289 Module.moduleTornDown += 1
4290
4291 class Test(unittest.TestCase):
4292 classSetUp = False
4293 classTornDown = False
4294 @classmethod
4295 def setUpClass(cls):
4296 Test.classSetUp = True
4297 @classmethod
4298 def tearDownClass(cls):
4299 Test.classTornDown = True
4300 def test_one(self):
4301 pass
4302 def test_two(self):
4303 pass
4304
4305 class Test2(unittest.TestCase):
4306 def test_one(self):
4307 pass
4308 def test_two(self):
4309 pass
4310 Test.__module__ = 'Module'
4311 Test2.__module__ = 'Module'
4312 sys.modules['Module'] = Module
4313
4314 result = self.runTests(Test, Test2)
4315 self.assertEqual(Module.moduleSetup, 1)
4316 self.assertEqual(Module.moduleTornDown, 0)
4317 self.assertEqual(result.testsRun, 0)
4318 self.assertFalse(Test.classSetUp)
4319 self.assertFalse(Test.classTornDown)
4320 self.assertEqual(len(result.errors), 1)
4321 error, _ = result.errors[0]
4322 self.assertEqual(str(error), 'setUpModule (Module)')
4323
4324 def test_testcase_with_missing_module(self):
4325 class Test(unittest.TestCase):
4326 def test_one(self):
4327 pass
4328 def test_two(self):
4329 pass
4330 Test.__module__ = 'Module'
4331 sys.modules.pop('Module', None)
4332
4333 result = self.runTests(Test)
4334 self.assertEqual(result.testsRun, 2)
4335
4336 def test_teardown_module(self):
4337 class Module(object):
4338 moduleTornDown = 0
4339 @staticmethod
4340 def tearDownModule():
4341 Module.moduleTornDown += 1
4342
4343 class Test(unittest.TestCase):
4344 def test_one(self):
4345 pass
4346 def test_two(self):
4347 pass
4348 Test.__module__ = 'Module'
4349 sys.modules['Module'] = Module
4350
4351 result = self.runTests(Test)
4352 self.assertEqual(Module.moduleTornDown, 1)
4353 self.assertEqual(result.testsRun, 2)
4354 self.assertEqual(len(result.errors), 0)
4355
4356 def test_error_in_teardown_module(self):
4357 class Module(object):
4358 moduleTornDown = 0
4359 @staticmethod
4360 def tearDownModule():
4361 Module.moduleTornDown += 1
4362 raise TypeError('foo')
4363
4364 class Test(unittest.TestCase):
4365 classSetUp = False
4366 classTornDown = False
4367 @classmethod
4368 def setUpClass(cls):
4369 Test.classSetUp = True
4370 @classmethod
4371 def tearDownClass(cls):
4372 Test.classTornDown = True
4373 def test_one(self):
4374 pass
4375 def test_two(self):
4376 pass
4377
4378 class Test2(unittest.TestCase):
4379 def test_one(self):
4380 pass
4381 def test_two(self):
4382 pass
4383 Test.__module__ = 'Module'
4384 Test2.__module__ = 'Module'
4385 sys.modules['Module'] = Module
4386
4387 result = self.runTests(Test, Test2)
4388 self.assertEqual(Module.moduleTornDown, 1)
4389 self.assertEqual(result.testsRun, 4)
4390 self.assertTrue(Test.classSetUp)
4391 self.assertTrue(Test.classTornDown)
4392 self.assertEqual(len(result.errors), 1)
4393 error, _ = result.errors[0]
4394 self.assertEqual(str(error), 'tearDownModule (Module)')
4395
Jim Fultonfafd8742004-08-28 15:22:12 +00004396######################################################################
4397## Main
4398######################################################################
4399
4400def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004401 support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00004402 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Benjamin Peterson25c95f12009-05-08 20:42:26 +00004403 Test_TestSkipping, Test_Assertions, TestLongMessage,
Benjamin Peterson847a4112010-03-14 15:04:17 +00004404 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner,
4405 Test_OldTestResult, TestSetups)
Jim Fultonfafd8742004-08-28 15:22:12 +00004406
Guido van Rossumd8faa362007-04-27 19:54:29 +00004407if __name__ == "__main__":
Jim Fultonfafd8742004-08-28 15:22:12 +00004408 test_main()