blob: e5219fdbcbe341cba18123a2e4487b781a974079 [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
Jim Fultonfafd8742004-08-28 15:22:12 +000021
Guido van Rossumd8faa362007-04-27 19:54:29 +000022### Support code
23################################################################
Jim Fultonfafd8742004-08-28 15:22:12 +000024
Guido van Rossumd8faa362007-04-27 19:54:29 +000025class LoggingResult(unittest.TestResult):
26 def __init__(self, log):
27 self._events = log
Guido van Rossumcd16bf62007-06-13 18:07:49 +000028 super().__init__()
Guido van Rossumd8faa362007-04-27 19:54:29 +000029
30 def startTest(self, test):
31 self._events.append('startTest')
Guido van Rossumcd16bf62007-06-13 18:07:49 +000032 super().startTest(test)
Guido van Rossumd8faa362007-04-27 19:54:29 +000033
Benjamin Peterson25c95f12009-05-08 20:42:26 +000034 def startTestRun(self):
35 self._events.append('startTestRun')
36 super(LoggingResult, self).startTestRun()
37
Guido van Rossumd8faa362007-04-27 19:54:29 +000038 def stopTest(self, test):
39 self._events.append('stopTest')
Guido van Rossumcd16bf62007-06-13 18:07:49 +000040 super().stopTest(test)
Guido van Rossumd8faa362007-04-27 19:54:29 +000041
Benjamin Peterson25c95f12009-05-08 20:42:26 +000042 def stopTestRun(self):
43 self._events.append('stopTestRun')
44 super(LoggingResult, self).stopTestRun()
45
Guido van Rossumd8faa362007-04-27 19:54:29 +000046 def addFailure(self, *args):
47 self._events.append('addFailure')
Guido van Rossumcd16bf62007-06-13 18:07:49 +000048 super().addFailure(*args)
Guido van Rossumd8faa362007-04-27 19:54:29 +000049
Benjamin Peterson5254c042009-03-23 22:25:03 +000050 def addSuccess(self, *args):
51 self._events.append('addSuccess')
52 super(LoggingResult, self).addSuccess(*args)
53
Guido van Rossumd8faa362007-04-27 19:54:29 +000054 def addError(self, *args):
55 self._events.append('addError')
Guido van Rossumcd16bf62007-06-13 18:07:49 +000056 super().addError(*args)
Guido van Rossumd8faa362007-04-27 19:54:29 +000057
Benjamin Peterson5254c042009-03-23 22:25:03 +000058 def addSkip(self, *args):
59 self._events.append('addSkip')
60 super(LoggingResult, self).addSkip(*args)
61
62 def addExpectedFailure(self, *args):
63 self._events.append('addExpectedFailure')
64 super(LoggingResult, self).addExpectedFailure(*args)
65
66 def addUnexpectedSuccess(self, *args):
67 self._events.append('addUnexpectedSuccess')
68 super(LoggingResult, self).addUnexpectedSuccess(*args)
69
70
Guido van Rossumd8faa362007-04-27 19:54:29 +000071class TestEquality(object):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000072 """Used as a mixin for TestCase"""
73
Guido van Rossumd8faa362007-04-27 19:54:29 +000074 # Check for a valid __eq__ implementation
75 def test_eq(self):
76 for obj_1, obj_2 in self.eq_pairs:
77 self.assertEqual(obj_1, obj_2)
78 self.assertEqual(obj_2, obj_1)
79
80 # Check for a valid __ne__ implementation
81 def test_ne(self):
82 for obj_1, obj_2 in self.ne_pairs:
Benjamin Petersone1759f82009-06-30 23:35:19 +000083 self.assertNotEqual(obj_1, obj_2)
84 self.assertNotEqual(obj_2, obj_1)
Guido van Rossumd8faa362007-04-27 19:54:29 +000085
86class TestHashing(object):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000087 """Used as a mixin for TestCase"""
88
Guido van Rossumd8faa362007-04-27 19:54:29 +000089 # Check for a valid __hash__ implementation
90 def test_hash(self):
91 for obj_1, obj_2 in self.eq_pairs:
92 try:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000093 if not hash(obj_1) == hash(obj_2):
94 self.fail("%r and %r do not hash equal" % (obj_1, obj_2))
Guido van Rossumd8faa362007-04-27 19:54:29 +000095 except KeyboardInterrupt:
96 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +000097 except Exception as e:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000098 self.fail("Problem hashing %r and %r: %s" % (obj_1, obj_2, e))
Guido van Rossumd8faa362007-04-27 19:54:29 +000099
100 for obj_1, obj_2 in self.ne_pairs:
101 try:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000102 if hash(obj_1) == hash(obj_2):
103 self.fail("%s and %s hash equal, but shouldn't" %
104 (obj_1, obj_2))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000105 except KeyboardInterrupt:
106 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +0000107 except Exception as e:
108 self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e))
109
110
Benjamin Peterson5254c042009-03-23 22:25:03 +0000111# List subclass we can add attributes to.
112class MyClassSuite(list):
113
Benjamin Peterson14a3dd72009-05-25 00:51:58 +0000114 def __init__(self, tests):
Benjamin Peterson5254c042009-03-23 22:25:03 +0000115 super(MyClassSuite, self).__init__(tests)
116
117
Guido van Rossumd8faa362007-04-27 19:54:29 +0000118################################################################
119### /Support code
120
121class Test_TestLoader(TestCase):
122
123 ### Tests for TestLoader.loadTestsFromTestCase
124 ################################################################
125
126 # "Return a suite of all tests cases contained in the TestCase-derived
127 # class testCaseClass"
128 def test_loadTestsFromTestCase(self):
129 class Foo(unittest.TestCase):
130 def test_1(self): pass
131 def test_2(self): pass
132 def foo_bar(self): pass
133
134 tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
135
136 loader = unittest.TestLoader()
137 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
138
139 # "Return a suite of all tests cases contained in the TestCase-derived
140 # class testCaseClass"
141 #
142 # Make sure it does the right thing even if no tests were found
143 def test_loadTestsFromTestCase__no_matches(self):
144 class Foo(unittest.TestCase):
145 def foo_bar(self): pass
146
147 empty_suite = unittest.TestSuite()
148
149 loader = unittest.TestLoader()
150 self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite)
151
152 # "Return a suite of all tests cases contained in the TestCase-derived
153 # class testCaseClass"
154 #
155 # What happens if loadTestsFromTestCase() is given an object
156 # that isn't a subclass of TestCase? Specifically, what happens
157 # if testCaseClass is a subclass of TestSuite?
158 #
159 # This is checked for specifically in the code, so we better add a
160 # test for it.
161 def test_loadTestsFromTestCase__TestSuite_subclass(self):
162 class NotATestCase(unittest.TestSuite):
163 pass
164
165 loader = unittest.TestLoader()
166 try:
167 loader.loadTestsFromTestCase(NotATestCase)
168 except TypeError:
169 pass
170 else:
171 self.fail('Should raise TypeError')
172
173 # "Return a suite of all tests cases contained in the TestCase-derived
174 # class testCaseClass"
175 #
176 # Make sure loadTestsFromTestCase() picks up the default test method
177 # name (as specified by TestCase), even though the method name does
178 # not match the default TestLoader.testMethodPrefix string
179 def test_loadTestsFromTestCase__default_method_name(self):
180 class Foo(unittest.TestCase):
181 def runTest(self):
182 pass
183
184 loader = unittest.TestLoader()
185 # This has to be false for the test to succeed
Benjamin Petersone1759f82009-06-30 23:35:19 +0000186 self.assertFalse('runTest'.startswith(loader.testMethodPrefix))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000187
188 suite = loader.loadTestsFromTestCase(Foo)
Ezio Melottie9615932010-01-24 19:26:24 +0000189 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000190 self.assertEqual(list(suite), [Foo('runTest')])
191
192 ################################################################
193 ### /Tests for TestLoader.loadTestsFromTestCase
194
195 ### Tests for TestLoader.loadTestsFromModule
196 ################################################################
197
198 # "This method searches `module` for classes derived from TestCase"
199 def test_loadTestsFromModule__TestCase_subclass(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000200 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000201 class MyTestCase(unittest.TestCase):
202 def test(self):
203 pass
204 m.testcase_1 = MyTestCase
205
206 loader = unittest.TestLoader()
207 suite = loader.loadTestsFromModule(m)
Ezio Melottie9615932010-01-24 19:26:24 +0000208 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000209
210 expected = [loader.suiteClass([MyTestCase('test')])]
211 self.assertEqual(list(suite), expected)
212
213 # "This method searches `module` for classes derived from TestCase"
214 #
215 # What happens if no tests are found (no TestCase instances)?
216 def test_loadTestsFromModule__no_TestCase_instances(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000217 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000218
219 loader = unittest.TestLoader()
220 suite = loader.loadTestsFromModule(m)
Ezio Melottie9615932010-01-24 19:26:24 +0000221 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000222 self.assertEqual(list(suite), [])
223
224 # "This method searches `module` for classes derived from TestCase"
225 #
226 # What happens if no tests are found (TestCases instances, but no tests)?
227 def test_loadTestsFromModule__no_TestCase_tests(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000228 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000229 class MyTestCase(unittest.TestCase):
230 pass
231 m.testcase_1 = MyTestCase
232
233 loader = unittest.TestLoader()
234 suite = loader.loadTestsFromModule(m)
Ezio Melottie9615932010-01-24 19:26:24 +0000235 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000236
237 self.assertEqual(list(suite), [loader.suiteClass()])
238
239 # "This method searches `module` for classes derived from TestCase"s
240 #
241 # What happens if loadTestsFromModule() is given something other
242 # than a module?
243 #
244 # XXX Currently, it succeeds anyway. This flexibility
245 # should either be documented or loadTestsFromModule() should
246 # raise a TypeError
247 #
248 # XXX Certain people are using this behaviour. We'll add a test for it
249 def test_loadTestsFromModule__not_a_module(self):
250 class MyTestCase(unittest.TestCase):
251 def test(self):
252 pass
253
254 class NotAModule(object):
255 test_2 = MyTestCase
256
257 loader = unittest.TestLoader()
258 suite = loader.loadTestsFromModule(NotAModule)
259
260 reference = [unittest.TestSuite([MyTestCase('test')])]
261 self.assertEqual(list(suite), reference)
262
Benjamin Petersond2397752009-06-27 23:45:02 +0000263
264 # Check that loadTestsFromModule honors (or not) a module
265 # with a load_tests function.
266 def test_loadTestsFromModule__load_tests(self):
267 m = types.ModuleType('m')
268 class MyTestCase(unittest.TestCase):
269 def test(self):
270 pass
271 m.testcase_1 = MyTestCase
272
273 load_tests_args = []
274 def load_tests(loader, tests, pattern):
Michael Foord41647d62010-02-06 00:26:13 +0000275 self.assertIsInstance(tests, unittest.TestSuite)
Benjamin Petersond2397752009-06-27 23:45:02 +0000276 load_tests_args.extend((loader, tests, pattern))
277 return tests
278 m.load_tests = load_tests
279
280 loader = unittest.TestLoader()
281 suite = loader.loadTestsFromModule(m)
Michael Foord41647d62010-02-06 00:26:13 +0000282 self.assertIsInstance(suite, unittest.TestSuite)
Benjamin Petersond2397752009-06-27 23:45:02 +0000283 self.assertEquals(load_tests_args, [loader, suite, None])
284
285 load_tests_args = []
286 suite = loader.loadTestsFromModule(m, use_load_tests=False)
287 self.assertEquals(load_tests_args, [])
288
Guido van Rossumd8faa362007-04-27 19:54:29 +0000289 ################################################################
290 ### /Tests for TestLoader.loadTestsFromModule()
291
292 ### Tests for TestLoader.loadTestsFromName()
293 ################################################################
294
295 # "The specifier name is a ``dotted name'' that may resolve either to
296 # a module, a test case class, a TestSuite instance, a test method
297 # within a test case class, or a callable object which returns a
298 # TestCase or TestSuite instance."
299 #
300 # Is ValueError raised in response to an empty name?
301 def test_loadTestsFromName__empty_name(self):
302 loader = unittest.TestLoader()
303
304 try:
305 loader.loadTestsFromName('')
306 except ValueError as e:
307 self.assertEqual(str(e), "Empty module name")
308 else:
309 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
310
311 # "The specifier name is a ``dotted name'' that may resolve either to
312 # a module, a test case class, a TestSuite instance, a test method
313 # within a test case class, or a callable object which returns a
314 # TestCase or TestSuite instance."
315 #
316 # What happens when the name contains invalid characters?
317 def test_loadTestsFromName__malformed_name(self):
318 loader = unittest.TestLoader()
319
320 # XXX Should this raise ValueError or ImportError?
321 try:
322 loader.loadTestsFromName('abc () //')
323 except ValueError:
324 pass
325 except ImportError:
326 pass
327 else:
328 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
329
330 # "The specifier name is a ``dotted name'' that may resolve ... to a
331 # module"
332 #
333 # What happens when a module by that name can't be found?
334 def test_loadTestsFromName__unknown_module_name(self):
335 loader = unittest.TestLoader()
336
337 try:
338 loader.loadTestsFromName('sdasfasfasdf')
339 except ImportError as e:
340 self.assertEqual(str(e), "No module named sdasfasfasdf")
341 else:
342 self.fail("TestLoader.loadTestsFromName failed to raise ImportError")
343
344 # "The specifier name is a ``dotted name'' that may resolve either to
345 # a module, a test case class, a TestSuite instance, a test method
346 # within a test case class, or a callable object which returns a
347 # TestCase or TestSuite instance."
348 #
349 # What happens when the module is found, but the attribute can't?
350 def test_loadTestsFromName__unknown_attr_name(self):
351 loader = unittest.TestLoader()
352
353 try:
354 loader.loadTestsFromName('unittest.sdasfasfasdf')
355 except AttributeError as e:
356 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
357 else:
358 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
359
360 # "The specifier name is a ``dotted name'' that may resolve either to
361 # a module, a test case class, a TestSuite instance, a test method
362 # within a test case class, or a callable object which returns a
363 # TestCase or TestSuite instance."
364 #
365 # What happens when we provide the module, but the attribute can't be
366 # found?
367 def test_loadTestsFromName__relative_unknown_name(self):
368 loader = unittest.TestLoader()
369
370 try:
371 loader.loadTestsFromName('sdasfasfasdf', unittest)
372 except AttributeError as e:
373 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
374 else:
375 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
376
377 # "The specifier name is a ``dotted name'' that may resolve either to
378 # a module, a test case class, a TestSuite instance, a test method
379 # within a test case class, or a callable object which returns a
380 # TestCase or TestSuite instance."
381 # ...
382 # "The method optionally resolves name relative to the given module"
383 #
384 # Does loadTestsFromName raise ValueError when passed an empty
385 # name relative to a provided module?
386 #
387 # XXX Should probably raise a ValueError instead of an AttributeError
388 def test_loadTestsFromName__relative_empty_name(self):
389 loader = unittest.TestLoader()
390
391 try:
392 loader.loadTestsFromName('', unittest)
393 except AttributeError as e:
394 pass
395 else:
396 self.fail("Failed to raise AttributeError")
397
398 # "The specifier name is a ``dotted name'' that may resolve either to
399 # a module, a test case class, a TestSuite instance, a test method
400 # within a test case class, or a callable object which returns a
401 # TestCase or TestSuite instance."
402 # ...
403 # "The method optionally resolves name relative to the given module"
404 #
405 # What happens when an impossible name is given, relative to the provided
406 # `module`?
407 def test_loadTestsFromName__relative_malformed_name(self):
408 loader = unittest.TestLoader()
409
410 # XXX Should this raise AttributeError or ValueError?
411 try:
412 loader.loadTestsFromName('abc () //', unittest)
413 except ValueError:
414 pass
415 except AttributeError:
416 pass
417 else:
418 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
419
420 # "The method optionally resolves name relative to the given module"
421 #
422 # Does loadTestsFromName raise TypeError when the `module` argument
423 # isn't a module object?
424 #
425 # XXX Accepts the not-a-module object, ignorning the object's type
426 # This should raise an exception or the method name should be changed
427 #
428 # XXX Some people are relying on this, so keep it for now
429 def test_loadTestsFromName__relative_not_a_module(self):
430 class MyTestCase(unittest.TestCase):
431 def test(self):
432 pass
433
434 class NotAModule(object):
435 test_2 = MyTestCase
436
437 loader = unittest.TestLoader()
438 suite = loader.loadTestsFromName('test_2', NotAModule)
439
440 reference = [MyTestCase('test')]
441 self.assertEqual(list(suite), reference)
442
443 # "The specifier name is a ``dotted name'' that may resolve either to
444 # a module, a test case class, a TestSuite instance, a test method
445 # within a test case class, or a callable object which returns a
446 # TestCase or TestSuite instance."
447 #
448 # Does it raise an exception if the name resolves to an invalid
449 # object?
450 def test_loadTestsFromName__relative_bad_object(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000451 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000452 m.testcase_1 = object()
453
454 loader = unittest.TestLoader()
455 try:
456 loader.loadTestsFromName('testcase_1', m)
457 except TypeError:
458 pass
459 else:
460 self.fail("Should have raised TypeError")
461
462 # "The specifier name is a ``dotted name'' that may
463 # resolve either to ... a test case class"
464 def test_loadTestsFromName__relative_TestCase_subclass(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000465 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000466 class MyTestCase(unittest.TestCase):
467 def test(self):
468 pass
469 m.testcase_1 = MyTestCase
470
471 loader = unittest.TestLoader()
472 suite = loader.loadTestsFromName('testcase_1', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000473 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000474 self.assertEqual(list(suite), [MyTestCase('test')])
475
476 # "The specifier name is a ``dotted name'' that may resolve either to
477 # a module, a test case class, a TestSuite instance, a test method
478 # within a test case class, or a callable object which returns a
479 # TestCase or TestSuite instance."
480 def test_loadTestsFromName__relative_TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000481 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000482 class MyTestCase(unittest.TestCase):
483 def test(self):
484 pass
485 m.testsuite = unittest.TestSuite([MyTestCase('test')])
486
487 loader = unittest.TestLoader()
488 suite = loader.loadTestsFromName('testsuite', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000489 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000490
491 self.assertEqual(list(suite), [MyTestCase('test')])
492
493 # "The specifier name is a ``dotted name'' that may resolve ... to
494 # ... a test method within a test case class"
495 def test_loadTestsFromName__relative_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000496 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000497 class MyTestCase(unittest.TestCase):
498 def test(self):
499 pass
500 m.testcase_1 = MyTestCase
501
502 loader = unittest.TestLoader()
503 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000504 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000505
506 self.assertEqual(list(suite), [MyTestCase('test')])
507
508 # "The specifier name is a ``dotted name'' that may resolve either to
509 # a module, a test case class, a TestSuite instance, a test method
510 # within a test case class, or a callable object which returns a
511 # TestCase or TestSuite instance."
512 #
513 # Does loadTestsFromName() raise the proper exception when trying to
514 # resolve "a test method within a test case class" that doesn't exist
515 # for the given name (relative to a provided module)?
516 def test_loadTestsFromName__relative_invalid_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000517 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000518 class MyTestCase(unittest.TestCase):
519 def test(self):
520 pass
521 m.testcase_1 = MyTestCase
522
523 loader = unittest.TestLoader()
524 try:
525 loader.loadTestsFromName('testcase_1.testfoo', m)
526 except AttributeError as e:
527 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
528 else:
529 self.fail("Failed to raise AttributeError")
530
531 # "The specifier name is a ``dotted name'' that may resolve ... to
532 # ... a callable object which returns a ... TestSuite instance"
533 def test_loadTestsFromName__callable__TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000534 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000535 testcase_1 = unittest.FunctionTestCase(lambda: None)
536 testcase_2 = unittest.FunctionTestCase(lambda: None)
537 def return_TestSuite():
538 return unittest.TestSuite([testcase_1, testcase_2])
539 m.return_TestSuite = return_TestSuite
540
541 loader = unittest.TestLoader()
542 suite = loader.loadTestsFromName('return_TestSuite', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000543 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000544 self.assertEqual(list(suite), [testcase_1, testcase_2])
545
546 # "The specifier name is a ``dotted name'' that may resolve ... to
547 # ... a callable object which returns a TestCase ... instance"
548 def test_loadTestsFromName__callable__TestCase_instance(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000549 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000550 testcase_1 = unittest.FunctionTestCase(lambda: None)
551 def return_TestCase():
552 return testcase_1
553 m.return_TestCase = return_TestCase
554
555 loader = unittest.TestLoader()
556 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000557 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000558 self.assertEqual(list(suite), [testcase_1])
559
560 # "The specifier name is a ``dotted name'' that may resolve ... to
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000561 # ... a callable object which returns a TestCase ... instance"
562 #*****************************************************************
563 #Override the suiteClass attribute to ensure that the suiteClass
564 #attribute is used
565 def test_loadTestsFromName__callable__TestCase_instance_ProperSuiteClass(self):
566 class SubTestSuite(unittest.TestSuite):
567 pass
568 m = types.ModuleType('m')
569 testcase_1 = unittest.FunctionTestCase(lambda: None)
570 def return_TestCase():
571 return testcase_1
572 m.return_TestCase = return_TestCase
573
574 loader = unittest.TestLoader()
575 loader.suiteClass = SubTestSuite
576 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000577 self.assertIsInstance(suite, loader.suiteClass)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000578 self.assertEqual(list(suite), [testcase_1])
579
580 # "The specifier name is a ``dotted name'' that may resolve ... to
581 # ... a test method within a test case class"
582 #*****************************************************************
583 #Override the suiteClass attribute to ensure that the suiteClass
584 #attribute is used
585 def test_loadTestsFromName__relative_testmethod_ProperSuiteClass(self):
586 class SubTestSuite(unittest.TestSuite):
587 pass
588 m = types.ModuleType('m')
589 class MyTestCase(unittest.TestCase):
590 def test(self):
591 pass
592 m.testcase_1 = MyTestCase
593
594 loader = unittest.TestLoader()
595 loader.suiteClass=SubTestSuite
596 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000597 self.assertIsInstance(suite, loader.suiteClass)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000598
599 self.assertEqual(list(suite), [MyTestCase('test')])
600
601 # "The specifier name is a ``dotted name'' that may resolve ... to
Guido van Rossumd8faa362007-04-27 19:54:29 +0000602 # ... a callable object which returns a TestCase or TestSuite instance"
603 #
604 # What happens if the callable returns something else?
605 def test_loadTestsFromName__callable__wrong_type(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000606 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000607 def return_wrong():
608 return 6
609 m.return_wrong = return_wrong
610
611 loader = unittest.TestLoader()
612 try:
613 suite = loader.loadTestsFromName('return_wrong', m)
614 except TypeError:
615 pass
616 else:
617 self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
618
619 # "The specifier can refer to modules and packages which have not been
620 # imported; they will be imported as a side-effect"
621 def test_loadTestsFromName__module_not_loaded(self):
622 # We're going to try to load this module as a side-effect, so it
623 # better not be loaded before we try.
624 #
625 # Why pick audioop? Google shows it isn't used very often, so there's
626 # a good chance that it won't be imported when this test is run
627 module_name = 'audioop'
628
Guido van Rossumd8faa362007-04-27 19:54:29 +0000629 if module_name in sys.modules:
630 del sys.modules[module_name]
631
632 loader = unittest.TestLoader()
633 try:
634 suite = loader.loadTestsFromName(module_name)
635
Ezio Melottie9615932010-01-24 19:26:24 +0000636 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000637 self.assertEqual(list(suite), [])
638
639 # audioop should now be loaded, thanks to loadTestsFromName()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000640 self.assertIn(module_name, sys.modules)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000641 finally:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000642 if module_name in sys.modules:
643 del sys.modules[module_name]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000644
645 ################################################################
646 ### Tests for TestLoader.loadTestsFromName()
647
648 ### Tests for TestLoader.loadTestsFromNames()
649 ################################################################
650
651 # "Similar to loadTestsFromName(), but takes a sequence of names rather
652 # than a single name."
653 #
654 # What happens if that sequence of names is empty?
655 def test_loadTestsFromNames__empty_name_list(self):
656 loader = unittest.TestLoader()
657
658 suite = loader.loadTestsFromNames([])
Ezio Melottie9615932010-01-24 19:26:24 +0000659 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000660 self.assertEqual(list(suite), [])
661
662 # "Similar to loadTestsFromName(), but takes a sequence of names rather
663 # than a single name."
664 # ...
665 # "The method optionally resolves name relative to the given module"
666 #
667 # What happens if that sequence of names is empty?
668 #
669 # XXX Should this raise a ValueError or just return an empty TestSuite?
670 def test_loadTestsFromNames__relative_empty_name_list(self):
671 loader = unittest.TestLoader()
672
673 suite = loader.loadTestsFromNames([], unittest)
Ezio Melottie9615932010-01-24 19:26:24 +0000674 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000675 self.assertEqual(list(suite), [])
676
677 # "The specifier name is a ``dotted name'' that may resolve either to
678 # a module, a test case class, a TestSuite instance, a test method
679 # within a test case class, or a callable object which returns a
680 # TestCase or TestSuite instance."
681 #
682 # Is ValueError raised in response to an empty name?
683 def test_loadTestsFromNames__empty_name(self):
684 loader = unittest.TestLoader()
685
686 try:
687 loader.loadTestsFromNames([''])
688 except ValueError as e:
689 self.assertEqual(str(e), "Empty module name")
690 else:
691 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
692
693 # "The specifier name is a ``dotted name'' that may resolve either to
694 # a module, a test case class, a TestSuite instance, a test method
695 # within a test case class, or a callable object which returns a
696 # TestCase or TestSuite instance."
697 #
698 # What happens when presented with an impossible module name?
699 def test_loadTestsFromNames__malformed_name(self):
700 loader = unittest.TestLoader()
701
702 # XXX Should this raise ValueError or ImportError?
703 try:
704 loader.loadTestsFromNames(['abc () //'])
705 except ValueError:
706 pass
707 except ImportError:
708 pass
709 else:
710 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
711
712 # "The specifier name is a ``dotted name'' that may resolve either to
713 # a module, a test case class, a TestSuite instance, a test method
714 # within a test case class, or a callable object which returns a
715 # TestCase or TestSuite instance."
716 #
717 # What happens when no module can be found for the given name?
718 def test_loadTestsFromNames__unknown_module_name(self):
719 loader = unittest.TestLoader()
720
721 try:
722 loader.loadTestsFromNames(['sdasfasfasdf'])
723 except ImportError as e:
724 self.assertEqual(str(e), "No module named sdasfasfasdf")
725 else:
726 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
727
728 # "The specifier name is a ``dotted name'' that may resolve either to
729 # a module, a test case class, a TestSuite instance, a test method
730 # within a test case class, or a callable object which returns a
731 # TestCase or TestSuite instance."
732 #
733 # What happens when the module can be found, but not the attribute?
734 def test_loadTestsFromNames__unknown_attr_name(self):
735 loader = unittest.TestLoader()
736
737 try:
738 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
739 except AttributeError as e:
740 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
741 else:
742 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
743
744 # "The specifier name is a ``dotted name'' that may resolve either to
745 # a module, a test case class, a TestSuite instance, a test method
746 # within a test case class, or a callable object which returns a
747 # TestCase or TestSuite instance."
748 # ...
749 # "The method optionally resolves name relative to the given module"
750 #
751 # What happens when given an unknown attribute on a specified `module`
752 # argument?
753 def test_loadTestsFromNames__unknown_name_relative_1(self):
754 loader = unittest.TestLoader()
755
756 try:
757 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
758 except AttributeError as e:
759 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
760 else:
761 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
762
763 # "The specifier name is a ``dotted name'' that may resolve either to
764 # a module, a test case class, a TestSuite instance, a test method
765 # within a test case class, or a callable object which returns a
766 # TestCase or TestSuite instance."
767 # ...
768 # "The method optionally resolves name relative to the given module"
769 #
770 # Do unknown attributes (relative to a provided module) still raise an
771 # exception even in the presence of valid attribute names?
772 def test_loadTestsFromNames__unknown_name_relative_2(self):
773 loader = unittest.TestLoader()
774
775 try:
776 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
777 except AttributeError as e:
778 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
779 else:
780 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
781
782 # "The specifier name is a ``dotted name'' that may resolve either to
783 # a module, a test case class, a TestSuite instance, a test method
784 # within a test case class, or a callable object which returns a
785 # TestCase or TestSuite instance."
786 # ...
787 # "The method optionally resolves name relative to the given module"
788 #
789 # What happens when faced with the empty string?
790 #
791 # XXX This currently raises AttributeError, though ValueError is probably
792 # more appropriate
793 def test_loadTestsFromNames__relative_empty_name(self):
794 loader = unittest.TestLoader()
795
796 try:
797 loader.loadTestsFromNames([''], unittest)
798 except AttributeError:
799 pass
800 else:
801 self.fail("Failed to raise ValueError")
802
803 # "The specifier name is a ``dotted name'' that may resolve either to
804 # a module, a test case class, a TestSuite instance, a test method
805 # within a test case class, or a callable object which returns a
806 # TestCase or TestSuite instance."
807 # ...
808 # "The method optionally resolves name relative to the given module"
809 #
810 # What happens when presented with an impossible attribute name?
811 def test_loadTestsFromNames__relative_malformed_name(self):
812 loader = unittest.TestLoader()
813
814 # XXX Should this raise AttributeError or ValueError?
815 try:
816 loader.loadTestsFromNames(['abc () //'], unittest)
817 except AttributeError:
818 pass
819 except ValueError:
820 pass
821 else:
822 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
823
824 # "The method optionally resolves name relative to the given module"
825 #
826 # Does loadTestsFromNames() make sure the provided `module` is in fact
827 # a module?
828 #
829 # XXX This validation is currently not done. This flexibility should
830 # either be documented or a TypeError should be raised.
831 def test_loadTestsFromNames__relative_not_a_module(self):
832 class MyTestCase(unittest.TestCase):
833 def test(self):
834 pass
835
836 class NotAModule(object):
837 test_2 = MyTestCase
838
839 loader = unittest.TestLoader()
840 suite = loader.loadTestsFromNames(['test_2'], NotAModule)
841
842 reference = [unittest.TestSuite([MyTestCase('test')])]
843 self.assertEqual(list(suite), reference)
844
845 # "The specifier name is a ``dotted name'' that may resolve either to
846 # a module, a test case class, a TestSuite instance, a test method
847 # within a test case class, or a callable object which returns a
848 # TestCase or TestSuite instance."
849 #
850 # Does it raise an exception if the name resolves to an invalid
851 # object?
852 def test_loadTestsFromNames__relative_bad_object(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000853 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000854 m.testcase_1 = object()
855
856 loader = unittest.TestLoader()
857 try:
858 loader.loadTestsFromNames(['testcase_1'], m)
859 except TypeError:
860 pass
861 else:
862 self.fail("Should have raised TypeError")
863
864 # "The specifier name is a ``dotted name'' that may resolve ... to
865 # ... a test case class"
866 def test_loadTestsFromNames__relative_TestCase_subclass(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000867 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000868 class MyTestCase(unittest.TestCase):
869 def test(self):
870 pass
871 m.testcase_1 = MyTestCase
872
873 loader = unittest.TestLoader()
874 suite = loader.loadTestsFromNames(['testcase_1'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000875 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000876
877 expected = loader.suiteClass([MyTestCase('test')])
878 self.assertEqual(list(suite), [expected])
879
880 # "The specifier name is a ``dotted name'' that may resolve ... to
881 # ... a TestSuite instance"
882 def test_loadTestsFromNames__relative_TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000883 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000884 class MyTestCase(unittest.TestCase):
885 def test(self):
886 pass
887 m.testsuite = unittest.TestSuite([MyTestCase('test')])
888
889 loader = unittest.TestLoader()
890 suite = loader.loadTestsFromNames(['testsuite'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000891 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000892
893 self.assertEqual(list(suite), [m.testsuite])
894
895 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
896 # test method within a test case class"
897 def test_loadTestsFromNames__relative_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000898 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000899 class MyTestCase(unittest.TestCase):
900 def test(self):
901 pass
902 m.testcase_1 = MyTestCase
903
904 loader = unittest.TestLoader()
905 suite = loader.loadTestsFromNames(['testcase_1.test'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000906 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000907
908 ref_suite = unittest.TestSuite([MyTestCase('test')])
909 self.assertEqual(list(suite), [ref_suite])
910
911 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
912 # test method within a test case class"
913 #
914 # Does the method gracefully handle names that initially look like they
915 # resolve to "a test method within a test case class" but don't?
916 def test_loadTestsFromNames__relative_invalid_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000917 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000918 class MyTestCase(unittest.TestCase):
919 def test(self):
920 pass
921 m.testcase_1 = MyTestCase
922
923 loader = unittest.TestLoader()
924 try:
925 loader.loadTestsFromNames(['testcase_1.testfoo'], m)
926 except AttributeError as e:
927 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
928 else:
929 self.fail("Failed to raise AttributeError")
930
931 # "The specifier name is a ``dotted name'' that may resolve ... to
932 # ... a callable object which returns a ... TestSuite instance"
933 def test_loadTestsFromNames__callable__TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000934 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000935 testcase_1 = unittest.FunctionTestCase(lambda: None)
936 testcase_2 = unittest.FunctionTestCase(lambda: None)
937 def return_TestSuite():
938 return unittest.TestSuite([testcase_1, testcase_2])
939 m.return_TestSuite = return_TestSuite
940
941 loader = unittest.TestLoader()
942 suite = loader.loadTestsFromNames(['return_TestSuite'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000943 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000944
945 expected = unittest.TestSuite([testcase_1, testcase_2])
946 self.assertEqual(list(suite), [expected])
947
948 # "The specifier name is a ``dotted name'' that may resolve ... to
949 # ... a callable object which returns a TestCase ... instance"
950 def test_loadTestsFromNames__callable__TestCase_instance(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000951 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000952 testcase_1 = unittest.FunctionTestCase(lambda: None)
953 def return_TestCase():
954 return testcase_1
955 m.return_TestCase = return_TestCase
956
957 loader = unittest.TestLoader()
958 suite = loader.loadTestsFromNames(['return_TestCase'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000959 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000960
961 ref_suite = unittest.TestSuite([testcase_1])
962 self.assertEqual(list(suite), [ref_suite])
963
964 # "The specifier name is a ``dotted name'' that may resolve ... to
965 # ... a callable object which returns a TestCase or TestSuite instance"
966 #
967 # Are staticmethods handled correctly?
968 def test_loadTestsFromNames__callable__call_staticmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000969 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000970 class Test1(unittest.TestCase):
971 def test(self):
972 pass
973
974 testcase_1 = Test1('test')
975 class Foo(unittest.TestCase):
976 @staticmethod
977 def foo():
978 return testcase_1
979 m.Foo = Foo
980
981 loader = unittest.TestLoader()
982 suite = loader.loadTestsFromNames(['Foo.foo'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000983 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000984
985 ref_suite = unittest.TestSuite([testcase_1])
986 self.assertEqual(list(suite), [ref_suite])
987
988 # "The specifier name is a ``dotted name'' that may resolve ... to
989 # ... a callable object which returns a TestCase or TestSuite instance"
990 #
991 # What happens when the callable returns something else?
992 def test_loadTestsFromNames__callable__wrong_type(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000993 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000994 def return_wrong():
995 return 6
996 m.return_wrong = return_wrong
997
998 loader = unittest.TestLoader()
999 try:
1000 suite = loader.loadTestsFromNames(['return_wrong'], m)
1001 except TypeError:
1002 pass
1003 else:
1004 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
1005
1006 # "The specifier can refer to modules and packages which have not been
1007 # imported; they will be imported as a side-effect"
1008 def test_loadTestsFromNames__module_not_loaded(self):
1009 # We're going to try to load this module as a side-effect, so it
1010 # better not be loaded before we try.
1011 #
1012 # Why pick audioop? Google shows it isn't used very often, so there's
1013 # a good chance that it won't be imported when this test is run
1014 module_name = 'audioop'
1015
Guido van Rossumd8faa362007-04-27 19:54:29 +00001016 if module_name in sys.modules:
1017 del sys.modules[module_name]
1018
1019 loader = unittest.TestLoader()
1020 try:
1021 suite = loader.loadTestsFromNames([module_name])
1022
Ezio Melottie9615932010-01-24 19:26:24 +00001023 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001024 self.assertEqual(list(suite), [unittest.TestSuite()])
1025
1026 # audioop should now be loaded, thanks to loadTestsFromName()
Benjamin Peterson577473f2010-01-19 00:09:57 +00001027 self.assertIn(module_name, sys.modules)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001028 finally:
Guido van Rossum360e4b82007-05-14 22:51:27 +00001029 if module_name in sys.modules:
1030 del sys.modules[module_name]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001031
1032 ################################################################
1033 ### /Tests for TestLoader.loadTestsFromNames()
1034
1035 ### Tests for TestLoader.getTestCaseNames()
1036 ################################################################
1037
1038 # "Return a sorted sequence of method names found within testCaseClass"
1039 #
1040 # Test.foobar is defined to make sure getTestCaseNames() respects
1041 # loader.testMethodPrefix
1042 def test_getTestCaseNames(self):
1043 class Test(unittest.TestCase):
1044 def test_1(self): pass
1045 def test_2(self): pass
1046 def foobar(self): pass
1047
1048 loader = unittest.TestLoader()
1049
1050 self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])
1051
1052 # "Return a sorted sequence of method names found within testCaseClass"
1053 #
1054 # Does getTestCaseNames() behave appropriately if no tests are found?
1055 def test_getTestCaseNames__no_tests(self):
1056 class Test(unittest.TestCase):
1057 def foobar(self): pass
1058
1059 loader = unittest.TestLoader()
1060
1061 self.assertEqual(loader.getTestCaseNames(Test), [])
1062
1063 # "Return a sorted sequence of method names found within testCaseClass"
1064 #
1065 # Are not-TestCases handled gracefully?
1066 #
1067 # XXX This should raise a TypeError, not return a list
1068 #
1069 # XXX It's too late in the 2.5 release cycle to fix this, but it should
1070 # probably be revisited for 2.6
1071 def test_getTestCaseNames__not_a_TestCase(self):
1072 class BadCase(int):
1073 def test_foo(self):
1074 pass
1075
1076 loader = unittest.TestLoader()
1077 names = loader.getTestCaseNames(BadCase)
1078
1079 self.assertEqual(names, ['test_foo'])
1080
1081 # "Return a sorted sequence of method names found within testCaseClass"
1082 #
1083 # Make sure inherited names are handled.
1084 #
1085 # TestP.foobar is defined to make sure getTestCaseNames() respects
1086 # loader.testMethodPrefix
1087 def test_getTestCaseNames__inheritance(self):
1088 class TestP(unittest.TestCase):
1089 def test_1(self): pass
1090 def test_2(self): pass
1091 def foobar(self): pass
1092
1093 class TestC(TestP):
1094 def test_1(self): pass
1095 def test_3(self): pass
1096
1097 loader = unittest.TestLoader()
1098
1099 names = ['test_1', 'test_2', 'test_3']
1100 self.assertEqual(loader.getTestCaseNames(TestC), names)
1101
1102 ################################################################
1103 ### /Tests for TestLoader.getTestCaseNames()
1104
1105 ### Tests for TestLoader.testMethodPrefix
1106 ################################################################
1107
1108 # "String giving the prefix of method names which will be interpreted as
1109 # test methods"
1110 #
1111 # Implicit in the documentation is that testMethodPrefix is respected by
1112 # all loadTestsFrom* methods.
1113 def test_testMethodPrefix__loadTestsFromTestCase(self):
1114 class Foo(unittest.TestCase):
1115 def test_1(self): pass
1116 def test_2(self): pass
1117 def foo_bar(self): pass
1118
1119 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1120 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1121
1122 loader = unittest.TestLoader()
1123 loader.testMethodPrefix = 'foo'
1124 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
1125
1126 loader.testMethodPrefix = 'test'
1127 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
1128
1129 # "String giving the prefix of method names which will be interpreted as
1130 # test methods"
1131 #
1132 # Implicit in the documentation is that testMethodPrefix is respected by
1133 # all loadTestsFrom* methods.
1134 def test_testMethodPrefix__loadTestsFromModule(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001135 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001136 class Foo(unittest.TestCase):
1137 def test_1(self): pass
1138 def test_2(self): pass
1139 def foo_bar(self): pass
1140 m.Foo = Foo
1141
1142 tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
1143 tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]
1144
1145 loader = unittest.TestLoader()
1146 loader.testMethodPrefix = 'foo'
1147 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
1148
1149 loader.testMethodPrefix = 'test'
1150 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
1151
1152 # "String giving the prefix of method names which will be interpreted as
1153 # test methods"
1154 #
1155 # Implicit in the documentation is that testMethodPrefix is respected by
1156 # all loadTestsFrom* methods.
1157 def test_testMethodPrefix__loadTestsFromName(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001158 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001159 class Foo(unittest.TestCase):
1160 def test_1(self): pass
1161 def test_2(self): pass
1162 def foo_bar(self): pass
1163 m.Foo = Foo
1164
1165 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1166 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1167
1168 loader = unittest.TestLoader()
1169 loader.testMethodPrefix = 'foo'
1170 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
1171
1172 loader.testMethodPrefix = 'test'
1173 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
1174
1175 # "String giving the prefix of method names which will be interpreted as
1176 # test methods"
1177 #
1178 # Implicit in the documentation is that testMethodPrefix is respected by
1179 # all loadTestsFrom* methods.
1180 def test_testMethodPrefix__loadTestsFromNames(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001181 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001182 class Foo(unittest.TestCase):
1183 def test_1(self): pass
1184 def test_2(self): pass
1185 def foo_bar(self): pass
1186 m.Foo = Foo
1187
1188 tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
1189 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1190 tests_2 = unittest.TestSuite([tests_2])
1191
1192 loader = unittest.TestLoader()
1193 loader.testMethodPrefix = 'foo'
1194 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)
1195
1196 loader.testMethodPrefix = 'test'
1197 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)
1198
1199 # "The default value is 'test'"
1200 def test_testMethodPrefix__default_value(self):
1201 loader = unittest.TestLoader()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001202 self.assertEqual(loader.testMethodPrefix, 'test')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001203
1204 ################################################################
1205 ### /Tests for TestLoader.testMethodPrefix
1206
1207 ### Tests for TestLoader.sortTestMethodsUsing
1208 ################################################################
1209
1210 # "Function to be used to compare method names when sorting them in
1211 # getTestCaseNames() and all the loadTestsFromX() methods"
1212 def test_sortTestMethodsUsing__loadTestsFromTestCase(self):
1213 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001214 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001215
1216 class Foo(unittest.TestCase):
1217 def test_1(self): pass
1218 def test_2(self): pass
1219
1220 loader = unittest.TestLoader()
1221 loader.sortTestMethodsUsing = reversed_cmp
1222
1223 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1224 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
1225
1226 # "Function to be used to compare method names when sorting them in
1227 # getTestCaseNames() and all the loadTestsFromX() methods"
1228 def test_sortTestMethodsUsing__loadTestsFromModule(self):
1229 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001230 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001231
Christian Heimes45f9af32007-11-27 21:50:00 +00001232 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001233 class Foo(unittest.TestCase):
1234 def test_1(self): pass
1235 def test_2(self): pass
1236 m.Foo = Foo
1237
1238 loader = unittest.TestLoader()
1239 loader.sortTestMethodsUsing = reversed_cmp
1240
1241 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1242 self.assertEqual(list(loader.loadTestsFromModule(m)), tests)
1243
1244 # "Function to be used to compare method names when sorting them in
1245 # getTestCaseNames() and all the loadTestsFromX() methods"
1246 def test_sortTestMethodsUsing__loadTestsFromName(self):
1247 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001248 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001249
Christian Heimes45f9af32007-11-27 21:50:00 +00001250 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001251 class Foo(unittest.TestCase):
1252 def test_1(self): pass
1253 def test_2(self): pass
1254 m.Foo = Foo
1255
1256 loader = unittest.TestLoader()
1257 loader.sortTestMethodsUsing = reversed_cmp
1258
1259 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1260 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
1261
1262 # "Function to be used to compare method names when sorting them in
1263 # getTestCaseNames() and all the loadTestsFromX() methods"
1264 def test_sortTestMethodsUsing__loadTestsFromNames(self):
1265 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001266 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001267
Christian Heimes45f9af32007-11-27 21:50:00 +00001268 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001269 class Foo(unittest.TestCase):
1270 def test_1(self): pass
1271 def test_2(self): pass
1272 m.Foo = Foo
1273
1274 loader = unittest.TestLoader()
1275 loader.sortTestMethodsUsing = reversed_cmp
1276
1277 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1278 self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)
1279
1280 # "Function to be used to compare method names when sorting them in
1281 # getTestCaseNames()"
1282 #
1283 # Does it actually affect getTestCaseNames()?
1284 def test_sortTestMethodsUsing__getTestCaseNames(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
1288 class Foo(unittest.TestCase):
1289 def test_1(self): pass
1290 def test_2(self): pass
1291
1292 loader = unittest.TestLoader()
1293 loader.sortTestMethodsUsing = reversed_cmp
1294
1295 test_names = ['test_2', 'test_1']
1296 self.assertEqual(loader.getTestCaseNames(Foo), test_names)
1297
1298 # "The default value is the built-in cmp() function"
Mark Dickinsona56c4672009-01-27 18:17:45 +00001299 # Since cmp is now defunct, we simply verify that the results
1300 # occur in the same order as they would with the default sort.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001301 def test_sortTestMethodsUsing__default_value(self):
1302 loader = unittest.TestLoader()
Mark Dickinsona56c4672009-01-27 18:17:45 +00001303
1304 class Foo(unittest.TestCase):
1305 def test_2(self): pass
1306 def test_3(self): pass
1307 def test_1(self): pass
1308
1309 test_names = ['test_2', 'test_3', 'test_1']
1310 self.assertEqual(loader.getTestCaseNames(Foo), sorted(test_names))
1311
Guido van Rossumd8faa362007-04-27 19:54:29 +00001312
1313 # "it can be set to None to disable the sort."
1314 #
1315 # XXX How is this different from reassigning cmp? Are the tests returned
1316 # in a random order or something? This behaviour should die
1317 def test_sortTestMethodsUsing__None(self):
1318 class Foo(unittest.TestCase):
1319 def test_1(self): pass
1320 def test_2(self): pass
1321
1322 loader = unittest.TestLoader()
1323 loader.sortTestMethodsUsing = None
1324
1325 test_names = ['test_2', 'test_1']
1326 self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))
1327
1328 ################################################################
1329 ### /Tests for TestLoader.sortTestMethodsUsing
1330
1331 ### Tests for TestLoader.suiteClass
1332 ################################################################
1333
1334 # "Callable object that constructs a test suite from a list of tests."
1335 def test_suiteClass__loadTestsFromTestCase(self):
1336 class Foo(unittest.TestCase):
1337 def test_1(self): pass
1338 def test_2(self): pass
1339 def foo_bar(self): pass
1340
1341 tests = [Foo('test_1'), Foo('test_2')]
1342
1343 loader = unittest.TestLoader()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001344 loader.suiteClass = list
Guido van Rossumd8faa362007-04-27 19:54:29 +00001345 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
1346
1347 # It is implicit in the documentation for TestLoader.suiteClass that
1348 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
1349 def test_suiteClass__loadTestsFromModule(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001350 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001351 class Foo(unittest.TestCase):
1352 def test_1(self): pass
1353 def test_2(self): pass
1354 def foo_bar(self): pass
1355 m.Foo = Foo
1356
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001357 tests = [[Foo('test_1'), Foo('test_2')]]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001358
1359 loader = unittest.TestLoader()
1360 loader.suiteClass = list
1361 self.assertEqual(loader.loadTestsFromModule(m), tests)
1362
1363 # It is implicit in the documentation for TestLoader.suiteClass that
1364 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
1365 def test_suiteClass__loadTestsFromName(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001366 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001367 class Foo(unittest.TestCase):
1368 def test_1(self): pass
1369 def test_2(self): pass
1370 def foo_bar(self): pass
1371 m.Foo = Foo
1372
1373 tests = [Foo('test_1'), Foo('test_2')]
1374
1375 loader = unittest.TestLoader()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001376 loader.suiteClass = list
Guido van Rossumd8faa362007-04-27 19:54:29 +00001377 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
1378
1379 # It is implicit in the documentation for TestLoader.suiteClass that
1380 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
1381 def test_suiteClass__loadTestsFromNames(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001382 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001383 class Foo(unittest.TestCase):
1384 def test_1(self): pass
1385 def test_2(self): pass
1386 def foo_bar(self): pass
1387 m.Foo = Foo
1388
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001389 tests = [[Foo('test_1'), Foo('test_2')]]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001390
1391 loader = unittest.TestLoader()
1392 loader.suiteClass = list
1393 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)
1394
1395 # "The default value is the TestSuite class"
1396 def test_suiteClass__default_value(self):
1397 loader = unittest.TestLoader()
Benjamin Petersone1759f82009-06-30 23:35:19 +00001398 self.assertTrue(loader.suiteClass is unittest.TestSuite)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001399
1400 ################################################################
1401 ### /Tests for TestLoader.suiteClass
1402
1403### Support code for Test_TestSuite
1404################################################################
1405
1406class Foo(unittest.TestCase):
1407 def test_1(self): pass
1408 def test_2(self): pass
1409 def test_3(self): pass
1410 def runTest(self): pass
1411
1412def _mk_TestSuite(*names):
1413 return unittest.TestSuite(Foo(n) for n in names)
1414
1415################################################################
1416### /Support code for Test_TestSuite
1417
1418class Test_TestSuite(TestCase, TestEquality):
1419
1420 ### Set up attributes needed by inherited tests
1421 ################################################################
1422
1423 # Used by TestEquality.test_eq
1424 eq_pairs = [(unittest.TestSuite(), unittest.TestSuite())
1425 ,(unittest.TestSuite(), unittest.TestSuite([]))
1426 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]
1427
1428 # Used by TestEquality.test_ne
1429 ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1'))
1430 ,(unittest.TestSuite([]), _mk_TestSuite('test_1'))
1431 ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3'))
1432 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]
1433
1434 ################################################################
1435 ### /Set up attributes needed by inherited tests
1436
1437 ### Tests for TestSuite.__init__
1438 ################################################################
1439
1440 # "class TestSuite([tests])"
1441 #
1442 # The tests iterable should be optional
1443 def test_init__tests_optional(self):
1444 suite = unittest.TestSuite()
1445
1446 self.assertEqual(suite.countTestCases(), 0)
1447
1448 # "class TestSuite([tests])"
1449 # ...
1450 # "If tests is given, it must be an iterable of individual test cases
1451 # or other test suites that will be used to build the suite initially"
1452 #
1453 # TestSuite should deal with empty tests iterables by allowing the
1454 # creation of an empty suite
1455 def test_init__empty_tests(self):
1456 suite = unittest.TestSuite([])
1457
1458 self.assertEqual(suite.countTestCases(), 0)
1459
1460 # "class TestSuite([tests])"
1461 # ...
1462 # "If tests is given, it must be an iterable of individual test cases
1463 # or other test suites that will be used to build the suite initially"
1464 #
1465 # TestSuite should allow any iterable to provide tests
1466 def test_init__tests_from_any_iterable(self):
1467 def tests():
1468 yield unittest.FunctionTestCase(lambda: None)
1469 yield unittest.FunctionTestCase(lambda: None)
1470
1471 suite_1 = unittest.TestSuite(tests())
1472 self.assertEqual(suite_1.countTestCases(), 2)
1473
1474 suite_2 = unittest.TestSuite(suite_1)
1475 self.assertEqual(suite_2.countTestCases(), 2)
1476
1477 suite_3 = unittest.TestSuite(set(suite_1))
1478 self.assertEqual(suite_3.countTestCases(), 2)
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 # Does TestSuite() also allow other TestSuite() instances to be present
1486 # in the tests iterable?
1487 def test_init__TestSuite_instances_in_tests(self):
1488 def tests():
1489 ftc = unittest.FunctionTestCase(lambda: None)
1490 yield unittest.TestSuite([ftc])
1491 yield unittest.FunctionTestCase(lambda: None)
1492
1493 suite = unittest.TestSuite(tests())
1494 self.assertEqual(suite.countTestCases(), 2)
1495
1496 ################################################################
1497 ### /Tests for TestSuite.__init__
1498
1499 # Container types should support the iter protocol
1500 def test_iter(self):
1501 test1 = unittest.FunctionTestCase(lambda: None)
1502 test2 = unittest.FunctionTestCase(lambda: None)
1503 suite = unittest.TestSuite((test1, test2))
1504
1505 self.assertEqual(list(suite), [test1, test2])
1506
1507 # "Return the number of tests represented by the this test object.
1508 # ...this method is also implemented by the TestSuite class, which can
1509 # return larger [greater than 1] values"
1510 #
1511 # Presumably an empty TestSuite returns 0?
1512 def test_countTestCases_zero_simple(self):
1513 suite = unittest.TestSuite()
1514
1515 self.assertEqual(suite.countTestCases(), 0)
1516
1517 # "Return the number of tests represented by the this test object.
1518 # ...this method is also implemented by the TestSuite class, which can
1519 # return larger [greater than 1] values"
1520 #
1521 # Presumably an empty TestSuite (even if it contains other empty
1522 # TestSuite instances) returns 0?
1523 def test_countTestCases_zero_nested(self):
1524 class Test1(unittest.TestCase):
1525 def test(self):
1526 pass
1527
1528 suite = unittest.TestSuite([unittest.TestSuite()])
1529
1530 self.assertEqual(suite.countTestCases(), 0)
1531
1532 # "Return the number of tests represented by the this test object.
1533 # ...this method is also implemented by the TestSuite class, which can
1534 # return larger [greater than 1] values"
1535 def test_countTestCases_simple(self):
1536 test1 = unittest.FunctionTestCase(lambda: None)
1537 test2 = unittest.FunctionTestCase(lambda: None)
1538 suite = unittest.TestSuite((test1, test2))
1539
1540 self.assertEqual(suite.countTestCases(), 2)
1541
1542 # "Return the number of tests represented by the this test object.
1543 # ...this method is also implemented by the TestSuite class, which can
1544 # return larger [greater than 1] values"
1545 #
1546 # Make sure this holds for nested TestSuite instances, too
1547 def test_countTestCases_nested(self):
1548 class Test1(unittest.TestCase):
1549 def test1(self): pass
1550 def test2(self): pass
1551
1552 test2 = unittest.FunctionTestCase(lambda: None)
1553 test3 = unittest.FunctionTestCase(lambda: None)
1554 child = unittest.TestSuite((Test1('test2'), test2))
1555 parent = unittest.TestSuite((test3, child, Test1('test1')))
1556
1557 self.assertEqual(parent.countTestCases(), 4)
1558
1559 # "Run the tests associated with this suite, collecting the result into
1560 # the test result object passed as result."
1561 #
1562 # And if there are no tests? What then?
1563 def test_run__empty_suite(self):
1564 events = []
1565 result = LoggingResult(events)
1566
1567 suite = unittest.TestSuite()
1568
1569 suite.run(result)
1570
1571 self.assertEqual(events, [])
1572
1573 # "Note that unlike TestCase.run(), TestSuite.run() requires the
1574 # "result object to be passed in."
1575 def test_run__requires_result(self):
1576 suite = unittest.TestSuite()
1577
1578 try:
1579 suite.run()
1580 except TypeError:
1581 pass
1582 else:
1583 self.fail("Failed to raise TypeError")
1584
1585 # "Run the tests associated with this suite, collecting the result into
1586 # the test result object passed as result."
1587 def test_run(self):
1588 events = []
1589 result = LoggingResult(events)
1590
1591 class LoggingCase(unittest.TestCase):
1592 def run(self, result):
1593 events.append('run %s' % self._testMethodName)
1594
1595 def test1(self): pass
1596 def test2(self): pass
1597
1598 tests = [LoggingCase('test1'), LoggingCase('test2')]
1599
1600 unittest.TestSuite(tests).run(result)
1601
1602 self.assertEqual(events, ['run test1', 'run test2'])
1603
1604 # "Add a TestCase ... to the suite"
1605 def test_addTest__TestCase(self):
1606 class Foo(unittest.TestCase):
1607 def test(self): pass
1608
1609 test = Foo('test')
1610 suite = unittest.TestSuite()
1611
1612 suite.addTest(test)
1613
1614 self.assertEqual(suite.countTestCases(), 1)
1615 self.assertEqual(list(suite), [test])
1616
1617 # "Add a ... TestSuite to the suite"
1618 def test_addTest__TestSuite(self):
1619 class Foo(unittest.TestCase):
1620 def test(self): pass
1621
1622 suite_2 = unittest.TestSuite([Foo('test')])
1623
1624 suite = unittest.TestSuite()
1625 suite.addTest(suite_2)
1626
1627 self.assertEqual(suite.countTestCases(), 1)
1628 self.assertEqual(list(suite), [suite_2])
1629
1630 # "Add all the tests from an iterable of TestCase and TestSuite
1631 # instances to this test suite."
1632 #
1633 # "This is equivalent to iterating over tests, calling addTest() for
1634 # each element"
1635 def test_addTests(self):
1636 class Foo(unittest.TestCase):
1637 def test_1(self): pass
1638 def test_2(self): pass
1639
1640 test_1 = Foo('test_1')
1641 test_2 = Foo('test_2')
1642 inner_suite = unittest.TestSuite([test_2])
1643
1644 def gen():
1645 yield test_1
1646 yield test_2
1647 yield inner_suite
1648
1649 suite_1 = unittest.TestSuite()
1650 suite_1.addTests(gen())
1651
1652 self.assertEqual(list(suite_1), list(gen()))
1653
1654 # "This is equivalent to iterating over tests, calling addTest() for
1655 # each element"
1656 suite_2 = unittest.TestSuite()
1657 for t in gen():
1658 suite_2.addTest(t)
1659
1660 self.assertEqual(suite_1, suite_2)
1661
1662 # "Add all the tests from an iterable of TestCase and TestSuite
1663 # instances to this test suite."
1664 #
1665 # What happens if it doesn't get an iterable?
1666 def test_addTest__noniterable(self):
1667 suite = unittest.TestSuite()
1668
1669 try:
1670 suite.addTests(5)
1671 except TypeError:
1672 pass
1673 else:
1674 self.fail("Failed to raise TypeError")
1675
1676 def test_addTest__noncallable(self):
1677 suite = unittest.TestSuite()
1678 self.assertRaises(TypeError, suite.addTest, 5)
1679
1680 def test_addTest__casesuiteclass(self):
1681 suite = unittest.TestSuite()
1682 self.assertRaises(TypeError, suite.addTest, Test_TestSuite)
1683 self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)
1684
1685 def test_addTests__string(self):
1686 suite = unittest.TestSuite()
1687 self.assertRaises(TypeError, suite.addTests, "foo")
1688
1689
1690class Test_FunctionTestCase(TestCase):
1691
1692 # "Return the number of tests represented by the this test object. For
1693 # TestCase instances, this will always be 1"
1694 def test_countTestCases(self):
1695 test = unittest.FunctionTestCase(lambda: None)
1696
1697 self.assertEqual(test.countTestCases(), 1)
1698
1699 # "When a setUp() method is defined, the test runner will run that method
1700 # prior to each test. Likewise, if a tearDown() method is defined, the
1701 # test runner will invoke that method after each test. In the example,
1702 # setUp() was used to create a fresh sequence for each test."
1703 #
1704 # Make sure the proper call order is maintained, even if setUp() raises
1705 # an exception.
1706 def test_run_call_order__error_in_setUp(self):
1707 events = []
1708 result = LoggingResult(events)
1709
1710 def setUp():
1711 events.append('setUp')
1712 raise RuntimeError('raised by setUp')
1713
1714 def test():
1715 events.append('test')
1716
1717 def tearDown():
1718 events.append('tearDown')
1719
1720 expected = ['startTest', 'setUp', 'addError', 'stopTest']
1721 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1722 self.assertEqual(events, expected)
1723
1724 # "When a setUp() method is defined, the test runner will run that method
1725 # prior to each test. Likewise, if a tearDown() method is defined, the
1726 # test runner will invoke that method after each test. In the example,
1727 # setUp() was used to create a fresh sequence for each test."
1728 #
1729 # Make sure the proper call order is maintained, even if the test raises
1730 # an error (as opposed to a failure).
1731 def test_run_call_order__error_in_test(self):
1732 events = []
1733 result = LoggingResult(events)
1734
1735 def setUp():
1736 events.append('setUp')
1737
1738 def test():
1739 events.append('test')
1740 raise RuntimeError('raised by test')
1741
1742 def tearDown():
1743 events.append('tearDown')
1744
1745 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
1746 'stopTest']
1747 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1748 self.assertEqual(events, expected)
1749
1750 # "When a setUp() method is defined, the test runner will run that method
1751 # prior to each test. Likewise, if a tearDown() method is defined, the
1752 # test runner will invoke that method after each test. In the example,
1753 # setUp() was used to create a fresh sequence for each test."
1754 #
1755 # Make sure the proper call order is maintained, even if the test signals
1756 # a failure (as opposed to an error).
1757 def test_run_call_order__failure_in_test(self):
1758 events = []
1759 result = LoggingResult(events)
1760
1761 def setUp():
1762 events.append('setUp')
1763
1764 def test():
1765 events.append('test')
1766 self.fail('raised by test')
1767
1768 def tearDown():
1769 events.append('tearDown')
1770
1771 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
1772 'stopTest']
1773 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1774 self.assertEqual(events, expected)
1775
1776 # "When a setUp() method is defined, the test runner will run that method
1777 # prior to each test. Likewise, if a tearDown() method is defined, the
1778 # test runner will invoke that method after each test. In the example,
1779 # setUp() was used to create a fresh sequence for each test."
1780 #
1781 # Make sure the proper call order is maintained, even if tearDown() raises
1782 # an exception.
1783 def test_run_call_order__error_in_tearDown(self):
1784 events = []
1785 result = LoggingResult(events)
1786
1787 def setUp():
1788 events.append('setUp')
1789
1790 def test():
1791 events.append('test')
1792
1793 def tearDown():
1794 events.append('tearDown')
1795 raise RuntimeError('raised by tearDown')
1796
1797 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
1798 'stopTest']
1799 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1800 self.assertEqual(events, expected)
1801
1802 # "Return a string identifying the specific test case."
1803 #
1804 # Because of the vague nature of the docs, I'm not going to lock this
1805 # test down too much. Really all that can be asserted is that the id()
1806 # will be a string (either 8-byte or unicode -- again, because the docs
1807 # just say "string")
1808 def test_id(self):
1809 test = unittest.FunctionTestCase(lambda: None)
1810
Ezio Melottie9615932010-01-24 19:26:24 +00001811 self.assertIsInstance(test.id(), str)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001812
1813 # "Returns a one-line description of the test, or None if no description
1814 # has been provided. The default implementation of this method returns
1815 # the first line of the test method's docstring, if available, or None."
1816 def test_shortDescription__no_docstring(self):
1817 test = unittest.FunctionTestCase(lambda: None)
1818
1819 self.assertEqual(test.shortDescription(), None)
1820
1821 # "Returns a one-line description of the test, or None if no description
1822 # has been provided. The default implementation of this method returns
1823 # the first line of the test method's docstring, if available, or None."
1824 def test_shortDescription__singleline_docstring(self):
1825 desc = "this tests foo"
1826 test = unittest.FunctionTestCase(lambda: None, description=desc)
1827
1828 self.assertEqual(test.shortDescription(), "this tests foo")
1829
1830class Test_TestResult(TestCase):
1831 # Note: there are not separate tests for TestResult.wasSuccessful(),
1832 # TestResult.errors, TestResult.failures, TestResult.testsRun or
1833 # TestResult.shouldStop because these only have meaning in terms of
1834 # other TestResult methods.
1835 #
1836 # Accordingly, tests for the aforenamed attributes are incorporated
1837 # in with the tests for the defining methods.
1838 ################################################################
1839
1840 def test_init(self):
1841 result = unittest.TestResult()
1842
Benjamin Petersone1759f82009-06-30 23:35:19 +00001843 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001844 self.assertEqual(len(result.errors), 0)
1845 self.assertEqual(len(result.failures), 0)
1846 self.assertEqual(result.testsRun, 0)
1847 self.assertEqual(result.shouldStop, False)
1848
1849 # "This method can be called to signal that the set of tests being
1850 # run should be aborted by setting the TestResult's shouldStop
1851 # attribute to True."
1852 def test_stop(self):
1853 result = unittest.TestResult()
1854
1855 result.stop()
1856
1857 self.assertEqual(result.shouldStop, True)
1858
1859 # "Called when the test case test is about to be run. The default
1860 # implementation simply increments the instance's testsRun counter."
1861 def test_startTest(self):
1862 class Foo(unittest.TestCase):
1863 def test_1(self):
1864 pass
1865
1866 test = Foo('test_1')
1867
1868 result = unittest.TestResult()
1869
1870 result.startTest(test)
1871
Benjamin Petersone1759f82009-06-30 23:35:19 +00001872 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001873 self.assertEqual(len(result.errors), 0)
1874 self.assertEqual(len(result.failures), 0)
1875 self.assertEqual(result.testsRun, 1)
1876 self.assertEqual(result.shouldStop, False)
1877
1878 result.stopTest(test)
1879
1880 # "Called after the test case test has been executed, regardless of
1881 # the outcome. The default implementation does nothing."
1882 def test_stopTest(self):
1883 class Foo(unittest.TestCase):
1884 def test_1(self):
1885 pass
1886
1887 test = Foo('test_1')
1888
1889 result = unittest.TestResult()
1890
1891 result.startTest(test)
1892
Benjamin Petersone1759f82009-06-30 23:35:19 +00001893 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001894 self.assertEqual(len(result.errors), 0)
1895 self.assertEqual(len(result.failures), 0)
1896 self.assertEqual(result.testsRun, 1)
1897 self.assertEqual(result.shouldStop, False)
1898
1899 result.stopTest(test)
1900
1901 # Same tests as above; make sure nothing has changed
Benjamin Petersone1759f82009-06-30 23:35:19 +00001902 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001903 self.assertEqual(len(result.errors), 0)
1904 self.assertEqual(len(result.failures), 0)
1905 self.assertEqual(result.testsRun, 1)
1906 self.assertEqual(result.shouldStop, False)
1907
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001908 # "Called before and after tests are run. The default implementation does nothing."
1909 def test_startTestRun_stopTestRun(self):
1910 result = unittest.TestResult()
1911 result.startTestRun()
1912 result.stopTestRun()
1913
Guido van Rossumd8faa362007-04-27 19:54:29 +00001914 # "addSuccess(test)"
1915 # ...
1916 # "Called when the test case test succeeds"
1917 # ...
1918 # "wasSuccessful() - Returns True if all tests run so far have passed,
1919 # otherwise returns False"
1920 # ...
1921 # "testsRun - The total number of tests run so far."
1922 # ...
1923 # "errors - A list containing 2-tuples of TestCase instances and
1924 # formatted tracebacks. Each tuple represents a test which raised an
1925 # unexpected exception. Contains formatted
1926 # tracebacks instead of sys.exc_info() results."
1927 # ...
1928 # "failures - A list containing 2-tuples of TestCase instances and
1929 # formatted tracebacks. Each tuple represents a test where a failure was
1930 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1931 # methods. Contains formatted tracebacks instead
1932 # of sys.exc_info() results."
1933 def test_addSuccess(self):
1934 class Foo(unittest.TestCase):
1935 def test_1(self):
1936 pass
1937
1938 test = Foo('test_1')
1939
1940 result = unittest.TestResult()
1941
1942 result.startTest(test)
1943 result.addSuccess(test)
1944 result.stopTest(test)
1945
Benjamin Petersone1759f82009-06-30 23:35:19 +00001946 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001947 self.assertEqual(len(result.errors), 0)
1948 self.assertEqual(len(result.failures), 0)
1949 self.assertEqual(result.testsRun, 1)
1950 self.assertEqual(result.shouldStop, False)
1951
1952 # "addFailure(test, err)"
1953 # ...
1954 # "Called when the test case test signals a failure. err is a tuple of
1955 # the form returned by sys.exc_info(): (type, value, traceback)"
1956 # ...
1957 # "wasSuccessful() - Returns True if all tests run so far have passed,
1958 # otherwise returns False"
1959 # ...
1960 # "testsRun - The total number of tests run so far."
1961 # ...
1962 # "errors - A list containing 2-tuples of TestCase instances and
1963 # formatted tracebacks. Each tuple represents a test which raised an
1964 # unexpected exception. Contains formatted
1965 # tracebacks instead of sys.exc_info() results."
1966 # ...
1967 # "failures - A list containing 2-tuples of TestCase instances and
1968 # formatted tracebacks. Each tuple represents a test where a failure was
1969 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1970 # methods. Contains formatted tracebacks instead
1971 # of sys.exc_info() results."
1972 def test_addFailure(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001973 class Foo(unittest.TestCase):
1974 def test_1(self):
1975 pass
1976
1977 test = Foo('test_1')
1978 try:
1979 test.fail("foo")
1980 except:
1981 exc_info_tuple = sys.exc_info()
1982
1983 result = unittest.TestResult()
1984
1985 result.startTest(test)
1986 result.addFailure(test, exc_info_tuple)
1987 result.stopTest(test)
1988
Benjamin Petersone1759f82009-06-30 23:35:19 +00001989 self.assertFalse(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001990 self.assertEqual(len(result.errors), 0)
1991 self.assertEqual(len(result.failures), 1)
1992 self.assertEqual(result.testsRun, 1)
1993 self.assertEqual(result.shouldStop, False)
1994
1995 test_case, formatted_exc = result.failures[0]
Benjamin Petersone1759f82009-06-30 23:35:19 +00001996 self.assertTrue(test_case is test)
Ezio Melottie9615932010-01-24 19:26:24 +00001997 self.assertIsInstance(formatted_exc, str)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001998
1999 # "addError(test, err)"
2000 # ...
2001 # "Called when the test case test raises an unexpected exception err
2002 # is a tuple of the form returned by sys.exc_info():
2003 # (type, value, traceback)"
2004 # ...
2005 # "wasSuccessful() - Returns True if all tests run so far have passed,
2006 # otherwise returns False"
2007 # ...
2008 # "testsRun - The total number of tests run so far."
2009 # ...
2010 # "errors - A list containing 2-tuples of TestCase instances and
2011 # formatted tracebacks. Each tuple represents a test which raised an
2012 # unexpected exception. Contains formatted
2013 # tracebacks instead of sys.exc_info() results."
2014 # ...
2015 # "failures - A list containing 2-tuples of TestCase instances and
2016 # formatted tracebacks. Each tuple represents a test where a failure was
2017 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
2018 # methods. Contains formatted tracebacks instead
2019 # of sys.exc_info() results."
2020 def test_addError(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002021 class Foo(unittest.TestCase):
2022 def test_1(self):
2023 pass
2024
2025 test = Foo('test_1')
2026 try:
2027 raise TypeError()
2028 except:
2029 exc_info_tuple = sys.exc_info()
2030
2031 result = unittest.TestResult()
2032
2033 result.startTest(test)
2034 result.addError(test, exc_info_tuple)
2035 result.stopTest(test)
2036
Benjamin Petersone1759f82009-06-30 23:35:19 +00002037 self.assertFalse(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00002038 self.assertEqual(len(result.errors), 1)
2039 self.assertEqual(len(result.failures), 0)
2040 self.assertEqual(result.testsRun, 1)
2041 self.assertEqual(result.shouldStop, False)
2042
2043 test_case, formatted_exc = result.errors[0]
Benjamin Petersone1759f82009-06-30 23:35:19 +00002044 self.assertTrue(test_case is test)
Ezio Melottie9615932010-01-24 19:26:24 +00002045 self.assertIsInstance(formatted_exc, str)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002046
2047### Support code for Test_TestCase
2048################################################################
2049
2050class Foo(unittest.TestCase):
2051 def runTest(self): pass
2052 def test1(self): pass
2053
2054class Bar(Foo):
2055 def test2(self): pass
2056
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002057class LoggingTestCase(unittest.TestCase):
2058 """A test case which logs its calls."""
2059
2060 def __init__(self, events):
2061 super(LoggingTestCase, self).__init__('test')
2062 self.events = events
2063
2064 def setUp(self):
2065 self.events.append('setUp')
2066
2067 def test(self):
2068 self.events.append('test')
2069
2070 def tearDown(self):
2071 self.events.append('tearDown')
2072
2073class ResultWithNoStartTestRunStopTestRun(object):
2074 """An object honouring TestResult before startTestRun/stopTestRun."""
2075
2076 def __init__(self):
2077 self.failures = []
2078 self.errors = []
2079 self.testsRun = 0
2080 self.skipped = []
2081 self.expectedFailures = []
2082 self.unexpectedSuccesses = []
2083 self.shouldStop = False
2084
2085 def startTest(self, test):
2086 pass
2087
2088 def stopTest(self, test):
2089 pass
2090
2091 def addError(self, test):
2092 pass
2093
2094 def addFailure(self, test):
2095 pass
2096
2097 def addSuccess(self, test):
2098 pass
2099
2100 def wasSuccessful(self):
2101 return True
2102
2103
Guido van Rossumd8faa362007-04-27 19:54:29 +00002104################################################################
2105### /Support code for Test_TestCase
2106
2107class Test_TestCase(TestCase, TestEquality, TestHashing):
2108
2109 ### Set up attributes used by inherited tests
2110 ################################################################
2111
2112 # Used by TestHashing.test_hash and TestEquality.test_eq
2113 eq_pairs = [(Foo('test1'), Foo('test1'))]
2114
2115 # Used by TestEquality.test_ne
2116 ne_pairs = [(Foo('test1'), Foo('runTest'))
2117 ,(Foo('test1'), Bar('test1'))
2118 ,(Foo('test1'), Bar('test2'))]
2119
2120 ################################################################
2121 ### /Set up attributes used by inherited tests
2122
2123
2124 # "class TestCase([methodName])"
2125 # ...
2126 # "Each instance of TestCase will run a single test method: the
2127 # method named methodName."
2128 # ...
2129 # "methodName defaults to "runTest"."
2130 #
2131 # Make sure it really is optional, and that it defaults to the proper
2132 # thing.
2133 def test_init__no_test_name(self):
2134 class Test(unittest.TestCase):
2135 def runTest(self): raise MyException()
2136 def test(self): pass
2137
2138 self.assertEqual(Test().id()[-13:], '.Test.runTest')
2139
2140 # "class TestCase([methodName])"
2141 # ...
2142 # "Each instance of TestCase will run a single test method: the
2143 # method named methodName."
2144 def test_init__test_name__valid(self):
2145 class Test(unittest.TestCase):
2146 def runTest(self): raise MyException()
2147 def test(self): pass
2148
2149 self.assertEqual(Test('test').id()[-10:], '.Test.test')
2150
2151 # "class TestCase([methodName])"
2152 # ...
2153 # "Each instance of TestCase will run a single test method: the
2154 # method named methodName."
2155 def test_init__test_name__invalid(self):
2156 class Test(unittest.TestCase):
2157 def runTest(self): raise MyException()
2158 def test(self): pass
2159
2160 try:
2161 Test('testfoo')
2162 except ValueError:
2163 pass
2164 else:
2165 self.fail("Failed to raise ValueError")
2166
2167 # "Return the number of tests represented by the this test object. For
2168 # TestCase instances, this will always be 1"
2169 def test_countTestCases(self):
2170 class Foo(unittest.TestCase):
2171 def test(self): pass
2172
2173 self.assertEqual(Foo('test').countTestCases(), 1)
2174
2175 # "Return the default type of test result object to be used to run this
2176 # test. For TestCase instances, this will always be
2177 # unittest.TestResult; subclasses of TestCase should
2178 # override this as necessary."
2179 def test_defaultTestResult(self):
2180 class Foo(unittest.TestCase):
2181 def runTest(self):
2182 pass
2183
2184 result = Foo().defaultTestResult()
2185 self.assertEqual(type(result), unittest.TestResult)
2186
2187 # "When a setUp() method is defined, the test runner will run that method
2188 # prior to each test. Likewise, if a tearDown() method is defined, the
2189 # test runner will invoke that method after each test. In the example,
2190 # setUp() was used to create a fresh sequence for each test."
2191 #
2192 # Make sure the proper call order is maintained, even if setUp() raises
2193 # an exception.
2194 def test_run_call_order__error_in_setUp(self):
2195 events = []
2196 result = LoggingResult(events)
2197
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002198 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002199 def setUp(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002200 super(Foo, self).setUp()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002201 raise RuntimeError('raised by Foo.setUp')
2202
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002203 Foo(events).run(result)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002204 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2205 self.assertEqual(events, expected)
2206
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002207 # "With a temporary result stopTestRun is called when setUp errors.
2208 def test_run_call_order__error_in_setUp_default_result(self):
2209 events = []
2210
2211 class Foo(LoggingTestCase):
2212 def defaultTestResult(self):
2213 return LoggingResult(self.events)
2214
2215 def setUp(self):
2216 super(Foo, self).setUp()
2217 raise RuntimeError('raised by Foo.setUp')
2218
2219 Foo(events).run()
2220 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2221 'stopTest', 'stopTestRun']
2222 self.assertEqual(events, expected)
2223
Guido van Rossumd8faa362007-04-27 19:54:29 +00002224 # "When a setUp() method is defined, the test runner will run that method
2225 # prior to each test. Likewise, if a tearDown() method is defined, the
2226 # test runner will invoke that method after each test. In the example,
2227 # setUp() was used to create a fresh sequence for each test."
2228 #
2229 # Make sure the proper call order is maintained, even if the test raises
2230 # an error (as opposed to a failure).
2231 def test_run_call_order__error_in_test(self):
2232 events = []
2233 result = LoggingResult(events)
2234
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002235 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002236 def test(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002237 super(Foo, self).test()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002238 raise RuntimeError('raised by Foo.test')
2239
Guido van Rossumd8faa362007-04-27 19:54:29 +00002240 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2241 'stopTest']
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002242 Foo(events).run(result)
2243 self.assertEqual(events, expected)
2244
2245 # "With a default result, an error in the test still results in stopTestRun
2246 # being called."
2247 def test_run_call_order__error_in_test_default_result(self):
2248 events = []
2249
2250 class Foo(LoggingTestCase):
2251 def defaultTestResult(self):
2252 return LoggingResult(self.events)
2253
2254 def test(self):
2255 super(Foo, self).test()
2256 raise RuntimeError('raised by Foo.test')
2257
2258 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2259 'tearDown', 'stopTest', 'stopTestRun']
2260 Foo(events).run()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002261 self.assertEqual(events, expected)
2262
2263 # "When a setUp() method is defined, the test runner will run that method
2264 # prior to each test. Likewise, if a tearDown() method is defined, the
2265 # test runner will invoke that method after each test. In the example,
2266 # setUp() was used to create a fresh sequence for each test."
2267 #
2268 # Make sure the proper call order is maintained, even if the test signals
2269 # a failure (as opposed to an error).
2270 def test_run_call_order__failure_in_test(self):
2271 events = []
2272 result = LoggingResult(events)
2273
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002274 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002275 def test(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002276 super(Foo, self).test()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002277 self.fail('raised by Foo.test')
2278
Guido van Rossumd8faa362007-04-27 19:54:29 +00002279 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2280 'stopTest']
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002281 Foo(events).run(result)
2282 self.assertEqual(events, expected)
2283
2284 # "When a test fails with a default result stopTestRun is still called."
2285 def test_run_call_order__failure_in_test_default_result(self):
2286
2287 class Foo(LoggingTestCase):
2288 def defaultTestResult(self):
2289 return LoggingResult(self.events)
2290 def test(self):
2291 super(Foo, self).test()
2292 self.fail('raised by Foo.test')
2293
2294 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2295 'tearDown', 'stopTest', 'stopTestRun']
2296 events = []
2297 Foo(events).run()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002298 self.assertEqual(events, expected)
2299
2300 # "When a setUp() method is defined, the test runner will run that method
2301 # prior to each test. Likewise, if a tearDown() method is defined, the
2302 # test runner will invoke that method after each test. In the example,
2303 # setUp() was used to create a fresh sequence for each test."
2304 #
2305 # Make sure the proper call order is maintained, even if tearDown() raises
2306 # an exception.
2307 def test_run_call_order__error_in_tearDown(self):
2308 events = []
2309 result = LoggingResult(events)
2310
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002311 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002312 def tearDown(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002313 super(Foo, self).tearDown()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002314 raise RuntimeError('raised by Foo.tearDown')
2315
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002316 Foo(events).run(result)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002317 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2318 'stopTest']
2319 self.assertEqual(events, expected)
2320
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002321 # "When tearDown errors with a default result stopTestRun is still called."
2322 def test_run_call_order__error_in_tearDown_default_result(self):
2323
2324 class Foo(LoggingTestCase):
2325 def defaultTestResult(self):
2326 return LoggingResult(self.events)
2327 def tearDown(self):
2328 super(Foo, self).tearDown()
2329 raise RuntimeError('raised by Foo.tearDown')
2330
2331 events = []
2332 Foo(events).run()
2333 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2334 'addError', 'stopTest', 'stopTestRun']
2335 self.assertEqual(events, expected)
2336
2337 # "TestCase.run() still works when the defaultTestResult is a TestResult
2338 # that does not support startTestRun and stopTestRun.
2339 def test_run_call_order_default_result(self):
2340
2341 class Foo(unittest.TestCase):
2342 def defaultTestResult(self):
2343 return ResultWithNoStartTestRunStopTestRun()
2344 def test(self):
2345 pass
2346
2347 Foo('test').run()
2348
Guido van Rossumd8faa362007-04-27 19:54:29 +00002349 # "This class attribute gives the exception raised by the test() method.
2350 # If a test framework needs to use a specialized exception, possibly to
2351 # carry additional information, it must subclass this exception in
2352 # order to ``play fair'' with the framework. The initial value of this
2353 # attribute is AssertionError"
2354 def test_failureException__default(self):
2355 class Foo(unittest.TestCase):
2356 def test(self):
2357 pass
2358
Benjamin Petersone1759f82009-06-30 23:35:19 +00002359 self.assertTrue(Foo('test').failureException is AssertionError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002360
2361 # "This class attribute gives the exception raised by the test() method.
2362 # If a test framework needs to use a specialized exception, possibly to
2363 # carry additional information, it must subclass this exception in
2364 # order to ``play fair'' with the framework."
2365 #
2366 # Make sure TestCase.run() respects the designated failureException
2367 def test_failureException__subclassing__explicit_raise(self):
2368 events = []
2369 result = LoggingResult(events)
2370
2371 class Foo(unittest.TestCase):
2372 def test(self):
2373 raise RuntimeError()
2374
2375 failureException = RuntimeError
2376
Benjamin Petersone1759f82009-06-30 23:35:19 +00002377 self.assertTrue(Foo('test').failureException is RuntimeError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002378
2379
2380 Foo('test').run(result)
2381 expected = ['startTest', 'addFailure', 'stopTest']
2382 self.assertEqual(events, expected)
2383
2384 # "This class attribute gives the exception raised by the test() method.
2385 # If a test framework needs to use a specialized exception, possibly to
2386 # carry additional information, it must subclass this exception in
2387 # order to ``play fair'' with the framework."
2388 #
2389 # Make sure TestCase.run() respects the designated failureException
2390 def test_failureException__subclassing__implicit_raise(self):
2391 events = []
2392 result = LoggingResult(events)
2393
2394 class Foo(unittest.TestCase):
2395 def test(self):
2396 self.fail("foo")
2397
2398 failureException = RuntimeError
2399
Benjamin Petersone1759f82009-06-30 23:35:19 +00002400 self.assertTrue(Foo('test').failureException is RuntimeError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002401
2402
2403 Foo('test').run(result)
2404 expected = ['startTest', 'addFailure', 'stopTest']
2405 self.assertEqual(events, expected)
2406
2407 # "The default implementation does nothing."
2408 def test_setUp(self):
2409 class Foo(unittest.TestCase):
2410 def runTest(self):
2411 pass
2412
2413 # ... and nothing should happen
2414 Foo().setUp()
2415
2416 # "The default implementation does nothing."
2417 def test_tearDown(self):
2418 class Foo(unittest.TestCase):
2419 def runTest(self):
2420 pass
2421
2422 # ... and nothing should happen
2423 Foo().tearDown()
2424
2425 # "Return a string identifying the specific test case."
2426 #
2427 # Because of the vague nature of the docs, I'm not going to lock this
2428 # test down too much. Really all that can be asserted is that the id()
2429 # will be a string (either 8-byte or unicode -- again, because the docs
2430 # just say "string")
2431 def test_id(self):
2432 class Foo(unittest.TestCase):
2433 def runTest(self):
2434 pass
2435
Ezio Melottie9615932010-01-24 19:26:24 +00002436 self.assertIsInstance(Foo().id(), str)
2437
Guido van Rossumd8faa362007-04-27 19:54:29 +00002438
Guido van Rossumd8faa362007-04-27 19:54:29 +00002439 # "If result is omitted or None, a temporary result object is created
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002440 # and used, but is not made available to the caller. As TestCase owns the
2441 # temporary result startTestRun and stopTestRun are called.
2442
Guido van Rossumd8faa362007-04-27 19:54:29 +00002443 def test_run__uses_defaultTestResult(self):
2444 events = []
2445
2446 class Foo(unittest.TestCase):
2447 def test(self):
2448 events.append('test')
2449
2450 def defaultTestResult(self):
2451 return LoggingResult(events)
2452
2453 # Make run() find a result object on its own
2454 Foo('test').run()
2455
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002456 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2457 'stopTest', 'stopTestRun']
Guido van Rossumd8faa362007-04-27 19:54:29 +00002458 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002459
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002460 def testShortDescriptionWithoutDocstring(self):
2461 self.assertEqual(
2462 self.shortDescription(),
2463 'testShortDescriptionWithoutDocstring (' + __name__ +
2464 '.Test_TestCase)')
2465
2466 def testShortDescriptionWithOneLineDocstring(self):
2467 """Tests shortDescription() for a method with a docstring."""
2468 self.assertEqual(
2469 self.shortDescription(),
2470 ('testShortDescriptionWithOneLineDocstring '
2471 '(' + __name__ + '.Test_TestCase)\n'
2472 'Tests shortDescription() for a method with a docstring.'))
2473
2474 def testShortDescriptionWithMultiLineDocstring(self):
2475 """Tests shortDescription() for a method with a longer docstring.
2476
2477 This method ensures that only the first line of a docstring is
2478 returned used in the short description, no matter how long the
2479 whole thing is.
2480 """
2481 self.assertEqual(
2482 self.shortDescription(),
2483 ('testShortDescriptionWithMultiLineDocstring '
2484 '(' + __name__ + '.Test_TestCase)\n'
2485 'Tests shortDescription() for a method with a longer '
2486 'docstring.'))
2487
2488 def testAddTypeEqualityFunc(self):
2489 class SadSnake(object):
2490 """Dummy class for test_addTypeEqualityFunc."""
2491 s1, s2 = SadSnake(), SadSnake()
2492 self.assertFalse(s1 == s2)
2493 def AllSnakesCreatedEqual(a, b, msg=None):
2494 return type(a) == type(b) == SadSnake
2495 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2496 self.assertEqual(s1, s2)
2497 # No this doesn't clean up and remove the SadSnake equality func
2498 # from this TestCase instance but since its a local nothing else
2499 # will ever notice that.
2500
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00002501 def testAssertIs(self):
2502 thing = object()
2503 self.assertIs(thing, thing)
2504 self.assertRaises(self.failureException, self.assertIs, thing, object())
2505
2506 def testAssertIsNot(self):
2507 thing = object()
2508 self.assertIsNot(thing, object())
2509 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2510
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00002511 def testAssertIsInstance(self):
2512 thing = []
2513 self.assertIsInstance(thing, list)
2514 self.assertRaises(self.failureException, self.assertIsInstance,
2515 thing, dict)
2516
2517 def testAssertNotIsInstance(self):
2518 thing = []
2519 self.assertNotIsInstance(thing, dict)
2520 self.assertRaises(self.failureException, self.assertNotIsInstance,
2521 thing, list)
2522
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002523 def testAssertIn(self):
2524 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2525
2526 self.assertIn('a', 'abc')
2527 self.assertIn(2, [1, 2, 3])
2528 self.assertIn('monkey', animals)
2529
2530 self.assertNotIn('d', 'abc')
2531 self.assertNotIn(0, [1, 2, 3])
2532 self.assertNotIn('otter', animals)
2533
2534 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2535 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2536 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2537 animals)
2538
2539 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2540 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2541 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2542 animals)
2543
2544 def testAssertDictContainsSubset(self):
2545 self.assertDictContainsSubset({}, {})
2546 self.assertDictContainsSubset({}, {'a': 1})
2547 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2548 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2549 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2550
2551 self.assertRaises(unittest.TestCase.failureException,
2552 self.assertDictContainsSubset, {'a': 2}, {'a': 1},
2553 '.*Mismatched values:.*')
2554
2555 self.assertRaises(unittest.TestCase.failureException,
2556 self.assertDictContainsSubset, {'c': 1}, {'a': 1},
2557 '.*Missing:.*')
2558
2559 self.assertRaises(unittest.TestCase.failureException,
2560 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2561 {'a': 1}, '.*Missing:.*')
2562
2563 self.assertRaises(unittest.TestCase.failureException,
2564 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2565 {'a': 1}, '.*Missing:.*Mismatched values:.*')
2566
2567 def testAssertEqual(self):
2568 equal_pairs = [
2569 ((), ()),
2570 ({}, {}),
2571 ([], []),
2572 (set(), set()),
2573 (frozenset(), frozenset())]
2574 for a, b in equal_pairs:
2575 # This mess of try excepts is to test the assertEqual behavior
2576 # itself.
2577 try:
2578 self.assertEqual(a, b)
2579 except self.failureException:
2580 self.fail('assertEqual(%r, %r) failed' % (a, b))
2581 try:
2582 self.assertEqual(a, b, msg='foo')
2583 except self.failureException:
2584 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2585 try:
2586 self.assertEqual(a, b, 'foo')
2587 except self.failureException:
2588 self.fail('assertEqual(%r, %r) with third parameter failed' %
2589 (a, b))
2590
2591 unequal_pairs = [
2592 ((), []),
2593 ({}, set()),
2594 (set([4,1]), frozenset([4,2])),
2595 (frozenset([4,5]), set([2,3])),
2596 (set([3,4]), set([5,4]))]
2597 for a, b in unequal_pairs:
2598 self.assertRaises(self.failureException, self.assertEqual, a, b)
2599 self.assertRaises(self.failureException, self.assertEqual, a, b,
2600 'foo')
2601 self.assertRaises(self.failureException, self.assertEqual, a, b,
2602 msg='foo')
2603
2604 def testEquality(self):
2605 self.assertListEqual([], [])
2606 self.assertTupleEqual((), ())
2607 self.assertSequenceEqual([], ())
2608
2609 a = [0, 'a', []]
2610 b = []
2611 self.assertRaises(unittest.TestCase.failureException,
2612 self.assertListEqual, a, b)
2613 self.assertRaises(unittest.TestCase.failureException,
2614 self.assertListEqual, tuple(a), tuple(b))
2615 self.assertRaises(unittest.TestCase.failureException,
2616 self.assertSequenceEqual, a, tuple(b))
2617
2618 b.extend(a)
2619 self.assertListEqual(a, b)
2620 self.assertTupleEqual(tuple(a), tuple(b))
2621 self.assertSequenceEqual(a, tuple(b))
2622 self.assertSequenceEqual(tuple(a), b)
2623
2624 self.assertRaises(self.failureException, self.assertListEqual,
2625 a, tuple(b))
2626 self.assertRaises(self.failureException, self.assertTupleEqual,
2627 tuple(a), b)
2628 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2629 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2630 tuple(b))
2631 self.assertRaises(self.failureException, self.assertSequenceEqual,
2632 None, tuple(b))
2633 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2634 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2635 self.assertRaises(self.failureException, self.assertSequenceEqual,
2636 1, 1)
2637
2638 self.assertDictEqual({}, {})
2639
2640 c = { 'x': 1 }
2641 d = {}
2642 self.assertRaises(unittest.TestCase.failureException,
2643 self.assertDictEqual, c, d)
2644
2645 d.update(c)
2646 self.assertDictEqual(c, d)
2647
2648 d['x'] = 0
2649 self.assertRaises(unittest.TestCase.failureException,
2650 self.assertDictEqual, c, d, 'These are unequal')
2651
2652 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2653 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2654 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2655
2656 self.assertSameElements([1, 2, 3], [3, 2, 1])
2657 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2658 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2659 self.assertRaises(self.failureException, self.assertSameElements,
2660 [10], [10, 11])
2661 self.assertRaises(self.failureException, self.assertSameElements,
2662 [10, 11], [10])
2663
2664 # Test that sequences of unhashable objects can be tested for sameness:
2665 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00002666
Benjamin Peterson3bb6b7a2009-04-04 16:46:24 +00002667 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002668 self.assertRaises(self.failureException, self.assertSameElements,
2669 [[1]], [[2]])
Michael Foorda5809c82009-04-04 18:55:09 +00002670 self.assertRaises(self.failureException, self.assertSameElements,
2671 [{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 2}])
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002672
2673 def testAssertSetEqual(self):
2674 set1 = set()
2675 set2 = set()
2676 self.assertSetEqual(set1, set2)
2677
2678 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2679 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2680 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2681 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2682
2683 set1 = set(['a'])
2684 set2 = set()
2685 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2686
2687 set1 = set(['a'])
2688 set2 = set(['a'])
2689 self.assertSetEqual(set1, set2)
2690
2691 set1 = set(['a'])
2692 set2 = set(['a', 'b'])
2693 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2694
2695 set1 = set(['a'])
2696 set2 = frozenset(['a', 'b'])
2697 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2698
2699 set1 = set(['a', 'b'])
2700 set2 = frozenset(['a', 'b'])
2701 self.assertSetEqual(set1, set2)
2702
2703 set1 = set()
2704 set2 = "foo"
2705 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2706 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2707
2708 # make sure any string formatting is tuple-safe
2709 set1 = set([(0, 1), (2, 3)])
2710 set2 = set([(4, 5)])
2711 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2712
2713 def testInequality(self):
2714 # Try ints
2715 self.assertGreater(2, 1)
2716 self.assertGreaterEqual(2, 1)
2717 self.assertGreaterEqual(1, 1)
2718 self.assertLess(1, 2)
2719 self.assertLessEqual(1, 2)
2720 self.assertLessEqual(1, 1)
2721 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2722 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2723 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2724 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2725 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2726 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2727
2728 # Try Floats
2729 self.assertGreater(1.1, 1.0)
2730 self.assertGreaterEqual(1.1, 1.0)
2731 self.assertGreaterEqual(1.0, 1.0)
2732 self.assertLess(1.0, 1.1)
2733 self.assertLessEqual(1.0, 1.1)
2734 self.assertLessEqual(1.0, 1.0)
2735 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2736 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2737 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2738 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2739 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2740 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2741
2742 # Try Strings
2743 self.assertGreater('bug', 'ant')
2744 self.assertGreaterEqual('bug', 'ant')
2745 self.assertGreaterEqual('ant', 'ant')
2746 self.assertLess('ant', 'bug')
2747 self.assertLessEqual('ant', 'bug')
2748 self.assertLessEqual('ant', 'ant')
2749 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2750 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2751 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2752 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2753 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2754 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2755
2756 # Try bytes
2757 self.assertGreater(b'bug', b'ant')
2758 self.assertGreaterEqual(b'bug', b'ant')
2759 self.assertGreaterEqual(b'ant', b'ant')
2760 self.assertLess(b'ant', b'bug')
2761 self.assertLessEqual(b'ant', b'bug')
2762 self.assertLessEqual(b'ant', b'ant')
2763 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'bug')
2764 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'ant')
2765 self.assertRaises(self.failureException, self.assertGreaterEqual, b'ant',
2766 b'bug')
2767 self.assertRaises(self.failureException, self.assertLess, b'bug', b'ant')
2768 self.assertRaises(self.failureException, self.assertLess, b'ant', b'ant')
2769 self.assertRaises(self.failureException, self.assertLessEqual, b'bug', b'ant')
2770
2771 def testAssertMultiLineEqual(self):
2772 sample_text = """\
2773http://www.python.org/doc/2.3/lib/module-unittest.html
2774test case
2775 A test case is the smallest unit of testing. [...]
2776"""
2777 revised_sample_text = """\
2778http://www.python.org/doc/2.4.1/lib/module-unittest.html
2779test case
2780 A test case is the smallest unit of testing. [...] You may provide your
2781 own implementation that does not subclass from TestCase, of course.
2782"""
2783 sample_text_error = """
2784- http://www.python.org/doc/2.3/lib/module-unittest.html
2785? ^
2786+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2787? ^^^
2788 test case
2789- A test case is the smallest unit of testing. [...]
2790+ A test case is the smallest unit of testing. [...] You may provide your
2791? +++++++++++++++++++++
2792+ own implementation that does not subclass from TestCase, of course.
2793"""
2794
2795 try:
2796 self.assertMultiLineEqual(sample_text, revised_sample_text)
2797 except self.failureException as e:
Michael Foord02834952010-02-08 23:10:39 +00002798 # no fair testing ourself with ourself, and assertEqual is used for strings
2799 # so can't use assertEqual either. Just use assertTrue.
2800 self.assertTrue(sample_text_error == str(e))
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002801
2802 def testAssertIsNone(self):
2803 self.assertIsNone(None)
2804 self.assertRaises(self.failureException, self.assertIsNone, False)
2805 self.assertIsNotNone('DjZoPloGears on Rails')
2806 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2807
2808 def testAssertRegexpMatches(self):
2809 self.assertRegexpMatches('asdfabasdf', r'ab+')
2810 self.assertRaises(self.failureException, self.assertRegexpMatches,
2811 'saaas', r'aaaa')
2812
2813 def testAssertRaisesRegexp(self):
2814 class ExceptionMock(Exception):
2815 pass
2816
2817 def Stub():
2818 raise ExceptionMock('We expect')
2819
2820 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2821 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2822
2823 def testAssertNotRaisesRegexp(self):
2824 self.assertRaisesRegexp(
Benjamin Peterson4f75b642009-04-04 16:39:09 +00002825 self.failureException, '^Exception not raised by <lambda>$',
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002826 self.assertRaisesRegexp, Exception, re.compile('x'),
2827 lambda: None)
2828 self.assertRaisesRegexp(
Benjamin Peterson4f75b642009-04-04 16:39:09 +00002829 self.failureException, '^Exception not raised by <lambda>$',
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002830 self.assertRaisesRegexp, Exception, 'x',
2831 lambda: None)
2832
2833 def testAssertRaisesRegexpMismatch(self):
2834 def Stub():
2835 raise Exception('Unexpected')
2836
2837 self.assertRaisesRegexp(
2838 self.failureException,
2839 r'"\^Expected\$" does not match "Unexpected"',
2840 self.assertRaisesRegexp, Exception, '^Expected$',
2841 Stub)
2842 self.assertRaisesRegexp(
2843 self.failureException,
2844 r'"\^Expected\$" does not match "Unexpected"',
2845 self.assertRaisesRegexp, Exception,
2846 re.compile('^Expected$'), Stub)
2847
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +00002848 def testAssertRaisesExcValue(self):
2849 class ExceptionMock(Exception):
2850 pass
2851
2852 def Stub(foo):
2853 raise ExceptionMock(foo)
2854 v = "particular value"
2855
2856 ctx = self.assertRaises(ExceptionMock)
2857 with ctx:
2858 Stub(v)
Ezio Melotti49008232010-02-08 21:57:48 +00002859 e = ctx.exception
Ezio Melottie9615932010-01-24 19:26:24 +00002860 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +00002861 self.assertEqual(e.args[0], v)
2862
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002863 def testSynonymAssertMethodNames(self):
2864 """Test undocumented method name synonyms.
2865
2866 Please do not use these methods names in your own code.
2867
2868 This test confirms their continued existence and functionality
2869 in order to avoid breaking existing code.
2870 """
2871 self.assertNotEquals(3, 5)
2872 self.assertEquals(3, 3)
2873 self.assertAlmostEquals(2.0, 2.0)
2874 self.assertNotAlmostEquals(3.0, 5.0)
2875 self.assert_(True)
2876
2877 def testPendingDeprecationMethodNames(self):
2878 """Test fail* methods pending deprecation, they will warn in 3.2.
2879
2880 Do not use these methods. They will go away in 3.3.
2881 """
Benjamin Peterson6bcbad52009-06-30 23:45:41 +00002882 old = (
2883 (self.failIfEqual, (3, 5)),
2884 (self.failUnlessEqual, (3, 3)),
2885 (self.failUnlessAlmostEqual, (2.0, 2.0)),
2886 (self.failIfAlmostEqual, (3.0, 5.0)),
2887 (self.failUnless, (True,)),
2888 (self.failUnlessRaises, (TypeError, lambda _: 3.14 + 'spam')),
2889 (self.failIf, (False,))
2890 )
2891 for meth, args in old:
2892 with warnings.catch_warnings(record=True) as w:
2893 meth(*args)
2894 self.assertEqual(len(w), 1)
2895 self.assertIs(w[0].category, DeprecationWarning)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002896
2897 def testDeepcopy(self):
2898 # Issue: 5660
2899 class TestableTest(TestCase):
2900 def testNothing(self):
2901 pass
2902
2903 test = TestableTest('testNothing')
2904
2905 # This shouldn't blow up
2906 deepcopy(test)
2907
Benjamin Peterson5254c042009-03-23 22:25:03 +00002908
2909class Test_TestSkipping(TestCase):
2910
2911 def test_skipping(self):
2912 class Foo(unittest.TestCase):
2913 def test_skip_me(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00002914 self.skipTest("skip")
Benjamin Peterson5254c042009-03-23 22:25:03 +00002915 events = []
2916 result = LoggingResult(events)
2917 test = Foo("test_skip_me")
2918 test.run(result)
2919 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2920 self.assertEqual(result.skipped, [(test, "skip")])
2921
2922 # Try letting setUp skip the test now.
2923 class Foo(unittest.TestCase):
2924 def setUp(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00002925 self.skipTest("testing")
Benjamin Peterson5254c042009-03-23 22:25:03 +00002926 def test_nothing(self): pass
2927 events = []
2928 result = LoggingResult(events)
2929 test = Foo("test_nothing")
2930 test.run(result)
2931 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2932 self.assertEqual(result.skipped, [(test, "testing")])
2933 self.assertEqual(result.testsRun, 1)
2934
2935 def test_skipping_decorators(self):
2936 op_table = ((unittest.skipUnless, False, True),
2937 (unittest.skipIf, True, False))
2938 for deco, do_skip, dont_skip in op_table:
2939 class Foo(unittest.TestCase):
2940 @deco(do_skip, "testing")
2941 def test_skip(self): pass
2942
2943 @deco(dont_skip, "testing")
2944 def test_dont_skip(self): pass
2945 test_do_skip = Foo("test_skip")
2946 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002947 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002948 events = []
2949 result = LoggingResult(events)
2950 suite.run(result)
2951 self.assertEqual(len(result.skipped), 1)
2952 expected = ['startTest', 'addSkip', 'stopTest',
2953 'startTest', 'addSuccess', 'stopTest']
2954 self.assertEqual(events, expected)
2955 self.assertEqual(result.testsRun, 2)
2956 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
2957 self.assertTrue(result.wasSuccessful())
2958
2959 def test_skip_class(self):
2960 @unittest.skip("testing")
2961 class Foo(unittest.TestCase):
2962 def test_1(self):
2963 record.append(1)
2964 record = []
2965 result = unittest.TestResult()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002966 test = Foo("test_1")
2967 suite = unittest.TestSuite([test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002968 suite.run(result)
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002969 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002970 self.assertEqual(record, [])
2971
2972 def test_expected_failure(self):
2973 class Foo(unittest.TestCase):
2974 @unittest.expectedFailure
2975 def test_die(self):
2976 self.fail("help me!")
2977 events = []
2978 result = LoggingResult(events)
2979 test = Foo("test_die")
2980 test.run(result)
2981 self.assertEqual(events,
2982 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Peterson52baa292009-03-24 00:56:30 +00002983 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson5254c042009-03-23 22:25:03 +00002984 self.assertTrue(result.wasSuccessful())
2985
2986 def test_unexpected_success(self):
2987 class Foo(unittest.TestCase):
2988 @unittest.expectedFailure
2989 def test_die(self):
2990 pass
2991 events = []
2992 result = LoggingResult(events)
2993 test = Foo("test_die")
2994 test.run(result)
2995 self.assertEqual(events,
2996 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
2997 self.assertFalse(result.failures)
Benjamin Peterson52baa292009-03-24 00:56:30 +00002998 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002999 self.assertTrue(result.wasSuccessful())
3000
3001
3002
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003003class Test_Assertions(TestCase):
3004 def test_AlmostEqual(self):
Benjamin Petersone1759f82009-06-30 23:35:19 +00003005 self.assertAlmostEqual(1.00000001, 1.0)
3006 self.assertNotAlmostEqual(1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003007 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003008 self.assertAlmostEqual, 1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003009 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003010 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003011
Benjamin Petersone1759f82009-06-30 23:35:19 +00003012 self.assertAlmostEqual(1.1, 1.0, places=0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003013 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003014 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003015
Benjamin Petersone1759f82009-06-30 23:35:19 +00003016 self.assertAlmostEqual(0, .1+.1j, places=0)
3017 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003018 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003019 self.assertAlmostEqual, 0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003020 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003021 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003022
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003023 self.assertAlmostEqual(float('inf'), float('inf'))
3024 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3025 float('inf'), float('inf'))
3026
3027
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003028 def test_assertRaises(self):
3029 def _raise(e):
3030 raise e
3031 self.assertRaises(KeyError, _raise, KeyError)
3032 self.assertRaises(KeyError, _raise, KeyError("key"))
3033 try:
3034 self.assertRaises(KeyError, lambda: None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003035 except self.failureException as e:
Ezio Melottib58e0bd2010-01-23 15:40:09 +00003036 self.assertIn("KeyError not raised", str(e))
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003037 else:
3038 self.fail("assertRaises() didn't fail")
3039 try:
3040 self.assertRaises(KeyError, _raise, ValueError)
3041 except ValueError:
3042 pass
3043 else:
3044 self.fail("assertRaises() didn't let exception pass through")
Ezio Melotti49008232010-02-08 21:57:48 +00003045 with self.assertRaises(KeyError) as cm:
3046 try:
3047 raise KeyError
3048 except Exception as e:
3049 exc = e
3050 raise
3051 self.assertIs(cm.exception, exc)
3052
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003053 with self.assertRaises(KeyError):
3054 raise KeyError("key")
3055 try:
3056 with self.assertRaises(KeyError):
3057 pass
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003058 except self.failureException as e:
Ezio Melottib58e0bd2010-01-23 15:40:09 +00003059 self.assertIn("KeyError not raised", str(e))
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003060 else:
3061 self.fail("assertRaises() didn't fail")
3062 try:
3063 with self.assertRaises(KeyError):
3064 raise ValueError
3065 except ValueError:
3066 pass
3067 else:
3068 self.fail("assertRaises() didn't let exception pass through")
3069
3070
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003071class TestLongMessage(TestCase):
3072 """Test that the individual asserts honour longMessage.
3073 This actually tests all the message behaviour for
3074 asserts that use longMessage."""
3075
3076 def setUp(self):
3077 class TestableTestFalse(TestCase):
3078 longMessage = False
3079 failureException = self.failureException
3080
3081 def testTest(self):
3082 pass
3083
3084 class TestableTestTrue(TestCase):
3085 longMessage = True
3086 failureException = self.failureException
3087
3088 def testTest(self):
3089 pass
3090
3091 self.testableTrue = TestableTestTrue('testTest')
3092 self.testableFalse = TestableTestFalse('testTest')
3093
3094 def testDefault(self):
3095 self.assertFalse(TestCase.longMessage)
3096
3097 def test_formatMsg(self):
3098 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3099 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3100
3101 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3102 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3103
3104 def assertMessages(self, methodName, args, errors):
3105 def getMethod(i):
3106 useTestableFalse = i < 2
3107 if useTestableFalse:
3108 test = self.testableFalse
3109 else:
3110 test = self.testableTrue
3111 return getattr(test, methodName)
3112
3113 for i, expected_regexp in enumerate(errors):
3114 testMethod = getMethod(i)
3115 kwargs = {}
3116 withMsg = i % 2
3117 if withMsg:
3118 kwargs = {"msg": "oops"}
3119
3120 with self.assertRaisesRegexp(self.failureException,
3121 expected_regexp=expected_regexp):
3122 testMethod(*args, **kwargs)
3123
3124 def testAssertTrue(self):
3125 self.assertMessages('assertTrue', (False,),
3126 ["^False is not True$", "^oops$", "^False is not True$",
3127 "^False is not True : oops$"])
3128
3129 def testAssertFalse(self):
3130 self.assertMessages('assertFalse', (True,),
3131 ["^True is not False$", "^oops$", "^True is not False$",
3132 "^True is not False : oops$"])
3133
3134 def testNotEqual(self):
3135 self.assertMessages('assertNotEqual', (1, 1),
3136 ["^1 == 1$", "^oops$", "^1 == 1$",
3137 "^1 == 1 : oops$"])
3138
3139 def testAlmostEqual(self):
3140 self.assertMessages('assertAlmostEqual', (1, 2),
3141 ["^1 != 2 within 7 places$", "^oops$",
3142 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3143
3144 def testNotAlmostEqual(self):
3145 self.assertMessages('assertNotAlmostEqual', (1, 1),
3146 ["^1 == 1 within 7 places$", "^oops$",
3147 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3148
3149 def test_baseAssertEqual(self):
3150 self.assertMessages('_baseAssertEqual', (1, 2),
3151 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3152
3153 def testAssertSequenceEqual(self):
3154 # Error messages are multiline so not testing on full message
3155 # assertTupleEqual and assertListEqual delegate to this method
3156 self.assertMessages('assertSequenceEqual', ([], [None]),
3157 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3158 r"\+ \[None\] : oops$"])
3159
3160 def testAssertSetEqual(self):
3161 self.assertMessages('assertSetEqual', (set(), set([None])),
3162 ["None$", "^oops$", "None$",
3163 "None : oops$"])
3164
3165 def testAssertIn(self):
3166 self.assertMessages('assertIn', (None, []),
3167 ['^None not found in \[\]$', "^oops$",
3168 '^None not found in \[\]$',
3169 '^None not found in \[\] : oops$'])
3170
3171 def testAssertNotIn(self):
3172 self.assertMessages('assertNotIn', (None, [None]),
3173 ['^None unexpectedly found in \[None\]$', "^oops$",
3174 '^None unexpectedly found in \[None\]$',
3175 '^None unexpectedly found in \[None\] : oops$'])
3176
3177 def testAssertDictEqual(self):
3178 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3179 [r"\+ \{'key': 'value'\}$", "^oops$",
3180 "\+ \{'key': 'value'\}$",
3181 "\+ \{'key': 'value'\} : oops$"])
3182
3183 def testAssertDictContainsSubset(self):
3184 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3185 ["^Missing: 'key'$", "^oops$",
3186 "^Missing: 'key'$",
3187 "^Missing: 'key' : oops$"])
3188
3189 def testAssertSameElements(self):
3190 self.assertMessages('assertSameElements', ([], [None]),
3191 [r"\[None\]$", "^oops$",
3192 r"\[None\]$",
3193 r"\[None\] : oops$"])
3194
3195 def testAssertMultiLineEqual(self):
3196 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3197 [r"\+ foo$", "^oops$",
3198 r"\+ foo$",
3199 r"\+ foo : oops$"])
3200
3201 def testAssertLess(self):
3202 self.assertMessages('assertLess', (2, 1),
3203 ["^2 not less than 1$", "^oops$",
3204 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3205
3206 def testAssertLessEqual(self):
3207 self.assertMessages('assertLessEqual', (2, 1),
3208 ["^2 not less than or equal to 1$", "^oops$",
3209 "^2 not less than or equal to 1$",
3210 "^2 not less than or equal to 1 : oops$"])
3211
3212 def testAssertGreater(self):
3213 self.assertMessages('assertGreater', (1, 2),
3214 ["^1 not greater than 2$", "^oops$",
3215 "^1 not greater than 2$",
3216 "^1 not greater than 2 : oops$"])
3217
3218 def testAssertGreaterEqual(self):
3219 self.assertMessages('assertGreaterEqual', (1, 2),
3220 ["^1 not greater than or equal to 2$", "^oops$",
3221 "^1 not greater than or equal to 2$",
3222 "^1 not greater than or equal to 2 : oops$"])
3223
3224 def testAssertIsNone(self):
3225 self.assertMessages('assertIsNone', ('not None',),
3226 ["^'not None' is not None$", "^oops$",
3227 "^'not None' is not None$",
3228 "^'not None' is not None : oops$"])
3229
3230 def testAssertIsNotNone(self):
3231 self.assertMessages('assertIsNotNone', (None,),
3232 ["^unexpectedly None$", "^oops$",
3233 "^unexpectedly None$",
3234 "^unexpectedly None : oops$"])
3235
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00003236 def testAssertIs(self):
3237 self.assertMessages('assertIs', (None, 'foo'),
3238 ["^None is not 'foo'$", "^oops$",
3239 "^None is not 'foo'$",
3240 "^None is not 'foo' : oops$"])
3241
3242 def testAssertIsNot(self):
3243 self.assertMessages('assertIsNot', (None, None),
3244 ["^unexpectedly identical: None$", "^oops$",
3245 "^unexpectedly identical: None$",
3246 "^unexpectedly identical: None : oops$"])
3247
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003248
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003249class TestCleanUp(TestCase):
3250
3251 def testCleanUp(self):
3252 class TestableTest(TestCase):
3253 def testNothing(self):
3254 pass
3255
3256 test = TestableTest('testNothing')
3257 self.assertEqual(test._cleanups, [])
3258
3259 cleanups = []
3260
3261 def cleanup1(*args, **kwargs):
3262 cleanups.append((1, args, kwargs))
3263
3264 def cleanup2(*args, **kwargs):
3265 cleanups.append((2, args, kwargs))
3266
3267 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3268 test.addCleanup(cleanup2)
3269
3270 self.assertEqual(test._cleanups,
3271 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3272 (cleanup2, (), {})])
3273
3274 result = test.doCleanups()
3275 self.assertTrue(result)
3276
3277 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3278
3279 def testCleanUpWithErrors(self):
3280 class TestableTest(TestCase):
3281 def testNothing(self):
3282 pass
3283
3284 class MockResult(object):
3285 errors = []
3286 def addError(self, test, exc_info):
3287 self.errors.append((test, exc_info))
3288
3289 result = MockResult()
3290 test = TestableTest('testNothing')
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00003291 test._resultForDoCleanups = result
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003292
3293 exc1 = Exception('foo')
3294 exc2 = Exception('bar')
3295 def cleanup1():
3296 raise exc1
3297
3298 def cleanup2():
3299 raise exc2
3300
3301 test.addCleanup(cleanup1)
3302 test.addCleanup(cleanup2)
3303
3304 self.assertFalse(test.doCleanups())
3305
3306 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3307 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3308 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3309
3310 def testCleanupInRun(self):
3311 blowUp = False
3312 ordering = []
3313
3314 class TestableTest(TestCase):
3315 def setUp(self):
3316 ordering.append('setUp')
3317 if blowUp:
3318 raise Exception('foo')
3319
3320 def testNothing(self):
3321 ordering.append('test')
3322
3323 def tearDown(self):
3324 ordering.append('tearDown')
3325
3326 test = TestableTest('testNothing')
3327
3328 def cleanup1():
3329 ordering.append('cleanup1')
3330 def cleanup2():
3331 ordering.append('cleanup2')
3332 test.addCleanup(cleanup1)
3333 test.addCleanup(cleanup2)
3334
3335 def success(some_test):
3336 self.assertEqual(some_test, test)
3337 ordering.append('success')
3338
3339 result = unittest.TestResult()
3340 result.addSuccess = success
3341
3342 test.run(result)
3343 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3344 'cleanup2', 'cleanup1', 'success'])
3345
3346 blowUp = True
3347 ordering = []
3348 test = TestableTest('testNothing')
3349 test.addCleanup(cleanup1)
3350 test.run(result)
3351 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3352
3353
3354class Test_TestProgram(TestCase):
3355
3356 # Horrible white box test
3357 def testNoExit(self):
3358 result = object()
3359 test = object()
3360
3361 class FakeRunner(object):
3362 def run(self, test):
3363 self.test = test
3364 return result
3365
3366 runner = FakeRunner()
3367
Benjamin Petersond2397752009-06-27 23:45:02 +00003368 oldParseArgs = TestProgram.parseArgs
3369 def restoreParseArgs():
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003370 TestProgram.parseArgs = oldParseArgs
Benjamin Petersond2397752009-06-27 23:45:02 +00003371 TestProgram.parseArgs = lambda *args: None
3372 self.addCleanup(restoreParseArgs)
3373
3374 def removeTest():
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003375 del TestProgram.test
Benjamin Petersond2397752009-06-27 23:45:02 +00003376 TestProgram.test = test
3377 self.addCleanup(removeTest)
3378
3379 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3380
3381 self.assertEqual(program.result, result)
3382 self.assertEqual(runner.test, test)
3383 self.assertEqual(program.verbosity, 2)
3384
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003385 class FooBar(unittest.TestCase):
3386 def testPass(self):
3387 assert True
3388 def testFail(self):
3389 assert False
3390
3391 class FooBarLoader(unittest.TestLoader):
3392 """Test loader that returns a suite containing FooBar."""
3393 def loadTestsFromModule(self, module):
3394 return self.suiteClass(
3395 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3396
3397
3398 def test_NonExit(self):
3399 program = unittest.main(exit=False,
3400 argv=["foobar"],
3401 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3402 testLoader=self.FooBarLoader())
3403 self.assertTrue(hasattr(program, 'result'))
3404
3405
3406 def test_Exit(self):
3407 self.assertRaises(
3408 SystemExit,
3409 unittest.main,
3410 argv=["foobar"],
3411 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3412 exit=True,
3413 testLoader=self.FooBarLoader())
3414
3415
3416 def test_ExitAsDefault(self):
3417 self.assertRaises(
3418 SystemExit,
3419 unittest.main,
3420 argv=["foobar"],
3421 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3422 testLoader=self.FooBarLoader())
3423
3424
3425class Test_TextTestRunner(TestCase):
3426 """Tests for TextTestRunner."""
3427
3428 def test_works_with_result_without_startTestRun_stopTestRun(self):
3429 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3430 separator2 = ''
3431 def printErrors(self):
3432 pass
3433
3434 class Runner(unittest.TextTestRunner):
3435 def __init__(self):
3436 super(Runner, self).__init__(io.StringIO())
3437
3438 def _makeResult(self):
3439 return OldTextResult()
3440
3441 runner = Runner()
3442 runner.run(unittest.TestSuite())
3443
3444 def test_startTestRun_stopTestRun_called(self):
3445 class LoggingTextResult(LoggingResult):
3446 separator2 = ''
3447 def printErrors(self):
3448 pass
3449
3450 class LoggingRunner(unittest.TextTestRunner):
3451 def __init__(self, events):
3452 super(LoggingRunner, self).__init__(io.StringIO())
3453 self._events = events
3454
3455 def _makeResult(self):
3456 return LoggingTextResult(self._events)
3457
3458 events = []
3459 runner = LoggingRunner(events)
3460 runner.run(unittest.TestSuite())
3461 expected = ['startTestRun', 'stopTestRun']
3462 self.assertEqual(events, expected)
3463
Antoine Pitrouc63ecee2009-11-10 21:34:48 +00003464 def test_pickle_unpickle(self):
3465 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3466 # required by test_multiprocessing under Windows (in verbose mode).
3467 stream = io.StringIO("foo")
3468 runner = unittest.TextTestRunner(stream)
3469 for protocol in range(2, pickle.HIGHEST_PROTOCOL + 1):
3470 s = pickle.dumps(runner, protocol)
3471 obj = pickle.loads(s)
3472 # StringIO objects never compare equal, a cheap test instead.
3473 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3474
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003475
Benjamin Petersond2397752009-06-27 23:45:02 +00003476class TestDiscovery(TestCase):
3477
3478 # Heavily mocked tests so I can avoid hitting the filesystem
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003479 def test_get_name_from_path(self):
Benjamin Petersond2397752009-06-27 23:45:02 +00003480 loader = unittest.TestLoader()
Benjamin Petersond2397752009-06-27 23:45:02 +00003481 loader._top_level_dir = '/foo'
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003482 name = loader._get_name_from_path('/foo/bar/baz.py')
3483 self.assertEqual(name, 'bar.baz')
Benjamin Petersond2397752009-06-27 23:45:02 +00003484
3485 if not __debug__:
3486 # asserts are off
3487 return
3488
3489 with self.assertRaises(AssertionError):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003490 loader._get_name_from_path('/bar/baz.py')
Benjamin Petersond2397752009-06-27 23:45:02 +00003491
3492 def test_find_tests(self):
3493 loader = unittest.TestLoader()
3494
3495 original_listdir = os.listdir
3496 def restore_listdir():
3497 os.listdir = original_listdir
3498 original_isfile = os.path.isfile
3499 def restore_isfile():
3500 os.path.isfile = original_isfile
3501 original_isdir = os.path.isdir
3502 def restore_isdir():
3503 os.path.isdir = original_isdir
3504
3505 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003506 'test.foo', 'test-not-a-module.py', 'another_dir'],
Benjamin Petersond2397752009-06-27 23:45:02 +00003507 ['test3.py', 'test4.py', ]]
3508 os.listdir = lambda path: path_lists.pop(0)
3509 self.addCleanup(restore_listdir)
3510
3511 def isdir(path):
3512 return path.endswith('dir')
3513 os.path.isdir = isdir
3514 self.addCleanup(restore_isdir)
3515
3516 def isfile(path):
3517 # another_dir is not a package and so shouldn't be recursed into
3518 return not path.endswith('dir') and not 'another_dir' in path
3519 os.path.isfile = isfile
3520 self.addCleanup(restore_isfile)
3521
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003522 loader._get_module_from_name = lambda path: path + ' module'
Benjamin Petersond2397752009-06-27 23:45:02 +00003523 loader.loadTestsFromModule = lambda module: module + ' tests'
3524
3525 loader._top_level_dir = '/foo'
3526 suite = list(loader._find_tests('/foo', 'test*.py'))
3527
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003528 expected = [name + ' module tests' for name in
3529 ('test1', 'test2')]
3530 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3531 ('test3', 'test4')])
Benjamin Petersond2397752009-06-27 23:45:02 +00003532 self.assertEqual(suite, expected)
3533
3534 def test_find_tests_with_package(self):
3535 loader = unittest.TestLoader()
3536
3537 original_listdir = os.listdir
3538 def restore_listdir():
3539 os.listdir = original_listdir
3540 original_isfile = os.path.isfile
3541 def restore_isfile():
3542 os.path.isfile = original_isfile
3543 original_isdir = os.path.isdir
3544 def restore_isdir():
3545 os.path.isdir = original_isdir
3546
3547 directories = ['a_directory', 'test_directory', 'test_directory2']
3548 path_lists = [directories, [], [], []]
3549 os.listdir = lambda path: path_lists.pop(0)
3550 self.addCleanup(restore_listdir)
3551
3552 os.path.isdir = lambda path: True
3553 self.addCleanup(restore_isdir)
3554
3555 os.path.isfile = lambda path: os.path.basename(path) not in directories
3556 self.addCleanup(restore_isfile)
3557
3558 class Module(object):
3559 paths = []
3560 load_tests_args = []
3561
3562 def __init__(self, path):
3563 self.path = path
3564 self.paths.append(path)
3565 if os.path.basename(path) == 'test_directory':
3566 def load_tests(loader, tests, pattern):
3567 self.load_tests_args.append((loader, tests, pattern))
3568 return 'load_tests'
3569 self.load_tests = load_tests
3570
3571 def __eq__(self, other):
3572 return self.path == other.path
3573
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003574 loader._get_module_from_name = lambda name: Module(name)
Benjamin Petersond2397752009-06-27 23:45:02 +00003575 def loadTestsFromModule(module, use_load_tests):
3576 if use_load_tests:
3577 raise self.failureException('use_load_tests should be False for packages')
3578 return module.path + ' module tests'
3579 loader.loadTestsFromModule = loadTestsFromModule
3580
3581 loader._top_level_dir = '/foo'
3582 # this time no '.py' on the pattern so that it can match
3583 # a test package
3584 suite = list(loader._find_tests('/foo', 'test*'))
3585
3586 # We should have loaded tests from the test_directory package by calling load_tests
3587 # and directly from the test_directory2 package
3588 self.assertEqual(suite,
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003589 ['load_tests', 'test_directory2' + ' module tests'])
3590 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Benjamin Petersond2397752009-06-27 23:45:02 +00003591
3592 # load_tests should have been called once with loader, tests and pattern
3593 self.assertEqual(Module.load_tests_args,
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003594 [(loader, 'test_directory' + ' module tests', 'test*')])
Benjamin Petersond2397752009-06-27 23:45:02 +00003595
3596 def test_discover(self):
3597 loader = unittest.TestLoader()
3598
3599 original_isfile = os.path.isfile
3600 def restore_isfile():
3601 os.path.isfile = original_isfile
3602
3603 os.path.isfile = lambda path: False
3604 self.addCleanup(restore_isfile)
3605
Nick Coghlan6ead5522009-10-18 13:19:33 +00003606 orig_sys_path = sys.path[:]
3607 def restore_path():
3608 sys.path[:] = orig_sys_path
3609 self.addCleanup(restore_path)
Benjamin Petersond2397752009-06-27 23:45:02 +00003610
Nick Coghlan6ead5522009-10-18 13:19:33 +00003611 full_path = os.path.abspath(os.path.normpath('/foo'))
Benjamin Petersond2397752009-06-27 23:45:02 +00003612 with self.assertRaises(ImportError):
3613 loader.discover('/foo/bar', top_level_dir='/foo')
3614
3615 self.assertEqual(loader._top_level_dir, full_path)
3616 self.assertIn(full_path, sys.path)
3617
3618 os.path.isfile = lambda path: True
3619 _find_tests_args = []
3620 def _find_tests(start_dir, pattern):
3621 _find_tests_args.append((start_dir, pattern))
3622 return ['tests']
3623 loader._find_tests = _find_tests
3624 loader.suiteClass = str
3625
3626 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3627
3628 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3629 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3630 self.assertEqual(suite, "['tests']")
3631 self.assertEqual(loader._top_level_dir, top_level_dir)
3632 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlan6ead5522009-10-18 13:19:33 +00003633 self.assertIn(top_level_dir, sys.path)
Benjamin Petersond2397752009-06-27 23:45:02 +00003634
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003635 def test_discover_with_modules_that_fail_to_import(self):
3636 loader = unittest.TestLoader()
3637
3638 listdir = os.listdir
3639 os.listdir = lambda _: ['test_this_does_not_exist.py']
3640 isfile = os.path.isfile
3641 os.path.isfile = lambda _: True
Nick Coghlan6ead5522009-10-18 13:19:33 +00003642 orig_sys_path = sys.path[:]
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003643 def restore():
3644 os.path.isfile = isfile
3645 os.listdir = listdir
Nick Coghlan6ead5522009-10-18 13:19:33 +00003646 sys.path[:] = orig_sys_path
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003647 self.addCleanup(restore)
3648
3649 suite = loader.discover('.')
Nick Coghlan6ead5522009-10-18 13:19:33 +00003650 self.assertIn(os.getcwd(), sys.path)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003651 self.assertEqual(suite.countTestCases(), 1)
3652 test = list(list(suite)[0])[0] # extract test from suite
3653
3654 with self.assertRaises(ImportError):
3655 test.test_this_does_not_exist()
3656
Benjamin Petersond2397752009-06-27 23:45:02 +00003657 def test_command_line_handling_parseArgs(self):
3658 # Haha - take that uninstantiable class
3659 program = object.__new__(TestProgram)
3660
3661 args = []
3662 def do_discovery(argv):
3663 args.extend(argv)
3664 program._do_discovery = do_discovery
3665 program.parseArgs(['something', 'discover'])
3666 self.assertEqual(args, [])
3667
3668 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3669 self.assertEqual(args, ['foo', 'bar'])
3670
3671 def test_command_line_handling_do_discovery_too_many_arguments(self):
3672 class Stop(Exception):
3673 pass
3674 def usageExit():
3675 raise Stop
3676
3677 program = object.__new__(TestProgram)
3678 program.usageExit = usageExit
3679
3680 with self.assertRaises(Stop):
3681 # too many args
3682 program._do_discovery(['one', 'two', 'three', 'four'])
3683
3684
3685 def test_command_line_handling_do_discovery_calls_loader(self):
3686 program = object.__new__(TestProgram)
3687
3688 class Loader(object):
3689 args = []
3690 def discover(self, start_dir, pattern, top_level_dir):
3691 self.args.append((start_dir, pattern, top_level_dir))
3692 return 'tests'
3693
3694 program._do_discovery(['-v'], Loader=Loader)
3695 self.assertEqual(program.verbosity, 2)
3696 self.assertEqual(program.test, 'tests')
3697 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3698
3699 Loader.args = []
3700 program = object.__new__(TestProgram)
3701 program._do_discovery(['--verbose'], Loader=Loader)
3702 self.assertEqual(program.test, 'tests')
3703 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3704
3705 Loader.args = []
3706 program = object.__new__(TestProgram)
3707 program._do_discovery([], Loader=Loader)
3708 self.assertEqual(program.test, 'tests')
3709 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3710
3711 Loader.args = []
3712 program = object.__new__(TestProgram)
3713 program._do_discovery(['fish'], Loader=Loader)
3714 self.assertEqual(program.test, 'tests')
3715 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3716
3717 Loader.args = []
3718 program = object.__new__(TestProgram)
3719 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3720 self.assertEqual(program.test, 'tests')
3721 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3722
3723 Loader.args = []
3724 program = object.__new__(TestProgram)
3725 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3726 self.assertEqual(program.test, 'tests')
3727 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3728
3729 Loader.args = []
3730 program = object.__new__(TestProgram)
3731 program._do_discovery(['-s', 'fish'], Loader=Loader)
3732 self.assertEqual(program.test, 'tests')
3733 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3734
3735 Loader.args = []
3736 program = object.__new__(TestProgram)
3737 program._do_discovery(['-t', 'fish'], Loader=Loader)
3738 self.assertEqual(program.test, 'tests')
3739 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3740
3741 Loader.args = []
3742 program = object.__new__(TestProgram)
3743 program._do_discovery(['-p', 'fish'], Loader=Loader)
3744 self.assertEqual(program.test, 'tests')
3745 self.assertEqual(Loader.args, [('.', 'fish', None)])
3746
3747 Loader.args = []
3748 program = object.__new__(TestProgram)
3749 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3750 self.assertEqual(program.test, 'tests')
3751 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3752 self.assertEqual(program.verbosity, 2)
3753
3754
Jim Fultonfafd8742004-08-28 15:22:12 +00003755######################################################################
3756## Main
3757######################################################################
3758
3759def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003760 support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003761 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003762 Test_TestSkipping, Test_Assertions, TestLongMessage,
Antoine Pitrouc63ecee2009-11-10 21:34:48 +00003763 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner)
Jim Fultonfafd8742004-08-28 15:22:12 +00003764
Guido van Rossumd8faa362007-04-27 19:54:29 +00003765if __name__ == "__main__":
Jim Fultonfafd8742004-08-28 15:22:12 +00003766 test_main()