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