blob: 75b9d0c7974098db560235e79395107c0256c052 [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
Michael Foord34c94622010-02-10 15:51:42 +00002047 def testGetDescriptionWithoutDocstring(self):
Michael Foord0b581e52010-02-10 15:53:19 +00002048 result = unittest.TextTestResult(None, True, 1)
Michael Foord34c94622010-02-10 15:51:42 +00002049 self.assertEqual(
2050 result.getDescription(self),
2051 'testGetDescriptionWithoutDocstring (' + __name__ +
2052 '.Test_TestResult)')
2053
R. David Murray378c0cf2010-02-24 01:46:21 +00002054 @unittest.skipIf(sys.flags.optimize >= 2,
2055 "Docstrings are omitted with -O2 and above")
Michael Foord34c94622010-02-10 15:51:42 +00002056 def testGetDescriptionWithOneLineDocstring(self):
2057 """Tests getDescription() for a method with a docstring."""
Michael Foord0b581e52010-02-10 15:53:19 +00002058 result = unittest.TextTestResult(None, True, 1)
Michael Foord34c94622010-02-10 15:51:42 +00002059 self.assertEqual(
2060 result.getDescription(self),
2061 ('testGetDescriptionWithOneLineDocstring '
2062 '(' + __name__ + '.Test_TestResult)\n'
2063 'Tests getDescription() for a method with a docstring.'))
2064
R. David Murray378c0cf2010-02-24 01:46:21 +00002065 @unittest.skipIf(sys.flags.optimize >= 2,
2066 "Docstrings are omitted with -O2 and above")
Michael Foord34c94622010-02-10 15:51:42 +00002067 def testGetDescriptionWithMultiLineDocstring(self):
2068 """Tests getDescription() for a method with a longer docstring.
2069 The second line of the docstring.
2070 """
Michael Foord0b581e52010-02-10 15:53:19 +00002071 result = unittest.TextTestResult(None, True, 1)
Michael Foord34c94622010-02-10 15:51:42 +00002072 self.assertEqual(
2073 result.getDescription(self),
2074 ('testGetDescriptionWithMultiLineDocstring '
2075 '(' + __name__ + '.Test_TestResult)\n'
2076 'Tests getDescription() for a method with a longer '
2077 'docstring.'))
2078
2079
Guido van Rossumd8faa362007-04-27 19:54:29 +00002080### Support code for Test_TestCase
2081################################################################
2082
2083class Foo(unittest.TestCase):
2084 def runTest(self): pass
2085 def test1(self): pass
2086
2087class Bar(Foo):
2088 def test2(self): pass
2089
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002090class LoggingTestCase(unittest.TestCase):
2091 """A test case which logs its calls."""
2092
2093 def __init__(self, events):
2094 super(LoggingTestCase, self).__init__('test')
2095 self.events = events
2096
2097 def setUp(self):
2098 self.events.append('setUp')
2099
2100 def test(self):
2101 self.events.append('test')
2102
2103 def tearDown(self):
2104 self.events.append('tearDown')
2105
2106class ResultWithNoStartTestRunStopTestRun(object):
2107 """An object honouring TestResult before startTestRun/stopTestRun."""
2108
2109 def __init__(self):
2110 self.failures = []
2111 self.errors = []
2112 self.testsRun = 0
2113 self.skipped = []
2114 self.expectedFailures = []
2115 self.unexpectedSuccesses = []
2116 self.shouldStop = False
2117
2118 def startTest(self, test):
2119 pass
2120
2121 def stopTest(self, test):
2122 pass
2123
2124 def addError(self, test):
2125 pass
2126
2127 def addFailure(self, test):
2128 pass
2129
2130 def addSuccess(self, test):
2131 pass
2132
2133 def wasSuccessful(self):
2134 return True
2135
2136
Guido van Rossumd8faa362007-04-27 19:54:29 +00002137################################################################
2138### /Support code for Test_TestCase
2139
2140class Test_TestCase(TestCase, TestEquality, TestHashing):
2141
2142 ### Set up attributes used by inherited tests
2143 ################################################################
2144
2145 # Used by TestHashing.test_hash and TestEquality.test_eq
2146 eq_pairs = [(Foo('test1'), Foo('test1'))]
2147
2148 # Used by TestEquality.test_ne
2149 ne_pairs = [(Foo('test1'), Foo('runTest'))
2150 ,(Foo('test1'), Bar('test1'))
2151 ,(Foo('test1'), Bar('test2'))]
2152
2153 ################################################################
2154 ### /Set up attributes used by inherited tests
2155
2156
2157 # "class TestCase([methodName])"
2158 # ...
2159 # "Each instance of TestCase will run a single test method: the
2160 # method named methodName."
2161 # ...
2162 # "methodName defaults to "runTest"."
2163 #
2164 # Make sure it really is optional, and that it defaults to the proper
2165 # thing.
2166 def test_init__no_test_name(self):
2167 class Test(unittest.TestCase):
2168 def runTest(self): raise MyException()
2169 def test(self): pass
2170
2171 self.assertEqual(Test().id()[-13:], '.Test.runTest')
2172
2173 # "class TestCase([methodName])"
2174 # ...
2175 # "Each instance of TestCase will run a single test method: the
2176 # method named methodName."
2177 def test_init__test_name__valid(self):
2178 class Test(unittest.TestCase):
2179 def runTest(self): raise MyException()
2180 def test(self): pass
2181
2182 self.assertEqual(Test('test').id()[-10:], '.Test.test')
2183
2184 # "class TestCase([methodName])"
2185 # ...
2186 # "Each instance of TestCase will run a single test method: the
2187 # method named methodName."
2188 def test_init__test_name__invalid(self):
2189 class Test(unittest.TestCase):
2190 def runTest(self): raise MyException()
2191 def test(self): pass
2192
2193 try:
2194 Test('testfoo')
2195 except ValueError:
2196 pass
2197 else:
2198 self.fail("Failed to raise ValueError")
2199
2200 # "Return the number of tests represented by the this test object. For
2201 # TestCase instances, this will always be 1"
2202 def test_countTestCases(self):
2203 class Foo(unittest.TestCase):
2204 def test(self): pass
2205
2206 self.assertEqual(Foo('test').countTestCases(), 1)
2207
2208 # "Return the default type of test result object to be used to run this
2209 # test. For TestCase instances, this will always be
2210 # unittest.TestResult; subclasses of TestCase should
2211 # override this as necessary."
2212 def test_defaultTestResult(self):
2213 class Foo(unittest.TestCase):
2214 def runTest(self):
2215 pass
2216
2217 result = Foo().defaultTestResult()
2218 self.assertEqual(type(result), unittest.TestResult)
2219
2220 # "When a setUp() method is defined, the test runner will run that method
2221 # prior to each test. Likewise, if a tearDown() method is defined, the
2222 # test runner will invoke that method after each test. In the example,
2223 # setUp() was used to create a fresh sequence for each test."
2224 #
2225 # Make sure the proper call order is maintained, even if setUp() raises
2226 # an exception.
2227 def test_run_call_order__error_in_setUp(self):
2228 events = []
2229 result = LoggingResult(events)
2230
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002231 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002232 def setUp(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002233 super(Foo, self).setUp()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002234 raise RuntimeError('raised by Foo.setUp')
2235
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002236 Foo(events).run(result)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002237 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2238 self.assertEqual(events, expected)
2239
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002240 # "With a temporary result stopTestRun is called when setUp errors.
2241 def test_run_call_order__error_in_setUp_default_result(self):
2242 events = []
2243
2244 class Foo(LoggingTestCase):
2245 def defaultTestResult(self):
2246 return LoggingResult(self.events)
2247
2248 def setUp(self):
2249 super(Foo, self).setUp()
2250 raise RuntimeError('raised by Foo.setUp')
2251
2252 Foo(events).run()
2253 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2254 'stopTest', 'stopTestRun']
2255 self.assertEqual(events, expected)
2256
Guido van Rossumd8faa362007-04-27 19:54:29 +00002257 # "When a setUp() method is defined, the test runner will run that method
2258 # prior to each test. Likewise, if a tearDown() method is defined, the
2259 # test runner will invoke that method after each test. In the example,
2260 # setUp() was used to create a fresh sequence for each test."
2261 #
2262 # Make sure the proper call order is maintained, even if the test raises
2263 # an error (as opposed to a failure).
2264 def test_run_call_order__error_in_test(self):
2265 events = []
2266 result = LoggingResult(events)
2267
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002268 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002269 def test(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002270 super(Foo, self).test()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002271 raise RuntimeError('raised by Foo.test')
2272
Guido van Rossumd8faa362007-04-27 19:54:29 +00002273 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2274 'stopTest']
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002275 Foo(events).run(result)
2276 self.assertEqual(events, expected)
2277
2278 # "With a default result, an error in the test still results in stopTestRun
2279 # being called."
2280 def test_run_call_order__error_in_test_default_result(self):
2281 events = []
2282
2283 class Foo(LoggingTestCase):
2284 def defaultTestResult(self):
2285 return LoggingResult(self.events)
2286
2287 def test(self):
2288 super(Foo, self).test()
2289 raise RuntimeError('raised by Foo.test')
2290
2291 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2292 'tearDown', 'stopTest', 'stopTestRun']
2293 Foo(events).run()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002294 self.assertEqual(events, expected)
2295
2296 # "When a setUp() method is defined, the test runner will run that method
2297 # prior to each test. Likewise, if a tearDown() method is defined, the
2298 # test runner will invoke that method after each test. In the example,
2299 # setUp() was used to create a fresh sequence for each test."
2300 #
2301 # Make sure the proper call order is maintained, even if the test signals
2302 # a failure (as opposed to an error).
2303 def test_run_call_order__failure_in_test(self):
2304 events = []
2305 result = LoggingResult(events)
2306
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002307 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002308 def test(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002309 super(Foo, self).test()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002310 self.fail('raised by Foo.test')
2311
Guido van Rossumd8faa362007-04-27 19:54:29 +00002312 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2313 'stopTest']
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002314 Foo(events).run(result)
2315 self.assertEqual(events, expected)
2316
2317 # "When a test fails with a default result stopTestRun is still called."
2318 def test_run_call_order__failure_in_test_default_result(self):
2319
2320 class Foo(LoggingTestCase):
2321 def defaultTestResult(self):
2322 return LoggingResult(self.events)
2323 def test(self):
2324 super(Foo, self).test()
2325 self.fail('raised by Foo.test')
2326
2327 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2328 'tearDown', 'stopTest', 'stopTestRun']
2329 events = []
2330 Foo(events).run()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002331 self.assertEqual(events, expected)
2332
2333 # "When a setUp() method is defined, the test runner will run that method
2334 # prior to each test. Likewise, if a tearDown() method is defined, the
2335 # test runner will invoke that method after each test. In the example,
2336 # setUp() was used to create a fresh sequence for each test."
2337 #
2338 # Make sure the proper call order is maintained, even if tearDown() raises
2339 # an exception.
2340 def test_run_call_order__error_in_tearDown(self):
2341 events = []
2342 result = LoggingResult(events)
2343
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002344 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002345 def tearDown(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002346 super(Foo, self).tearDown()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002347 raise RuntimeError('raised by Foo.tearDown')
2348
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002349 Foo(events).run(result)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002350 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2351 'stopTest']
2352 self.assertEqual(events, expected)
2353
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002354 # "When tearDown errors with a default result stopTestRun is still called."
2355 def test_run_call_order__error_in_tearDown_default_result(self):
2356
2357 class Foo(LoggingTestCase):
2358 def defaultTestResult(self):
2359 return LoggingResult(self.events)
2360 def tearDown(self):
2361 super(Foo, self).tearDown()
2362 raise RuntimeError('raised by Foo.tearDown')
2363
2364 events = []
2365 Foo(events).run()
2366 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2367 'addError', 'stopTest', 'stopTestRun']
2368 self.assertEqual(events, expected)
2369
2370 # "TestCase.run() still works when the defaultTestResult is a TestResult
2371 # that does not support startTestRun and stopTestRun.
2372 def test_run_call_order_default_result(self):
2373
2374 class Foo(unittest.TestCase):
2375 def defaultTestResult(self):
2376 return ResultWithNoStartTestRunStopTestRun()
2377 def test(self):
2378 pass
2379
2380 Foo('test').run()
2381
Guido van Rossumd8faa362007-04-27 19:54:29 +00002382 # "This class attribute gives the exception raised by the test() method.
2383 # If a test framework needs to use a specialized exception, possibly to
2384 # carry additional information, it must subclass this exception in
2385 # order to ``play fair'' with the framework. The initial value of this
2386 # attribute is AssertionError"
2387 def test_failureException__default(self):
2388 class Foo(unittest.TestCase):
2389 def test(self):
2390 pass
2391
Benjamin Petersone1759f82009-06-30 23:35:19 +00002392 self.assertTrue(Foo('test').failureException is AssertionError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002393
2394 # "This class attribute gives the exception raised by the test() method.
2395 # If a test framework needs to use a specialized exception, possibly to
2396 # carry additional information, it must subclass this exception in
2397 # order to ``play fair'' with the framework."
2398 #
2399 # Make sure TestCase.run() respects the designated failureException
2400 def test_failureException__subclassing__explicit_raise(self):
2401 events = []
2402 result = LoggingResult(events)
2403
2404 class Foo(unittest.TestCase):
2405 def test(self):
2406 raise RuntimeError()
2407
2408 failureException = RuntimeError
2409
Benjamin Petersone1759f82009-06-30 23:35:19 +00002410 self.assertTrue(Foo('test').failureException is RuntimeError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002411
2412
2413 Foo('test').run(result)
2414 expected = ['startTest', 'addFailure', 'stopTest']
2415 self.assertEqual(events, expected)
2416
2417 # "This class attribute gives the exception raised by the test() method.
2418 # If a test framework needs to use a specialized exception, possibly to
2419 # carry additional information, it must subclass this exception in
2420 # order to ``play fair'' with the framework."
2421 #
2422 # Make sure TestCase.run() respects the designated failureException
2423 def test_failureException__subclassing__implicit_raise(self):
2424 events = []
2425 result = LoggingResult(events)
2426
2427 class Foo(unittest.TestCase):
2428 def test(self):
2429 self.fail("foo")
2430
2431 failureException = RuntimeError
2432
Benjamin Petersone1759f82009-06-30 23:35:19 +00002433 self.assertTrue(Foo('test').failureException is RuntimeError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002434
2435
2436 Foo('test').run(result)
2437 expected = ['startTest', 'addFailure', 'stopTest']
2438 self.assertEqual(events, expected)
2439
2440 # "The default implementation does nothing."
2441 def test_setUp(self):
2442 class Foo(unittest.TestCase):
2443 def runTest(self):
2444 pass
2445
2446 # ... and nothing should happen
2447 Foo().setUp()
2448
2449 # "The default implementation does nothing."
2450 def test_tearDown(self):
2451 class Foo(unittest.TestCase):
2452 def runTest(self):
2453 pass
2454
2455 # ... and nothing should happen
2456 Foo().tearDown()
2457
2458 # "Return a string identifying the specific test case."
2459 #
2460 # Because of the vague nature of the docs, I'm not going to lock this
2461 # test down too much. Really all that can be asserted is that the id()
2462 # will be a string (either 8-byte or unicode -- again, because the docs
2463 # just say "string")
2464 def test_id(self):
2465 class Foo(unittest.TestCase):
2466 def runTest(self):
2467 pass
2468
Ezio Melottie9615932010-01-24 19:26:24 +00002469 self.assertIsInstance(Foo().id(), str)
2470
Guido van Rossumd8faa362007-04-27 19:54:29 +00002471
Guido van Rossumd8faa362007-04-27 19:54:29 +00002472 # "If result is omitted or None, a temporary result object is created
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002473 # and used, but is not made available to the caller. As TestCase owns the
2474 # temporary result startTestRun and stopTestRun are called.
2475
Guido van Rossumd8faa362007-04-27 19:54:29 +00002476 def test_run__uses_defaultTestResult(self):
2477 events = []
2478
2479 class Foo(unittest.TestCase):
2480 def test(self):
2481 events.append('test')
2482
2483 def defaultTestResult(self):
2484 return LoggingResult(events)
2485
2486 # Make run() find a result object on its own
2487 Foo('test').run()
2488
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002489 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2490 'stopTest', 'stopTestRun']
Guido van Rossumd8faa362007-04-27 19:54:29 +00002491 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002492
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002493 def testShortDescriptionWithoutDocstring(self):
Michael Foord34c94622010-02-10 15:51:42 +00002494 self.assertIsNone(self.shortDescription())
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002495
R. David Murray378c0cf2010-02-24 01:46:21 +00002496 @unittest.skipIf(sys.flags.optimize >= 2,
2497 "Docstrings are omitted with -O2 and above")
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002498 def testShortDescriptionWithOneLineDocstring(self):
2499 """Tests shortDescription() for a method with a docstring."""
2500 self.assertEqual(
2501 self.shortDescription(),
Michael Foord34c94622010-02-10 15:51:42 +00002502 'Tests shortDescription() for a method with a docstring.')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002503
R. David Murray378c0cf2010-02-24 01:46:21 +00002504 @unittest.skipIf(sys.flags.optimize >= 2,
2505 "Docstrings are omitted with -O2 and above")
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002506 def testShortDescriptionWithMultiLineDocstring(self):
2507 """Tests shortDescription() for a method with a longer docstring.
2508
2509 This method ensures that only the first line of a docstring is
2510 returned used in the short description, no matter how long the
2511 whole thing is.
2512 """
2513 self.assertEqual(
2514 self.shortDescription(),
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002515 'Tests shortDescription() for a method with a longer '
Michael Foord34c94622010-02-10 15:51:42 +00002516 'docstring.')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002517
2518 def testAddTypeEqualityFunc(self):
2519 class SadSnake(object):
2520 """Dummy class for test_addTypeEqualityFunc."""
2521 s1, s2 = SadSnake(), SadSnake()
2522 self.assertFalse(s1 == s2)
2523 def AllSnakesCreatedEqual(a, b, msg=None):
2524 return type(a) == type(b) == SadSnake
2525 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2526 self.assertEqual(s1, s2)
2527 # No this doesn't clean up and remove the SadSnake equality func
2528 # from this TestCase instance but since its a local nothing else
2529 # will ever notice that.
2530
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00002531 def testAssertIs(self):
2532 thing = object()
2533 self.assertIs(thing, thing)
2534 self.assertRaises(self.failureException, self.assertIs, thing, object())
2535
2536 def testAssertIsNot(self):
2537 thing = object()
2538 self.assertIsNot(thing, object())
2539 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2540
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00002541 def testAssertIsInstance(self):
2542 thing = []
2543 self.assertIsInstance(thing, list)
2544 self.assertRaises(self.failureException, self.assertIsInstance,
2545 thing, dict)
2546
2547 def testAssertNotIsInstance(self):
2548 thing = []
2549 self.assertNotIsInstance(thing, dict)
2550 self.assertRaises(self.failureException, self.assertNotIsInstance,
2551 thing, list)
2552
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002553 def testAssertIn(self):
2554 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2555
2556 self.assertIn('a', 'abc')
2557 self.assertIn(2, [1, 2, 3])
2558 self.assertIn('monkey', animals)
2559
2560 self.assertNotIn('d', 'abc')
2561 self.assertNotIn(0, [1, 2, 3])
2562 self.assertNotIn('otter', animals)
2563
2564 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2565 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2566 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2567 animals)
2568
2569 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2570 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2571 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2572 animals)
2573
2574 def testAssertDictContainsSubset(self):
2575 self.assertDictContainsSubset({}, {})
2576 self.assertDictContainsSubset({}, {'a': 1})
2577 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2578 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2579 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2580
2581 self.assertRaises(unittest.TestCase.failureException,
2582 self.assertDictContainsSubset, {'a': 2}, {'a': 1},
2583 '.*Mismatched values:.*')
2584
2585 self.assertRaises(unittest.TestCase.failureException,
2586 self.assertDictContainsSubset, {'c': 1}, {'a': 1},
2587 '.*Missing:.*')
2588
2589 self.assertRaises(unittest.TestCase.failureException,
2590 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2591 {'a': 1}, '.*Missing:.*')
2592
2593 self.assertRaises(unittest.TestCase.failureException,
2594 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2595 {'a': 1}, '.*Missing:.*Mismatched values:.*')
2596
2597 def testAssertEqual(self):
2598 equal_pairs = [
2599 ((), ()),
2600 ({}, {}),
2601 ([], []),
2602 (set(), set()),
2603 (frozenset(), frozenset())]
2604 for a, b in equal_pairs:
2605 # This mess of try excepts is to test the assertEqual behavior
2606 # itself.
2607 try:
2608 self.assertEqual(a, b)
2609 except self.failureException:
2610 self.fail('assertEqual(%r, %r) failed' % (a, b))
2611 try:
2612 self.assertEqual(a, b, msg='foo')
2613 except self.failureException:
2614 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2615 try:
2616 self.assertEqual(a, b, 'foo')
2617 except self.failureException:
2618 self.fail('assertEqual(%r, %r) with third parameter failed' %
2619 (a, b))
2620
2621 unequal_pairs = [
2622 ((), []),
2623 ({}, set()),
2624 (set([4,1]), frozenset([4,2])),
2625 (frozenset([4,5]), set([2,3])),
2626 (set([3,4]), set([5,4]))]
2627 for a, b in unequal_pairs:
2628 self.assertRaises(self.failureException, self.assertEqual, a, b)
2629 self.assertRaises(self.failureException, self.assertEqual, a, b,
2630 'foo')
2631 self.assertRaises(self.failureException, self.assertEqual, a, b,
2632 msg='foo')
2633
2634 def testEquality(self):
2635 self.assertListEqual([], [])
2636 self.assertTupleEqual((), ())
2637 self.assertSequenceEqual([], ())
2638
2639 a = [0, 'a', []]
2640 b = []
2641 self.assertRaises(unittest.TestCase.failureException,
2642 self.assertListEqual, a, b)
2643 self.assertRaises(unittest.TestCase.failureException,
2644 self.assertListEqual, tuple(a), tuple(b))
2645 self.assertRaises(unittest.TestCase.failureException,
2646 self.assertSequenceEqual, a, tuple(b))
2647
2648 b.extend(a)
2649 self.assertListEqual(a, b)
2650 self.assertTupleEqual(tuple(a), tuple(b))
2651 self.assertSequenceEqual(a, tuple(b))
2652 self.assertSequenceEqual(tuple(a), b)
2653
2654 self.assertRaises(self.failureException, self.assertListEqual,
2655 a, tuple(b))
2656 self.assertRaises(self.failureException, self.assertTupleEqual,
2657 tuple(a), b)
2658 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2659 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2660 tuple(b))
2661 self.assertRaises(self.failureException, self.assertSequenceEqual,
2662 None, tuple(b))
2663 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2664 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2665 self.assertRaises(self.failureException, self.assertSequenceEqual,
2666 1, 1)
2667
2668 self.assertDictEqual({}, {})
2669
2670 c = { 'x': 1 }
2671 d = {}
2672 self.assertRaises(unittest.TestCase.failureException,
2673 self.assertDictEqual, c, d)
2674
2675 d.update(c)
2676 self.assertDictEqual(c, d)
2677
2678 d['x'] = 0
2679 self.assertRaises(unittest.TestCase.failureException,
2680 self.assertDictEqual, c, d, 'These are unequal')
2681
2682 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2683 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2684 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2685
2686 self.assertSameElements([1, 2, 3], [3, 2, 1])
2687 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2688 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2689 self.assertRaises(self.failureException, self.assertSameElements,
2690 [10], [10, 11])
2691 self.assertRaises(self.failureException, self.assertSameElements,
2692 [10, 11], [10])
2693
2694 # Test that sequences of unhashable objects can be tested for sameness:
2695 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00002696
Benjamin Peterson3bb6b7a2009-04-04 16:46:24 +00002697 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002698 self.assertRaises(self.failureException, self.assertSameElements,
2699 [[1]], [[2]])
Michael Foorda5809c82009-04-04 18:55:09 +00002700 self.assertRaises(self.failureException, self.assertSameElements,
2701 [{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 2}])
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002702
2703 def testAssertSetEqual(self):
2704 set1 = set()
2705 set2 = set()
2706 self.assertSetEqual(set1, set2)
2707
2708 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2709 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2710 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2711 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2712
2713 set1 = set(['a'])
2714 set2 = set()
2715 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2716
2717 set1 = set(['a'])
2718 set2 = set(['a'])
2719 self.assertSetEqual(set1, set2)
2720
2721 set1 = set(['a'])
2722 set2 = set(['a', 'b'])
2723 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2724
2725 set1 = set(['a'])
2726 set2 = frozenset(['a', 'b'])
2727 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2728
2729 set1 = set(['a', 'b'])
2730 set2 = frozenset(['a', 'b'])
2731 self.assertSetEqual(set1, set2)
2732
2733 set1 = set()
2734 set2 = "foo"
2735 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2736 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2737
2738 # make sure any string formatting is tuple-safe
2739 set1 = set([(0, 1), (2, 3)])
2740 set2 = set([(4, 5)])
2741 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2742
2743 def testInequality(self):
2744 # Try ints
2745 self.assertGreater(2, 1)
2746 self.assertGreaterEqual(2, 1)
2747 self.assertGreaterEqual(1, 1)
2748 self.assertLess(1, 2)
2749 self.assertLessEqual(1, 2)
2750 self.assertLessEqual(1, 1)
2751 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2752 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2753 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2754 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2755 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2756 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2757
2758 # Try Floats
2759 self.assertGreater(1.1, 1.0)
2760 self.assertGreaterEqual(1.1, 1.0)
2761 self.assertGreaterEqual(1.0, 1.0)
2762 self.assertLess(1.0, 1.1)
2763 self.assertLessEqual(1.0, 1.1)
2764 self.assertLessEqual(1.0, 1.0)
2765 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2766 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2767 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2768 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2769 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2770 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2771
2772 # Try Strings
2773 self.assertGreater('bug', 'ant')
2774 self.assertGreaterEqual('bug', 'ant')
2775 self.assertGreaterEqual('ant', 'ant')
2776 self.assertLess('ant', 'bug')
2777 self.assertLessEqual('ant', 'bug')
2778 self.assertLessEqual('ant', 'ant')
2779 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2780 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2781 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2782 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2783 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2784 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2785
2786 # Try bytes
2787 self.assertGreater(b'bug', b'ant')
2788 self.assertGreaterEqual(b'bug', b'ant')
2789 self.assertGreaterEqual(b'ant', b'ant')
2790 self.assertLess(b'ant', b'bug')
2791 self.assertLessEqual(b'ant', b'bug')
2792 self.assertLessEqual(b'ant', b'ant')
2793 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'bug')
2794 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'ant')
2795 self.assertRaises(self.failureException, self.assertGreaterEqual, b'ant',
2796 b'bug')
2797 self.assertRaises(self.failureException, self.assertLess, b'bug', b'ant')
2798 self.assertRaises(self.failureException, self.assertLess, b'ant', b'ant')
2799 self.assertRaises(self.failureException, self.assertLessEqual, b'bug', b'ant')
2800
2801 def testAssertMultiLineEqual(self):
2802 sample_text = """\
2803http://www.python.org/doc/2.3/lib/module-unittest.html
2804test case
2805 A test case is the smallest unit of testing. [...]
2806"""
2807 revised_sample_text = """\
2808http://www.python.org/doc/2.4.1/lib/module-unittest.html
2809test case
2810 A test case is the smallest unit of testing. [...] You may provide your
2811 own implementation that does not subclass from TestCase, of course.
2812"""
2813 sample_text_error = """
2814- http://www.python.org/doc/2.3/lib/module-unittest.html
2815? ^
2816+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2817? ^^^
2818 test case
2819- A test case is the smallest unit of testing. [...]
2820+ A test case is the smallest unit of testing. [...] You may provide your
2821? +++++++++++++++++++++
2822+ own implementation that does not subclass from TestCase, of course.
2823"""
2824
2825 try:
2826 self.assertMultiLineEqual(sample_text, revised_sample_text)
2827 except self.failureException as e:
Michael Foord02834952010-02-08 23:10:39 +00002828 # no fair testing ourself with ourself, and assertEqual is used for strings
2829 # so can't use assertEqual either. Just use assertTrue.
2830 self.assertTrue(sample_text_error == str(e))
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002831
2832 def testAssertIsNone(self):
2833 self.assertIsNone(None)
2834 self.assertRaises(self.failureException, self.assertIsNone, False)
2835 self.assertIsNotNone('DjZoPloGears on Rails')
2836 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2837
2838 def testAssertRegexpMatches(self):
2839 self.assertRegexpMatches('asdfabasdf', r'ab+')
2840 self.assertRaises(self.failureException, self.assertRegexpMatches,
2841 'saaas', r'aaaa')
2842
2843 def testAssertRaisesRegexp(self):
2844 class ExceptionMock(Exception):
2845 pass
2846
2847 def Stub():
2848 raise ExceptionMock('We expect')
2849
2850 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2851 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2852
2853 def testAssertNotRaisesRegexp(self):
2854 self.assertRaisesRegexp(
Benjamin Peterson4f75b642009-04-04 16:39:09 +00002855 self.failureException, '^Exception not raised by <lambda>$',
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002856 self.assertRaisesRegexp, Exception, re.compile('x'),
2857 lambda: None)
2858 self.assertRaisesRegexp(
Benjamin Peterson4f75b642009-04-04 16:39:09 +00002859 self.failureException, '^Exception not raised by <lambda>$',
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002860 self.assertRaisesRegexp, Exception, 'x',
2861 lambda: None)
2862
2863 def testAssertRaisesRegexpMismatch(self):
2864 def Stub():
2865 raise Exception('Unexpected')
2866
2867 self.assertRaisesRegexp(
2868 self.failureException,
2869 r'"\^Expected\$" does not match "Unexpected"',
2870 self.assertRaisesRegexp, Exception, '^Expected$',
2871 Stub)
2872 self.assertRaisesRegexp(
2873 self.failureException,
2874 r'"\^Expected\$" does not match "Unexpected"',
2875 self.assertRaisesRegexp, Exception,
2876 re.compile('^Expected$'), Stub)
2877
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +00002878 def testAssertRaisesExcValue(self):
2879 class ExceptionMock(Exception):
2880 pass
2881
2882 def Stub(foo):
2883 raise ExceptionMock(foo)
2884 v = "particular value"
2885
2886 ctx = self.assertRaises(ExceptionMock)
2887 with ctx:
2888 Stub(v)
Ezio Melotti49008232010-02-08 21:57:48 +00002889 e = ctx.exception
Ezio Melottie9615932010-01-24 19:26:24 +00002890 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +00002891 self.assertEqual(e.args[0], v)
2892
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002893 def testSynonymAssertMethodNames(self):
2894 """Test undocumented method name synonyms.
2895
2896 Please do not use these methods names in your own code.
2897
2898 This test confirms their continued existence and functionality
2899 in order to avoid breaking existing code.
2900 """
2901 self.assertNotEquals(3, 5)
2902 self.assertEquals(3, 3)
2903 self.assertAlmostEquals(2.0, 2.0)
2904 self.assertNotAlmostEquals(3.0, 5.0)
2905 self.assert_(True)
2906
2907 def testPendingDeprecationMethodNames(self):
2908 """Test fail* methods pending deprecation, they will warn in 3.2.
2909
2910 Do not use these methods. They will go away in 3.3.
2911 """
Benjamin Peterson6bcbad52009-06-30 23:45:41 +00002912 old = (
2913 (self.failIfEqual, (3, 5)),
2914 (self.failUnlessEqual, (3, 3)),
2915 (self.failUnlessAlmostEqual, (2.0, 2.0)),
2916 (self.failIfAlmostEqual, (3.0, 5.0)),
2917 (self.failUnless, (True,)),
2918 (self.failUnlessRaises, (TypeError, lambda _: 3.14 + 'spam')),
2919 (self.failIf, (False,))
2920 )
2921 for meth, args in old:
2922 with warnings.catch_warnings(record=True) as w:
2923 meth(*args)
2924 self.assertEqual(len(w), 1)
2925 self.assertIs(w[0].category, DeprecationWarning)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002926
2927 def testDeepcopy(self):
2928 # Issue: 5660
2929 class TestableTest(TestCase):
2930 def testNothing(self):
2931 pass
2932
2933 test = TestableTest('testNothing')
2934
2935 # This shouldn't blow up
2936 deepcopy(test)
2937
Benjamin Peterson5254c042009-03-23 22:25:03 +00002938
2939class Test_TestSkipping(TestCase):
2940
2941 def test_skipping(self):
2942 class Foo(unittest.TestCase):
2943 def test_skip_me(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00002944 self.skipTest("skip")
Benjamin Peterson5254c042009-03-23 22:25:03 +00002945 events = []
2946 result = LoggingResult(events)
2947 test = Foo("test_skip_me")
2948 test.run(result)
2949 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2950 self.assertEqual(result.skipped, [(test, "skip")])
2951
2952 # Try letting setUp skip the test now.
2953 class Foo(unittest.TestCase):
2954 def setUp(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00002955 self.skipTest("testing")
Benjamin Peterson5254c042009-03-23 22:25:03 +00002956 def test_nothing(self): pass
2957 events = []
2958 result = LoggingResult(events)
2959 test = Foo("test_nothing")
2960 test.run(result)
2961 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2962 self.assertEqual(result.skipped, [(test, "testing")])
2963 self.assertEqual(result.testsRun, 1)
2964
2965 def test_skipping_decorators(self):
2966 op_table = ((unittest.skipUnless, False, True),
2967 (unittest.skipIf, True, False))
2968 for deco, do_skip, dont_skip in op_table:
2969 class Foo(unittest.TestCase):
2970 @deco(do_skip, "testing")
2971 def test_skip(self): pass
2972
2973 @deco(dont_skip, "testing")
2974 def test_dont_skip(self): pass
2975 test_do_skip = Foo("test_skip")
2976 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002977 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002978 events = []
2979 result = LoggingResult(events)
2980 suite.run(result)
2981 self.assertEqual(len(result.skipped), 1)
2982 expected = ['startTest', 'addSkip', 'stopTest',
2983 'startTest', 'addSuccess', 'stopTest']
2984 self.assertEqual(events, expected)
2985 self.assertEqual(result.testsRun, 2)
2986 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
2987 self.assertTrue(result.wasSuccessful())
2988
2989 def test_skip_class(self):
2990 @unittest.skip("testing")
2991 class Foo(unittest.TestCase):
2992 def test_1(self):
2993 record.append(1)
2994 record = []
2995 result = unittest.TestResult()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002996 test = Foo("test_1")
2997 suite = unittest.TestSuite([test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002998 suite.run(result)
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002999 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003000 self.assertEqual(record, [])
3001
3002 def test_expected_failure(self):
3003 class Foo(unittest.TestCase):
3004 @unittest.expectedFailure
3005 def test_die(self):
3006 self.fail("help me!")
3007 events = []
3008 result = LoggingResult(events)
3009 test = Foo("test_die")
3010 test.run(result)
3011 self.assertEqual(events,
3012 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Peterson52baa292009-03-24 00:56:30 +00003013 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson5254c042009-03-23 22:25:03 +00003014 self.assertTrue(result.wasSuccessful())
3015
3016 def test_unexpected_success(self):
3017 class Foo(unittest.TestCase):
3018 @unittest.expectedFailure
3019 def test_die(self):
3020 pass
3021 events = []
3022 result = LoggingResult(events)
3023 test = Foo("test_die")
3024 test.run(result)
3025 self.assertEqual(events,
3026 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3027 self.assertFalse(result.failures)
Benjamin Peterson52baa292009-03-24 00:56:30 +00003028 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003029 self.assertTrue(result.wasSuccessful())
3030
3031
3032
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003033class Test_Assertions(TestCase):
3034 def test_AlmostEqual(self):
Benjamin Petersone1759f82009-06-30 23:35:19 +00003035 self.assertAlmostEqual(1.00000001, 1.0)
3036 self.assertNotAlmostEqual(1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003037 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003038 self.assertAlmostEqual, 1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003039 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003040 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003041
Benjamin Petersone1759f82009-06-30 23:35:19 +00003042 self.assertAlmostEqual(1.1, 1.0, places=0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003043 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003044 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003045
Benjamin Petersone1759f82009-06-30 23:35:19 +00003046 self.assertAlmostEqual(0, .1+.1j, places=0)
3047 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003048 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003049 self.assertAlmostEqual, 0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003050 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003051 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003052
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003053 self.assertAlmostEqual(float('inf'), float('inf'))
3054 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3055 float('inf'), float('inf'))
3056
3057
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003058 def test_assertRaises(self):
3059 def _raise(e):
3060 raise e
3061 self.assertRaises(KeyError, _raise, KeyError)
3062 self.assertRaises(KeyError, _raise, KeyError("key"))
3063 try:
3064 self.assertRaises(KeyError, lambda: None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003065 except self.failureException as e:
Ezio Melottib58e0bd2010-01-23 15:40:09 +00003066 self.assertIn("KeyError not raised", str(e))
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003067 else:
3068 self.fail("assertRaises() didn't fail")
3069 try:
3070 self.assertRaises(KeyError, _raise, ValueError)
3071 except ValueError:
3072 pass
3073 else:
3074 self.fail("assertRaises() didn't let exception pass through")
Ezio Melotti49008232010-02-08 21:57:48 +00003075 with self.assertRaises(KeyError) as cm:
3076 try:
3077 raise KeyError
3078 except Exception as e:
3079 exc = e
3080 raise
3081 self.assertIs(cm.exception, exc)
3082
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003083 with self.assertRaises(KeyError):
3084 raise KeyError("key")
3085 try:
3086 with self.assertRaises(KeyError):
3087 pass
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003088 except self.failureException as e:
Ezio Melottib58e0bd2010-01-23 15:40:09 +00003089 self.assertIn("KeyError not raised", str(e))
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003090 else:
3091 self.fail("assertRaises() didn't fail")
3092 try:
3093 with self.assertRaises(KeyError):
3094 raise ValueError
3095 except ValueError:
3096 pass
3097 else:
3098 self.fail("assertRaises() didn't let exception pass through")
3099
3100
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003101class TestLongMessage(TestCase):
3102 """Test that the individual asserts honour longMessage.
3103 This actually tests all the message behaviour for
3104 asserts that use longMessage."""
3105
3106 def setUp(self):
3107 class TestableTestFalse(TestCase):
3108 longMessage = False
3109 failureException = self.failureException
3110
3111 def testTest(self):
3112 pass
3113
3114 class TestableTestTrue(TestCase):
3115 longMessage = True
3116 failureException = self.failureException
3117
3118 def testTest(self):
3119 pass
3120
3121 self.testableTrue = TestableTestTrue('testTest')
3122 self.testableFalse = TestableTestFalse('testTest')
3123
3124 def testDefault(self):
3125 self.assertFalse(TestCase.longMessage)
3126
3127 def test_formatMsg(self):
3128 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3129 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3130
3131 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3132 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3133
3134 def assertMessages(self, methodName, args, errors):
3135 def getMethod(i):
3136 useTestableFalse = i < 2
3137 if useTestableFalse:
3138 test = self.testableFalse
3139 else:
3140 test = self.testableTrue
3141 return getattr(test, methodName)
3142
3143 for i, expected_regexp in enumerate(errors):
3144 testMethod = getMethod(i)
3145 kwargs = {}
3146 withMsg = i % 2
3147 if withMsg:
3148 kwargs = {"msg": "oops"}
3149
3150 with self.assertRaisesRegexp(self.failureException,
3151 expected_regexp=expected_regexp):
3152 testMethod(*args, **kwargs)
3153
3154 def testAssertTrue(self):
3155 self.assertMessages('assertTrue', (False,),
3156 ["^False is not True$", "^oops$", "^False is not True$",
3157 "^False is not True : oops$"])
3158
3159 def testAssertFalse(self):
3160 self.assertMessages('assertFalse', (True,),
3161 ["^True is not False$", "^oops$", "^True is not False$",
3162 "^True is not False : oops$"])
3163
3164 def testNotEqual(self):
3165 self.assertMessages('assertNotEqual', (1, 1),
3166 ["^1 == 1$", "^oops$", "^1 == 1$",
3167 "^1 == 1 : oops$"])
3168
3169 def testAlmostEqual(self):
3170 self.assertMessages('assertAlmostEqual', (1, 2),
3171 ["^1 != 2 within 7 places$", "^oops$",
3172 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3173
3174 def testNotAlmostEqual(self):
3175 self.assertMessages('assertNotAlmostEqual', (1, 1),
3176 ["^1 == 1 within 7 places$", "^oops$",
3177 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3178
3179 def test_baseAssertEqual(self):
3180 self.assertMessages('_baseAssertEqual', (1, 2),
3181 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3182
3183 def testAssertSequenceEqual(self):
3184 # Error messages are multiline so not testing on full message
3185 # assertTupleEqual and assertListEqual delegate to this method
3186 self.assertMessages('assertSequenceEqual', ([], [None]),
3187 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3188 r"\+ \[None\] : oops$"])
3189
3190 def testAssertSetEqual(self):
3191 self.assertMessages('assertSetEqual', (set(), set([None])),
3192 ["None$", "^oops$", "None$",
3193 "None : oops$"])
3194
3195 def testAssertIn(self):
3196 self.assertMessages('assertIn', (None, []),
3197 ['^None not found in \[\]$', "^oops$",
3198 '^None not found in \[\]$',
3199 '^None not found in \[\] : oops$'])
3200
3201 def testAssertNotIn(self):
3202 self.assertMessages('assertNotIn', (None, [None]),
3203 ['^None unexpectedly found in \[None\]$', "^oops$",
3204 '^None unexpectedly found in \[None\]$',
3205 '^None unexpectedly found in \[None\] : oops$'])
3206
3207 def testAssertDictEqual(self):
3208 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3209 [r"\+ \{'key': 'value'\}$", "^oops$",
3210 "\+ \{'key': 'value'\}$",
3211 "\+ \{'key': 'value'\} : oops$"])
3212
3213 def testAssertDictContainsSubset(self):
3214 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3215 ["^Missing: 'key'$", "^oops$",
3216 "^Missing: 'key'$",
3217 "^Missing: 'key' : oops$"])
3218
3219 def testAssertSameElements(self):
3220 self.assertMessages('assertSameElements', ([], [None]),
3221 [r"\[None\]$", "^oops$",
3222 r"\[None\]$",
3223 r"\[None\] : oops$"])
3224
3225 def testAssertMultiLineEqual(self):
3226 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3227 [r"\+ foo$", "^oops$",
3228 r"\+ foo$",
3229 r"\+ foo : oops$"])
3230
3231 def testAssertLess(self):
3232 self.assertMessages('assertLess', (2, 1),
3233 ["^2 not less than 1$", "^oops$",
3234 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3235
3236 def testAssertLessEqual(self):
3237 self.assertMessages('assertLessEqual', (2, 1),
3238 ["^2 not less than or equal to 1$", "^oops$",
3239 "^2 not less than or equal to 1$",
3240 "^2 not less than or equal to 1 : oops$"])
3241
3242 def testAssertGreater(self):
3243 self.assertMessages('assertGreater', (1, 2),
3244 ["^1 not greater than 2$", "^oops$",
3245 "^1 not greater than 2$",
3246 "^1 not greater than 2 : oops$"])
3247
3248 def testAssertGreaterEqual(self):
3249 self.assertMessages('assertGreaterEqual', (1, 2),
3250 ["^1 not greater than or equal to 2$", "^oops$",
3251 "^1 not greater than or equal to 2$",
3252 "^1 not greater than or equal to 2 : oops$"])
3253
3254 def testAssertIsNone(self):
3255 self.assertMessages('assertIsNone', ('not None',),
3256 ["^'not None' is not None$", "^oops$",
3257 "^'not None' is not None$",
3258 "^'not None' is not None : oops$"])
3259
3260 def testAssertIsNotNone(self):
3261 self.assertMessages('assertIsNotNone', (None,),
3262 ["^unexpectedly None$", "^oops$",
3263 "^unexpectedly None$",
3264 "^unexpectedly None : oops$"])
3265
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00003266 def testAssertIs(self):
3267 self.assertMessages('assertIs', (None, 'foo'),
3268 ["^None is not 'foo'$", "^oops$",
3269 "^None is not 'foo'$",
3270 "^None is not 'foo' : oops$"])
3271
3272 def testAssertIsNot(self):
3273 self.assertMessages('assertIsNot', (None, None),
3274 ["^unexpectedly identical: None$", "^oops$",
3275 "^unexpectedly identical: None$",
3276 "^unexpectedly identical: None : oops$"])
3277
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003278
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003279class TestCleanUp(TestCase):
3280
3281 def testCleanUp(self):
3282 class TestableTest(TestCase):
3283 def testNothing(self):
3284 pass
3285
3286 test = TestableTest('testNothing')
3287 self.assertEqual(test._cleanups, [])
3288
3289 cleanups = []
3290
3291 def cleanup1(*args, **kwargs):
3292 cleanups.append((1, args, kwargs))
3293
3294 def cleanup2(*args, **kwargs):
3295 cleanups.append((2, args, kwargs))
3296
3297 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3298 test.addCleanup(cleanup2)
3299
3300 self.assertEqual(test._cleanups,
3301 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3302 (cleanup2, (), {})])
3303
3304 result = test.doCleanups()
3305 self.assertTrue(result)
3306
3307 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3308
3309 def testCleanUpWithErrors(self):
3310 class TestableTest(TestCase):
3311 def testNothing(self):
3312 pass
3313
3314 class MockResult(object):
3315 errors = []
3316 def addError(self, test, exc_info):
3317 self.errors.append((test, exc_info))
3318
3319 result = MockResult()
3320 test = TestableTest('testNothing')
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00003321 test._resultForDoCleanups = result
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003322
3323 exc1 = Exception('foo')
3324 exc2 = Exception('bar')
3325 def cleanup1():
3326 raise exc1
3327
3328 def cleanup2():
3329 raise exc2
3330
3331 test.addCleanup(cleanup1)
3332 test.addCleanup(cleanup2)
3333
3334 self.assertFalse(test.doCleanups())
3335
3336 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3337 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3338 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3339
3340 def testCleanupInRun(self):
3341 blowUp = False
3342 ordering = []
3343
3344 class TestableTest(TestCase):
3345 def setUp(self):
3346 ordering.append('setUp')
3347 if blowUp:
3348 raise Exception('foo')
3349
3350 def testNothing(self):
3351 ordering.append('test')
3352
3353 def tearDown(self):
3354 ordering.append('tearDown')
3355
3356 test = TestableTest('testNothing')
3357
3358 def cleanup1():
3359 ordering.append('cleanup1')
3360 def cleanup2():
3361 ordering.append('cleanup2')
3362 test.addCleanup(cleanup1)
3363 test.addCleanup(cleanup2)
3364
3365 def success(some_test):
3366 self.assertEqual(some_test, test)
3367 ordering.append('success')
3368
3369 result = unittest.TestResult()
3370 result.addSuccess = success
3371
3372 test.run(result)
3373 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3374 'cleanup2', 'cleanup1', 'success'])
3375
3376 blowUp = True
3377 ordering = []
3378 test = TestableTest('testNothing')
3379 test.addCleanup(cleanup1)
3380 test.run(result)
3381 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3382
3383
3384class Test_TestProgram(TestCase):
3385
3386 # Horrible white box test
3387 def testNoExit(self):
3388 result = object()
3389 test = object()
3390
3391 class FakeRunner(object):
3392 def run(self, test):
3393 self.test = test
3394 return result
3395
3396 runner = FakeRunner()
3397
Benjamin Petersond2397752009-06-27 23:45:02 +00003398 oldParseArgs = TestProgram.parseArgs
3399 def restoreParseArgs():
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003400 TestProgram.parseArgs = oldParseArgs
Benjamin Petersond2397752009-06-27 23:45:02 +00003401 TestProgram.parseArgs = lambda *args: None
3402 self.addCleanup(restoreParseArgs)
3403
3404 def removeTest():
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003405 del TestProgram.test
Benjamin Petersond2397752009-06-27 23:45:02 +00003406 TestProgram.test = test
3407 self.addCleanup(removeTest)
3408
3409 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3410
3411 self.assertEqual(program.result, result)
3412 self.assertEqual(runner.test, test)
3413 self.assertEqual(program.verbosity, 2)
3414
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003415 class FooBar(unittest.TestCase):
3416 def testPass(self):
3417 assert True
3418 def testFail(self):
3419 assert False
3420
3421 class FooBarLoader(unittest.TestLoader):
3422 """Test loader that returns a suite containing FooBar."""
3423 def loadTestsFromModule(self, module):
3424 return self.suiteClass(
3425 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3426
3427
3428 def test_NonExit(self):
3429 program = unittest.main(exit=False,
3430 argv=["foobar"],
3431 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3432 testLoader=self.FooBarLoader())
3433 self.assertTrue(hasattr(program, 'result'))
3434
3435
3436 def test_Exit(self):
3437 self.assertRaises(
3438 SystemExit,
3439 unittest.main,
3440 argv=["foobar"],
3441 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3442 exit=True,
3443 testLoader=self.FooBarLoader())
3444
3445
3446 def test_ExitAsDefault(self):
3447 self.assertRaises(
3448 SystemExit,
3449 unittest.main,
3450 argv=["foobar"],
3451 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3452 testLoader=self.FooBarLoader())
3453
3454
3455class Test_TextTestRunner(TestCase):
3456 """Tests for TextTestRunner."""
3457
3458 def test_works_with_result_without_startTestRun_stopTestRun(self):
3459 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3460 separator2 = ''
3461 def printErrors(self):
3462 pass
3463
3464 class Runner(unittest.TextTestRunner):
3465 def __init__(self):
3466 super(Runner, self).__init__(io.StringIO())
3467
3468 def _makeResult(self):
3469 return OldTextResult()
3470
3471 runner = Runner()
3472 runner.run(unittest.TestSuite())
3473
3474 def test_startTestRun_stopTestRun_called(self):
3475 class LoggingTextResult(LoggingResult):
3476 separator2 = ''
3477 def printErrors(self):
3478 pass
3479
3480 class LoggingRunner(unittest.TextTestRunner):
3481 def __init__(self, events):
3482 super(LoggingRunner, self).__init__(io.StringIO())
3483 self._events = events
3484
3485 def _makeResult(self):
3486 return LoggingTextResult(self._events)
3487
3488 events = []
3489 runner = LoggingRunner(events)
3490 runner.run(unittest.TestSuite())
3491 expected = ['startTestRun', 'stopTestRun']
3492 self.assertEqual(events, expected)
3493
Antoine Pitrouc63ecee2009-11-10 21:34:48 +00003494 def test_pickle_unpickle(self):
3495 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3496 # required by test_multiprocessing under Windows (in verbose mode).
3497 stream = io.StringIO("foo")
3498 runner = unittest.TextTestRunner(stream)
3499 for protocol in range(2, pickle.HIGHEST_PROTOCOL + 1):
3500 s = pickle.dumps(runner, protocol)
3501 obj = pickle.loads(s)
3502 # StringIO objects never compare equal, a cheap test instead.
3503 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3504
Michael Foord34c94622010-02-10 15:51:42 +00003505 def test_resultclass(self):
3506 def MockResultClass(*args):
3507 return args
3508 STREAM = object()
3509 DESCRIPTIONS = object()
3510 VERBOSITY = object()
3511 runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY,
3512 resultclass=MockResultClass)
3513 self.assertEqual(runner.resultclass, MockResultClass)
3514
3515 expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY)
3516 self.assertEqual(runner._makeResult(), expectedresult)
3517
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003518
Benjamin Petersond2397752009-06-27 23:45:02 +00003519class TestDiscovery(TestCase):
3520
3521 # Heavily mocked tests so I can avoid hitting the filesystem
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003522 def test_get_name_from_path(self):
Benjamin Petersond2397752009-06-27 23:45:02 +00003523 loader = unittest.TestLoader()
Benjamin Petersond2397752009-06-27 23:45:02 +00003524 loader._top_level_dir = '/foo'
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003525 name = loader._get_name_from_path('/foo/bar/baz.py')
3526 self.assertEqual(name, 'bar.baz')
Benjamin Petersond2397752009-06-27 23:45:02 +00003527
3528 if not __debug__:
3529 # asserts are off
3530 return
3531
3532 with self.assertRaises(AssertionError):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003533 loader._get_name_from_path('/bar/baz.py')
Benjamin Petersond2397752009-06-27 23:45:02 +00003534
3535 def test_find_tests(self):
3536 loader = unittest.TestLoader()
3537
3538 original_listdir = os.listdir
3539 def restore_listdir():
3540 os.listdir = original_listdir
3541 original_isfile = os.path.isfile
3542 def restore_isfile():
3543 os.path.isfile = original_isfile
3544 original_isdir = os.path.isdir
3545 def restore_isdir():
3546 os.path.isdir = original_isdir
3547
3548 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003549 'test.foo', 'test-not-a-module.py', 'another_dir'],
Benjamin Petersond2397752009-06-27 23:45:02 +00003550 ['test3.py', 'test4.py', ]]
3551 os.listdir = lambda path: path_lists.pop(0)
3552 self.addCleanup(restore_listdir)
3553
3554 def isdir(path):
3555 return path.endswith('dir')
3556 os.path.isdir = isdir
3557 self.addCleanup(restore_isdir)
3558
3559 def isfile(path):
3560 # another_dir is not a package and so shouldn't be recursed into
3561 return not path.endswith('dir') and not 'another_dir' in path
3562 os.path.isfile = isfile
3563 self.addCleanup(restore_isfile)
3564
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003565 loader._get_module_from_name = lambda path: path + ' module'
Benjamin Petersond2397752009-06-27 23:45:02 +00003566 loader.loadTestsFromModule = lambda module: module + ' tests'
3567
3568 loader._top_level_dir = '/foo'
3569 suite = list(loader._find_tests('/foo', 'test*.py'))
3570
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003571 expected = [name + ' module tests' for name in
3572 ('test1', 'test2')]
3573 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3574 ('test3', 'test4')])
Benjamin Petersond2397752009-06-27 23:45:02 +00003575 self.assertEqual(suite, expected)
3576
3577 def test_find_tests_with_package(self):
3578 loader = unittest.TestLoader()
3579
3580 original_listdir = os.listdir
3581 def restore_listdir():
3582 os.listdir = original_listdir
3583 original_isfile = os.path.isfile
3584 def restore_isfile():
3585 os.path.isfile = original_isfile
3586 original_isdir = os.path.isdir
3587 def restore_isdir():
3588 os.path.isdir = original_isdir
3589
3590 directories = ['a_directory', 'test_directory', 'test_directory2']
3591 path_lists = [directories, [], [], []]
3592 os.listdir = lambda path: path_lists.pop(0)
3593 self.addCleanup(restore_listdir)
3594
3595 os.path.isdir = lambda path: True
3596 self.addCleanup(restore_isdir)
3597
3598 os.path.isfile = lambda path: os.path.basename(path) not in directories
3599 self.addCleanup(restore_isfile)
3600
3601 class Module(object):
3602 paths = []
3603 load_tests_args = []
3604
3605 def __init__(self, path):
3606 self.path = path
3607 self.paths.append(path)
3608 if os.path.basename(path) == 'test_directory':
3609 def load_tests(loader, tests, pattern):
3610 self.load_tests_args.append((loader, tests, pattern))
3611 return 'load_tests'
3612 self.load_tests = load_tests
3613
3614 def __eq__(self, other):
3615 return self.path == other.path
3616
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003617 loader._get_module_from_name = lambda name: Module(name)
Benjamin Petersond2397752009-06-27 23:45:02 +00003618 def loadTestsFromModule(module, use_load_tests):
3619 if use_load_tests:
3620 raise self.failureException('use_load_tests should be False for packages')
3621 return module.path + ' module tests'
3622 loader.loadTestsFromModule = loadTestsFromModule
3623
3624 loader._top_level_dir = '/foo'
3625 # this time no '.py' on the pattern so that it can match
3626 # a test package
3627 suite = list(loader._find_tests('/foo', 'test*'))
3628
3629 # We should have loaded tests from the test_directory package by calling load_tests
3630 # and directly from the test_directory2 package
3631 self.assertEqual(suite,
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003632 ['load_tests', 'test_directory2' + ' module tests'])
3633 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Benjamin Petersond2397752009-06-27 23:45:02 +00003634
3635 # load_tests should have been called once with loader, tests and pattern
3636 self.assertEqual(Module.load_tests_args,
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003637 [(loader, 'test_directory' + ' module tests', 'test*')])
Benjamin Petersond2397752009-06-27 23:45:02 +00003638
3639 def test_discover(self):
3640 loader = unittest.TestLoader()
3641
3642 original_isfile = os.path.isfile
3643 def restore_isfile():
3644 os.path.isfile = original_isfile
3645
3646 os.path.isfile = lambda path: False
3647 self.addCleanup(restore_isfile)
3648
Nick Coghlan6ead5522009-10-18 13:19:33 +00003649 orig_sys_path = sys.path[:]
3650 def restore_path():
3651 sys.path[:] = orig_sys_path
3652 self.addCleanup(restore_path)
Benjamin Petersond2397752009-06-27 23:45:02 +00003653
Nick Coghlan6ead5522009-10-18 13:19:33 +00003654 full_path = os.path.abspath(os.path.normpath('/foo'))
Benjamin Petersond2397752009-06-27 23:45:02 +00003655 with self.assertRaises(ImportError):
3656 loader.discover('/foo/bar', top_level_dir='/foo')
3657
3658 self.assertEqual(loader._top_level_dir, full_path)
3659 self.assertIn(full_path, sys.path)
3660
3661 os.path.isfile = lambda path: True
3662 _find_tests_args = []
3663 def _find_tests(start_dir, pattern):
3664 _find_tests_args.append((start_dir, pattern))
3665 return ['tests']
3666 loader._find_tests = _find_tests
3667 loader.suiteClass = str
3668
3669 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3670
3671 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3672 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3673 self.assertEqual(suite, "['tests']")
3674 self.assertEqual(loader._top_level_dir, top_level_dir)
3675 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlan6ead5522009-10-18 13:19:33 +00003676 self.assertIn(top_level_dir, sys.path)
Benjamin Petersond2397752009-06-27 23:45:02 +00003677
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003678 def test_discover_with_modules_that_fail_to_import(self):
3679 loader = unittest.TestLoader()
3680
3681 listdir = os.listdir
3682 os.listdir = lambda _: ['test_this_does_not_exist.py']
3683 isfile = os.path.isfile
3684 os.path.isfile = lambda _: True
Nick Coghlan6ead5522009-10-18 13:19:33 +00003685 orig_sys_path = sys.path[:]
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003686 def restore():
3687 os.path.isfile = isfile
3688 os.listdir = listdir
Nick Coghlan6ead5522009-10-18 13:19:33 +00003689 sys.path[:] = orig_sys_path
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003690 self.addCleanup(restore)
3691
3692 suite = loader.discover('.')
Nick Coghlan6ead5522009-10-18 13:19:33 +00003693 self.assertIn(os.getcwd(), sys.path)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003694 self.assertEqual(suite.countTestCases(), 1)
3695 test = list(list(suite)[0])[0] # extract test from suite
3696
3697 with self.assertRaises(ImportError):
3698 test.test_this_does_not_exist()
3699
Benjamin Petersond2397752009-06-27 23:45:02 +00003700 def test_command_line_handling_parseArgs(self):
3701 # Haha - take that uninstantiable class
3702 program = object.__new__(TestProgram)
3703
3704 args = []
3705 def do_discovery(argv):
3706 args.extend(argv)
3707 program._do_discovery = do_discovery
3708 program.parseArgs(['something', 'discover'])
3709 self.assertEqual(args, [])
3710
3711 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3712 self.assertEqual(args, ['foo', 'bar'])
3713
3714 def test_command_line_handling_do_discovery_too_many_arguments(self):
3715 class Stop(Exception):
3716 pass
3717 def usageExit():
3718 raise Stop
3719
3720 program = object.__new__(TestProgram)
3721 program.usageExit = usageExit
3722
3723 with self.assertRaises(Stop):
3724 # too many args
3725 program._do_discovery(['one', 'two', 'three', 'four'])
3726
3727
3728 def test_command_line_handling_do_discovery_calls_loader(self):
3729 program = object.__new__(TestProgram)
3730
3731 class Loader(object):
3732 args = []
3733 def discover(self, start_dir, pattern, top_level_dir):
3734 self.args.append((start_dir, pattern, top_level_dir))
3735 return 'tests'
3736
3737 program._do_discovery(['-v'], Loader=Loader)
3738 self.assertEqual(program.verbosity, 2)
3739 self.assertEqual(program.test, 'tests')
3740 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3741
3742 Loader.args = []
3743 program = object.__new__(TestProgram)
3744 program._do_discovery(['--verbose'], Loader=Loader)
3745 self.assertEqual(program.test, 'tests')
3746 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3747
3748 Loader.args = []
3749 program = object.__new__(TestProgram)
3750 program._do_discovery([], Loader=Loader)
3751 self.assertEqual(program.test, 'tests')
3752 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3753
3754 Loader.args = []
3755 program = object.__new__(TestProgram)
3756 program._do_discovery(['fish'], Loader=Loader)
3757 self.assertEqual(program.test, 'tests')
3758 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3759
3760 Loader.args = []
3761 program = object.__new__(TestProgram)
3762 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3763 self.assertEqual(program.test, 'tests')
3764 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3765
3766 Loader.args = []
3767 program = object.__new__(TestProgram)
3768 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3769 self.assertEqual(program.test, 'tests')
3770 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3771
3772 Loader.args = []
3773 program = object.__new__(TestProgram)
3774 program._do_discovery(['-s', 'fish'], Loader=Loader)
3775 self.assertEqual(program.test, 'tests')
3776 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3777
3778 Loader.args = []
3779 program = object.__new__(TestProgram)
3780 program._do_discovery(['-t', 'fish'], Loader=Loader)
3781 self.assertEqual(program.test, 'tests')
3782 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3783
3784 Loader.args = []
3785 program = object.__new__(TestProgram)
3786 program._do_discovery(['-p', 'fish'], Loader=Loader)
3787 self.assertEqual(program.test, 'tests')
3788 self.assertEqual(Loader.args, [('.', 'fish', None)])
3789
3790 Loader.args = []
3791 program = object.__new__(TestProgram)
3792 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3793 self.assertEqual(program.test, 'tests')
3794 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3795 self.assertEqual(program.verbosity, 2)
3796
3797
Jim Fultonfafd8742004-08-28 15:22:12 +00003798######################################################################
3799## Main
3800######################################################################
3801
3802def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003803 support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003804 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003805 Test_TestSkipping, Test_Assertions, TestLongMessage,
Antoine Pitrouc63ecee2009-11-10 21:34:48 +00003806 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner)
Jim Fultonfafd8742004-08-28 15:22:12 +00003807
Guido van Rossumd8faa362007-04-27 19:54:29 +00003808if __name__ == "__main__":
Jim Fultonfafd8742004-08-28 15:22:12 +00003809 test_main()