blob: b4716a41cca50df71fb08f2881aa238d61b063dc [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 Peterson847a4112010-03-14 15:04:17 +00002099classDict = dict(unittest.TestResult.__dict__)
2100for m in ('addSkip', 'addExpectedFailure', 'addUnexpectedSuccess',
2101 '__init__'):
2102 del classDict[m]
2103
2104def __init__(self, stream=None, descriptions=None, verbosity=None):
2105 self.failures = []
2106 self.errors = []
2107 self.testsRun = 0
2108 self.shouldStop = False
2109classDict['__init__'] = __init__
2110OldResult = type('OldResult', (object,), classDict)
2111
2112class Test_OldTestResult(unittest.TestCase):
2113
2114 def assertOldResultWarning(self, test, failures):
2115 with warnings.catch_warnings(record=True) as log:
2116 result = OldResult()
2117 test.run(result)
2118 self.assertEqual(len(result.failures), failures)
2119 warning, = log
2120 self.assertIs(warning.category, RuntimeWarning)
2121
2122 def testOldTestResult(self):
2123 class Test(unittest.TestCase):
2124 def testSkip(self):
2125 self.skipTest('foobar')
2126 @unittest.expectedFailure
2127 def testExpectedFail(self):
2128 raise TypeError
2129 @unittest.expectedFailure
2130 def testUnexpectedSuccess(self):
2131 pass
2132
2133 for test_name, should_pass in (('testSkip', True),
2134 ('testExpectedFail', True),
2135 ('testUnexpectedSuccess', False)):
2136 test = Test(test_name)
2137 self.assertOldResultWarning(test, int(not should_pass))
2138
2139 def testOldTestTesultSetup(self):
2140 class Test(unittest.TestCase):
2141 def setUp(self):
2142 self.skipTest('no reason')
2143 def testFoo(self):
2144 pass
2145 self.assertOldResultWarning(Test('testFoo'), 0)
2146
2147 def testOldTestResultClass(self):
2148 @unittest.skip('no reason')
2149 class Test(unittest.TestCase):
2150 def testFoo(self):
2151 pass
2152 self.assertOldResultWarning(Test('testFoo'), 0)
2153
2154 def testOldResultWithRunner(self):
2155 class Test(unittest.TestCase):
2156 def testFoo(self):
2157 pass
2158 runner = unittest.TextTestRunner(resultclass=OldResult,
2159 stream=io.StringIO())
2160 # This will raise an exception if TextTestRunner can't handle old
2161 # test result objects
2162 runner.run(Test('testFoo'))
Michael Foord34c94622010-02-10 15:51:42 +00002163
Guido van Rossumd8faa362007-04-27 19:54:29 +00002164### Support code for Test_TestCase
2165################################################################
2166
2167class Foo(unittest.TestCase):
2168 def runTest(self): pass
2169 def test1(self): pass
2170
2171class Bar(Foo):
2172 def test2(self): pass
2173
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002174class LoggingTestCase(unittest.TestCase):
2175 """A test case which logs its calls."""
2176
2177 def __init__(self, events):
2178 super(LoggingTestCase, self).__init__('test')
2179 self.events = events
2180
2181 def setUp(self):
2182 self.events.append('setUp')
2183
2184 def test(self):
2185 self.events.append('test')
2186
2187 def tearDown(self):
2188 self.events.append('tearDown')
2189
2190class ResultWithNoStartTestRunStopTestRun(object):
2191 """An object honouring TestResult before startTestRun/stopTestRun."""
2192
2193 def __init__(self):
2194 self.failures = []
2195 self.errors = []
2196 self.testsRun = 0
2197 self.skipped = []
2198 self.expectedFailures = []
2199 self.unexpectedSuccesses = []
2200 self.shouldStop = False
2201
2202 def startTest(self, test):
2203 pass
2204
2205 def stopTest(self, test):
2206 pass
2207
2208 def addError(self, test):
2209 pass
2210
2211 def addFailure(self, test):
2212 pass
2213
2214 def addSuccess(self, test):
2215 pass
2216
2217 def wasSuccessful(self):
2218 return True
2219
2220
Guido van Rossumd8faa362007-04-27 19:54:29 +00002221################################################################
2222### /Support code for Test_TestCase
2223
2224class Test_TestCase(TestCase, TestEquality, TestHashing):
2225
2226 ### Set up attributes used by inherited tests
2227 ################################################################
2228
2229 # Used by TestHashing.test_hash and TestEquality.test_eq
2230 eq_pairs = [(Foo('test1'), Foo('test1'))]
2231
2232 # Used by TestEquality.test_ne
2233 ne_pairs = [(Foo('test1'), Foo('runTest'))
2234 ,(Foo('test1'), Bar('test1'))
2235 ,(Foo('test1'), Bar('test2'))]
2236
2237 ################################################################
2238 ### /Set up attributes used by inherited tests
2239
2240
2241 # "class TestCase([methodName])"
2242 # ...
2243 # "Each instance of TestCase will run a single test method: the
2244 # method named methodName."
2245 # ...
2246 # "methodName defaults to "runTest"."
2247 #
2248 # Make sure it really is optional, and that it defaults to the proper
2249 # thing.
2250 def test_init__no_test_name(self):
2251 class Test(unittest.TestCase):
2252 def runTest(self): raise MyException()
2253 def test(self): pass
2254
2255 self.assertEqual(Test().id()[-13:], '.Test.runTest')
2256
2257 # "class TestCase([methodName])"
2258 # ...
2259 # "Each instance of TestCase will run a single test method: the
2260 # method named methodName."
2261 def test_init__test_name__valid(self):
2262 class Test(unittest.TestCase):
2263 def runTest(self): raise MyException()
2264 def test(self): pass
2265
2266 self.assertEqual(Test('test').id()[-10:], '.Test.test')
2267
2268 # "class TestCase([methodName])"
2269 # ...
2270 # "Each instance of TestCase will run a single test method: the
2271 # method named methodName."
2272 def test_init__test_name__invalid(self):
2273 class Test(unittest.TestCase):
2274 def runTest(self): raise MyException()
2275 def test(self): pass
2276
2277 try:
2278 Test('testfoo')
2279 except ValueError:
2280 pass
2281 else:
2282 self.fail("Failed to raise ValueError")
2283
2284 # "Return the number of tests represented by the this test object. For
2285 # TestCase instances, this will always be 1"
2286 def test_countTestCases(self):
2287 class Foo(unittest.TestCase):
2288 def test(self): pass
2289
2290 self.assertEqual(Foo('test').countTestCases(), 1)
2291
2292 # "Return the default type of test result object to be used to run this
2293 # test. For TestCase instances, this will always be
2294 # unittest.TestResult; subclasses of TestCase should
2295 # override this as necessary."
2296 def test_defaultTestResult(self):
2297 class Foo(unittest.TestCase):
2298 def runTest(self):
2299 pass
2300
2301 result = Foo().defaultTestResult()
2302 self.assertEqual(type(result), unittest.TestResult)
2303
2304 # "When a setUp() method is defined, the test runner will run that method
2305 # prior to each test. Likewise, if a tearDown() method is defined, the
2306 # test runner will invoke that method after each test. In the example,
2307 # setUp() was used to create a fresh sequence for each test."
2308 #
2309 # Make sure the proper call order is maintained, even if setUp() raises
2310 # an exception.
2311 def test_run_call_order__error_in_setUp(self):
2312 events = []
2313 result = LoggingResult(events)
2314
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002315 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002316 def setUp(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002317 super(Foo, self).setUp()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002318 raise RuntimeError('raised by Foo.setUp')
2319
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002320 Foo(events).run(result)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002321 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2322 self.assertEqual(events, expected)
2323
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002324 # "With a temporary result stopTestRun is called when setUp errors.
2325 def test_run_call_order__error_in_setUp_default_result(self):
2326 events = []
2327
2328 class Foo(LoggingTestCase):
2329 def defaultTestResult(self):
2330 return LoggingResult(self.events)
2331
2332 def setUp(self):
2333 super(Foo, self).setUp()
2334 raise RuntimeError('raised by Foo.setUp')
2335
2336 Foo(events).run()
2337 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2338 'stopTest', 'stopTestRun']
2339 self.assertEqual(events, expected)
2340
Guido van Rossumd8faa362007-04-27 19:54:29 +00002341 # "When a setUp() method is defined, the test runner will run that method
2342 # prior to each test. Likewise, if a tearDown() method is defined, the
2343 # test runner will invoke that method after each test. In the example,
2344 # setUp() was used to create a fresh sequence for each test."
2345 #
2346 # Make sure the proper call order is maintained, even if the test raises
2347 # an error (as opposed to a failure).
2348 def test_run_call_order__error_in_test(self):
2349 events = []
2350 result = LoggingResult(events)
2351
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002352 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002353 def test(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002354 super(Foo, self).test()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002355 raise RuntimeError('raised by Foo.test')
2356
Guido van Rossumd8faa362007-04-27 19:54:29 +00002357 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2358 'stopTest']
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002359 Foo(events).run(result)
2360 self.assertEqual(events, expected)
2361
2362 # "With a default result, an error in the test still results in stopTestRun
2363 # being called."
2364 def test_run_call_order__error_in_test_default_result(self):
2365 events = []
2366
2367 class Foo(LoggingTestCase):
2368 def defaultTestResult(self):
2369 return LoggingResult(self.events)
2370
2371 def test(self):
2372 super(Foo, self).test()
2373 raise RuntimeError('raised by Foo.test')
2374
2375 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2376 'tearDown', 'stopTest', 'stopTestRun']
2377 Foo(events).run()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002378 self.assertEqual(events, expected)
2379
2380 # "When a setUp() method is defined, the test runner will run that method
2381 # prior to each test. Likewise, if a tearDown() method is defined, the
2382 # test runner will invoke that method after each test. In the example,
2383 # setUp() was used to create a fresh sequence for each test."
2384 #
2385 # Make sure the proper call order is maintained, even if the test signals
2386 # a failure (as opposed to an error).
2387 def test_run_call_order__failure_in_test(self):
2388 events = []
2389 result = LoggingResult(events)
2390
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002391 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002392 def test(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002393 super(Foo, self).test()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002394 self.fail('raised by Foo.test')
2395
Guido van Rossumd8faa362007-04-27 19:54:29 +00002396 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2397 'stopTest']
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002398 Foo(events).run(result)
2399 self.assertEqual(events, expected)
2400
2401 # "When a test fails with a default result stopTestRun is still called."
2402 def test_run_call_order__failure_in_test_default_result(self):
2403
2404 class Foo(LoggingTestCase):
2405 def defaultTestResult(self):
2406 return LoggingResult(self.events)
2407 def test(self):
2408 super(Foo, self).test()
2409 self.fail('raised by Foo.test')
2410
2411 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2412 'tearDown', 'stopTest', 'stopTestRun']
2413 events = []
2414 Foo(events).run()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002415 self.assertEqual(events, expected)
2416
2417 # "When a setUp() method is defined, the test runner will run that method
2418 # prior to each test. Likewise, if a tearDown() method is defined, the
2419 # test runner will invoke that method after each test. In the example,
2420 # setUp() was used to create a fresh sequence for each test."
2421 #
2422 # Make sure the proper call order is maintained, even if tearDown() raises
2423 # an exception.
2424 def test_run_call_order__error_in_tearDown(self):
2425 events = []
2426 result = LoggingResult(events)
2427
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002428 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002429 def tearDown(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002430 super(Foo, self).tearDown()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002431 raise RuntimeError('raised by Foo.tearDown')
2432
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002433 Foo(events).run(result)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002434 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2435 'stopTest']
2436 self.assertEqual(events, expected)
2437
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002438 # "When tearDown errors with a default result stopTestRun is still called."
2439 def test_run_call_order__error_in_tearDown_default_result(self):
2440
2441 class Foo(LoggingTestCase):
2442 def defaultTestResult(self):
2443 return LoggingResult(self.events)
2444 def tearDown(self):
2445 super(Foo, self).tearDown()
2446 raise RuntimeError('raised by Foo.tearDown')
2447
2448 events = []
2449 Foo(events).run()
2450 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2451 'addError', 'stopTest', 'stopTestRun']
2452 self.assertEqual(events, expected)
2453
2454 # "TestCase.run() still works when the defaultTestResult is a TestResult
2455 # that does not support startTestRun and stopTestRun.
2456 def test_run_call_order_default_result(self):
2457
2458 class Foo(unittest.TestCase):
2459 def defaultTestResult(self):
2460 return ResultWithNoStartTestRunStopTestRun()
2461 def test(self):
2462 pass
2463
2464 Foo('test').run()
2465
Guido van Rossumd8faa362007-04-27 19:54:29 +00002466 # "This class attribute gives the exception raised by the test() method.
2467 # If a test framework needs to use a specialized exception, possibly to
2468 # carry additional information, it must subclass this exception in
2469 # order to ``play fair'' with the framework. The initial value of this
2470 # attribute is AssertionError"
2471 def test_failureException__default(self):
2472 class Foo(unittest.TestCase):
2473 def test(self):
2474 pass
2475
Benjamin Petersone1759f82009-06-30 23:35:19 +00002476 self.assertTrue(Foo('test').failureException is AssertionError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002477
2478 # "This class attribute gives the exception raised by the test() method.
2479 # If a test framework needs to use a specialized exception, possibly to
2480 # carry additional information, it must subclass this exception in
2481 # order to ``play fair'' with the framework."
2482 #
2483 # Make sure TestCase.run() respects the designated failureException
2484 def test_failureException__subclassing__explicit_raise(self):
2485 events = []
2486 result = LoggingResult(events)
2487
2488 class Foo(unittest.TestCase):
2489 def test(self):
2490 raise RuntimeError()
2491
2492 failureException = RuntimeError
2493
Benjamin Petersone1759f82009-06-30 23:35:19 +00002494 self.assertTrue(Foo('test').failureException is RuntimeError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002495
2496
2497 Foo('test').run(result)
2498 expected = ['startTest', 'addFailure', 'stopTest']
2499 self.assertEqual(events, expected)
2500
2501 # "This class attribute gives the exception raised by the test() method.
2502 # If a test framework needs to use a specialized exception, possibly to
2503 # carry additional information, it must subclass this exception in
2504 # order to ``play fair'' with the framework."
2505 #
2506 # Make sure TestCase.run() respects the designated failureException
2507 def test_failureException__subclassing__implicit_raise(self):
2508 events = []
2509 result = LoggingResult(events)
2510
2511 class Foo(unittest.TestCase):
2512 def test(self):
2513 self.fail("foo")
2514
2515 failureException = RuntimeError
2516
Benjamin Petersone1759f82009-06-30 23:35:19 +00002517 self.assertTrue(Foo('test').failureException is RuntimeError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002518
2519
2520 Foo('test').run(result)
2521 expected = ['startTest', 'addFailure', 'stopTest']
2522 self.assertEqual(events, expected)
2523
2524 # "The default implementation does nothing."
2525 def test_setUp(self):
2526 class Foo(unittest.TestCase):
2527 def runTest(self):
2528 pass
2529
2530 # ... and nothing should happen
2531 Foo().setUp()
2532
2533 # "The default implementation does nothing."
2534 def test_tearDown(self):
2535 class Foo(unittest.TestCase):
2536 def runTest(self):
2537 pass
2538
2539 # ... and nothing should happen
2540 Foo().tearDown()
2541
2542 # "Return a string identifying the specific test case."
2543 #
2544 # Because of the vague nature of the docs, I'm not going to lock this
2545 # test down too much. Really all that can be asserted is that the id()
2546 # will be a string (either 8-byte or unicode -- again, because the docs
2547 # just say "string")
2548 def test_id(self):
2549 class Foo(unittest.TestCase):
2550 def runTest(self):
2551 pass
2552
Ezio Melottie9615932010-01-24 19:26:24 +00002553 self.assertIsInstance(Foo().id(), str)
2554
Guido van Rossumd8faa362007-04-27 19:54:29 +00002555
Guido van Rossumd8faa362007-04-27 19:54:29 +00002556 # "If result is omitted or None, a temporary result object is created
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002557 # and used, but is not made available to the caller. As TestCase owns the
2558 # temporary result startTestRun and stopTestRun are called.
2559
Guido van Rossumd8faa362007-04-27 19:54:29 +00002560 def test_run__uses_defaultTestResult(self):
2561 events = []
2562
2563 class Foo(unittest.TestCase):
2564 def test(self):
2565 events.append('test')
2566
2567 def defaultTestResult(self):
2568 return LoggingResult(events)
2569
2570 # Make run() find a result object on its own
2571 Foo('test').run()
2572
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002573 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2574 'stopTest', 'stopTestRun']
Guido van Rossumd8faa362007-04-27 19:54:29 +00002575 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002576
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002577 def testShortDescriptionWithoutDocstring(self):
Michael Foord34c94622010-02-10 15:51:42 +00002578 self.assertIsNone(self.shortDescription())
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002579
R. David Murray378c0cf2010-02-24 01:46:21 +00002580 @unittest.skipIf(sys.flags.optimize >= 2,
2581 "Docstrings are omitted with -O2 and above")
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002582 def testShortDescriptionWithOneLineDocstring(self):
2583 """Tests shortDescription() for a method with a docstring."""
2584 self.assertEqual(
2585 self.shortDescription(),
Michael Foord34c94622010-02-10 15:51:42 +00002586 'Tests shortDescription() for a method with a docstring.')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002587
R. David Murray378c0cf2010-02-24 01:46:21 +00002588 @unittest.skipIf(sys.flags.optimize >= 2,
2589 "Docstrings are omitted with -O2 and above")
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002590 def testShortDescriptionWithMultiLineDocstring(self):
2591 """Tests shortDescription() for a method with a longer docstring.
2592
2593 This method ensures that only the first line of a docstring is
2594 returned used in the short description, no matter how long the
2595 whole thing is.
2596 """
2597 self.assertEqual(
2598 self.shortDescription(),
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002599 'Tests shortDescription() for a method with a longer '
Michael Foord34c94622010-02-10 15:51:42 +00002600 'docstring.')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002601
2602 def testAddTypeEqualityFunc(self):
2603 class SadSnake(object):
2604 """Dummy class for test_addTypeEqualityFunc."""
2605 s1, s2 = SadSnake(), SadSnake()
2606 self.assertFalse(s1 == s2)
2607 def AllSnakesCreatedEqual(a, b, msg=None):
2608 return type(a) == type(b) == SadSnake
2609 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2610 self.assertEqual(s1, s2)
2611 # No this doesn't clean up and remove the SadSnake equality func
2612 # from this TestCase instance but since its a local nothing else
2613 # will ever notice that.
2614
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00002615 def testAssertIs(self):
2616 thing = object()
2617 self.assertIs(thing, thing)
2618 self.assertRaises(self.failureException, self.assertIs, thing, object())
2619
2620 def testAssertIsNot(self):
2621 thing = object()
2622 self.assertIsNot(thing, object())
2623 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2624
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00002625 def testAssertIsInstance(self):
2626 thing = []
2627 self.assertIsInstance(thing, list)
2628 self.assertRaises(self.failureException, self.assertIsInstance,
2629 thing, dict)
2630
2631 def testAssertNotIsInstance(self):
2632 thing = []
2633 self.assertNotIsInstance(thing, dict)
2634 self.assertRaises(self.failureException, self.assertNotIsInstance,
2635 thing, list)
2636
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002637 def testAssertIn(self):
2638 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2639
2640 self.assertIn('a', 'abc')
2641 self.assertIn(2, [1, 2, 3])
2642 self.assertIn('monkey', animals)
2643
2644 self.assertNotIn('d', 'abc')
2645 self.assertNotIn(0, [1, 2, 3])
2646 self.assertNotIn('otter', animals)
2647
2648 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2649 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2650 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2651 animals)
2652
2653 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2654 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2655 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2656 animals)
2657
2658 def testAssertDictContainsSubset(self):
2659 self.assertDictContainsSubset({}, {})
2660 self.assertDictContainsSubset({}, {'a': 1})
2661 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2662 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2663 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2664
Benjamin Peterson847a4112010-03-14 15:04:17 +00002665 with self.assertRaises(self.failureException):
2666 self.assertDictContainsSubset({1: "one"}, {})
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002667
Benjamin Peterson847a4112010-03-14 15:04:17 +00002668 with self.assertRaises(self.failureException):
2669 self.assertDictContainsSubset({'a': 2}, {'a': 1})
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002670
Benjamin Peterson847a4112010-03-14 15:04:17 +00002671 with self.assertRaises(self.failureException):
2672 self.assertDictContainsSubset({'c': 1}, {'a': 1})
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002673
Benjamin Peterson847a4112010-03-14 15:04:17 +00002674 with self.assertRaises(self.failureException):
2675 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2676
2677 with self.assertRaises(self.failureException):
2678 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2679
2680 with warnings.catch_warnings(record=True):
2681 # silence the UnicodeWarning
2682 one = ''.join(chr(i) for i in range(255))
2683 # this used to cause a UnicodeDecodeError constructing the failure msg
2684 with self.assertRaises(self.failureException):
2685 self.assertDictContainsSubset({'foo': one}, {'foo': '\uFFFD'})
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002686
2687 def testAssertEqual(self):
2688 equal_pairs = [
2689 ((), ()),
2690 ({}, {}),
2691 ([], []),
2692 (set(), set()),
2693 (frozenset(), frozenset())]
2694 for a, b in equal_pairs:
2695 # This mess of try excepts is to test the assertEqual behavior
2696 # itself.
2697 try:
2698 self.assertEqual(a, b)
2699 except self.failureException:
2700 self.fail('assertEqual(%r, %r) failed' % (a, b))
2701 try:
2702 self.assertEqual(a, b, msg='foo')
2703 except self.failureException:
2704 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2705 try:
2706 self.assertEqual(a, b, 'foo')
2707 except self.failureException:
2708 self.fail('assertEqual(%r, %r) with third parameter failed' %
2709 (a, b))
2710
2711 unequal_pairs = [
2712 ((), []),
2713 ({}, set()),
2714 (set([4,1]), frozenset([4,2])),
2715 (frozenset([4,5]), set([2,3])),
2716 (set([3,4]), set([5,4]))]
2717 for a, b in unequal_pairs:
2718 self.assertRaises(self.failureException, self.assertEqual, a, b)
2719 self.assertRaises(self.failureException, self.assertEqual, a, b,
2720 'foo')
2721 self.assertRaises(self.failureException, self.assertEqual, a, b,
2722 msg='foo')
2723
2724 def testEquality(self):
2725 self.assertListEqual([], [])
2726 self.assertTupleEqual((), ())
2727 self.assertSequenceEqual([], ())
2728
2729 a = [0, 'a', []]
2730 b = []
2731 self.assertRaises(unittest.TestCase.failureException,
2732 self.assertListEqual, a, b)
2733 self.assertRaises(unittest.TestCase.failureException,
2734 self.assertListEqual, tuple(a), tuple(b))
2735 self.assertRaises(unittest.TestCase.failureException,
2736 self.assertSequenceEqual, a, tuple(b))
2737
2738 b.extend(a)
2739 self.assertListEqual(a, b)
2740 self.assertTupleEqual(tuple(a), tuple(b))
2741 self.assertSequenceEqual(a, tuple(b))
2742 self.assertSequenceEqual(tuple(a), b)
2743
2744 self.assertRaises(self.failureException, self.assertListEqual,
2745 a, tuple(b))
2746 self.assertRaises(self.failureException, self.assertTupleEqual,
2747 tuple(a), b)
2748 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2749 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2750 tuple(b))
2751 self.assertRaises(self.failureException, self.assertSequenceEqual,
2752 None, tuple(b))
2753 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2754 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2755 self.assertRaises(self.failureException, self.assertSequenceEqual,
2756 1, 1)
2757
2758 self.assertDictEqual({}, {})
2759
2760 c = { 'x': 1 }
2761 d = {}
2762 self.assertRaises(unittest.TestCase.failureException,
2763 self.assertDictEqual, c, d)
2764
2765 d.update(c)
2766 self.assertDictEqual(c, d)
2767
2768 d['x'] = 0
2769 self.assertRaises(unittest.TestCase.failureException,
2770 self.assertDictEqual, c, d, 'These are unequal')
2771
2772 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2773 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2774 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2775
Michael Foord8442a602010-03-20 16:58:04 +00002776 def testAssertItemsEqual(self):
2777 a = object()
2778 self.assertItemsEqual([1, 2, 3], [3, 2, 1])
2779 self.assertItemsEqual(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2780 self.assertItemsEqual([a, a, 2, 2, 3], (a, 2, 3, a, 2))
2781 self.assertItemsEqual([1, "2", "a", "a"], ["a", "2", True, "a"])
2782 self.assertRaises(self.failureException, self.assertItemsEqual,
2783 [1, 2] + [3] * 100, [1] * 100 + [2, 3])
2784 self.assertRaises(self.failureException, self.assertItemsEqual,
2785 [1, "2", "a", "a"], ["a", "2", True, 1])
2786 self.assertRaises(self.failureException, self.assertItemsEqual,
2787 [10], [10, 11])
2788 self.assertRaises(self.failureException, self.assertItemsEqual,
2789 [10, 11], [10])
2790 self.assertRaises(self.failureException, self.assertItemsEqual,
2791 [10, 11, 10], [10, 11])
2792
2793 # Test that sequences of unhashable objects can be tested for sameness:
2794 self.assertItemsEqual([[1, 2], [3, 4], 0], [False, [3, 4], [1, 2]])
2795
2796 # hashable types, but not orderable
2797 self.assertRaises(self.failureException, self.assertItemsEqual,
2798 [], [divmod, 'x', 1, 5j, 2j, frozenset()])
2799 # comparing dicts raises a py3k warning
2800 self.assertItemsEqual([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2801 # comparing heterogenous non-hashable sequences raises a py3k warning
2802 self.assertItemsEqual([1, 'x', divmod, []], [divmod, [], 'x', 1])
2803 self.assertRaises(self.failureException, self.assertItemsEqual,
2804 [], [divmod, [], 'x', 1, 5j, 2j, set()])
2805 self.assertRaises(self.failureException, self.assertItemsEqual,
2806 [[1]], [[2]])
2807
2808 # Same elements, but not same sequence length
2809 self.assertRaises(self.failureException, self.assertItemsEqual,
2810 [1, 1, 2], [2, 1])
2811 self.assertRaises(self.failureException, self.assertItemsEqual,
2812 [1, 1, "2", "a", "a"], ["2", "2", True, "a"])
2813 self.assertRaises(self.failureException, self.assertItemsEqual,
2814 [1, {'b': 2}, None, True], [{'b': 2}, True, None])
2815
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002816 def testAssertSetEqual(self):
2817 set1 = set()
2818 set2 = set()
2819 self.assertSetEqual(set1, set2)
2820
2821 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2822 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2823 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2824 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2825
2826 set1 = set(['a'])
2827 set2 = set()
2828 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2829
2830 set1 = set(['a'])
2831 set2 = set(['a'])
2832 self.assertSetEqual(set1, set2)
2833
2834 set1 = set(['a'])
2835 set2 = set(['a', 'b'])
2836 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2837
2838 set1 = set(['a'])
2839 set2 = frozenset(['a', 'b'])
2840 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2841
2842 set1 = set(['a', 'b'])
2843 set2 = frozenset(['a', 'b'])
2844 self.assertSetEqual(set1, set2)
2845
2846 set1 = set()
2847 set2 = "foo"
2848 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2849 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2850
2851 # make sure any string formatting is tuple-safe
2852 set1 = set([(0, 1), (2, 3)])
2853 set2 = set([(4, 5)])
2854 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2855
2856 def testInequality(self):
2857 # Try ints
2858 self.assertGreater(2, 1)
2859 self.assertGreaterEqual(2, 1)
2860 self.assertGreaterEqual(1, 1)
2861 self.assertLess(1, 2)
2862 self.assertLessEqual(1, 2)
2863 self.assertLessEqual(1, 1)
2864 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2865 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2866 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2867 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2868 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2869 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2870
2871 # Try Floats
2872 self.assertGreater(1.1, 1.0)
2873 self.assertGreaterEqual(1.1, 1.0)
2874 self.assertGreaterEqual(1.0, 1.0)
2875 self.assertLess(1.0, 1.1)
2876 self.assertLessEqual(1.0, 1.1)
2877 self.assertLessEqual(1.0, 1.0)
2878 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2879 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2880 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2881 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2882 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2883 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2884
2885 # Try Strings
2886 self.assertGreater('bug', 'ant')
2887 self.assertGreaterEqual('bug', 'ant')
2888 self.assertGreaterEqual('ant', 'ant')
2889 self.assertLess('ant', 'bug')
2890 self.assertLessEqual('ant', 'bug')
2891 self.assertLessEqual('ant', 'ant')
2892 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2893 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2894 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2895 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2896 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2897 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2898
2899 # Try bytes
2900 self.assertGreater(b'bug', b'ant')
2901 self.assertGreaterEqual(b'bug', b'ant')
2902 self.assertGreaterEqual(b'ant', b'ant')
2903 self.assertLess(b'ant', b'bug')
2904 self.assertLessEqual(b'ant', b'bug')
2905 self.assertLessEqual(b'ant', b'ant')
2906 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'bug')
2907 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'ant')
2908 self.assertRaises(self.failureException, self.assertGreaterEqual, b'ant',
2909 b'bug')
2910 self.assertRaises(self.failureException, self.assertLess, b'bug', b'ant')
2911 self.assertRaises(self.failureException, self.assertLess, b'ant', b'ant')
2912 self.assertRaises(self.failureException, self.assertLessEqual, b'bug', b'ant')
2913
2914 def testAssertMultiLineEqual(self):
2915 sample_text = """\
2916http://www.python.org/doc/2.3/lib/module-unittest.html
2917test case
2918 A test case is the smallest unit of testing. [...]
2919"""
2920 revised_sample_text = """\
2921http://www.python.org/doc/2.4.1/lib/module-unittest.html
2922test case
2923 A test case is the smallest unit of testing. [...] You may provide your
2924 own implementation that does not subclass from TestCase, of course.
2925"""
2926 sample_text_error = """
2927- http://www.python.org/doc/2.3/lib/module-unittest.html
2928? ^
2929+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2930? ^^^
2931 test case
2932- A test case is the smallest unit of testing. [...]
2933+ A test case is the smallest unit of testing. [...] You may provide your
2934? +++++++++++++++++++++
2935+ own implementation that does not subclass from TestCase, of course.
2936"""
2937
2938 try:
2939 self.assertMultiLineEqual(sample_text, revised_sample_text)
2940 except self.failureException as e:
Michael Foord02834952010-02-08 23:10:39 +00002941 # no fair testing ourself with ourself, and assertEqual is used for strings
2942 # so can't use assertEqual either. Just use assertTrue.
2943 self.assertTrue(sample_text_error == str(e))
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002944
2945 def testAssertIsNone(self):
2946 self.assertIsNone(None)
2947 self.assertRaises(self.failureException, self.assertIsNone, False)
2948 self.assertIsNotNone('DjZoPloGears on Rails')
2949 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2950
2951 def testAssertRegexpMatches(self):
2952 self.assertRegexpMatches('asdfabasdf', r'ab+')
2953 self.assertRaises(self.failureException, self.assertRegexpMatches,
2954 'saaas', r'aaaa')
2955
2956 def testAssertRaisesRegexp(self):
2957 class ExceptionMock(Exception):
2958 pass
2959
2960 def Stub():
2961 raise ExceptionMock('We expect')
2962
2963 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2964 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2965
2966 def testAssertNotRaisesRegexp(self):
2967 self.assertRaisesRegexp(
Benjamin Peterson4f75b642009-04-04 16:39:09 +00002968 self.failureException, '^Exception not raised by <lambda>$',
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002969 self.assertRaisesRegexp, Exception, re.compile('x'),
2970 lambda: None)
2971 self.assertRaisesRegexp(
Benjamin Peterson4f75b642009-04-04 16:39:09 +00002972 self.failureException, '^Exception not raised by <lambda>$',
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002973 self.assertRaisesRegexp, Exception, 'x',
2974 lambda: None)
2975
2976 def testAssertRaisesRegexpMismatch(self):
2977 def Stub():
2978 raise Exception('Unexpected')
2979
2980 self.assertRaisesRegexp(
2981 self.failureException,
2982 r'"\^Expected\$" does not match "Unexpected"',
2983 self.assertRaisesRegexp, Exception, '^Expected$',
2984 Stub)
2985 self.assertRaisesRegexp(
2986 self.failureException,
2987 r'"\^Expected\$" does not match "Unexpected"',
2988 self.assertRaisesRegexp, Exception,
2989 re.compile('^Expected$'), Stub)
2990
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +00002991 def testAssertRaisesExcValue(self):
2992 class ExceptionMock(Exception):
2993 pass
2994
2995 def Stub(foo):
2996 raise ExceptionMock(foo)
2997 v = "particular value"
2998
2999 ctx = self.assertRaises(ExceptionMock)
3000 with ctx:
3001 Stub(v)
Ezio Melotti49008232010-02-08 21:57:48 +00003002 e = ctx.exception
Ezio Melottie9615932010-01-24 19:26:24 +00003003 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +00003004 self.assertEqual(e.args[0], v)
3005
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003006 def testSynonymAssertMethodNames(self):
3007 """Test undocumented method name synonyms.
3008
3009 Please do not use these methods names in your own code.
3010
3011 This test confirms their continued existence and functionality
3012 in order to avoid breaking existing code.
3013 """
3014 self.assertNotEquals(3, 5)
3015 self.assertEquals(3, 3)
3016 self.assertAlmostEquals(2.0, 2.0)
3017 self.assertNotAlmostEquals(3.0, 5.0)
3018 self.assert_(True)
3019
3020 def testPendingDeprecationMethodNames(self):
3021 """Test fail* methods pending deprecation, they will warn in 3.2.
3022
3023 Do not use these methods. They will go away in 3.3.
3024 """
Benjamin Peterson6bcbad52009-06-30 23:45:41 +00003025 old = (
3026 (self.failIfEqual, (3, 5)),
3027 (self.failUnlessEqual, (3, 3)),
3028 (self.failUnlessAlmostEqual, (2.0, 2.0)),
3029 (self.failIfAlmostEqual, (3.0, 5.0)),
3030 (self.failUnless, (True,)),
3031 (self.failUnlessRaises, (TypeError, lambda _: 3.14 + 'spam')),
Michael Foord91c9da32010-03-20 17:21:27 +00003032 (self.failIf, (False,)),
3033 (self.assertSameElements, ([1, 1, 2, 3], [1, 2, 3]))
Benjamin Peterson6bcbad52009-06-30 23:45:41 +00003034 )
3035 for meth, args in old:
3036 with warnings.catch_warnings(record=True) as w:
3037 meth(*args)
3038 self.assertEqual(len(w), 1)
3039 self.assertIs(w[0].category, DeprecationWarning)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003040
3041 def testDeepcopy(self):
3042 # Issue: 5660
3043 class TestableTest(TestCase):
3044 def testNothing(self):
3045 pass
3046
3047 test = TestableTest('testNothing')
3048
3049 # This shouldn't blow up
3050 deepcopy(test)
3051
Benjamin Peterson5254c042009-03-23 22:25:03 +00003052
3053class Test_TestSkipping(TestCase):
3054
3055 def test_skipping(self):
3056 class Foo(unittest.TestCase):
3057 def test_skip_me(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00003058 self.skipTest("skip")
Benjamin Peterson5254c042009-03-23 22:25:03 +00003059 events = []
3060 result = LoggingResult(events)
3061 test = Foo("test_skip_me")
3062 test.run(result)
3063 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3064 self.assertEqual(result.skipped, [(test, "skip")])
3065
3066 # Try letting setUp skip the test now.
3067 class Foo(unittest.TestCase):
3068 def setUp(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00003069 self.skipTest("testing")
Benjamin Peterson5254c042009-03-23 22:25:03 +00003070 def test_nothing(self): pass
3071 events = []
3072 result = LoggingResult(events)
3073 test = Foo("test_nothing")
3074 test.run(result)
3075 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3076 self.assertEqual(result.skipped, [(test, "testing")])
3077 self.assertEqual(result.testsRun, 1)
3078
3079 def test_skipping_decorators(self):
3080 op_table = ((unittest.skipUnless, False, True),
3081 (unittest.skipIf, True, False))
3082 for deco, do_skip, dont_skip in op_table:
3083 class Foo(unittest.TestCase):
3084 @deco(do_skip, "testing")
3085 def test_skip(self): pass
3086
3087 @deco(dont_skip, "testing")
3088 def test_dont_skip(self): pass
3089 test_do_skip = Foo("test_skip")
3090 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00003091 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003092 events = []
3093 result = LoggingResult(events)
3094 suite.run(result)
3095 self.assertEqual(len(result.skipped), 1)
3096 expected = ['startTest', 'addSkip', 'stopTest',
3097 'startTest', 'addSuccess', 'stopTest']
3098 self.assertEqual(events, expected)
3099 self.assertEqual(result.testsRun, 2)
3100 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
3101 self.assertTrue(result.wasSuccessful())
3102
3103 def test_skip_class(self):
3104 @unittest.skip("testing")
3105 class Foo(unittest.TestCase):
3106 def test_1(self):
3107 record.append(1)
3108 record = []
3109 result = unittest.TestResult()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00003110 test = Foo("test_1")
3111 suite = unittest.TestSuite([test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003112 suite.run(result)
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00003113 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003114 self.assertEqual(record, [])
3115
3116 def test_expected_failure(self):
3117 class Foo(unittest.TestCase):
3118 @unittest.expectedFailure
3119 def test_die(self):
3120 self.fail("help me!")
3121 events = []
3122 result = LoggingResult(events)
3123 test = Foo("test_die")
3124 test.run(result)
3125 self.assertEqual(events,
3126 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Peterson52baa292009-03-24 00:56:30 +00003127 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson5254c042009-03-23 22:25:03 +00003128 self.assertTrue(result.wasSuccessful())
3129
3130 def test_unexpected_success(self):
3131 class Foo(unittest.TestCase):
3132 @unittest.expectedFailure
3133 def test_die(self):
3134 pass
3135 events = []
3136 result = LoggingResult(events)
3137 test = Foo("test_die")
3138 test.run(result)
3139 self.assertEqual(events,
3140 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3141 self.assertFalse(result.failures)
Benjamin Peterson52baa292009-03-24 00:56:30 +00003142 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003143 self.assertTrue(result.wasSuccessful())
3144
Benjamin Peterson847a4112010-03-14 15:04:17 +00003145 def test_skip_doesnt_run_setup(self):
3146 class Foo(unittest.TestCase):
3147 wasSetUp = False
3148 wasTornDown = False
3149 def setUp(self):
3150 Foo.wasSetUp = True
3151 def tornDown(self):
3152 Foo.wasTornDown = True
3153 @unittest.skip('testing')
3154 def test_1(self):
3155 pass
3156
3157 result = unittest.TestResult()
3158 test = Foo("test_1")
3159 suite = unittest.TestSuite([test])
3160 suite.run(result)
3161 self.assertEqual(result.skipped, [(test, "testing")])
3162 self.assertFalse(Foo.wasSetUp)
3163 self.assertFalse(Foo.wasTornDown)
3164
3165 def test_decorated_skip(self):
3166 def decorator(func):
3167 def inner(*a):
3168 return func(*a)
3169 return inner
3170
3171 class Foo(unittest.TestCase):
3172 @decorator
3173 @unittest.skip('testing')
3174 def test_1(self):
3175 pass
3176
3177 result = unittest.TestResult()
3178 test = Foo("test_1")
3179 suite = unittest.TestSuite([test])
3180 suite.run(result)
3181 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003182
3183
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003184class Test_Assertions(TestCase):
3185 def test_AlmostEqual(self):
Benjamin Petersone1759f82009-06-30 23:35:19 +00003186 self.assertAlmostEqual(1.00000001, 1.0)
3187 self.assertNotAlmostEqual(1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003188 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003189 self.assertAlmostEqual, 1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003190 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003191 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003192
Benjamin Petersone1759f82009-06-30 23:35:19 +00003193 self.assertAlmostEqual(1.1, 1.0, places=0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003194 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003195 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003196
Benjamin Petersone1759f82009-06-30 23:35:19 +00003197 self.assertAlmostEqual(0, .1+.1j, places=0)
3198 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003199 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003200 self.assertAlmostEqual, 0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003201 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003202 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003203
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003204 self.assertAlmostEqual(float('inf'), float('inf'))
3205 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3206 float('inf'), float('inf'))
3207
3208
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003209 def test_assertRaises(self):
3210 def _raise(e):
3211 raise e
3212 self.assertRaises(KeyError, _raise, KeyError)
3213 self.assertRaises(KeyError, _raise, KeyError("key"))
3214 try:
3215 self.assertRaises(KeyError, lambda: None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003216 except self.failureException as e:
Ezio Melottib58e0bd2010-01-23 15:40:09 +00003217 self.assertIn("KeyError not raised", str(e))
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003218 else:
3219 self.fail("assertRaises() didn't fail")
3220 try:
3221 self.assertRaises(KeyError, _raise, ValueError)
3222 except ValueError:
3223 pass
3224 else:
3225 self.fail("assertRaises() didn't let exception pass through")
Ezio Melotti49008232010-02-08 21:57:48 +00003226 with self.assertRaises(KeyError) as cm:
3227 try:
3228 raise KeyError
3229 except Exception as e:
3230 exc = e
3231 raise
3232 self.assertIs(cm.exception, exc)
3233
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003234 with self.assertRaises(KeyError):
3235 raise KeyError("key")
3236 try:
3237 with self.assertRaises(KeyError):
3238 pass
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003239 except self.failureException as e:
Ezio Melottib58e0bd2010-01-23 15:40:09 +00003240 self.assertIn("KeyError not raised", str(e))
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003241 else:
3242 self.fail("assertRaises() didn't fail")
3243 try:
3244 with self.assertRaises(KeyError):
3245 raise ValueError
3246 except ValueError:
3247 pass
3248 else:
3249 self.fail("assertRaises() didn't let exception pass through")
3250
3251
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003252class TestLongMessage(TestCase):
3253 """Test that the individual asserts honour longMessage.
3254 This actually tests all the message behaviour for
3255 asserts that use longMessage."""
3256
3257 def setUp(self):
3258 class TestableTestFalse(TestCase):
3259 longMessage = False
3260 failureException = self.failureException
3261
3262 def testTest(self):
3263 pass
3264
3265 class TestableTestTrue(TestCase):
3266 longMessage = True
3267 failureException = self.failureException
3268
3269 def testTest(self):
3270 pass
3271
3272 self.testableTrue = TestableTestTrue('testTest')
3273 self.testableFalse = TestableTestFalse('testTest')
3274
3275 def testDefault(self):
3276 self.assertFalse(TestCase.longMessage)
3277
3278 def test_formatMsg(self):
3279 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3280 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3281
3282 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3283 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3284
Benjamin Peterson847a4112010-03-14 15:04:17 +00003285 # This blows up if _formatMessage uses string concatenation
3286 self.testableTrue._formatMessage(object(), 'foo')
3287
3288 def test_formatMessage_unicode_error(self):
3289 with warnings.catch_warnings(record=True):
3290 # This causes a UnicodeWarning due to its craziness
3291 one = ''.join(chr(i) for i in range(255))
3292 # this used to cause a UnicodeDecodeError constructing msg
3293 self.testableTrue._formatMessage(one, '\uFFFD')
3294
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003295 def assertMessages(self, methodName, args, errors):
3296 def getMethod(i):
3297 useTestableFalse = i < 2
3298 if useTestableFalse:
3299 test = self.testableFalse
3300 else:
3301 test = self.testableTrue
3302 return getattr(test, methodName)
3303
3304 for i, expected_regexp in enumerate(errors):
3305 testMethod = getMethod(i)
3306 kwargs = {}
3307 withMsg = i % 2
3308 if withMsg:
3309 kwargs = {"msg": "oops"}
3310
3311 with self.assertRaisesRegexp(self.failureException,
3312 expected_regexp=expected_regexp):
3313 testMethod(*args, **kwargs)
3314
3315 def testAssertTrue(self):
3316 self.assertMessages('assertTrue', (False,),
3317 ["^False is not True$", "^oops$", "^False is not True$",
3318 "^False is not True : oops$"])
3319
3320 def testAssertFalse(self):
3321 self.assertMessages('assertFalse', (True,),
3322 ["^True is not False$", "^oops$", "^True is not False$",
3323 "^True is not False : oops$"])
3324
3325 def testNotEqual(self):
3326 self.assertMessages('assertNotEqual', (1, 1),
3327 ["^1 == 1$", "^oops$", "^1 == 1$",
3328 "^1 == 1 : oops$"])
3329
3330 def testAlmostEqual(self):
3331 self.assertMessages('assertAlmostEqual', (1, 2),
3332 ["^1 != 2 within 7 places$", "^oops$",
3333 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3334
3335 def testNotAlmostEqual(self):
3336 self.assertMessages('assertNotAlmostEqual', (1, 1),
3337 ["^1 == 1 within 7 places$", "^oops$",
3338 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3339
3340 def test_baseAssertEqual(self):
3341 self.assertMessages('_baseAssertEqual', (1, 2),
3342 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3343
3344 def testAssertSequenceEqual(self):
3345 # Error messages are multiline so not testing on full message
3346 # assertTupleEqual and assertListEqual delegate to this method
3347 self.assertMessages('assertSequenceEqual', ([], [None]),
3348 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3349 r"\+ \[None\] : oops$"])
3350
3351 def testAssertSetEqual(self):
3352 self.assertMessages('assertSetEqual', (set(), set([None])),
3353 ["None$", "^oops$", "None$",
3354 "None : oops$"])
3355
3356 def testAssertIn(self):
3357 self.assertMessages('assertIn', (None, []),
3358 ['^None not found in \[\]$', "^oops$",
3359 '^None not found in \[\]$',
3360 '^None not found in \[\] : oops$'])
3361
3362 def testAssertNotIn(self):
3363 self.assertMessages('assertNotIn', (None, [None]),
3364 ['^None unexpectedly found in \[None\]$', "^oops$",
3365 '^None unexpectedly found in \[None\]$',
3366 '^None unexpectedly found in \[None\] : oops$'])
3367
3368 def testAssertDictEqual(self):
3369 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3370 [r"\+ \{'key': 'value'\}$", "^oops$",
3371 "\+ \{'key': 'value'\}$",
3372 "\+ \{'key': 'value'\} : oops$"])
3373
3374 def testAssertDictContainsSubset(self):
3375 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3376 ["^Missing: 'key'$", "^oops$",
3377 "^Missing: 'key'$",
3378 "^Missing: 'key' : oops$"])
3379
Michael Foord8442a602010-03-20 16:58:04 +00003380 def testAssertItemsEqual(self):
3381 self.assertMessages('assertItemsEqual', ([], [None]),
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003382 [r"\[None\]$", "^oops$",
3383 r"\[None\]$",
3384 r"\[None\] : oops$"])
3385
3386 def testAssertMultiLineEqual(self):
3387 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3388 [r"\+ foo$", "^oops$",
3389 r"\+ foo$",
3390 r"\+ foo : oops$"])
3391
3392 def testAssertLess(self):
3393 self.assertMessages('assertLess', (2, 1),
3394 ["^2 not less than 1$", "^oops$",
3395 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3396
3397 def testAssertLessEqual(self):
3398 self.assertMessages('assertLessEqual', (2, 1),
3399 ["^2 not less than or equal to 1$", "^oops$",
3400 "^2 not less than or equal to 1$",
3401 "^2 not less than or equal to 1 : oops$"])
3402
3403 def testAssertGreater(self):
3404 self.assertMessages('assertGreater', (1, 2),
3405 ["^1 not greater than 2$", "^oops$",
3406 "^1 not greater than 2$",
3407 "^1 not greater than 2 : oops$"])
3408
3409 def testAssertGreaterEqual(self):
3410 self.assertMessages('assertGreaterEqual', (1, 2),
3411 ["^1 not greater than or equal to 2$", "^oops$",
3412 "^1 not greater than or equal to 2$",
3413 "^1 not greater than or equal to 2 : oops$"])
3414
3415 def testAssertIsNone(self):
3416 self.assertMessages('assertIsNone', ('not None',),
3417 ["^'not None' is not None$", "^oops$",
3418 "^'not None' is not None$",
3419 "^'not None' is not None : oops$"])
3420
3421 def testAssertIsNotNone(self):
3422 self.assertMessages('assertIsNotNone', (None,),
3423 ["^unexpectedly None$", "^oops$",
3424 "^unexpectedly None$",
3425 "^unexpectedly None : oops$"])
3426
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00003427 def testAssertIs(self):
3428 self.assertMessages('assertIs', (None, 'foo'),
3429 ["^None is not 'foo'$", "^oops$",
3430 "^None is not 'foo'$",
3431 "^None is not 'foo' : oops$"])
3432
3433 def testAssertIsNot(self):
3434 self.assertMessages('assertIsNot', (None, None),
3435 ["^unexpectedly identical: None$", "^oops$",
3436 "^unexpectedly identical: None$",
3437 "^unexpectedly identical: None : oops$"])
3438
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003439
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003440class TestCleanUp(TestCase):
3441
3442 def testCleanUp(self):
3443 class TestableTest(TestCase):
3444 def testNothing(self):
3445 pass
3446
3447 test = TestableTest('testNothing')
3448 self.assertEqual(test._cleanups, [])
3449
3450 cleanups = []
3451
3452 def cleanup1(*args, **kwargs):
3453 cleanups.append((1, args, kwargs))
3454
3455 def cleanup2(*args, **kwargs):
3456 cleanups.append((2, args, kwargs))
3457
3458 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3459 test.addCleanup(cleanup2)
3460
3461 self.assertEqual(test._cleanups,
3462 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3463 (cleanup2, (), {})])
3464
3465 result = test.doCleanups()
3466 self.assertTrue(result)
3467
3468 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3469
3470 def testCleanUpWithErrors(self):
3471 class TestableTest(TestCase):
3472 def testNothing(self):
3473 pass
3474
3475 class MockResult(object):
3476 errors = []
3477 def addError(self, test, exc_info):
3478 self.errors.append((test, exc_info))
3479
3480 result = MockResult()
3481 test = TestableTest('testNothing')
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00003482 test._resultForDoCleanups = result
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003483
3484 exc1 = Exception('foo')
3485 exc2 = Exception('bar')
3486 def cleanup1():
3487 raise exc1
3488
3489 def cleanup2():
3490 raise exc2
3491
3492 test.addCleanup(cleanup1)
3493 test.addCleanup(cleanup2)
3494
3495 self.assertFalse(test.doCleanups())
3496
3497 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3498 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3499 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3500
3501 def testCleanupInRun(self):
3502 blowUp = False
3503 ordering = []
3504
3505 class TestableTest(TestCase):
3506 def setUp(self):
3507 ordering.append('setUp')
3508 if blowUp:
3509 raise Exception('foo')
3510
3511 def testNothing(self):
3512 ordering.append('test')
3513
3514 def tearDown(self):
3515 ordering.append('tearDown')
3516
3517 test = TestableTest('testNothing')
3518
3519 def cleanup1():
3520 ordering.append('cleanup1')
3521 def cleanup2():
3522 ordering.append('cleanup2')
3523 test.addCleanup(cleanup1)
3524 test.addCleanup(cleanup2)
3525
3526 def success(some_test):
3527 self.assertEqual(some_test, test)
3528 ordering.append('success')
3529
3530 result = unittest.TestResult()
3531 result.addSuccess = success
3532
3533 test.run(result)
3534 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3535 'cleanup2', 'cleanup1', 'success'])
3536
3537 blowUp = True
3538 ordering = []
3539 test = TestableTest('testNothing')
3540 test.addCleanup(cleanup1)
3541 test.run(result)
3542 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3543
3544
3545class Test_TestProgram(TestCase):
3546
3547 # Horrible white box test
3548 def testNoExit(self):
3549 result = object()
3550 test = object()
3551
3552 class FakeRunner(object):
3553 def run(self, test):
3554 self.test = test
3555 return result
3556
3557 runner = FakeRunner()
3558
Benjamin Petersond2397752009-06-27 23:45:02 +00003559 oldParseArgs = TestProgram.parseArgs
3560 def restoreParseArgs():
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003561 TestProgram.parseArgs = oldParseArgs
Benjamin Petersond2397752009-06-27 23:45:02 +00003562 TestProgram.parseArgs = lambda *args: None
3563 self.addCleanup(restoreParseArgs)
3564
3565 def removeTest():
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003566 del TestProgram.test
Benjamin Petersond2397752009-06-27 23:45:02 +00003567 TestProgram.test = test
3568 self.addCleanup(removeTest)
3569
3570 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3571
3572 self.assertEqual(program.result, result)
3573 self.assertEqual(runner.test, test)
3574 self.assertEqual(program.verbosity, 2)
3575
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003576 class FooBar(unittest.TestCase):
3577 def testPass(self):
3578 assert True
3579 def testFail(self):
3580 assert False
3581
3582 class FooBarLoader(unittest.TestLoader):
3583 """Test loader that returns a suite containing FooBar."""
3584 def loadTestsFromModule(self, module):
3585 return self.suiteClass(
3586 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3587
3588
3589 def test_NonExit(self):
3590 program = unittest.main(exit=False,
3591 argv=["foobar"],
3592 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3593 testLoader=self.FooBarLoader())
3594 self.assertTrue(hasattr(program, 'result'))
3595
3596
3597 def test_Exit(self):
3598 self.assertRaises(
3599 SystemExit,
3600 unittest.main,
3601 argv=["foobar"],
3602 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3603 exit=True,
3604 testLoader=self.FooBarLoader())
3605
3606
3607 def test_ExitAsDefault(self):
3608 self.assertRaises(
3609 SystemExit,
3610 unittest.main,
3611 argv=["foobar"],
3612 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3613 testLoader=self.FooBarLoader())
3614
3615
3616class Test_TextTestRunner(TestCase):
3617 """Tests for TextTestRunner."""
3618
3619 def test_works_with_result_without_startTestRun_stopTestRun(self):
3620 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3621 separator2 = ''
3622 def printErrors(self):
3623 pass
3624
3625 class Runner(unittest.TextTestRunner):
3626 def __init__(self):
3627 super(Runner, self).__init__(io.StringIO())
3628
3629 def _makeResult(self):
3630 return OldTextResult()
3631
3632 runner = Runner()
3633 runner.run(unittest.TestSuite())
3634
3635 def test_startTestRun_stopTestRun_called(self):
3636 class LoggingTextResult(LoggingResult):
3637 separator2 = ''
3638 def printErrors(self):
3639 pass
3640
3641 class LoggingRunner(unittest.TextTestRunner):
3642 def __init__(self, events):
3643 super(LoggingRunner, self).__init__(io.StringIO())
3644 self._events = events
3645
3646 def _makeResult(self):
3647 return LoggingTextResult(self._events)
3648
3649 events = []
3650 runner = LoggingRunner(events)
3651 runner.run(unittest.TestSuite())
3652 expected = ['startTestRun', 'stopTestRun']
3653 self.assertEqual(events, expected)
3654
Antoine Pitrouc63ecee2009-11-10 21:34:48 +00003655 def test_pickle_unpickle(self):
3656 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3657 # required by test_multiprocessing under Windows (in verbose mode).
3658 stream = io.StringIO("foo")
3659 runner = unittest.TextTestRunner(stream)
3660 for protocol in range(2, pickle.HIGHEST_PROTOCOL + 1):
3661 s = pickle.dumps(runner, protocol)
3662 obj = pickle.loads(s)
3663 # StringIO objects never compare equal, a cheap test instead.
3664 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3665
Michael Foord34c94622010-02-10 15:51:42 +00003666 def test_resultclass(self):
3667 def MockResultClass(*args):
3668 return args
3669 STREAM = object()
3670 DESCRIPTIONS = object()
3671 VERBOSITY = object()
3672 runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY,
3673 resultclass=MockResultClass)
3674 self.assertEqual(runner.resultclass, MockResultClass)
3675
3676 expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY)
3677 self.assertEqual(runner._makeResult(), expectedresult)
3678
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003679
Benjamin Petersond2397752009-06-27 23:45:02 +00003680class TestDiscovery(TestCase):
3681
3682 # Heavily mocked tests so I can avoid hitting the filesystem
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003683 def test_get_name_from_path(self):
Benjamin Petersond2397752009-06-27 23:45:02 +00003684 loader = unittest.TestLoader()
Benjamin Petersond2397752009-06-27 23:45:02 +00003685 loader._top_level_dir = '/foo'
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003686 name = loader._get_name_from_path('/foo/bar/baz.py')
3687 self.assertEqual(name, 'bar.baz')
Benjamin Petersond2397752009-06-27 23:45:02 +00003688
3689 if not __debug__:
3690 # asserts are off
3691 return
3692
3693 with self.assertRaises(AssertionError):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003694 loader._get_name_from_path('/bar/baz.py')
Benjamin Petersond2397752009-06-27 23:45:02 +00003695
3696 def test_find_tests(self):
3697 loader = unittest.TestLoader()
3698
3699 original_listdir = os.listdir
3700 def restore_listdir():
3701 os.listdir = original_listdir
3702 original_isfile = os.path.isfile
3703 def restore_isfile():
3704 os.path.isfile = original_isfile
3705 original_isdir = os.path.isdir
3706 def restore_isdir():
3707 os.path.isdir = original_isdir
3708
3709 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003710 'test.foo', 'test-not-a-module.py', 'another_dir'],
Benjamin Petersond2397752009-06-27 23:45:02 +00003711 ['test3.py', 'test4.py', ]]
3712 os.listdir = lambda path: path_lists.pop(0)
3713 self.addCleanup(restore_listdir)
3714
3715 def isdir(path):
3716 return path.endswith('dir')
3717 os.path.isdir = isdir
3718 self.addCleanup(restore_isdir)
3719
3720 def isfile(path):
3721 # another_dir is not a package and so shouldn't be recursed into
3722 return not path.endswith('dir') and not 'another_dir' in path
3723 os.path.isfile = isfile
3724 self.addCleanup(restore_isfile)
3725
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003726 loader._get_module_from_name = lambda path: path + ' module'
Benjamin Petersond2397752009-06-27 23:45:02 +00003727 loader.loadTestsFromModule = lambda module: module + ' tests'
3728
3729 loader._top_level_dir = '/foo'
3730 suite = list(loader._find_tests('/foo', 'test*.py'))
3731
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003732 expected = [name + ' module tests' for name in
3733 ('test1', 'test2')]
3734 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3735 ('test3', 'test4')])
Benjamin Petersond2397752009-06-27 23:45:02 +00003736 self.assertEqual(suite, expected)
3737
3738 def test_find_tests_with_package(self):
3739 loader = unittest.TestLoader()
3740
3741 original_listdir = os.listdir
3742 def restore_listdir():
3743 os.listdir = original_listdir
3744 original_isfile = os.path.isfile
3745 def restore_isfile():
3746 os.path.isfile = original_isfile
3747 original_isdir = os.path.isdir
3748 def restore_isdir():
3749 os.path.isdir = original_isdir
3750
3751 directories = ['a_directory', 'test_directory', 'test_directory2']
3752 path_lists = [directories, [], [], []]
3753 os.listdir = lambda path: path_lists.pop(0)
3754 self.addCleanup(restore_listdir)
3755
3756 os.path.isdir = lambda path: True
3757 self.addCleanup(restore_isdir)
3758
3759 os.path.isfile = lambda path: os.path.basename(path) not in directories
3760 self.addCleanup(restore_isfile)
3761
3762 class Module(object):
3763 paths = []
3764 load_tests_args = []
3765
3766 def __init__(self, path):
3767 self.path = path
3768 self.paths.append(path)
3769 if os.path.basename(path) == 'test_directory':
3770 def load_tests(loader, tests, pattern):
3771 self.load_tests_args.append((loader, tests, pattern))
3772 return 'load_tests'
3773 self.load_tests = load_tests
3774
3775 def __eq__(self, other):
3776 return self.path == other.path
3777
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003778 loader._get_module_from_name = lambda name: Module(name)
Benjamin Petersond2397752009-06-27 23:45:02 +00003779 def loadTestsFromModule(module, use_load_tests):
3780 if use_load_tests:
3781 raise self.failureException('use_load_tests should be False for packages')
3782 return module.path + ' module tests'
3783 loader.loadTestsFromModule = loadTestsFromModule
3784
3785 loader._top_level_dir = '/foo'
3786 # this time no '.py' on the pattern so that it can match
3787 # a test package
3788 suite = list(loader._find_tests('/foo', 'test*'))
3789
3790 # We should have loaded tests from the test_directory package by calling load_tests
3791 # and directly from the test_directory2 package
3792 self.assertEqual(suite,
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003793 ['load_tests', 'test_directory2' + ' module tests'])
3794 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Benjamin Petersond2397752009-06-27 23:45:02 +00003795
3796 # load_tests should have been called once with loader, tests and pattern
3797 self.assertEqual(Module.load_tests_args,
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003798 [(loader, 'test_directory' + ' module tests', 'test*')])
Benjamin Petersond2397752009-06-27 23:45:02 +00003799
3800 def test_discover(self):
3801 loader = unittest.TestLoader()
3802
3803 original_isfile = os.path.isfile
3804 def restore_isfile():
3805 os.path.isfile = original_isfile
3806
3807 os.path.isfile = lambda path: False
3808 self.addCleanup(restore_isfile)
3809
Nick Coghlan6ead5522009-10-18 13:19:33 +00003810 orig_sys_path = sys.path[:]
3811 def restore_path():
3812 sys.path[:] = orig_sys_path
3813 self.addCleanup(restore_path)
Benjamin Petersond2397752009-06-27 23:45:02 +00003814
Nick Coghlan6ead5522009-10-18 13:19:33 +00003815 full_path = os.path.abspath(os.path.normpath('/foo'))
Benjamin Petersond2397752009-06-27 23:45:02 +00003816 with self.assertRaises(ImportError):
3817 loader.discover('/foo/bar', top_level_dir='/foo')
3818
3819 self.assertEqual(loader._top_level_dir, full_path)
3820 self.assertIn(full_path, sys.path)
3821
3822 os.path.isfile = lambda path: True
3823 _find_tests_args = []
3824 def _find_tests(start_dir, pattern):
3825 _find_tests_args.append((start_dir, pattern))
3826 return ['tests']
3827 loader._find_tests = _find_tests
3828 loader.suiteClass = str
3829
3830 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3831
3832 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3833 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3834 self.assertEqual(suite, "['tests']")
3835 self.assertEqual(loader._top_level_dir, top_level_dir)
3836 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlan6ead5522009-10-18 13:19:33 +00003837 self.assertIn(top_level_dir, sys.path)
Benjamin Petersond2397752009-06-27 23:45:02 +00003838
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003839 def test_discover_with_modules_that_fail_to_import(self):
3840 loader = unittest.TestLoader()
3841
3842 listdir = os.listdir
3843 os.listdir = lambda _: ['test_this_does_not_exist.py']
3844 isfile = os.path.isfile
3845 os.path.isfile = lambda _: True
Nick Coghlan6ead5522009-10-18 13:19:33 +00003846 orig_sys_path = sys.path[:]
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003847 def restore():
3848 os.path.isfile = isfile
3849 os.listdir = listdir
Nick Coghlan6ead5522009-10-18 13:19:33 +00003850 sys.path[:] = orig_sys_path
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003851 self.addCleanup(restore)
3852
3853 suite = loader.discover('.')
Nick Coghlan6ead5522009-10-18 13:19:33 +00003854 self.assertIn(os.getcwd(), sys.path)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003855 self.assertEqual(suite.countTestCases(), 1)
3856 test = list(list(suite)[0])[0] # extract test from suite
3857
3858 with self.assertRaises(ImportError):
3859 test.test_this_does_not_exist()
3860
Benjamin Petersond2397752009-06-27 23:45:02 +00003861 def test_command_line_handling_parseArgs(self):
3862 # Haha - take that uninstantiable class
3863 program = object.__new__(TestProgram)
3864
3865 args = []
3866 def do_discovery(argv):
3867 args.extend(argv)
3868 program._do_discovery = do_discovery
3869 program.parseArgs(['something', 'discover'])
3870 self.assertEqual(args, [])
3871
3872 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3873 self.assertEqual(args, ['foo', 'bar'])
3874
3875 def test_command_line_handling_do_discovery_too_many_arguments(self):
3876 class Stop(Exception):
3877 pass
3878 def usageExit():
3879 raise Stop
3880
3881 program = object.__new__(TestProgram)
3882 program.usageExit = usageExit
3883
3884 with self.assertRaises(Stop):
3885 # too many args
3886 program._do_discovery(['one', 'two', 'three', 'four'])
3887
3888
3889 def test_command_line_handling_do_discovery_calls_loader(self):
3890 program = object.__new__(TestProgram)
3891
3892 class Loader(object):
3893 args = []
3894 def discover(self, start_dir, pattern, top_level_dir):
3895 self.args.append((start_dir, pattern, top_level_dir))
3896 return 'tests'
3897
3898 program._do_discovery(['-v'], Loader=Loader)
3899 self.assertEqual(program.verbosity, 2)
3900 self.assertEqual(program.test, 'tests')
3901 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3902
3903 Loader.args = []
3904 program = object.__new__(TestProgram)
3905 program._do_discovery(['--verbose'], Loader=Loader)
3906 self.assertEqual(program.test, 'tests')
3907 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3908
3909 Loader.args = []
3910 program = object.__new__(TestProgram)
3911 program._do_discovery([], Loader=Loader)
3912 self.assertEqual(program.test, 'tests')
3913 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3914
3915 Loader.args = []
3916 program = object.__new__(TestProgram)
3917 program._do_discovery(['fish'], Loader=Loader)
3918 self.assertEqual(program.test, 'tests')
3919 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3920
3921 Loader.args = []
3922 program = object.__new__(TestProgram)
3923 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3924 self.assertEqual(program.test, 'tests')
3925 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3926
3927 Loader.args = []
3928 program = object.__new__(TestProgram)
3929 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3930 self.assertEqual(program.test, 'tests')
3931 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3932
3933 Loader.args = []
3934 program = object.__new__(TestProgram)
3935 program._do_discovery(['-s', 'fish'], Loader=Loader)
3936 self.assertEqual(program.test, 'tests')
3937 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3938
3939 Loader.args = []
3940 program = object.__new__(TestProgram)
3941 program._do_discovery(['-t', 'fish'], Loader=Loader)
3942 self.assertEqual(program.test, 'tests')
3943 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3944
3945 Loader.args = []
3946 program = object.__new__(TestProgram)
3947 program._do_discovery(['-p', 'fish'], Loader=Loader)
3948 self.assertEqual(program.test, 'tests')
3949 self.assertEqual(Loader.args, [('.', 'fish', None)])
3950
3951 Loader.args = []
3952 program = object.__new__(TestProgram)
3953 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3954 self.assertEqual(program.test, 'tests')
3955 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3956 self.assertEqual(program.verbosity, 2)
3957
3958
Benjamin Peterson847a4112010-03-14 15:04:17 +00003959class TestSetups(unittest.TestCase):
3960
3961 def getRunner(self):
3962 return unittest.TextTestRunner(resultclass=resultFactory,
3963 stream=io.StringIO())
3964 def runTests(self, *cases):
3965 suite = unittest.TestSuite()
3966 for case in cases:
3967 tests = unittest.defaultTestLoader.loadTestsFromTestCase(case)
3968 suite.addTests(tests)
3969
3970 runner = self.getRunner()
3971
3972 # creating a nested suite exposes some potential bugs
3973 realSuite = unittest.TestSuite()
3974 realSuite.addTest(suite)
3975 # adding empty suites to the end exposes potential bugs
3976 suite.addTest(unittest.TestSuite())
3977 realSuite.addTest(unittest.TestSuite())
3978 return runner.run(realSuite)
3979
3980 def test_setup_class(self):
3981 class Test(unittest.TestCase):
3982 setUpCalled = 0
3983 @classmethod
3984 def setUpClass(cls):
3985 Test.setUpCalled += 1
3986 unittest.TestCase.setUpClass()
3987 def test_one(self):
3988 pass
3989 def test_two(self):
3990 pass
3991
3992 result = self.runTests(Test)
3993
3994 self.assertEqual(Test.setUpCalled, 1)
3995 self.assertEqual(result.testsRun, 2)
3996 self.assertEqual(len(result.errors), 0)
3997
3998 def test_teardown_class(self):
3999 class Test(unittest.TestCase):
4000 tearDownCalled = 0
4001 @classmethod
4002 def tearDownClass(cls):
4003 Test.tearDownCalled += 1
4004 unittest.TestCase.tearDownClass()
4005 def test_one(self):
4006 pass
4007 def test_two(self):
4008 pass
4009
4010 result = self.runTests(Test)
4011
4012 self.assertEqual(Test.tearDownCalled, 1)
4013 self.assertEqual(result.testsRun, 2)
4014 self.assertEqual(len(result.errors), 0)
4015
4016 def test_teardown_class_two_classes(self):
4017 class Test(unittest.TestCase):
4018 tearDownCalled = 0
4019 @classmethod
4020 def tearDownClass(cls):
4021 Test.tearDownCalled += 1
4022 unittest.TestCase.tearDownClass()
4023 def test_one(self):
4024 pass
4025 def test_two(self):
4026 pass
4027
4028 class Test2(unittest.TestCase):
4029 tearDownCalled = 0
4030 @classmethod
4031 def tearDownClass(cls):
4032 Test2.tearDownCalled += 1
4033 unittest.TestCase.tearDownClass()
4034 def test_one(self):
4035 pass
4036 def test_two(self):
4037 pass
4038
4039 result = self.runTests(Test, Test2)
4040
4041 self.assertEqual(Test.tearDownCalled, 1)
4042 self.assertEqual(Test2.tearDownCalled, 1)
4043 self.assertEqual(result.testsRun, 4)
4044 self.assertEqual(len(result.errors), 0)
4045
4046 def test_error_in_setupclass(self):
4047 class BrokenTest(unittest.TestCase):
4048 @classmethod
4049 def setUpClass(cls):
4050 raise TypeError('foo')
4051 def test_one(self):
4052 pass
4053 def test_two(self):
4054 pass
4055
4056 result = self.runTests(BrokenTest)
4057
4058 self.assertEqual(result.testsRun, 0)
4059 self.assertEqual(len(result.errors), 1)
4060 error, _ = result.errors[0]
4061 self.assertEqual(str(error),
4062 'classSetUp (%s.BrokenTest)' % __name__)
4063
4064 def test_error_in_teardown_class(self):
4065 class Test(unittest.TestCase):
4066 tornDown = 0
4067 @classmethod
4068 def tearDownClass(cls):
4069 Test.tornDown += 1
4070 raise TypeError('foo')
4071 def test_one(self):
4072 pass
4073 def test_two(self):
4074 pass
4075
4076 class Test2(unittest.TestCase):
4077 tornDown = 0
4078 @classmethod
4079 def tearDownClass(cls):
4080 Test2.tornDown += 1
4081 raise TypeError('foo')
4082 def test_one(self):
4083 pass
4084 def test_two(self):
4085 pass
4086
4087 result = self.runTests(Test, Test2)
4088 self.assertEqual(result.testsRun, 4)
4089 self.assertEqual(len(result.errors), 2)
4090 self.assertEqual(Test.tornDown, 1)
4091 self.assertEqual(Test2.tornDown, 1)
4092
4093 error, _ = result.errors[0]
4094 self.assertEqual(str(error),
4095 'classTearDown (%s.Test)' % __name__)
4096
4097 def test_class_not_torndown_when_setup_fails(self):
4098 class Test(unittest.TestCase):
4099 tornDown = False
4100 @classmethod
4101 def setUpClass(cls):
4102 raise TypeError
4103 @classmethod
4104 def tearDownClass(cls):
4105 Test.tornDown = True
4106 raise TypeError('foo')
4107 def test_one(self):
4108 pass
4109
4110 self.runTests(Test)
4111 self.assertFalse(Test.tornDown)
4112
4113 def test_class_not_setup_or_torndown_when_skipped(self):
4114 class Test(unittest.TestCase):
4115 classSetUp = False
4116 tornDown = False
4117 @classmethod
4118 def setUpClass(cls):
4119 Test.classSetUp = True
4120 @classmethod
4121 def tearDownClass(cls):
4122 Test.tornDown = True
4123 def test_one(self):
4124 pass
4125
4126 Test = unittest.skip("hop")(Test)
4127 self.runTests(Test)
4128 self.assertFalse(Test.classSetUp)
4129 self.assertFalse(Test.tornDown)
4130
4131 def test_setup_teardown_order_with_pathological_suite(self):
4132 results = []
4133
4134 class Module1(object):
4135 @staticmethod
4136 def setUpModule():
4137 results.append('Module1.setUpModule')
4138 @staticmethod
4139 def tearDownModule():
4140 results.append('Module1.tearDownModule')
4141
4142 class Module2(object):
4143 @staticmethod
4144 def setUpModule():
4145 results.append('Module2.setUpModule')
4146 @staticmethod
4147 def tearDownModule():
4148 results.append('Module2.tearDownModule')
4149
4150 class Test1(unittest.TestCase):
4151 @classmethod
4152 def setUpClass(cls):
4153 results.append('setup 1')
4154 @classmethod
4155 def tearDownClass(cls):
4156 results.append('teardown 1')
4157 def testOne(self):
4158 results.append('Test1.testOne')
4159 def testTwo(self):
4160 results.append('Test1.testTwo')
4161
4162 class Test2(unittest.TestCase):
4163 @classmethod
4164 def setUpClass(cls):
4165 results.append('setup 2')
4166 @classmethod
4167 def tearDownClass(cls):
4168 results.append('teardown 2')
4169 def testOne(self):
4170 results.append('Test2.testOne')
4171 def testTwo(self):
4172 results.append('Test2.testTwo')
4173
4174 class Test3(unittest.TestCase):
4175 @classmethod
4176 def setUpClass(cls):
4177 results.append('setup 3')
4178 @classmethod
4179 def tearDownClass(cls):
4180 results.append('teardown 3')
4181 def testOne(self):
4182 results.append('Test3.testOne')
4183 def testTwo(self):
4184 results.append('Test3.testTwo')
4185
4186 Test1.__module__ = Test2.__module__ = 'Module'
4187 Test3.__module__ = 'Module2'
4188 sys.modules['Module'] = Module1
4189 sys.modules['Module2'] = Module2
4190
4191 first = unittest.TestSuite((Test1('testOne'),))
4192 second = unittest.TestSuite((Test1('testTwo'),))
4193 third = unittest.TestSuite((Test2('testOne'),))
4194 fourth = unittest.TestSuite((Test2('testTwo'),))
4195 fifth = unittest.TestSuite((Test3('testOne'),))
4196 sixth = unittest.TestSuite((Test3('testTwo'),))
4197 suite = unittest.TestSuite((first, second, third, fourth, fifth, sixth))
4198
4199 runner = self.getRunner()
4200 result = runner.run(suite)
4201 self.assertEqual(result.testsRun, 6)
4202 self.assertEqual(len(result.errors), 0)
4203
4204 self.assertEqual(results,
4205 ['Module1.setUpModule', 'setup 1',
4206 'Test1.testOne', 'Test1.testTwo', 'teardown 1',
4207 'setup 2', 'Test2.testOne', 'Test2.testTwo',
4208 'teardown 2', 'Module1.tearDownModule',
4209 'Module2.setUpModule', 'setup 3',
4210 'Test3.testOne', 'Test3.testTwo',
4211 'teardown 3', 'Module2.tearDownModule'])
4212
4213 def test_setup_module(self):
4214 class Module(object):
4215 moduleSetup = 0
4216 @staticmethod
4217 def setUpModule():
4218 Module.moduleSetup += 1
4219
4220 class Test(unittest.TestCase):
4221 def test_one(self):
4222 pass
4223 def test_two(self):
4224 pass
4225 Test.__module__ = 'Module'
4226 sys.modules['Module'] = Module
4227
4228 result = self.runTests(Test)
4229 self.assertEqual(Module.moduleSetup, 1)
4230 self.assertEqual(result.testsRun, 2)
4231 self.assertEqual(len(result.errors), 0)
4232
4233 def test_error_in_setup_module(self):
4234 class Module(object):
4235 moduleSetup = 0
4236 moduleTornDown = 0
4237 @staticmethod
4238 def setUpModule():
4239 Module.moduleSetup += 1
4240 raise TypeError('foo')
4241 @staticmethod
4242 def tearDownModule():
4243 Module.moduleTornDown += 1
4244
4245 class Test(unittest.TestCase):
4246 classSetUp = False
4247 classTornDown = False
4248 @classmethod
4249 def setUpClass(cls):
4250 Test.classSetUp = True
4251 @classmethod
4252 def tearDownClass(cls):
4253 Test.classTornDown = True
4254 def test_one(self):
4255 pass
4256 def test_two(self):
4257 pass
4258
4259 class Test2(unittest.TestCase):
4260 def test_one(self):
4261 pass
4262 def test_two(self):
4263 pass
4264 Test.__module__ = 'Module'
4265 Test2.__module__ = 'Module'
4266 sys.modules['Module'] = Module
4267
4268 result = self.runTests(Test, Test2)
4269 self.assertEqual(Module.moduleSetup, 1)
4270 self.assertEqual(Module.moduleTornDown, 0)
4271 self.assertEqual(result.testsRun, 0)
4272 self.assertFalse(Test.classSetUp)
4273 self.assertFalse(Test.classTornDown)
4274 self.assertEqual(len(result.errors), 1)
4275 error, _ = result.errors[0]
4276 self.assertEqual(str(error), 'setUpModule (Module)')
4277
4278 def test_testcase_with_missing_module(self):
4279 class Test(unittest.TestCase):
4280 def test_one(self):
4281 pass
4282 def test_two(self):
4283 pass
4284 Test.__module__ = 'Module'
4285 sys.modules.pop('Module', None)
4286
4287 result = self.runTests(Test)
4288 self.assertEqual(result.testsRun, 2)
4289
4290 def test_teardown_module(self):
4291 class Module(object):
4292 moduleTornDown = 0
4293 @staticmethod
4294 def tearDownModule():
4295 Module.moduleTornDown += 1
4296
4297 class Test(unittest.TestCase):
4298 def test_one(self):
4299 pass
4300 def test_two(self):
4301 pass
4302 Test.__module__ = 'Module'
4303 sys.modules['Module'] = Module
4304
4305 result = self.runTests(Test)
4306 self.assertEqual(Module.moduleTornDown, 1)
4307 self.assertEqual(result.testsRun, 2)
4308 self.assertEqual(len(result.errors), 0)
4309
4310 def test_error_in_teardown_module(self):
4311 class Module(object):
4312 moduleTornDown = 0
4313 @staticmethod
4314 def tearDownModule():
4315 Module.moduleTornDown += 1
4316 raise TypeError('foo')
4317
4318 class Test(unittest.TestCase):
4319 classSetUp = False
4320 classTornDown = False
4321 @classmethod
4322 def setUpClass(cls):
4323 Test.classSetUp = True
4324 @classmethod
4325 def tearDownClass(cls):
4326 Test.classTornDown = True
4327 def test_one(self):
4328 pass
4329 def test_two(self):
4330 pass
4331
4332 class Test2(unittest.TestCase):
4333 def test_one(self):
4334 pass
4335 def test_two(self):
4336 pass
4337 Test.__module__ = 'Module'
4338 Test2.__module__ = 'Module'
4339 sys.modules['Module'] = Module
4340
4341 result = self.runTests(Test, Test2)
4342 self.assertEqual(Module.moduleTornDown, 1)
4343 self.assertEqual(result.testsRun, 4)
4344 self.assertTrue(Test.classSetUp)
4345 self.assertTrue(Test.classTornDown)
4346 self.assertEqual(len(result.errors), 1)
4347 error, _ = result.errors[0]
4348 self.assertEqual(str(error), 'tearDownModule (Module)')
4349
Jim Fultonfafd8742004-08-28 15:22:12 +00004350######################################################################
4351## Main
4352######################################################################
4353
4354def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004355 support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00004356 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Benjamin Peterson25c95f12009-05-08 20:42:26 +00004357 Test_TestSkipping, Test_Assertions, TestLongMessage,
Benjamin Peterson847a4112010-03-14 15:04:17 +00004358 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner,
4359 Test_OldTestResult, TestSetups)
Jim Fultonfafd8742004-08-28 15:22:12 +00004360
Guido van Rossumd8faa362007-04-27 19:54:29 +00004361if __name__ == "__main__":
Jim Fultonfafd8742004-08-28 15:22:12 +00004362 test_main()