blob: f24a92925973100f438c3df95e2e1a486a9109a0 [file] [log] [blame]
Jim Fultonfafd8742004-08-28 15:22:12 +00001"""Test script for unittest.
2
Guido van Rossumd8faa362007-04-27 19:54:29 +00003By Collin Winter <collinw at gmail.com>
4
5Still need testing:
6 TestCase.{assert,fail}* methods (some are tested implicitly)
Jim Fultonfafd8742004-08-28 15:22:12 +00007"""
8
Benjamin Petersonbed7d042009-07-19 21:01:52 +00009import builtins
Benjamin Petersond2397752009-06-27 23:45:02 +000010import os
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000011import re
Benjamin Petersond2397752009-06-27 23:45:02 +000012import sys
Benjamin Peterson6bcbad52009-06-30 23:45:41 +000013import warnings
Benjamin Petersonee8712c2008-05-20 21:35:26 +000014from test import support
Jim Fultonfafd8742004-08-28 15:22:12 +000015import unittest
Benjamin Peterson25c95f12009-05-08 20:42:26 +000016from unittest import TestCase, TestProgram
Christian Heimes45f9af32007-11-27 21:50:00 +000017import types
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000018from copy import deepcopy
Benjamin Peterson25c95f12009-05-08 20:42:26 +000019import io
Antoine Pitrouc63ecee2009-11-10 21:34:48 +000020import pickle
Benjamin Peterson847a4112010-03-14 15:04:17 +000021import warnings
22
Jim Fultonfafd8742004-08-28 15:22:12 +000023
Guido van Rossumd8faa362007-04-27 19:54:29 +000024### Support code
25################################################################
Jim Fultonfafd8742004-08-28 15:22:12 +000026
Benjamin Peterson847a4112010-03-14 15:04:17 +000027def resultFactory(*_):
28 return unittest.TestResult()
29
Guido van Rossumd8faa362007-04-27 19:54:29 +000030class LoggingResult(unittest.TestResult):
31 def __init__(self, log):
32 self._events = log
Guido van Rossumcd16bf62007-06-13 18:07:49 +000033 super().__init__()
Guido van Rossumd8faa362007-04-27 19:54:29 +000034
35 def startTest(self, test):
36 self._events.append('startTest')
Guido van Rossumcd16bf62007-06-13 18:07:49 +000037 super().startTest(test)
Guido van Rossumd8faa362007-04-27 19:54:29 +000038
Benjamin Peterson25c95f12009-05-08 20:42:26 +000039 def startTestRun(self):
40 self._events.append('startTestRun')
41 super(LoggingResult, self).startTestRun()
42
Guido van Rossumd8faa362007-04-27 19:54:29 +000043 def stopTest(self, test):
44 self._events.append('stopTest')
Guido van Rossumcd16bf62007-06-13 18:07:49 +000045 super().stopTest(test)
Guido van Rossumd8faa362007-04-27 19:54:29 +000046
Benjamin Peterson25c95f12009-05-08 20:42:26 +000047 def stopTestRun(self):
48 self._events.append('stopTestRun')
49 super(LoggingResult, self).stopTestRun()
50
Guido van Rossumd8faa362007-04-27 19:54:29 +000051 def addFailure(self, *args):
52 self._events.append('addFailure')
Guido van Rossumcd16bf62007-06-13 18:07:49 +000053 super().addFailure(*args)
Guido van Rossumd8faa362007-04-27 19:54:29 +000054
Benjamin Peterson5254c042009-03-23 22:25:03 +000055 def addSuccess(self, *args):
56 self._events.append('addSuccess')
57 super(LoggingResult, self).addSuccess(*args)
58
Guido van Rossumd8faa362007-04-27 19:54:29 +000059 def addError(self, *args):
60 self._events.append('addError')
Guido van Rossumcd16bf62007-06-13 18:07:49 +000061 super().addError(*args)
Guido van Rossumd8faa362007-04-27 19:54:29 +000062
Benjamin Peterson5254c042009-03-23 22:25:03 +000063 def addSkip(self, *args):
64 self._events.append('addSkip')
65 super(LoggingResult, self).addSkip(*args)
66
67 def addExpectedFailure(self, *args):
68 self._events.append('addExpectedFailure')
69 super(LoggingResult, self).addExpectedFailure(*args)
70
71 def addUnexpectedSuccess(self, *args):
72 self._events.append('addUnexpectedSuccess')
73 super(LoggingResult, self).addUnexpectedSuccess(*args)
74
75
Guido van Rossumd8faa362007-04-27 19:54:29 +000076class TestEquality(object):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000077 """Used as a mixin for TestCase"""
78
Guido van Rossumd8faa362007-04-27 19:54:29 +000079 # Check for a valid __eq__ implementation
80 def test_eq(self):
81 for obj_1, obj_2 in self.eq_pairs:
82 self.assertEqual(obj_1, obj_2)
83 self.assertEqual(obj_2, obj_1)
84
85 # Check for a valid __ne__ implementation
86 def test_ne(self):
87 for obj_1, obj_2 in self.ne_pairs:
Benjamin Petersone1759f82009-06-30 23:35:19 +000088 self.assertNotEqual(obj_1, obj_2)
89 self.assertNotEqual(obj_2, obj_1)
Guido van Rossumd8faa362007-04-27 19:54:29 +000090
91class TestHashing(object):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000092 """Used as a mixin for TestCase"""
93
Guido van Rossumd8faa362007-04-27 19:54:29 +000094 # Check for a valid __hash__ implementation
95 def test_hash(self):
96 for obj_1, obj_2 in self.eq_pairs:
97 try:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000098 if not hash(obj_1) == hash(obj_2):
99 self.fail("%r and %r do not hash equal" % (obj_1, obj_2))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000100 except KeyboardInterrupt:
101 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +0000102 except Exception as e:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000103 self.fail("Problem hashing %r and %r: %s" % (obj_1, obj_2, e))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000104
105 for obj_1, obj_2 in self.ne_pairs:
106 try:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000107 if hash(obj_1) == hash(obj_2):
108 self.fail("%s and %s hash equal, but shouldn't" %
109 (obj_1, obj_2))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000110 except KeyboardInterrupt:
111 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +0000112 except Exception as e:
113 self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e))
114
115
Benjamin Peterson5254c042009-03-23 22:25:03 +0000116# List subclass we can add attributes to.
117class MyClassSuite(list):
118
Benjamin Peterson14a3dd72009-05-25 00:51:58 +0000119 def __init__(self, tests):
Benjamin Peterson5254c042009-03-23 22:25:03 +0000120 super(MyClassSuite, self).__init__(tests)
121
122
Guido van Rossumd8faa362007-04-27 19:54:29 +0000123################################################################
124### /Support code
125
126class Test_TestLoader(TestCase):
127
128 ### Tests for TestLoader.loadTestsFromTestCase
129 ################################################################
130
131 # "Return a suite of all tests cases contained in the TestCase-derived
132 # class testCaseClass"
133 def test_loadTestsFromTestCase(self):
134 class Foo(unittest.TestCase):
135 def test_1(self): pass
136 def test_2(self): pass
137 def foo_bar(self): pass
138
139 tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
140
141 loader = unittest.TestLoader()
142 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
143
144 # "Return a suite of all tests cases contained in the TestCase-derived
145 # class testCaseClass"
146 #
147 # Make sure it does the right thing even if no tests were found
148 def test_loadTestsFromTestCase__no_matches(self):
149 class Foo(unittest.TestCase):
150 def foo_bar(self): pass
151
152 empty_suite = unittest.TestSuite()
153
154 loader = unittest.TestLoader()
155 self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite)
156
157 # "Return a suite of all tests cases contained in the TestCase-derived
158 # class testCaseClass"
159 #
160 # What happens if loadTestsFromTestCase() is given an object
161 # that isn't a subclass of TestCase? Specifically, what happens
162 # if testCaseClass is a subclass of TestSuite?
163 #
164 # This is checked for specifically in the code, so we better add a
165 # test for it.
166 def test_loadTestsFromTestCase__TestSuite_subclass(self):
167 class NotATestCase(unittest.TestSuite):
168 pass
169
170 loader = unittest.TestLoader()
171 try:
172 loader.loadTestsFromTestCase(NotATestCase)
173 except TypeError:
174 pass
175 else:
176 self.fail('Should raise TypeError')
177
178 # "Return a suite of all tests cases contained in the TestCase-derived
179 # class testCaseClass"
180 #
181 # Make sure loadTestsFromTestCase() picks up the default test method
182 # name (as specified by TestCase), even though the method name does
183 # not match the default TestLoader.testMethodPrefix string
184 def test_loadTestsFromTestCase__default_method_name(self):
185 class Foo(unittest.TestCase):
186 def runTest(self):
187 pass
188
189 loader = unittest.TestLoader()
190 # This has to be false for the test to succeed
Benjamin Petersone1759f82009-06-30 23:35:19 +0000191 self.assertFalse('runTest'.startswith(loader.testMethodPrefix))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000192
193 suite = loader.loadTestsFromTestCase(Foo)
Ezio Melottie9615932010-01-24 19:26:24 +0000194 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000195 self.assertEqual(list(suite), [Foo('runTest')])
196
197 ################################################################
198 ### /Tests for TestLoader.loadTestsFromTestCase
199
200 ### Tests for TestLoader.loadTestsFromModule
201 ################################################################
202
203 # "This method searches `module` for classes derived from TestCase"
204 def test_loadTestsFromModule__TestCase_subclass(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000205 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000206 class MyTestCase(unittest.TestCase):
207 def test(self):
208 pass
209 m.testcase_1 = MyTestCase
210
211 loader = unittest.TestLoader()
212 suite = loader.loadTestsFromModule(m)
Ezio Melottie9615932010-01-24 19:26:24 +0000213 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000214
215 expected = [loader.suiteClass([MyTestCase('test')])]
216 self.assertEqual(list(suite), expected)
217
218 # "This method searches `module` for classes derived from TestCase"
219 #
220 # What happens if no tests are found (no TestCase instances)?
221 def test_loadTestsFromModule__no_TestCase_instances(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000222 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000223
224 loader = unittest.TestLoader()
225 suite = loader.loadTestsFromModule(m)
Ezio Melottie9615932010-01-24 19:26:24 +0000226 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000227 self.assertEqual(list(suite), [])
228
229 # "This method searches `module` for classes derived from TestCase"
230 #
231 # What happens if no tests are found (TestCases instances, but no tests)?
232 def test_loadTestsFromModule__no_TestCase_tests(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000233 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000234 class MyTestCase(unittest.TestCase):
235 pass
236 m.testcase_1 = MyTestCase
237
238 loader = unittest.TestLoader()
239 suite = loader.loadTestsFromModule(m)
Ezio Melottie9615932010-01-24 19:26:24 +0000240 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000241
242 self.assertEqual(list(suite), [loader.suiteClass()])
243
244 # "This method searches `module` for classes derived from TestCase"s
245 #
246 # What happens if loadTestsFromModule() is given something other
247 # than a module?
248 #
249 # XXX Currently, it succeeds anyway. This flexibility
250 # should either be documented or loadTestsFromModule() should
251 # raise a TypeError
252 #
253 # XXX Certain people are using this behaviour. We'll add a test for it
254 def test_loadTestsFromModule__not_a_module(self):
255 class MyTestCase(unittest.TestCase):
256 def test(self):
257 pass
258
259 class NotAModule(object):
260 test_2 = MyTestCase
261
262 loader = unittest.TestLoader()
263 suite = loader.loadTestsFromModule(NotAModule)
264
265 reference = [unittest.TestSuite([MyTestCase('test')])]
266 self.assertEqual(list(suite), reference)
267
Benjamin Petersond2397752009-06-27 23:45:02 +0000268
269 # Check that loadTestsFromModule honors (or not) a module
270 # with a load_tests function.
271 def test_loadTestsFromModule__load_tests(self):
272 m = types.ModuleType('m')
273 class MyTestCase(unittest.TestCase):
274 def test(self):
275 pass
276 m.testcase_1 = MyTestCase
277
278 load_tests_args = []
279 def load_tests(loader, tests, pattern):
Michael Foord41647d62010-02-06 00:26:13 +0000280 self.assertIsInstance(tests, unittest.TestSuite)
Benjamin Petersond2397752009-06-27 23:45:02 +0000281 load_tests_args.extend((loader, tests, pattern))
282 return tests
283 m.load_tests = load_tests
284
285 loader = unittest.TestLoader()
286 suite = loader.loadTestsFromModule(m)
Michael Foord41647d62010-02-06 00:26:13 +0000287 self.assertIsInstance(suite, unittest.TestSuite)
Benjamin Petersond2397752009-06-27 23:45:02 +0000288 self.assertEquals(load_tests_args, [loader, suite, None])
289
290 load_tests_args = []
291 suite = loader.loadTestsFromModule(m, use_load_tests=False)
292 self.assertEquals(load_tests_args, [])
293
Guido van Rossumd8faa362007-04-27 19:54:29 +0000294 ################################################################
295 ### /Tests for TestLoader.loadTestsFromModule()
296
297 ### Tests for TestLoader.loadTestsFromName()
298 ################################################################
299
300 # "The specifier name is a ``dotted name'' that may resolve either to
301 # a module, a test case class, a TestSuite instance, a test method
302 # within a test case class, or a callable object which returns a
303 # TestCase or TestSuite instance."
304 #
305 # Is ValueError raised in response to an empty name?
306 def test_loadTestsFromName__empty_name(self):
307 loader = unittest.TestLoader()
308
309 try:
310 loader.loadTestsFromName('')
311 except ValueError as e:
312 self.assertEqual(str(e), "Empty module name")
313 else:
314 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
315
316 # "The specifier name is a ``dotted name'' that may resolve either to
317 # a module, a test case class, a TestSuite instance, a test method
318 # within a test case class, or a callable object which returns a
319 # TestCase or TestSuite instance."
320 #
321 # What happens when the name contains invalid characters?
322 def test_loadTestsFromName__malformed_name(self):
323 loader = unittest.TestLoader()
324
325 # XXX Should this raise ValueError or ImportError?
326 try:
327 loader.loadTestsFromName('abc () //')
328 except ValueError:
329 pass
330 except ImportError:
331 pass
332 else:
333 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
334
335 # "The specifier name is a ``dotted name'' that may resolve ... to a
336 # module"
337 #
338 # What happens when a module by that name can't be found?
339 def test_loadTestsFromName__unknown_module_name(self):
340 loader = unittest.TestLoader()
341
342 try:
343 loader.loadTestsFromName('sdasfasfasdf')
344 except ImportError as e:
345 self.assertEqual(str(e), "No module named sdasfasfasdf")
346 else:
347 self.fail("TestLoader.loadTestsFromName failed to raise ImportError")
348
349 # "The specifier name is a ``dotted name'' that may resolve either to
350 # a module, a test case class, a TestSuite instance, a test method
351 # within a test case class, or a callable object which returns a
352 # TestCase or TestSuite instance."
353 #
354 # What happens when the module is found, but the attribute can't?
355 def test_loadTestsFromName__unknown_attr_name(self):
356 loader = unittest.TestLoader()
357
358 try:
359 loader.loadTestsFromName('unittest.sdasfasfasdf')
360 except AttributeError as e:
361 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
362 else:
363 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
364
365 # "The specifier name is a ``dotted name'' that may resolve either to
366 # a module, a test case class, a TestSuite instance, a test method
367 # within a test case class, or a callable object which returns a
368 # TestCase or TestSuite instance."
369 #
370 # What happens when we provide the module, but the attribute can't be
371 # found?
372 def test_loadTestsFromName__relative_unknown_name(self):
373 loader = unittest.TestLoader()
374
375 try:
376 loader.loadTestsFromName('sdasfasfasdf', unittest)
377 except AttributeError as e:
378 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
379 else:
380 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
381
382 # "The specifier name is a ``dotted name'' that may resolve either to
383 # a module, a test case class, a TestSuite instance, a test method
384 # within a test case class, or a callable object which returns a
385 # TestCase or TestSuite instance."
386 # ...
387 # "The method optionally resolves name relative to the given module"
388 #
389 # Does loadTestsFromName raise ValueError when passed an empty
390 # name relative to a provided module?
391 #
392 # XXX Should probably raise a ValueError instead of an AttributeError
393 def test_loadTestsFromName__relative_empty_name(self):
394 loader = unittest.TestLoader()
395
396 try:
397 loader.loadTestsFromName('', unittest)
398 except AttributeError as e:
399 pass
400 else:
401 self.fail("Failed to raise AttributeError")
402
403 # "The specifier name is a ``dotted name'' that may resolve either to
404 # a module, a test case class, a TestSuite instance, a test method
405 # within a test case class, or a callable object which returns a
406 # TestCase or TestSuite instance."
407 # ...
408 # "The method optionally resolves name relative to the given module"
409 #
410 # What happens when an impossible name is given, relative to the provided
411 # `module`?
412 def test_loadTestsFromName__relative_malformed_name(self):
413 loader = unittest.TestLoader()
414
415 # XXX Should this raise AttributeError or ValueError?
416 try:
417 loader.loadTestsFromName('abc () //', unittest)
418 except ValueError:
419 pass
420 except AttributeError:
421 pass
422 else:
423 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
424
425 # "The method optionally resolves name relative to the given module"
426 #
427 # Does loadTestsFromName raise TypeError when the `module` argument
428 # isn't a module object?
429 #
430 # XXX Accepts the not-a-module object, ignorning the object's type
431 # This should raise an exception or the method name should be changed
432 #
433 # XXX Some people are relying on this, so keep it for now
434 def test_loadTestsFromName__relative_not_a_module(self):
435 class MyTestCase(unittest.TestCase):
436 def test(self):
437 pass
438
439 class NotAModule(object):
440 test_2 = MyTestCase
441
442 loader = unittest.TestLoader()
443 suite = loader.loadTestsFromName('test_2', NotAModule)
444
445 reference = [MyTestCase('test')]
446 self.assertEqual(list(suite), reference)
447
448 # "The specifier name is a ``dotted name'' that may resolve either to
449 # a module, a test case class, a TestSuite instance, a test method
450 # within a test case class, or a callable object which returns a
451 # TestCase or TestSuite instance."
452 #
453 # Does it raise an exception if the name resolves to an invalid
454 # object?
455 def test_loadTestsFromName__relative_bad_object(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000456 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000457 m.testcase_1 = object()
458
459 loader = unittest.TestLoader()
460 try:
461 loader.loadTestsFromName('testcase_1', m)
462 except TypeError:
463 pass
464 else:
465 self.fail("Should have raised TypeError")
466
467 # "The specifier name is a ``dotted name'' that may
468 # resolve either to ... a test case class"
469 def test_loadTestsFromName__relative_TestCase_subclass(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000470 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000471 class MyTestCase(unittest.TestCase):
472 def test(self):
473 pass
474 m.testcase_1 = MyTestCase
475
476 loader = unittest.TestLoader()
477 suite = loader.loadTestsFromName('testcase_1', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000478 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000479 self.assertEqual(list(suite), [MyTestCase('test')])
480
481 # "The specifier name is a ``dotted name'' that may resolve either to
482 # a module, a test case class, a TestSuite instance, a test method
483 # within a test case class, or a callable object which returns a
484 # TestCase or TestSuite instance."
485 def test_loadTestsFromName__relative_TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000486 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000487 class MyTestCase(unittest.TestCase):
488 def test(self):
489 pass
490 m.testsuite = unittest.TestSuite([MyTestCase('test')])
491
492 loader = unittest.TestLoader()
493 suite = loader.loadTestsFromName('testsuite', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000494 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000495
496 self.assertEqual(list(suite), [MyTestCase('test')])
497
498 # "The specifier name is a ``dotted name'' that may resolve ... to
499 # ... a test method within a test case class"
500 def test_loadTestsFromName__relative_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000501 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000502 class MyTestCase(unittest.TestCase):
503 def test(self):
504 pass
505 m.testcase_1 = MyTestCase
506
507 loader = unittest.TestLoader()
508 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000509 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000510
511 self.assertEqual(list(suite), [MyTestCase('test')])
512
513 # "The specifier name is a ``dotted name'' that may resolve either to
514 # a module, a test case class, a TestSuite instance, a test method
515 # within a test case class, or a callable object which returns a
516 # TestCase or TestSuite instance."
517 #
518 # Does loadTestsFromName() raise the proper exception when trying to
519 # resolve "a test method within a test case class" that doesn't exist
520 # for the given name (relative to a provided module)?
521 def test_loadTestsFromName__relative_invalid_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000522 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000523 class MyTestCase(unittest.TestCase):
524 def test(self):
525 pass
526 m.testcase_1 = MyTestCase
527
528 loader = unittest.TestLoader()
529 try:
530 loader.loadTestsFromName('testcase_1.testfoo', m)
531 except AttributeError as e:
532 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
533 else:
534 self.fail("Failed to raise AttributeError")
535
536 # "The specifier name is a ``dotted name'' that may resolve ... to
537 # ... a callable object which returns a ... TestSuite instance"
538 def test_loadTestsFromName__callable__TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000539 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000540 testcase_1 = unittest.FunctionTestCase(lambda: None)
541 testcase_2 = unittest.FunctionTestCase(lambda: None)
542 def return_TestSuite():
543 return unittest.TestSuite([testcase_1, testcase_2])
544 m.return_TestSuite = return_TestSuite
545
546 loader = unittest.TestLoader()
547 suite = loader.loadTestsFromName('return_TestSuite', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000548 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000549 self.assertEqual(list(suite), [testcase_1, testcase_2])
550
551 # "The specifier name is a ``dotted name'' that may resolve ... to
552 # ... a callable object which returns a TestCase ... instance"
553 def test_loadTestsFromName__callable__TestCase_instance(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000554 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000555 testcase_1 = unittest.FunctionTestCase(lambda: None)
556 def return_TestCase():
557 return testcase_1
558 m.return_TestCase = return_TestCase
559
560 loader = unittest.TestLoader()
561 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000562 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000563 self.assertEqual(list(suite), [testcase_1])
564
565 # "The specifier name is a ``dotted name'' that may resolve ... to
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000566 # ... a callable object which returns a TestCase ... instance"
567 #*****************************************************************
568 #Override the suiteClass attribute to ensure that the suiteClass
569 #attribute is used
570 def test_loadTestsFromName__callable__TestCase_instance_ProperSuiteClass(self):
571 class SubTestSuite(unittest.TestSuite):
572 pass
573 m = types.ModuleType('m')
574 testcase_1 = unittest.FunctionTestCase(lambda: None)
575 def return_TestCase():
576 return testcase_1
577 m.return_TestCase = return_TestCase
578
579 loader = unittest.TestLoader()
580 loader.suiteClass = SubTestSuite
581 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000582 self.assertIsInstance(suite, loader.suiteClass)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000583 self.assertEqual(list(suite), [testcase_1])
584
585 # "The specifier name is a ``dotted name'' that may resolve ... to
586 # ... a test method within a test case class"
587 #*****************************************************************
588 #Override the suiteClass attribute to ensure that the suiteClass
589 #attribute is used
590 def test_loadTestsFromName__relative_testmethod_ProperSuiteClass(self):
591 class SubTestSuite(unittest.TestSuite):
592 pass
593 m = types.ModuleType('m')
594 class MyTestCase(unittest.TestCase):
595 def test(self):
596 pass
597 m.testcase_1 = MyTestCase
598
599 loader = unittest.TestLoader()
600 loader.suiteClass=SubTestSuite
601 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000602 self.assertIsInstance(suite, loader.suiteClass)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000603
604 self.assertEqual(list(suite), [MyTestCase('test')])
605
606 # "The specifier name is a ``dotted name'' that may resolve ... to
Guido van Rossumd8faa362007-04-27 19:54:29 +0000607 # ... a callable object which returns a TestCase or TestSuite instance"
608 #
609 # What happens if the callable returns something else?
610 def test_loadTestsFromName__callable__wrong_type(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000611 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000612 def return_wrong():
613 return 6
614 m.return_wrong = return_wrong
615
616 loader = unittest.TestLoader()
617 try:
618 suite = loader.loadTestsFromName('return_wrong', m)
619 except TypeError:
620 pass
621 else:
622 self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
623
624 # "The specifier can refer to modules and packages which have not been
625 # imported; they will be imported as a side-effect"
626 def test_loadTestsFromName__module_not_loaded(self):
627 # We're going to try to load this module as a side-effect, so it
628 # better not be loaded before we try.
629 #
630 # Why pick audioop? Google shows it isn't used very often, so there's
631 # a good chance that it won't be imported when this test is run
632 module_name = 'audioop'
633
Guido van Rossumd8faa362007-04-27 19:54:29 +0000634 if module_name in sys.modules:
635 del sys.modules[module_name]
636
637 loader = unittest.TestLoader()
638 try:
639 suite = loader.loadTestsFromName(module_name)
640
Ezio Melottie9615932010-01-24 19:26:24 +0000641 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000642 self.assertEqual(list(suite), [])
643
644 # audioop should now be loaded, thanks to loadTestsFromName()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000645 self.assertIn(module_name, sys.modules)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000646 finally:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000647 if module_name in sys.modules:
648 del sys.modules[module_name]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000649
650 ################################################################
651 ### Tests for TestLoader.loadTestsFromName()
652
653 ### Tests for TestLoader.loadTestsFromNames()
654 ################################################################
655
656 # "Similar to loadTestsFromName(), but takes a sequence of names rather
657 # than a single name."
658 #
659 # What happens if that sequence of names is empty?
660 def test_loadTestsFromNames__empty_name_list(self):
661 loader = unittest.TestLoader()
662
663 suite = loader.loadTestsFromNames([])
Ezio Melottie9615932010-01-24 19:26:24 +0000664 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000665 self.assertEqual(list(suite), [])
666
667 # "Similar to loadTestsFromName(), but takes a sequence of names rather
668 # than a single name."
669 # ...
670 # "The method optionally resolves name relative to the given module"
671 #
672 # What happens if that sequence of names is empty?
673 #
674 # XXX Should this raise a ValueError or just return an empty TestSuite?
675 def test_loadTestsFromNames__relative_empty_name_list(self):
676 loader = unittest.TestLoader()
677
678 suite = loader.loadTestsFromNames([], unittest)
Ezio Melottie9615932010-01-24 19:26:24 +0000679 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000680 self.assertEqual(list(suite), [])
681
682 # "The specifier name is a ``dotted name'' that may resolve either to
683 # a module, a test case class, a TestSuite instance, a test method
684 # within a test case class, or a callable object which returns a
685 # TestCase or TestSuite instance."
686 #
687 # Is ValueError raised in response to an empty name?
688 def test_loadTestsFromNames__empty_name(self):
689 loader = unittest.TestLoader()
690
691 try:
692 loader.loadTestsFromNames([''])
693 except ValueError as e:
694 self.assertEqual(str(e), "Empty module name")
695 else:
696 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
697
698 # "The specifier name is a ``dotted name'' that may resolve either to
699 # a module, a test case class, a TestSuite instance, a test method
700 # within a test case class, or a callable object which returns a
701 # TestCase or TestSuite instance."
702 #
703 # What happens when presented with an impossible module name?
704 def test_loadTestsFromNames__malformed_name(self):
705 loader = unittest.TestLoader()
706
707 # XXX Should this raise ValueError or ImportError?
708 try:
709 loader.loadTestsFromNames(['abc () //'])
710 except ValueError:
711 pass
712 except ImportError:
713 pass
714 else:
715 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
716
717 # "The specifier name is a ``dotted name'' that may resolve either to
718 # a module, a test case class, a TestSuite instance, a test method
719 # within a test case class, or a callable object which returns a
720 # TestCase or TestSuite instance."
721 #
722 # What happens when no module can be found for the given name?
723 def test_loadTestsFromNames__unknown_module_name(self):
724 loader = unittest.TestLoader()
725
726 try:
727 loader.loadTestsFromNames(['sdasfasfasdf'])
728 except ImportError as e:
729 self.assertEqual(str(e), "No module named sdasfasfasdf")
730 else:
731 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
732
733 # "The specifier name is a ``dotted name'' that may resolve either to
734 # a module, a test case class, a TestSuite instance, a test method
735 # within a test case class, or a callable object which returns a
736 # TestCase or TestSuite instance."
737 #
738 # What happens when the module can be found, but not the attribute?
739 def test_loadTestsFromNames__unknown_attr_name(self):
740 loader = unittest.TestLoader()
741
742 try:
743 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
744 except AttributeError as e:
745 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
746 else:
747 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
748
749 # "The specifier name is a ``dotted name'' that may resolve either to
750 # a module, a test case class, a TestSuite instance, a test method
751 # within a test case class, or a callable object which returns a
752 # TestCase or TestSuite instance."
753 # ...
754 # "The method optionally resolves name relative to the given module"
755 #
756 # What happens when given an unknown attribute on a specified `module`
757 # argument?
758 def test_loadTestsFromNames__unknown_name_relative_1(self):
759 loader = unittest.TestLoader()
760
761 try:
762 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
763 except AttributeError as e:
764 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
765 else:
766 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
767
768 # "The specifier name is a ``dotted name'' that may resolve either to
769 # a module, a test case class, a TestSuite instance, a test method
770 # within a test case class, or a callable object which returns a
771 # TestCase or TestSuite instance."
772 # ...
773 # "The method optionally resolves name relative to the given module"
774 #
775 # Do unknown attributes (relative to a provided module) still raise an
776 # exception even in the presence of valid attribute names?
777 def test_loadTestsFromNames__unknown_name_relative_2(self):
778 loader = unittest.TestLoader()
779
780 try:
781 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
782 except AttributeError as e:
783 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
784 else:
785 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
786
787 # "The specifier name is a ``dotted name'' that may resolve either to
788 # a module, a test case class, a TestSuite instance, a test method
789 # within a test case class, or a callable object which returns a
790 # TestCase or TestSuite instance."
791 # ...
792 # "The method optionally resolves name relative to the given module"
793 #
794 # What happens when faced with the empty string?
795 #
796 # XXX This currently raises AttributeError, though ValueError is probably
797 # more appropriate
798 def test_loadTestsFromNames__relative_empty_name(self):
799 loader = unittest.TestLoader()
800
801 try:
802 loader.loadTestsFromNames([''], unittest)
803 except AttributeError:
804 pass
805 else:
806 self.fail("Failed to raise ValueError")
807
808 # "The specifier name is a ``dotted name'' that may resolve either to
809 # a module, a test case class, a TestSuite instance, a test method
810 # within a test case class, or a callable object which returns a
811 # TestCase or TestSuite instance."
812 # ...
813 # "The method optionally resolves name relative to the given module"
814 #
815 # What happens when presented with an impossible attribute name?
816 def test_loadTestsFromNames__relative_malformed_name(self):
817 loader = unittest.TestLoader()
818
819 # XXX Should this raise AttributeError or ValueError?
820 try:
821 loader.loadTestsFromNames(['abc () //'], unittest)
822 except AttributeError:
823 pass
824 except ValueError:
825 pass
826 else:
827 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
828
829 # "The method optionally resolves name relative to the given module"
830 #
831 # Does loadTestsFromNames() make sure the provided `module` is in fact
832 # a module?
833 #
834 # XXX This validation is currently not done. This flexibility should
835 # either be documented or a TypeError should be raised.
836 def test_loadTestsFromNames__relative_not_a_module(self):
837 class MyTestCase(unittest.TestCase):
838 def test(self):
839 pass
840
841 class NotAModule(object):
842 test_2 = MyTestCase
843
844 loader = unittest.TestLoader()
845 suite = loader.loadTestsFromNames(['test_2'], NotAModule)
846
847 reference = [unittest.TestSuite([MyTestCase('test')])]
848 self.assertEqual(list(suite), reference)
849
850 # "The specifier name is a ``dotted name'' that may resolve either to
851 # a module, a test case class, a TestSuite instance, a test method
852 # within a test case class, or a callable object which returns a
853 # TestCase or TestSuite instance."
854 #
855 # Does it raise an exception if the name resolves to an invalid
856 # object?
857 def test_loadTestsFromNames__relative_bad_object(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000858 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000859 m.testcase_1 = object()
860
861 loader = unittest.TestLoader()
862 try:
863 loader.loadTestsFromNames(['testcase_1'], m)
864 except TypeError:
865 pass
866 else:
867 self.fail("Should have raised TypeError")
868
869 # "The specifier name is a ``dotted name'' that may resolve ... to
870 # ... a test case class"
871 def test_loadTestsFromNames__relative_TestCase_subclass(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000872 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000873 class MyTestCase(unittest.TestCase):
874 def test(self):
875 pass
876 m.testcase_1 = MyTestCase
877
878 loader = unittest.TestLoader()
879 suite = loader.loadTestsFromNames(['testcase_1'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000880 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000881
882 expected = loader.suiteClass([MyTestCase('test')])
883 self.assertEqual(list(suite), [expected])
884
885 # "The specifier name is a ``dotted name'' that may resolve ... to
886 # ... a TestSuite instance"
887 def test_loadTestsFromNames__relative_TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000888 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000889 class MyTestCase(unittest.TestCase):
890 def test(self):
891 pass
892 m.testsuite = unittest.TestSuite([MyTestCase('test')])
893
894 loader = unittest.TestLoader()
895 suite = loader.loadTestsFromNames(['testsuite'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000896 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000897
898 self.assertEqual(list(suite), [m.testsuite])
899
900 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
901 # test method within a test case class"
902 def test_loadTestsFromNames__relative_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000903 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000904 class MyTestCase(unittest.TestCase):
905 def test(self):
906 pass
907 m.testcase_1 = MyTestCase
908
909 loader = unittest.TestLoader()
910 suite = loader.loadTestsFromNames(['testcase_1.test'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000911 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000912
913 ref_suite = unittest.TestSuite([MyTestCase('test')])
914 self.assertEqual(list(suite), [ref_suite])
915
916 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
917 # test method within a test case class"
918 #
919 # Does the method gracefully handle names that initially look like they
920 # resolve to "a test method within a test case class" but don't?
921 def test_loadTestsFromNames__relative_invalid_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000922 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000923 class MyTestCase(unittest.TestCase):
924 def test(self):
925 pass
926 m.testcase_1 = MyTestCase
927
928 loader = unittest.TestLoader()
929 try:
930 loader.loadTestsFromNames(['testcase_1.testfoo'], m)
931 except AttributeError as e:
932 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
933 else:
934 self.fail("Failed to raise AttributeError")
935
936 # "The specifier name is a ``dotted name'' that may resolve ... to
937 # ... a callable object which returns a ... TestSuite instance"
938 def test_loadTestsFromNames__callable__TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000939 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000940 testcase_1 = unittest.FunctionTestCase(lambda: None)
941 testcase_2 = unittest.FunctionTestCase(lambda: None)
942 def return_TestSuite():
943 return unittest.TestSuite([testcase_1, testcase_2])
944 m.return_TestSuite = return_TestSuite
945
946 loader = unittest.TestLoader()
947 suite = loader.loadTestsFromNames(['return_TestSuite'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000948 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000949
950 expected = unittest.TestSuite([testcase_1, testcase_2])
951 self.assertEqual(list(suite), [expected])
952
953 # "The specifier name is a ``dotted name'' that may resolve ... to
954 # ... a callable object which returns a TestCase ... instance"
955 def test_loadTestsFromNames__callable__TestCase_instance(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000956 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000957 testcase_1 = unittest.FunctionTestCase(lambda: None)
958 def return_TestCase():
959 return testcase_1
960 m.return_TestCase = return_TestCase
961
962 loader = unittest.TestLoader()
963 suite = loader.loadTestsFromNames(['return_TestCase'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000964 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000965
966 ref_suite = unittest.TestSuite([testcase_1])
967 self.assertEqual(list(suite), [ref_suite])
968
969 # "The specifier name is a ``dotted name'' that may resolve ... to
970 # ... a callable object which returns a TestCase or TestSuite instance"
971 #
972 # Are staticmethods handled correctly?
973 def test_loadTestsFromNames__callable__call_staticmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000974 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000975 class Test1(unittest.TestCase):
976 def test(self):
977 pass
978
979 testcase_1 = Test1('test')
980 class Foo(unittest.TestCase):
981 @staticmethod
982 def foo():
983 return testcase_1
984 m.Foo = Foo
985
986 loader = unittest.TestLoader()
987 suite = loader.loadTestsFromNames(['Foo.foo'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000988 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000989
990 ref_suite = unittest.TestSuite([testcase_1])
991 self.assertEqual(list(suite), [ref_suite])
992
993 # "The specifier name is a ``dotted name'' that may resolve ... to
994 # ... a callable object which returns a TestCase or TestSuite instance"
995 #
996 # What happens when the callable returns something else?
997 def test_loadTestsFromNames__callable__wrong_type(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000998 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000999 def return_wrong():
1000 return 6
1001 m.return_wrong = return_wrong
1002
1003 loader = unittest.TestLoader()
1004 try:
1005 suite = loader.loadTestsFromNames(['return_wrong'], m)
1006 except TypeError:
1007 pass
1008 else:
1009 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
1010
1011 # "The specifier can refer to modules and packages which have not been
1012 # imported; they will be imported as a side-effect"
1013 def test_loadTestsFromNames__module_not_loaded(self):
1014 # We're going to try to load this module as a side-effect, so it
1015 # better not be loaded before we try.
1016 #
1017 # Why pick audioop? Google shows it isn't used very often, so there's
1018 # a good chance that it won't be imported when this test is run
1019 module_name = 'audioop'
1020
Guido van Rossumd8faa362007-04-27 19:54:29 +00001021 if module_name in sys.modules:
1022 del sys.modules[module_name]
1023
1024 loader = unittest.TestLoader()
1025 try:
1026 suite = loader.loadTestsFromNames([module_name])
1027
Ezio Melottie9615932010-01-24 19:26:24 +00001028 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001029 self.assertEqual(list(suite), [unittest.TestSuite()])
1030
1031 # audioop should now be loaded, thanks to loadTestsFromName()
Benjamin Peterson577473f2010-01-19 00:09:57 +00001032 self.assertIn(module_name, sys.modules)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001033 finally:
Guido van Rossum360e4b82007-05-14 22:51:27 +00001034 if module_name in sys.modules:
1035 del sys.modules[module_name]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001036
1037 ################################################################
1038 ### /Tests for TestLoader.loadTestsFromNames()
1039
1040 ### Tests for TestLoader.getTestCaseNames()
1041 ################################################################
1042
1043 # "Return a sorted sequence of method names found within testCaseClass"
1044 #
1045 # Test.foobar is defined to make sure getTestCaseNames() respects
1046 # loader.testMethodPrefix
1047 def test_getTestCaseNames(self):
1048 class Test(unittest.TestCase):
1049 def test_1(self): pass
1050 def test_2(self): pass
1051 def foobar(self): pass
1052
1053 loader = unittest.TestLoader()
1054
1055 self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])
1056
1057 # "Return a sorted sequence of method names found within testCaseClass"
1058 #
1059 # Does getTestCaseNames() behave appropriately if no tests are found?
1060 def test_getTestCaseNames__no_tests(self):
1061 class Test(unittest.TestCase):
1062 def foobar(self): pass
1063
1064 loader = unittest.TestLoader()
1065
1066 self.assertEqual(loader.getTestCaseNames(Test), [])
1067
1068 # "Return a sorted sequence of method names found within testCaseClass"
1069 #
1070 # Are not-TestCases handled gracefully?
1071 #
1072 # XXX This should raise a TypeError, not return a list
1073 #
1074 # XXX It's too late in the 2.5 release cycle to fix this, but it should
1075 # probably be revisited for 2.6
1076 def test_getTestCaseNames__not_a_TestCase(self):
1077 class BadCase(int):
1078 def test_foo(self):
1079 pass
1080
1081 loader = unittest.TestLoader()
1082 names = loader.getTestCaseNames(BadCase)
1083
1084 self.assertEqual(names, ['test_foo'])
1085
1086 # "Return a sorted sequence of method names found within testCaseClass"
1087 #
1088 # Make sure inherited names are handled.
1089 #
1090 # TestP.foobar is defined to make sure getTestCaseNames() respects
1091 # loader.testMethodPrefix
1092 def test_getTestCaseNames__inheritance(self):
1093 class TestP(unittest.TestCase):
1094 def test_1(self): pass
1095 def test_2(self): pass
1096 def foobar(self): pass
1097
1098 class TestC(TestP):
1099 def test_1(self): pass
1100 def test_3(self): pass
1101
1102 loader = unittest.TestLoader()
1103
1104 names = ['test_1', 'test_2', 'test_3']
1105 self.assertEqual(loader.getTestCaseNames(TestC), names)
1106
1107 ################################################################
1108 ### /Tests for TestLoader.getTestCaseNames()
1109
1110 ### Tests for TestLoader.testMethodPrefix
1111 ################################################################
1112
1113 # "String giving the prefix of method names which will be interpreted as
1114 # test methods"
1115 #
1116 # Implicit in the documentation is that testMethodPrefix is respected by
1117 # all loadTestsFrom* methods.
1118 def test_testMethodPrefix__loadTestsFromTestCase(self):
1119 class Foo(unittest.TestCase):
1120 def test_1(self): pass
1121 def test_2(self): pass
1122 def foo_bar(self): pass
1123
1124 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1125 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1126
1127 loader = unittest.TestLoader()
1128 loader.testMethodPrefix = 'foo'
1129 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
1130
1131 loader.testMethodPrefix = 'test'
1132 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
1133
1134 # "String giving the prefix of method names which will be interpreted as
1135 # test methods"
1136 #
1137 # Implicit in the documentation is that testMethodPrefix is respected by
1138 # all loadTestsFrom* methods.
1139 def test_testMethodPrefix__loadTestsFromModule(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001140 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001141 class Foo(unittest.TestCase):
1142 def test_1(self): pass
1143 def test_2(self): pass
1144 def foo_bar(self): pass
1145 m.Foo = Foo
1146
1147 tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
1148 tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]
1149
1150 loader = unittest.TestLoader()
1151 loader.testMethodPrefix = 'foo'
1152 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
1153
1154 loader.testMethodPrefix = 'test'
1155 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
1156
1157 # "String giving the prefix of method names which will be interpreted as
1158 # test methods"
1159 #
1160 # Implicit in the documentation is that testMethodPrefix is respected by
1161 # all loadTestsFrom* methods.
1162 def test_testMethodPrefix__loadTestsFromName(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001163 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001164 class Foo(unittest.TestCase):
1165 def test_1(self): pass
1166 def test_2(self): pass
1167 def foo_bar(self): pass
1168 m.Foo = Foo
1169
1170 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1171 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1172
1173 loader = unittest.TestLoader()
1174 loader.testMethodPrefix = 'foo'
1175 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
1176
1177 loader.testMethodPrefix = 'test'
1178 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
1179
1180 # "String giving the prefix of method names which will be interpreted as
1181 # test methods"
1182 #
1183 # Implicit in the documentation is that testMethodPrefix is respected by
1184 # all loadTestsFrom* methods.
1185 def test_testMethodPrefix__loadTestsFromNames(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001186 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001187 class Foo(unittest.TestCase):
1188 def test_1(self): pass
1189 def test_2(self): pass
1190 def foo_bar(self): pass
1191 m.Foo = Foo
1192
1193 tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
1194 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1195 tests_2 = unittest.TestSuite([tests_2])
1196
1197 loader = unittest.TestLoader()
1198 loader.testMethodPrefix = 'foo'
1199 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)
1200
1201 loader.testMethodPrefix = 'test'
1202 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)
1203
1204 # "The default value is 'test'"
1205 def test_testMethodPrefix__default_value(self):
1206 loader = unittest.TestLoader()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001207 self.assertEqual(loader.testMethodPrefix, 'test')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001208
1209 ################################################################
1210 ### /Tests for TestLoader.testMethodPrefix
1211
1212 ### Tests for TestLoader.sortTestMethodsUsing
1213 ################################################################
1214
1215 # "Function to be used to compare method names when sorting them in
1216 # getTestCaseNames() and all the loadTestsFromX() methods"
1217 def test_sortTestMethodsUsing__loadTestsFromTestCase(self):
1218 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001219 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001220
1221 class Foo(unittest.TestCase):
1222 def test_1(self): pass
1223 def test_2(self): pass
1224
1225 loader = unittest.TestLoader()
1226 loader.sortTestMethodsUsing = reversed_cmp
1227
1228 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1229 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
1230
1231 # "Function to be used to compare method names when sorting them in
1232 # getTestCaseNames() and all the loadTestsFromX() methods"
1233 def test_sortTestMethodsUsing__loadTestsFromModule(self):
1234 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001235 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001236
Christian Heimes45f9af32007-11-27 21:50:00 +00001237 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001238 class Foo(unittest.TestCase):
1239 def test_1(self): pass
1240 def test_2(self): pass
1241 m.Foo = Foo
1242
1243 loader = unittest.TestLoader()
1244 loader.sortTestMethodsUsing = reversed_cmp
1245
1246 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1247 self.assertEqual(list(loader.loadTestsFromModule(m)), tests)
1248
1249 # "Function to be used to compare method names when sorting them in
1250 # getTestCaseNames() and all the loadTestsFromX() methods"
1251 def test_sortTestMethodsUsing__loadTestsFromName(self):
1252 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001253 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001254
Christian Heimes45f9af32007-11-27 21:50:00 +00001255 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001256 class Foo(unittest.TestCase):
1257 def test_1(self): pass
1258 def test_2(self): pass
1259 m.Foo = Foo
1260
1261 loader = unittest.TestLoader()
1262 loader.sortTestMethodsUsing = reversed_cmp
1263
1264 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1265 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
1266
1267 # "Function to be used to compare method names when sorting them in
1268 # getTestCaseNames() and all the loadTestsFromX() methods"
1269 def test_sortTestMethodsUsing__loadTestsFromNames(self):
1270 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001271 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001272
Christian Heimes45f9af32007-11-27 21:50:00 +00001273 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001274 class Foo(unittest.TestCase):
1275 def test_1(self): pass
1276 def test_2(self): pass
1277 m.Foo = Foo
1278
1279 loader = unittest.TestLoader()
1280 loader.sortTestMethodsUsing = reversed_cmp
1281
1282 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1283 self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)
1284
1285 # "Function to be used to compare method names when sorting them in
1286 # getTestCaseNames()"
1287 #
1288 # Does it actually affect getTestCaseNames()?
1289 def test_sortTestMethodsUsing__getTestCaseNames(self):
1290 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001291 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001292
1293 class Foo(unittest.TestCase):
1294 def test_1(self): pass
1295 def test_2(self): pass
1296
1297 loader = unittest.TestLoader()
1298 loader.sortTestMethodsUsing = reversed_cmp
1299
1300 test_names = ['test_2', 'test_1']
1301 self.assertEqual(loader.getTestCaseNames(Foo), test_names)
1302
1303 # "The default value is the built-in cmp() function"
Mark Dickinsona56c4672009-01-27 18:17:45 +00001304 # Since cmp is now defunct, we simply verify that the results
1305 # occur in the same order as they would with the default sort.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001306 def test_sortTestMethodsUsing__default_value(self):
1307 loader = unittest.TestLoader()
Mark Dickinsona56c4672009-01-27 18:17:45 +00001308
1309 class Foo(unittest.TestCase):
1310 def test_2(self): pass
1311 def test_3(self): pass
1312 def test_1(self): pass
1313
1314 test_names = ['test_2', 'test_3', 'test_1']
1315 self.assertEqual(loader.getTestCaseNames(Foo), sorted(test_names))
1316
Guido van Rossumd8faa362007-04-27 19:54:29 +00001317
1318 # "it can be set to None to disable the sort."
1319 #
1320 # XXX How is this different from reassigning cmp? Are the tests returned
1321 # in a random order or something? This behaviour should die
1322 def test_sortTestMethodsUsing__None(self):
1323 class Foo(unittest.TestCase):
1324 def test_1(self): pass
1325 def test_2(self): pass
1326
1327 loader = unittest.TestLoader()
1328 loader.sortTestMethodsUsing = None
1329
1330 test_names = ['test_2', 'test_1']
1331 self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))
1332
1333 ################################################################
1334 ### /Tests for TestLoader.sortTestMethodsUsing
1335
1336 ### Tests for TestLoader.suiteClass
1337 ################################################################
1338
1339 # "Callable object that constructs a test suite from a list of tests."
1340 def test_suiteClass__loadTestsFromTestCase(self):
1341 class Foo(unittest.TestCase):
1342 def test_1(self): pass
1343 def test_2(self): pass
1344 def foo_bar(self): pass
1345
1346 tests = [Foo('test_1'), Foo('test_2')]
1347
1348 loader = unittest.TestLoader()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001349 loader.suiteClass = list
Guido van Rossumd8faa362007-04-27 19:54:29 +00001350 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
1351
1352 # It is implicit in the documentation for TestLoader.suiteClass that
1353 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
1354 def test_suiteClass__loadTestsFromModule(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001355 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001356 class Foo(unittest.TestCase):
1357 def test_1(self): pass
1358 def test_2(self): pass
1359 def foo_bar(self): pass
1360 m.Foo = Foo
1361
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001362 tests = [[Foo('test_1'), Foo('test_2')]]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001363
1364 loader = unittest.TestLoader()
1365 loader.suiteClass = list
1366 self.assertEqual(loader.loadTestsFromModule(m), tests)
1367
1368 # It is implicit in the documentation for TestLoader.suiteClass that
1369 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
1370 def test_suiteClass__loadTestsFromName(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001371 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001372 class Foo(unittest.TestCase):
1373 def test_1(self): pass
1374 def test_2(self): pass
1375 def foo_bar(self): pass
1376 m.Foo = Foo
1377
1378 tests = [Foo('test_1'), Foo('test_2')]
1379
1380 loader = unittest.TestLoader()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001381 loader.suiteClass = list
Guido van Rossumd8faa362007-04-27 19:54:29 +00001382 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
1383
1384 # It is implicit in the documentation for TestLoader.suiteClass that
1385 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
1386 def test_suiteClass__loadTestsFromNames(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001387 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001388 class Foo(unittest.TestCase):
1389 def test_1(self): pass
1390 def test_2(self): pass
1391 def foo_bar(self): pass
1392 m.Foo = Foo
1393
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001394 tests = [[Foo('test_1'), Foo('test_2')]]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001395
1396 loader = unittest.TestLoader()
1397 loader.suiteClass = list
1398 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)
1399
1400 # "The default value is the TestSuite class"
1401 def test_suiteClass__default_value(self):
1402 loader = unittest.TestLoader()
Benjamin Petersone1759f82009-06-30 23:35:19 +00001403 self.assertTrue(loader.suiteClass is unittest.TestSuite)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001404
1405 ################################################################
1406 ### /Tests for TestLoader.suiteClass
1407
1408### Support code for Test_TestSuite
1409################################################################
1410
1411class Foo(unittest.TestCase):
1412 def test_1(self): pass
1413 def test_2(self): pass
1414 def test_3(self): pass
1415 def runTest(self): pass
1416
1417def _mk_TestSuite(*names):
1418 return unittest.TestSuite(Foo(n) for n in names)
1419
1420################################################################
1421### /Support code for Test_TestSuite
1422
1423class Test_TestSuite(TestCase, TestEquality):
1424
1425 ### Set up attributes needed by inherited tests
1426 ################################################################
1427
1428 # Used by TestEquality.test_eq
1429 eq_pairs = [(unittest.TestSuite(), unittest.TestSuite())
1430 ,(unittest.TestSuite(), unittest.TestSuite([]))
1431 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]
1432
1433 # Used by TestEquality.test_ne
1434 ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1'))
1435 ,(unittest.TestSuite([]), _mk_TestSuite('test_1'))
1436 ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3'))
1437 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]
1438
1439 ################################################################
1440 ### /Set up attributes needed by inherited tests
1441
1442 ### Tests for TestSuite.__init__
1443 ################################################################
1444
1445 # "class TestSuite([tests])"
1446 #
1447 # The tests iterable should be optional
1448 def test_init__tests_optional(self):
1449 suite = unittest.TestSuite()
1450
1451 self.assertEqual(suite.countTestCases(), 0)
1452
1453 # "class TestSuite([tests])"
1454 # ...
1455 # "If tests is given, it must be an iterable of individual test cases
1456 # or other test suites that will be used to build the suite initially"
1457 #
1458 # TestSuite should deal with empty tests iterables by allowing the
1459 # creation of an empty suite
1460 def test_init__empty_tests(self):
1461 suite = unittest.TestSuite([])
1462
1463 self.assertEqual(suite.countTestCases(), 0)
1464
1465 # "class TestSuite([tests])"
1466 # ...
1467 # "If tests is given, it must be an iterable of individual test cases
1468 # or other test suites that will be used to build the suite initially"
1469 #
1470 # TestSuite should allow any iterable to provide tests
1471 def test_init__tests_from_any_iterable(self):
1472 def tests():
1473 yield unittest.FunctionTestCase(lambda: None)
1474 yield unittest.FunctionTestCase(lambda: None)
1475
1476 suite_1 = unittest.TestSuite(tests())
1477 self.assertEqual(suite_1.countTestCases(), 2)
1478
1479 suite_2 = unittest.TestSuite(suite_1)
1480 self.assertEqual(suite_2.countTestCases(), 2)
1481
1482 suite_3 = unittest.TestSuite(set(suite_1))
1483 self.assertEqual(suite_3.countTestCases(), 2)
1484
1485 # "class TestSuite([tests])"
1486 # ...
1487 # "If tests is given, it must be an iterable of individual test cases
1488 # or other test suites that will be used to build the suite initially"
1489 #
1490 # Does TestSuite() also allow other TestSuite() instances to be present
1491 # in the tests iterable?
1492 def test_init__TestSuite_instances_in_tests(self):
1493 def tests():
1494 ftc = unittest.FunctionTestCase(lambda: None)
1495 yield unittest.TestSuite([ftc])
1496 yield unittest.FunctionTestCase(lambda: None)
1497
1498 suite = unittest.TestSuite(tests())
1499 self.assertEqual(suite.countTestCases(), 2)
1500
1501 ################################################################
1502 ### /Tests for TestSuite.__init__
1503
1504 # Container types should support the iter protocol
1505 def test_iter(self):
1506 test1 = unittest.FunctionTestCase(lambda: None)
1507 test2 = unittest.FunctionTestCase(lambda: None)
1508 suite = unittest.TestSuite((test1, test2))
1509
1510 self.assertEqual(list(suite), [test1, test2])
1511
1512 # "Return the number of tests represented by the this test object.
1513 # ...this method is also implemented by the TestSuite class, which can
1514 # return larger [greater than 1] values"
1515 #
1516 # Presumably an empty TestSuite returns 0?
1517 def test_countTestCases_zero_simple(self):
1518 suite = unittest.TestSuite()
1519
1520 self.assertEqual(suite.countTestCases(), 0)
1521
1522 # "Return the number of tests represented by the this test object.
1523 # ...this method is also implemented by the TestSuite class, which can
1524 # return larger [greater than 1] values"
1525 #
1526 # Presumably an empty TestSuite (even if it contains other empty
1527 # TestSuite instances) returns 0?
1528 def test_countTestCases_zero_nested(self):
1529 class Test1(unittest.TestCase):
1530 def test(self):
1531 pass
1532
1533 suite = unittest.TestSuite([unittest.TestSuite()])
1534
1535 self.assertEqual(suite.countTestCases(), 0)
1536
1537 # "Return the number of tests represented by the this test object.
1538 # ...this method is also implemented by the TestSuite class, which can
1539 # return larger [greater than 1] values"
1540 def test_countTestCases_simple(self):
1541 test1 = unittest.FunctionTestCase(lambda: None)
1542 test2 = unittest.FunctionTestCase(lambda: None)
1543 suite = unittest.TestSuite((test1, test2))
1544
1545 self.assertEqual(suite.countTestCases(), 2)
1546
1547 # "Return the number of tests represented by the this test object.
1548 # ...this method is also implemented by the TestSuite class, which can
1549 # return larger [greater than 1] values"
1550 #
1551 # Make sure this holds for nested TestSuite instances, too
1552 def test_countTestCases_nested(self):
1553 class Test1(unittest.TestCase):
1554 def test1(self): pass
1555 def test2(self): pass
1556
1557 test2 = unittest.FunctionTestCase(lambda: None)
1558 test3 = unittest.FunctionTestCase(lambda: None)
1559 child = unittest.TestSuite((Test1('test2'), test2))
1560 parent = unittest.TestSuite((test3, child, Test1('test1')))
1561
1562 self.assertEqual(parent.countTestCases(), 4)
1563
1564 # "Run the tests associated with this suite, collecting the result into
1565 # the test result object passed as result."
1566 #
1567 # And if there are no tests? What then?
1568 def test_run__empty_suite(self):
1569 events = []
1570 result = LoggingResult(events)
1571
1572 suite = unittest.TestSuite()
1573
1574 suite.run(result)
1575
1576 self.assertEqual(events, [])
1577
1578 # "Note that unlike TestCase.run(), TestSuite.run() requires the
1579 # "result object to be passed in."
1580 def test_run__requires_result(self):
1581 suite = unittest.TestSuite()
1582
1583 try:
1584 suite.run()
1585 except TypeError:
1586 pass
1587 else:
1588 self.fail("Failed to raise TypeError")
1589
1590 # "Run the tests associated with this suite, collecting the result into
1591 # the test result object passed as result."
1592 def test_run(self):
1593 events = []
1594 result = LoggingResult(events)
1595
1596 class LoggingCase(unittest.TestCase):
1597 def run(self, result):
1598 events.append('run %s' % self._testMethodName)
1599
1600 def test1(self): pass
1601 def test2(self): pass
1602
1603 tests = [LoggingCase('test1'), LoggingCase('test2')]
1604
1605 unittest.TestSuite(tests).run(result)
1606
1607 self.assertEqual(events, ['run test1', 'run test2'])
1608
1609 # "Add a TestCase ... to the suite"
1610 def test_addTest__TestCase(self):
1611 class Foo(unittest.TestCase):
1612 def test(self): pass
1613
1614 test = Foo('test')
1615 suite = unittest.TestSuite()
1616
1617 suite.addTest(test)
1618
1619 self.assertEqual(suite.countTestCases(), 1)
1620 self.assertEqual(list(suite), [test])
1621
1622 # "Add a ... TestSuite to the suite"
1623 def test_addTest__TestSuite(self):
1624 class Foo(unittest.TestCase):
1625 def test(self): pass
1626
1627 suite_2 = unittest.TestSuite([Foo('test')])
1628
1629 suite = unittest.TestSuite()
1630 suite.addTest(suite_2)
1631
1632 self.assertEqual(suite.countTestCases(), 1)
1633 self.assertEqual(list(suite), [suite_2])
1634
1635 # "Add all the tests from an iterable of TestCase and TestSuite
1636 # instances to this test suite."
1637 #
1638 # "This is equivalent to iterating over tests, calling addTest() for
1639 # each element"
1640 def test_addTests(self):
1641 class Foo(unittest.TestCase):
1642 def test_1(self): pass
1643 def test_2(self): pass
1644
1645 test_1 = Foo('test_1')
1646 test_2 = Foo('test_2')
1647 inner_suite = unittest.TestSuite([test_2])
1648
1649 def gen():
1650 yield test_1
1651 yield test_2
1652 yield inner_suite
1653
1654 suite_1 = unittest.TestSuite()
1655 suite_1.addTests(gen())
1656
1657 self.assertEqual(list(suite_1), list(gen()))
1658
1659 # "This is equivalent to iterating over tests, calling addTest() for
1660 # each element"
1661 suite_2 = unittest.TestSuite()
1662 for t in gen():
1663 suite_2.addTest(t)
1664
1665 self.assertEqual(suite_1, suite_2)
1666
1667 # "Add all the tests from an iterable of TestCase and TestSuite
1668 # instances to this test suite."
1669 #
1670 # What happens if it doesn't get an iterable?
1671 def test_addTest__noniterable(self):
1672 suite = unittest.TestSuite()
1673
1674 try:
1675 suite.addTests(5)
1676 except TypeError:
1677 pass
1678 else:
1679 self.fail("Failed to raise TypeError")
1680
1681 def test_addTest__noncallable(self):
1682 suite = unittest.TestSuite()
1683 self.assertRaises(TypeError, suite.addTest, 5)
1684
1685 def test_addTest__casesuiteclass(self):
1686 suite = unittest.TestSuite()
1687 self.assertRaises(TypeError, suite.addTest, Test_TestSuite)
1688 self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)
1689
1690 def test_addTests__string(self):
1691 suite = unittest.TestSuite()
1692 self.assertRaises(TypeError, suite.addTests, "foo")
1693
1694
1695class Test_FunctionTestCase(TestCase):
1696
1697 # "Return the number of tests represented by the this test object. For
1698 # TestCase instances, this will always be 1"
1699 def test_countTestCases(self):
1700 test = unittest.FunctionTestCase(lambda: None)
1701
1702 self.assertEqual(test.countTestCases(), 1)
1703
1704 # "When a setUp() method is defined, the test runner will run that method
1705 # prior to each test. Likewise, if a tearDown() method is defined, the
1706 # test runner will invoke that method after each test. In the example,
1707 # setUp() was used to create a fresh sequence for each test."
1708 #
1709 # Make sure the proper call order is maintained, even if setUp() raises
1710 # an exception.
1711 def test_run_call_order__error_in_setUp(self):
1712 events = []
1713 result = LoggingResult(events)
1714
1715 def setUp():
1716 events.append('setUp')
1717 raise RuntimeError('raised by setUp')
1718
1719 def test():
1720 events.append('test')
1721
1722 def tearDown():
1723 events.append('tearDown')
1724
1725 expected = ['startTest', 'setUp', 'addError', 'stopTest']
1726 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1727 self.assertEqual(events, expected)
1728
1729 # "When a setUp() method is defined, the test runner will run that method
1730 # prior to each test. Likewise, if a tearDown() method is defined, the
1731 # test runner will invoke that method after each test. In the example,
1732 # setUp() was used to create a fresh sequence for each test."
1733 #
1734 # Make sure the proper call order is maintained, even if the test raises
1735 # an error (as opposed to a failure).
1736 def test_run_call_order__error_in_test(self):
1737 events = []
1738 result = LoggingResult(events)
1739
1740 def setUp():
1741 events.append('setUp')
1742
1743 def test():
1744 events.append('test')
1745 raise RuntimeError('raised by test')
1746
1747 def tearDown():
1748 events.append('tearDown')
1749
1750 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
1751 'stopTest']
1752 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1753 self.assertEqual(events, expected)
1754
1755 # "When a setUp() method is defined, the test runner will run that method
1756 # prior to each test. Likewise, if a tearDown() method is defined, the
1757 # test runner will invoke that method after each test. In the example,
1758 # setUp() was used to create a fresh sequence for each test."
1759 #
1760 # Make sure the proper call order is maintained, even if the test signals
1761 # a failure (as opposed to an error).
1762 def test_run_call_order__failure_in_test(self):
1763 events = []
1764 result = LoggingResult(events)
1765
1766 def setUp():
1767 events.append('setUp')
1768
1769 def test():
1770 events.append('test')
1771 self.fail('raised by test')
1772
1773 def tearDown():
1774 events.append('tearDown')
1775
1776 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
1777 'stopTest']
1778 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1779 self.assertEqual(events, expected)
1780
1781 # "When a setUp() method is defined, the test runner will run that method
1782 # prior to each test. Likewise, if a tearDown() method is defined, the
1783 # test runner will invoke that method after each test. In the example,
1784 # setUp() was used to create a fresh sequence for each test."
1785 #
1786 # Make sure the proper call order is maintained, even if tearDown() raises
1787 # an exception.
1788 def test_run_call_order__error_in_tearDown(self):
1789 events = []
1790 result = LoggingResult(events)
1791
1792 def setUp():
1793 events.append('setUp')
1794
1795 def test():
1796 events.append('test')
1797
1798 def tearDown():
1799 events.append('tearDown')
1800 raise RuntimeError('raised by tearDown')
1801
1802 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
1803 'stopTest']
1804 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1805 self.assertEqual(events, expected)
1806
1807 # "Return a string identifying the specific test case."
1808 #
1809 # Because of the vague nature of the docs, I'm not going to lock this
1810 # test down too much. Really all that can be asserted is that the id()
1811 # will be a string (either 8-byte or unicode -- again, because the docs
1812 # just say "string")
1813 def test_id(self):
1814 test = unittest.FunctionTestCase(lambda: None)
1815
Ezio Melottie9615932010-01-24 19:26:24 +00001816 self.assertIsInstance(test.id(), str)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001817
1818 # "Returns a one-line description of the test, or None if no description
1819 # has been provided. The default implementation of this method returns
1820 # the first line of the test method's docstring, if available, or None."
1821 def test_shortDescription__no_docstring(self):
1822 test = unittest.FunctionTestCase(lambda: None)
1823
1824 self.assertEqual(test.shortDescription(), None)
1825
1826 # "Returns a one-line description of the test, or None if no description
1827 # has been provided. The default implementation of this method returns
1828 # the first line of the test method's docstring, if available, or None."
1829 def test_shortDescription__singleline_docstring(self):
1830 desc = "this tests foo"
1831 test = unittest.FunctionTestCase(lambda: None, description=desc)
1832
1833 self.assertEqual(test.shortDescription(), "this tests foo")
1834
1835class Test_TestResult(TestCase):
1836 # Note: there are not separate tests for TestResult.wasSuccessful(),
1837 # TestResult.errors, TestResult.failures, TestResult.testsRun or
1838 # TestResult.shouldStop because these only have meaning in terms of
1839 # other TestResult methods.
1840 #
1841 # Accordingly, tests for the aforenamed attributes are incorporated
1842 # in with the tests for the defining methods.
1843 ################################################################
1844
1845 def test_init(self):
1846 result = unittest.TestResult()
1847
Benjamin Petersone1759f82009-06-30 23:35:19 +00001848 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001849 self.assertEqual(len(result.errors), 0)
1850 self.assertEqual(len(result.failures), 0)
1851 self.assertEqual(result.testsRun, 0)
1852 self.assertEqual(result.shouldStop, False)
1853
1854 # "This method can be called to signal that the set of tests being
1855 # run should be aborted by setting the TestResult's shouldStop
1856 # attribute to True."
1857 def test_stop(self):
1858 result = unittest.TestResult()
1859
1860 result.stop()
1861
1862 self.assertEqual(result.shouldStop, True)
1863
1864 # "Called when the test case test is about to be run. The default
1865 # implementation simply increments the instance's testsRun counter."
1866 def test_startTest(self):
1867 class Foo(unittest.TestCase):
1868 def test_1(self):
1869 pass
1870
1871 test = Foo('test_1')
1872
1873 result = unittest.TestResult()
1874
1875 result.startTest(test)
1876
Benjamin Petersone1759f82009-06-30 23:35:19 +00001877 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001878 self.assertEqual(len(result.errors), 0)
1879 self.assertEqual(len(result.failures), 0)
1880 self.assertEqual(result.testsRun, 1)
1881 self.assertEqual(result.shouldStop, False)
1882
1883 result.stopTest(test)
1884
1885 # "Called after the test case test has been executed, regardless of
1886 # the outcome. The default implementation does nothing."
1887 def test_stopTest(self):
1888 class Foo(unittest.TestCase):
1889 def test_1(self):
1890 pass
1891
1892 test = Foo('test_1')
1893
1894 result = unittest.TestResult()
1895
1896 result.startTest(test)
1897
Benjamin Petersone1759f82009-06-30 23:35:19 +00001898 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001899 self.assertEqual(len(result.errors), 0)
1900 self.assertEqual(len(result.failures), 0)
1901 self.assertEqual(result.testsRun, 1)
1902 self.assertEqual(result.shouldStop, False)
1903
1904 result.stopTest(test)
1905
1906 # Same tests as above; make sure nothing has changed
Benjamin Petersone1759f82009-06-30 23:35:19 +00001907 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001908 self.assertEqual(len(result.errors), 0)
1909 self.assertEqual(len(result.failures), 0)
1910 self.assertEqual(result.testsRun, 1)
1911 self.assertEqual(result.shouldStop, False)
1912
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001913 # "Called before and after tests are run. The default implementation does nothing."
1914 def test_startTestRun_stopTestRun(self):
1915 result = unittest.TestResult()
1916 result.startTestRun()
1917 result.stopTestRun()
1918
Guido van Rossumd8faa362007-04-27 19:54:29 +00001919 # "addSuccess(test)"
1920 # ...
1921 # "Called when the test case test succeeds"
1922 # ...
1923 # "wasSuccessful() - Returns True if all tests run so far have passed,
1924 # otherwise returns False"
1925 # ...
1926 # "testsRun - The total number of tests run so far."
1927 # ...
1928 # "errors - A list containing 2-tuples of TestCase instances and
1929 # formatted tracebacks. Each tuple represents a test which raised an
1930 # unexpected exception. Contains formatted
1931 # tracebacks instead of sys.exc_info() results."
1932 # ...
1933 # "failures - A list containing 2-tuples of TestCase instances and
1934 # formatted tracebacks. Each tuple represents a test where a failure was
1935 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1936 # methods. Contains formatted tracebacks instead
1937 # of sys.exc_info() results."
1938 def test_addSuccess(self):
1939 class Foo(unittest.TestCase):
1940 def test_1(self):
1941 pass
1942
1943 test = Foo('test_1')
1944
1945 result = unittest.TestResult()
1946
1947 result.startTest(test)
1948 result.addSuccess(test)
1949 result.stopTest(test)
1950
Benjamin Petersone1759f82009-06-30 23:35:19 +00001951 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001952 self.assertEqual(len(result.errors), 0)
1953 self.assertEqual(len(result.failures), 0)
1954 self.assertEqual(result.testsRun, 1)
1955 self.assertEqual(result.shouldStop, False)
1956
1957 # "addFailure(test, err)"
1958 # ...
1959 # "Called when the test case test signals a failure. err is a tuple of
1960 # the form returned by sys.exc_info(): (type, value, traceback)"
1961 # ...
1962 # "wasSuccessful() - Returns True if all tests run so far have passed,
1963 # otherwise returns False"
1964 # ...
1965 # "testsRun - The total number of tests run so far."
1966 # ...
1967 # "errors - A list containing 2-tuples of TestCase instances and
1968 # formatted tracebacks. Each tuple represents a test which raised an
1969 # unexpected exception. Contains formatted
1970 # tracebacks instead of sys.exc_info() results."
1971 # ...
1972 # "failures - A list containing 2-tuples of TestCase instances and
1973 # formatted tracebacks. Each tuple represents a test where a failure was
1974 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1975 # methods. Contains formatted tracebacks instead
1976 # of sys.exc_info() results."
1977 def test_addFailure(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001978 class Foo(unittest.TestCase):
1979 def test_1(self):
1980 pass
1981
1982 test = Foo('test_1')
1983 try:
1984 test.fail("foo")
1985 except:
1986 exc_info_tuple = sys.exc_info()
1987
1988 result = unittest.TestResult()
1989
1990 result.startTest(test)
1991 result.addFailure(test, exc_info_tuple)
1992 result.stopTest(test)
1993
Benjamin Petersone1759f82009-06-30 23:35:19 +00001994 self.assertFalse(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001995 self.assertEqual(len(result.errors), 0)
1996 self.assertEqual(len(result.failures), 1)
1997 self.assertEqual(result.testsRun, 1)
1998 self.assertEqual(result.shouldStop, False)
1999
2000 test_case, formatted_exc = result.failures[0]
Benjamin Petersone1759f82009-06-30 23:35:19 +00002001 self.assertTrue(test_case is test)
Ezio Melottie9615932010-01-24 19:26:24 +00002002 self.assertIsInstance(formatted_exc, str)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002003
2004 # "addError(test, err)"
2005 # ...
2006 # "Called when the test case test raises an unexpected exception err
2007 # is a tuple of the form returned by sys.exc_info():
2008 # (type, value, traceback)"
2009 # ...
2010 # "wasSuccessful() - Returns True if all tests run so far have passed,
2011 # otherwise returns False"
2012 # ...
2013 # "testsRun - The total number of tests run so far."
2014 # ...
2015 # "errors - A list containing 2-tuples of TestCase instances and
2016 # formatted tracebacks. Each tuple represents a test which raised an
2017 # unexpected exception. Contains formatted
2018 # tracebacks instead of sys.exc_info() results."
2019 # ...
2020 # "failures - A list containing 2-tuples of TestCase instances and
2021 # formatted tracebacks. Each tuple represents a test where a failure was
2022 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
2023 # methods. Contains formatted tracebacks instead
2024 # of sys.exc_info() results."
2025 def test_addError(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002026 class Foo(unittest.TestCase):
2027 def test_1(self):
2028 pass
2029
2030 test = Foo('test_1')
2031 try:
2032 raise TypeError()
2033 except:
2034 exc_info_tuple = sys.exc_info()
2035
2036 result = unittest.TestResult()
2037
2038 result.startTest(test)
2039 result.addError(test, exc_info_tuple)
2040 result.stopTest(test)
2041
Benjamin Petersone1759f82009-06-30 23:35:19 +00002042 self.assertFalse(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00002043 self.assertEqual(len(result.errors), 1)
2044 self.assertEqual(len(result.failures), 0)
2045 self.assertEqual(result.testsRun, 1)
2046 self.assertEqual(result.shouldStop, False)
2047
2048 test_case, formatted_exc = result.errors[0]
Benjamin Petersone1759f82009-06-30 23:35:19 +00002049 self.assertTrue(test_case is test)
Ezio Melottie9615932010-01-24 19:26:24 +00002050 self.assertIsInstance(formatted_exc, str)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002051
Michael Foord34c94622010-02-10 15:51:42 +00002052 def testGetDescriptionWithoutDocstring(self):
Michael Foord0b581e52010-02-10 15:53:19 +00002053 result = unittest.TextTestResult(None, True, 1)
Michael Foord34c94622010-02-10 15:51:42 +00002054 self.assertEqual(
2055 result.getDescription(self),
2056 'testGetDescriptionWithoutDocstring (' + __name__ +
2057 '.Test_TestResult)')
2058
R. David Murray378c0cf2010-02-24 01:46:21 +00002059 @unittest.skipIf(sys.flags.optimize >= 2,
2060 "Docstrings are omitted with -O2 and above")
Michael Foord34c94622010-02-10 15:51:42 +00002061 def testGetDescriptionWithOneLineDocstring(self):
2062 """Tests getDescription() for a method with a docstring."""
Michael Foord0b581e52010-02-10 15:53:19 +00002063 result = unittest.TextTestResult(None, True, 1)
Michael Foord34c94622010-02-10 15:51:42 +00002064 self.assertEqual(
2065 result.getDescription(self),
2066 ('testGetDescriptionWithOneLineDocstring '
2067 '(' + __name__ + '.Test_TestResult)\n'
2068 'Tests getDescription() for a method with a docstring.'))
2069
R. David Murray378c0cf2010-02-24 01:46:21 +00002070 @unittest.skipIf(sys.flags.optimize >= 2,
2071 "Docstrings are omitted with -O2 and above")
Michael Foord34c94622010-02-10 15:51:42 +00002072 def testGetDescriptionWithMultiLineDocstring(self):
2073 """Tests getDescription() for a method with a longer docstring.
2074 The second line of the docstring.
2075 """
Michael Foord0b581e52010-02-10 15:53:19 +00002076 result = unittest.TextTestResult(None, True, 1)
Michael Foord34c94622010-02-10 15:51:42 +00002077 self.assertEqual(
2078 result.getDescription(self),
2079 ('testGetDescriptionWithMultiLineDocstring '
2080 '(' + __name__ + '.Test_TestResult)\n'
2081 'Tests getDescription() for a method with a longer '
2082 'docstring.'))
2083
Benjamin Peterson847a4112010-03-14 15:04:17 +00002084classDict = dict(unittest.TestResult.__dict__)
2085for m in ('addSkip', 'addExpectedFailure', 'addUnexpectedSuccess',
2086 '__init__'):
2087 del classDict[m]
2088
2089def __init__(self, stream=None, descriptions=None, verbosity=None):
2090 self.failures = []
2091 self.errors = []
2092 self.testsRun = 0
2093 self.shouldStop = False
2094classDict['__init__'] = __init__
2095OldResult = type('OldResult', (object,), classDict)
2096
2097class Test_OldTestResult(unittest.TestCase):
2098
2099 def assertOldResultWarning(self, test, failures):
2100 with warnings.catch_warnings(record=True) as log:
2101 result = OldResult()
2102 test.run(result)
2103 self.assertEqual(len(result.failures), failures)
2104 warning, = log
2105 self.assertIs(warning.category, RuntimeWarning)
2106
2107 def testOldTestResult(self):
2108 class Test(unittest.TestCase):
2109 def testSkip(self):
2110 self.skipTest('foobar')
2111 @unittest.expectedFailure
2112 def testExpectedFail(self):
2113 raise TypeError
2114 @unittest.expectedFailure
2115 def testUnexpectedSuccess(self):
2116 pass
2117
2118 for test_name, should_pass in (('testSkip', True),
2119 ('testExpectedFail', True),
2120 ('testUnexpectedSuccess', False)):
2121 test = Test(test_name)
2122 self.assertOldResultWarning(test, int(not should_pass))
2123
2124 def testOldTestTesultSetup(self):
2125 class Test(unittest.TestCase):
2126 def setUp(self):
2127 self.skipTest('no reason')
2128 def testFoo(self):
2129 pass
2130 self.assertOldResultWarning(Test('testFoo'), 0)
2131
2132 def testOldTestResultClass(self):
2133 @unittest.skip('no reason')
2134 class Test(unittest.TestCase):
2135 def testFoo(self):
2136 pass
2137 self.assertOldResultWarning(Test('testFoo'), 0)
2138
2139 def testOldResultWithRunner(self):
2140 class Test(unittest.TestCase):
2141 def testFoo(self):
2142 pass
2143 runner = unittest.TextTestRunner(resultclass=OldResult,
2144 stream=io.StringIO())
2145 # This will raise an exception if TextTestRunner can't handle old
2146 # test result objects
2147 runner.run(Test('testFoo'))
Michael Foord34c94622010-02-10 15:51:42 +00002148
Guido van Rossumd8faa362007-04-27 19:54:29 +00002149### Support code for Test_TestCase
2150################################################################
2151
2152class Foo(unittest.TestCase):
2153 def runTest(self): pass
2154 def test1(self): pass
2155
2156class Bar(Foo):
2157 def test2(self): pass
2158
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002159class LoggingTestCase(unittest.TestCase):
2160 """A test case which logs its calls."""
2161
2162 def __init__(self, events):
2163 super(LoggingTestCase, self).__init__('test')
2164 self.events = events
2165
2166 def setUp(self):
2167 self.events.append('setUp')
2168
2169 def test(self):
2170 self.events.append('test')
2171
2172 def tearDown(self):
2173 self.events.append('tearDown')
2174
2175class ResultWithNoStartTestRunStopTestRun(object):
2176 """An object honouring TestResult before startTestRun/stopTestRun."""
2177
2178 def __init__(self):
2179 self.failures = []
2180 self.errors = []
2181 self.testsRun = 0
2182 self.skipped = []
2183 self.expectedFailures = []
2184 self.unexpectedSuccesses = []
2185 self.shouldStop = False
2186
2187 def startTest(self, test):
2188 pass
2189
2190 def stopTest(self, test):
2191 pass
2192
2193 def addError(self, test):
2194 pass
2195
2196 def addFailure(self, test):
2197 pass
2198
2199 def addSuccess(self, test):
2200 pass
2201
2202 def wasSuccessful(self):
2203 return True
2204
2205
Guido van Rossumd8faa362007-04-27 19:54:29 +00002206################################################################
2207### /Support code for Test_TestCase
2208
2209class Test_TestCase(TestCase, TestEquality, TestHashing):
2210
2211 ### Set up attributes used by inherited tests
2212 ################################################################
2213
2214 # Used by TestHashing.test_hash and TestEquality.test_eq
2215 eq_pairs = [(Foo('test1'), Foo('test1'))]
2216
2217 # Used by TestEquality.test_ne
2218 ne_pairs = [(Foo('test1'), Foo('runTest'))
2219 ,(Foo('test1'), Bar('test1'))
2220 ,(Foo('test1'), Bar('test2'))]
2221
2222 ################################################################
2223 ### /Set up attributes used by inherited tests
2224
2225
2226 # "class TestCase([methodName])"
2227 # ...
2228 # "Each instance of TestCase will run a single test method: the
2229 # method named methodName."
2230 # ...
2231 # "methodName defaults to "runTest"."
2232 #
2233 # Make sure it really is optional, and that it defaults to the proper
2234 # thing.
2235 def test_init__no_test_name(self):
2236 class Test(unittest.TestCase):
2237 def runTest(self): raise MyException()
2238 def test(self): pass
2239
2240 self.assertEqual(Test().id()[-13:], '.Test.runTest')
2241
2242 # "class TestCase([methodName])"
2243 # ...
2244 # "Each instance of TestCase will run a single test method: the
2245 # method named methodName."
2246 def test_init__test_name__valid(self):
2247 class Test(unittest.TestCase):
2248 def runTest(self): raise MyException()
2249 def test(self): pass
2250
2251 self.assertEqual(Test('test').id()[-10:], '.Test.test')
2252
2253 # "class TestCase([methodName])"
2254 # ...
2255 # "Each instance of TestCase will run a single test method: the
2256 # method named methodName."
2257 def test_init__test_name__invalid(self):
2258 class Test(unittest.TestCase):
2259 def runTest(self): raise MyException()
2260 def test(self): pass
2261
2262 try:
2263 Test('testfoo')
2264 except ValueError:
2265 pass
2266 else:
2267 self.fail("Failed to raise ValueError")
2268
2269 # "Return the number of tests represented by the this test object. For
2270 # TestCase instances, this will always be 1"
2271 def test_countTestCases(self):
2272 class Foo(unittest.TestCase):
2273 def test(self): pass
2274
2275 self.assertEqual(Foo('test').countTestCases(), 1)
2276
2277 # "Return the default type of test result object to be used to run this
2278 # test. For TestCase instances, this will always be
2279 # unittest.TestResult; subclasses of TestCase should
2280 # override this as necessary."
2281 def test_defaultTestResult(self):
2282 class Foo(unittest.TestCase):
2283 def runTest(self):
2284 pass
2285
2286 result = Foo().defaultTestResult()
2287 self.assertEqual(type(result), unittest.TestResult)
2288
2289 # "When a setUp() method is defined, the test runner will run that method
2290 # prior to each test. Likewise, if a tearDown() method is defined, the
2291 # test runner will invoke that method after each test. In the example,
2292 # setUp() was used to create a fresh sequence for each test."
2293 #
2294 # Make sure the proper call order is maintained, even if setUp() raises
2295 # an exception.
2296 def test_run_call_order__error_in_setUp(self):
2297 events = []
2298 result = LoggingResult(events)
2299
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002300 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002301 def setUp(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002302 super(Foo, self).setUp()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002303 raise RuntimeError('raised by Foo.setUp')
2304
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002305 Foo(events).run(result)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002306 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2307 self.assertEqual(events, expected)
2308
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002309 # "With a temporary result stopTestRun is called when setUp errors.
2310 def test_run_call_order__error_in_setUp_default_result(self):
2311 events = []
2312
2313 class Foo(LoggingTestCase):
2314 def defaultTestResult(self):
2315 return LoggingResult(self.events)
2316
2317 def setUp(self):
2318 super(Foo, self).setUp()
2319 raise RuntimeError('raised by Foo.setUp')
2320
2321 Foo(events).run()
2322 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2323 'stopTest', 'stopTestRun']
2324 self.assertEqual(events, expected)
2325
Guido van Rossumd8faa362007-04-27 19:54:29 +00002326 # "When a setUp() method is defined, the test runner will run that method
2327 # prior to each test. Likewise, if a tearDown() method is defined, the
2328 # test runner will invoke that method after each test. In the example,
2329 # setUp() was used to create a fresh sequence for each test."
2330 #
2331 # Make sure the proper call order is maintained, even if the test raises
2332 # an error (as opposed to a failure).
2333 def test_run_call_order__error_in_test(self):
2334 events = []
2335 result = LoggingResult(events)
2336
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002337 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002338 def test(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002339 super(Foo, self).test()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002340 raise RuntimeError('raised by Foo.test')
2341
Guido van Rossumd8faa362007-04-27 19:54:29 +00002342 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2343 'stopTest']
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002344 Foo(events).run(result)
2345 self.assertEqual(events, expected)
2346
2347 # "With a default result, an error in the test still results in stopTestRun
2348 # being called."
2349 def test_run_call_order__error_in_test_default_result(self):
2350 events = []
2351
2352 class Foo(LoggingTestCase):
2353 def defaultTestResult(self):
2354 return LoggingResult(self.events)
2355
2356 def test(self):
2357 super(Foo, self).test()
2358 raise RuntimeError('raised by Foo.test')
2359
2360 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2361 'tearDown', 'stopTest', 'stopTestRun']
2362 Foo(events).run()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002363 self.assertEqual(events, expected)
2364
2365 # "When a setUp() method is defined, the test runner will run that method
2366 # prior to each test. Likewise, if a tearDown() method is defined, the
2367 # test runner will invoke that method after each test. In the example,
2368 # setUp() was used to create a fresh sequence for each test."
2369 #
2370 # Make sure the proper call order is maintained, even if the test signals
2371 # a failure (as opposed to an error).
2372 def test_run_call_order__failure_in_test(self):
2373 events = []
2374 result = LoggingResult(events)
2375
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002376 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002377 def test(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002378 super(Foo, self).test()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002379 self.fail('raised by Foo.test')
2380
Guido van Rossumd8faa362007-04-27 19:54:29 +00002381 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2382 'stopTest']
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002383 Foo(events).run(result)
2384 self.assertEqual(events, expected)
2385
2386 # "When a test fails with a default result stopTestRun is still called."
2387 def test_run_call_order__failure_in_test_default_result(self):
2388
2389 class Foo(LoggingTestCase):
2390 def defaultTestResult(self):
2391 return LoggingResult(self.events)
2392 def test(self):
2393 super(Foo, self).test()
2394 self.fail('raised by Foo.test')
2395
2396 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2397 'tearDown', 'stopTest', 'stopTestRun']
2398 events = []
2399 Foo(events).run()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002400 self.assertEqual(events, expected)
2401
2402 # "When a setUp() method is defined, the test runner will run that method
2403 # prior to each test. Likewise, if a tearDown() method is defined, the
2404 # test runner will invoke that method after each test. In the example,
2405 # setUp() was used to create a fresh sequence for each test."
2406 #
2407 # Make sure the proper call order is maintained, even if tearDown() raises
2408 # an exception.
2409 def test_run_call_order__error_in_tearDown(self):
2410 events = []
2411 result = LoggingResult(events)
2412
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002413 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002414 def tearDown(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002415 super(Foo, self).tearDown()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002416 raise RuntimeError('raised by Foo.tearDown')
2417
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002418 Foo(events).run(result)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002419 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2420 'stopTest']
2421 self.assertEqual(events, expected)
2422
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002423 # "When tearDown errors with a default result stopTestRun is still called."
2424 def test_run_call_order__error_in_tearDown_default_result(self):
2425
2426 class Foo(LoggingTestCase):
2427 def defaultTestResult(self):
2428 return LoggingResult(self.events)
2429 def tearDown(self):
2430 super(Foo, self).tearDown()
2431 raise RuntimeError('raised by Foo.tearDown')
2432
2433 events = []
2434 Foo(events).run()
2435 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2436 'addError', 'stopTest', 'stopTestRun']
2437 self.assertEqual(events, expected)
2438
2439 # "TestCase.run() still works when the defaultTestResult is a TestResult
2440 # that does not support startTestRun and stopTestRun.
2441 def test_run_call_order_default_result(self):
2442
2443 class Foo(unittest.TestCase):
2444 def defaultTestResult(self):
2445 return ResultWithNoStartTestRunStopTestRun()
2446 def test(self):
2447 pass
2448
2449 Foo('test').run()
2450
Guido van Rossumd8faa362007-04-27 19:54:29 +00002451 # "This class attribute gives the exception raised by the test() method.
2452 # If a test framework needs to use a specialized exception, possibly to
2453 # carry additional information, it must subclass this exception in
2454 # order to ``play fair'' with the framework. The initial value of this
2455 # attribute is AssertionError"
2456 def test_failureException__default(self):
2457 class Foo(unittest.TestCase):
2458 def test(self):
2459 pass
2460
Benjamin Petersone1759f82009-06-30 23:35:19 +00002461 self.assertTrue(Foo('test').failureException is AssertionError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002462
2463 # "This class attribute gives the exception raised by the test() method.
2464 # If a test framework needs to use a specialized exception, possibly to
2465 # carry additional information, it must subclass this exception in
2466 # order to ``play fair'' with the framework."
2467 #
2468 # Make sure TestCase.run() respects the designated failureException
2469 def test_failureException__subclassing__explicit_raise(self):
2470 events = []
2471 result = LoggingResult(events)
2472
2473 class Foo(unittest.TestCase):
2474 def test(self):
2475 raise RuntimeError()
2476
2477 failureException = RuntimeError
2478
Benjamin Petersone1759f82009-06-30 23:35:19 +00002479 self.assertTrue(Foo('test').failureException is RuntimeError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002480
2481
2482 Foo('test').run(result)
2483 expected = ['startTest', 'addFailure', 'stopTest']
2484 self.assertEqual(events, expected)
2485
2486 # "This class attribute gives the exception raised by the test() method.
2487 # If a test framework needs to use a specialized exception, possibly to
2488 # carry additional information, it must subclass this exception in
2489 # order to ``play fair'' with the framework."
2490 #
2491 # Make sure TestCase.run() respects the designated failureException
2492 def test_failureException__subclassing__implicit_raise(self):
2493 events = []
2494 result = LoggingResult(events)
2495
2496 class Foo(unittest.TestCase):
2497 def test(self):
2498 self.fail("foo")
2499
2500 failureException = RuntimeError
2501
Benjamin Petersone1759f82009-06-30 23:35:19 +00002502 self.assertTrue(Foo('test').failureException is RuntimeError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002503
2504
2505 Foo('test').run(result)
2506 expected = ['startTest', 'addFailure', 'stopTest']
2507 self.assertEqual(events, expected)
2508
2509 # "The default implementation does nothing."
2510 def test_setUp(self):
2511 class Foo(unittest.TestCase):
2512 def runTest(self):
2513 pass
2514
2515 # ... and nothing should happen
2516 Foo().setUp()
2517
2518 # "The default implementation does nothing."
2519 def test_tearDown(self):
2520 class Foo(unittest.TestCase):
2521 def runTest(self):
2522 pass
2523
2524 # ... and nothing should happen
2525 Foo().tearDown()
2526
2527 # "Return a string identifying the specific test case."
2528 #
2529 # Because of the vague nature of the docs, I'm not going to lock this
2530 # test down too much. Really all that can be asserted is that the id()
2531 # will be a string (either 8-byte or unicode -- again, because the docs
2532 # just say "string")
2533 def test_id(self):
2534 class Foo(unittest.TestCase):
2535 def runTest(self):
2536 pass
2537
Ezio Melottie9615932010-01-24 19:26:24 +00002538 self.assertIsInstance(Foo().id(), str)
2539
Guido van Rossumd8faa362007-04-27 19:54:29 +00002540
Guido van Rossumd8faa362007-04-27 19:54:29 +00002541 # "If result is omitted or None, a temporary result object is created
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002542 # and used, but is not made available to the caller. As TestCase owns the
2543 # temporary result startTestRun and stopTestRun are called.
2544
Guido van Rossumd8faa362007-04-27 19:54:29 +00002545 def test_run__uses_defaultTestResult(self):
2546 events = []
2547
2548 class Foo(unittest.TestCase):
2549 def test(self):
2550 events.append('test')
2551
2552 def defaultTestResult(self):
2553 return LoggingResult(events)
2554
2555 # Make run() find a result object on its own
2556 Foo('test').run()
2557
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002558 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2559 'stopTest', 'stopTestRun']
Guido van Rossumd8faa362007-04-27 19:54:29 +00002560 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002561
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002562 def testShortDescriptionWithoutDocstring(self):
Michael Foord34c94622010-02-10 15:51:42 +00002563 self.assertIsNone(self.shortDescription())
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002564
R. David Murray378c0cf2010-02-24 01:46:21 +00002565 @unittest.skipIf(sys.flags.optimize >= 2,
2566 "Docstrings are omitted with -O2 and above")
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002567 def testShortDescriptionWithOneLineDocstring(self):
2568 """Tests shortDescription() for a method with a docstring."""
2569 self.assertEqual(
2570 self.shortDescription(),
Michael Foord34c94622010-02-10 15:51:42 +00002571 'Tests shortDescription() for a method with a docstring.')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002572
R. David Murray378c0cf2010-02-24 01:46:21 +00002573 @unittest.skipIf(sys.flags.optimize >= 2,
2574 "Docstrings are omitted with -O2 and above")
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002575 def testShortDescriptionWithMultiLineDocstring(self):
2576 """Tests shortDescription() for a method with a longer docstring.
2577
2578 This method ensures that only the first line of a docstring is
2579 returned used in the short description, no matter how long the
2580 whole thing is.
2581 """
2582 self.assertEqual(
2583 self.shortDescription(),
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002584 'Tests shortDescription() for a method with a longer '
Michael Foord34c94622010-02-10 15:51:42 +00002585 'docstring.')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002586
2587 def testAddTypeEqualityFunc(self):
2588 class SadSnake(object):
2589 """Dummy class for test_addTypeEqualityFunc."""
2590 s1, s2 = SadSnake(), SadSnake()
2591 self.assertFalse(s1 == s2)
2592 def AllSnakesCreatedEqual(a, b, msg=None):
2593 return type(a) == type(b) == SadSnake
2594 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2595 self.assertEqual(s1, s2)
2596 # No this doesn't clean up and remove the SadSnake equality func
2597 # from this TestCase instance but since its a local nothing else
2598 # will ever notice that.
2599
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00002600 def testAssertIs(self):
2601 thing = object()
2602 self.assertIs(thing, thing)
2603 self.assertRaises(self.failureException, self.assertIs, thing, object())
2604
2605 def testAssertIsNot(self):
2606 thing = object()
2607 self.assertIsNot(thing, object())
2608 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2609
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00002610 def testAssertIsInstance(self):
2611 thing = []
2612 self.assertIsInstance(thing, list)
2613 self.assertRaises(self.failureException, self.assertIsInstance,
2614 thing, dict)
2615
2616 def testAssertNotIsInstance(self):
2617 thing = []
2618 self.assertNotIsInstance(thing, dict)
2619 self.assertRaises(self.failureException, self.assertNotIsInstance,
2620 thing, list)
2621
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002622 def testAssertIn(self):
2623 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2624
2625 self.assertIn('a', 'abc')
2626 self.assertIn(2, [1, 2, 3])
2627 self.assertIn('monkey', animals)
2628
2629 self.assertNotIn('d', 'abc')
2630 self.assertNotIn(0, [1, 2, 3])
2631 self.assertNotIn('otter', animals)
2632
2633 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2634 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2635 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2636 animals)
2637
2638 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2639 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2640 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2641 animals)
2642
2643 def testAssertDictContainsSubset(self):
2644 self.assertDictContainsSubset({}, {})
2645 self.assertDictContainsSubset({}, {'a': 1})
2646 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2647 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2648 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2649
Benjamin Peterson847a4112010-03-14 15:04:17 +00002650 with self.assertRaises(self.failureException):
2651 self.assertDictContainsSubset({1: "one"}, {})
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002652
Benjamin Peterson847a4112010-03-14 15:04:17 +00002653 with self.assertRaises(self.failureException):
2654 self.assertDictContainsSubset({'a': 2}, {'a': 1})
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002655
Benjamin Peterson847a4112010-03-14 15:04:17 +00002656 with self.assertRaises(self.failureException):
2657 self.assertDictContainsSubset({'c': 1}, {'a': 1})
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002658
Benjamin Peterson847a4112010-03-14 15:04:17 +00002659 with self.assertRaises(self.failureException):
2660 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2661
2662 with self.assertRaises(self.failureException):
2663 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2664
2665 with warnings.catch_warnings(record=True):
2666 # silence the UnicodeWarning
2667 one = ''.join(chr(i) for i in range(255))
2668 # this used to cause a UnicodeDecodeError constructing the failure msg
2669 with self.assertRaises(self.failureException):
2670 self.assertDictContainsSubset({'foo': one}, {'foo': '\uFFFD'})
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002671
2672 def testAssertEqual(self):
2673 equal_pairs = [
2674 ((), ()),
2675 ({}, {}),
2676 ([], []),
2677 (set(), set()),
2678 (frozenset(), frozenset())]
2679 for a, b in equal_pairs:
2680 # This mess of try excepts is to test the assertEqual behavior
2681 # itself.
2682 try:
2683 self.assertEqual(a, b)
2684 except self.failureException:
2685 self.fail('assertEqual(%r, %r) failed' % (a, b))
2686 try:
2687 self.assertEqual(a, b, msg='foo')
2688 except self.failureException:
2689 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2690 try:
2691 self.assertEqual(a, b, 'foo')
2692 except self.failureException:
2693 self.fail('assertEqual(%r, %r) with third parameter failed' %
2694 (a, b))
2695
2696 unequal_pairs = [
2697 ((), []),
2698 ({}, set()),
2699 (set([4,1]), frozenset([4,2])),
2700 (frozenset([4,5]), set([2,3])),
2701 (set([3,4]), set([5,4]))]
2702 for a, b in unequal_pairs:
2703 self.assertRaises(self.failureException, self.assertEqual, a, b)
2704 self.assertRaises(self.failureException, self.assertEqual, a, b,
2705 'foo')
2706 self.assertRaises(self.failureException, self.assertEqual, a, b,
2707 msg='foo')
2708
2709 def testEquality(self):
2710 self.assertListEqual([], [])
2711 self.assertTupleEqual((), ())
2712 self.assertSequenceEqual([], ())
2713
2714 a = [0, 'a', []]
2715 b = []
2716 self.assertRaises(unittest.TestCase.failureException,
2717 self.assertListEqual, a, b)
2718 self.assertRaises(unittest.TestCase.failureException,
2719 self.assertListEqual, tuple(a), tuple(b))
2720 self.assertRaises(unittest.TestCase.failureException,
2721 self.assertSequenceEqual, a, tuple(b))
2722
2723 b.extend(a)
2724 self.assertListEqual(a, b)
2725 self.assertTupleEqual(tuple(a), tuple(b))
2726 self.assertSequenceEqual(a, tuple(b))
2727 self.assertSequenceEqual(tuple(a), b)
2728
2729 self.assertRaises(self.failureException, self.assertListEqual,
2730 a, tuple(b))
2731 self.assertRaises(self.failureException, self.assertTupleEqual,
2732 tuple(a), b)
2733 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2734 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2735 tuple(b))
2736 self.assertRaises(self.failureException, self.assertSequenceEqual,
2737 None, tuple(b))
2738 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2739 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2740 self.assertRaises(self.failureException, self.assertSequenceEqual,
2741 1, 1)
2742
2743 self.assertDictEqual({}, {})
2744
2745 c = { 'x': 1 }
2746 d = {}
2747 self.assertRaises(unittest.TestCase.failureException,
2748 self.assertDictEqual, c, d)
2749
2750 d.update(c)
2751 self.assertDictEqual(c, d)
2752
2753 d['x'] = 0
2754 self.assertRaises(unittest.TestCase.failureException,
2755 self.assertDictEqual, c, d, 'These are unequal')
2756
2757 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2758 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2759 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2760
Michael Foord8442a602010-03-20 16:58:04 +00002761 def testAssertItemsEqual(self):
2762 a = object()
2763 self.assertItemsEqual([1, 2, 3], [3, 2, 1])
2764 self.assertItemsEqual(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2765 self.assertItemsEqual([a, a, 2, 2, 3], (a, 2, 3, a, 2))
2766 self.assertItemsEqual([1, "2", "a", "a"], ["a", "2", True, "a"])
2767 self.assertRaises(self.failureException, self.assertItemsEqual,
2768 [1, 2] + [3] * 100, [1] * 100 + [2, 3])
2769 self.assertRaises(self.failureException, self.assertItemsEqual,
2770 [1, "2", "a", "a"], ["a", "2", True, 1])
2771 self.assertRaises(self.failureException, self.assertItemsEqual,
2772 [10], [10, 11])
2773 self.assertRaises(self.failureException, self.assertItemsEqual,
2774 [10, 11], [10])
2775 self.assertRaises(self.failureException, self.assertItemsEqual,
2776 [10, 11, 10], [10, 11])
2777
2778 # Test that sequences of unhashable objects can be tested for sameness:
2779 self.assertItemsEqual([[1, 2], [3, 4], 0], [False, [3, 4], [1, 2]])
2780
2781 # hashable types, but not orderable
2782 self.assertRaises(self.failureException, self.assertItemsEqual,
2783 [], [divmod, 'x', 1, 5j, 2j, frozenset()])
2784 # comparing dicts raises a py3k warning
2785 self.assertItemsEqual([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2786 # comparing heterogenous non-hashable sequences raises a py3k warning
2787 self.assertItemsEqual([1, 'x', divmod, []], [divmod, [], 'x', 1])
2788 self.assertRaises(self.failureException, self.assertItemsEqual,
2789 [], [divmod, [], 'x', 1, 5j, 2j, set()])
2790 self.assertRaises(self.failureException, self.assertItemsEqual,
2791 [[1]], [[2]])
2792
2793 # Same elements, but not same sequence length
2794 self.assertRaises(self.failureException, self.assertItemsEqual,
2795 [1, 1, 2], [2, 1])
2796 self.assertRaises(self.failureException, self.assertItemsEqual,
2797 [1, 1, "2", "a", "a"], ["2", "2", True, "a"])
2798 self.assertRaises(self.failureException, self.assertItemsEqual,
2799 [1, {'b': 2}, None, True], [{'b': 2}, True, None])
2800
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002801 def testAssertSetEqual(self):
2802 set1 = set()
2803 set2 = set()
2804 self.assertSetEqual(set1, set2)
2805
2806 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2807 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2808 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2809 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2810
2811 set1 = set(['a'])
2812 set2 = set()
2813 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2814
2815 set1 = set(['a'])
2816 set2 = set(['a'])
2817 self.assertSetEqual(set1, set2)
2818
2819 set1 = set(['a'])
2820 set2 = set(['a', 'b'])
2821 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2822
2823 set1 = set(['a'])
2824 set2 = frozenset(['a', 'b'])
2825 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2826
2827 set1 = set(['a', 'b'])
2828 set2 = frozenset(['a', 'b'])
2829 self.assertSetEqual(set1, set2)
2830
2831 set1 = set()
2832 set2 = "foo"
2833 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2834 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2835
2836 # make sure any string formatting is tuple-safe
2837 set1 = set([(0, 1), (2, 3)])
2838 set2 = set([(4, 5)])
2839 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2840
2841 def testInequality(self):
2842 # Try ints
2843 self.assertGreater(2, 1)
2844 self.assertGreaterEqual(2, 1)
2845 self.assertGreaterEqual(1, 1)
2846 self.assertLess(1, 2)
2847 self.assertLessEqual(1, 2)
2848 self.assertLessEqual(1, 1)
2849 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2850 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2851 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2852 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2853 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2854 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2855
2856 # Try Floats
2857 self.assertGreater(1.1, 1.0)
2858 self.assertGreaterEqual(1.1, 1.0)
2859 self.assertGreaterEqual(1.0, 1.0)
2860 self.assertLess(1.0, 1.1)
2861 self.assertLessEqual(1.0, 1.1)
2862 self.assertLessEqual(1.0, 1.0)
2863 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2864 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2865 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2866 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2867 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2868 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2869
2870 # Try Strings
2871 self.assertGreater('bug', 'ant')
2872 self.assertGreaterEqual('bug', 'ant')
2873 self.assertGreaterEqual('ant', 'ant')
2874 self.assertLess('ant', 'bug')
2875 self.assertLessEqual('ant', 'bug')
2876 self.assertLessEqual('ant', 'ant')
2877 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2878 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2879 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2880 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2881 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2882 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2883
2884 # Try bytes
2885 self.assertGreater(b'bug', b'ant')
2886 self.assertGreaterEqual(b'bug', b'ant')
2887 self.assertGreaterEqual(b'ant', b'ant')
2888 self.assertLess(b'ant', b'bug')
2889 self.assertLessEqual(b'ant', b'bug')
2890 self.assertLessEqual(b'ant', b'ant')
2891 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'bug')
2892 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'ant')
2893 self.assertRaises(self.failureException, self.assertGreaterEqual, b'ant',
2894 b'bug')
2895 self.assertRaises(self.failureException, self.assertLess, b'bug', b'ant')
2896 self.assertRaises(self.failureException, self.assertLess, b'ant', b'ant')
2897 self.assertRaises(self.failureException, self.assertLessEqual, b'bug', b'ant')
2898
2899 def testAssertMultiLineEqual(self):
2900 sample_text = """\
2901http://www.python.org/doc/2.3/lib/module-unittest.html
2902test case
2903 A test case is the smallest unit of testing. [...]
2904"""
2905 revised_sample_text = """\
2906http://www.python.org/doc/2.4.1/lib/module-unittest.html
2907test case
2908 A test case is the smallest unit of testing. [...] You may provide your
2909 own implementation that does not subclass from TestCase, of course.
2910"""
2911 sample_text_error = """
2912- http://www.python.org/doc/2.3/lib/module-unittest.html
2913? ^
2914+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2915? ^^^
2916 test case
2917- A test case is the smallest unit of testing. [...]
2918+ A test case is the smallest unit of testing. [...] You may provide your
2919? +++++++++++++++++++++
2920+ own implementation that does not subclass from TestCase, of course.
2921"""
2922
2923 try:
2924 self.assertMultiLineEqual(sample_text, revised_sample_text)
2925 except self.failureException as e:
Michael Foord02834952010-02-08 23:10:39 +00002926 # no fair testing ourself with ourself, and assertEqual is used for strings
2927 # so can't use assertEqual either. Just use assertTrue.
2928 self.assertTrue(sample_text_error == str(e))
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002929
2930 def testAssertIsNone(self):
2931 self.assertIsNone(None)
2932 self.assertRaises(self.failureException, self.assertIsNone, False)
2933 self.assertIsNotNone('DjZoPloGears on Rails')
2934 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2935
2936 def testAssertRegexpMatches(self):
2937 self.assertRegexpMatches('asdfabasdf', r'ab+')
2938 self.assertRaises(self.failureException, self.assertRegexpMatches,
2939 'saaas', r'aaaa')
2940
2941 def testAssertRaisesRegexp(self):
2942 class ExceptionMock(Exception):
2943 pass
2944
2945 def Stub():
2946 raise ExceptionMock('We expect')
2947
2948 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2949 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2950
2951 def testAssertNotRaisesRegexp(self):
2952 self.assertRaisesRegexp(
Benjamin Peterson4f75b642009-04-04 16:39:09 +00002953 self.failureException, '^Exception not raised by <lambda>$',
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002954 self.assertRaisesRegexp, Exception, re.compile('x'),
2955 lambda: None)
2956 self.assertRaisesRegexp(
Benjamin Peterson4f75b642009-04-04 16:39:09 +00002957 self.failureException, '^Exception not raised by <lambda>$',
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002958 self.assertRaisesRegexp, Exception, 'x',
2959 lambda: None)
2960
2961 def testAssertRaisesRegexpMismatch(self):
2962 def Stub():
2963 raise Exception('Unexpected')
2964
2965 self.assertRaisesRegexp(
2966 self.failureException,
2967 r'"\^Expected\$" does not match "Unexpected"',
2968 self.assertRaisesRegexp, Exception, '^Expected$',
2969 Stub)
2970 self.assertRaisesRegexp(
2971 self.failureException,
2972 r'"\^Expected\$" does not match "Unexpected"',
2973 self.assertRaisesRegexp, Exception,
2974 re.compile('^Expected$'), Stub)
2975
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +00002976 def testAssertRaisesExcValue(self):
2977 class ExceptionMock(Exception):
2978 pass
2979
2980 def Stub(foo):
2981 raise ExceptionMock(foo)
2982 v = "particular value"
2983
2984 ctx = self.assertRaises(ExceptionMock)
2985 with ctx:
2986 Stub(v)
Ezio Melotti49008232010-02-08 21:57:48 +00002987 e = ctx.exception
Ezio Melottie9615932010-01-24 19:26:24 +00002988 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +00002989 self.assertEqual(e.args[0], v)
2990
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002991 def testSynonymAssertMethodNames(self):
2992 """Test undocumented method name synonyms.
2993
2994 Please do not use these methods names in your own code.
2995
2996 This test confirms their continued existence and functionality
2997 in order to avoid breaking existing code.
2998 """
2999 self.assertNotEquals(3, 5)
3000 self.assertEquals(3, 3)
3001 self.assertAlmostEquals(2.0, 2.0)
3002 self.assertNotAlmostEquals(3.0, 5.0)
3003 self.assert_(True)
3004
3005 def testPendingDeprecationMethodNames(self):
3006 """Test fail* methods pending deprecation, they will warn in 3.2.
3007
3008 Do not use these methods. They will go away in 3.3.
3009 """
Benjamin Peterson6bcbad52009-06-30 23:45:41 +00003010 old = (
3011 (self.failIfEqual, (3, 5)),
3012 (self.failUnlessEqual, (3, 3)),
3013 (self.failUnlessAlmostEqual, (2.0, 2.0)),
3014 (self.failIfAlmostEqual, (3.0, 5.0)),
3015 (self.failUnless, (True,)),
3016 (self.failUnlessRaises, (TypeError, lambda _: 3.14 + 'spam')),
Michael Foord91c9da32010-03-20 17:21:27 +00003017 (self.failIf, (False,)),
3018 (self.assertSameElements, ([1, 1, 2, 3], [1, 2, 3]))
Benjamin Peterson6bcbad52009-06-30 23:45:41 +00003019 )
3020 for meth, args in old:
3021 with warnings.catch_warnings(record=True) as w:
3022 meth(*args)
3023 self.assertEqual(len(w), 1)
3024 self.assertIs(w[0].category, DeprecationWarning)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003025
3026 def testDeepcopy(self):
3027 # Issue: 5660
3028 class TestableTest(TestCase):
3029 def testNothing(self):
3030 pass
3031
3032 test = TestableTest('testNothing')
3033
3034 # This shouldn't blow up
3035 deepcopy(test)
3036
Benjamin Peterson5254c042009-03-23 22:25:03 +00003037
3038class Test_TestSkipping(TestCase):
3039
3040 def test_skipping(self):
3041 class Foo(unittest.TestCase):
3042 def test_skip_me(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00003043 self.skipTest("skip")
Benjamin Peterson5254c042009-03-23 22:25:03 +00003044 events = []
3045 result = LoggingResult(events)
3046 test = Foo("test_skip_me")
3047 test.run(result)
3048 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3049 self.assertEqual(result.skipped, [(test, "skip")])
3050
3051 # Try letting setUp skip the test now.
3052 class Foo(unittest.TestCase):
3053 def setUp(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00003054 self.skipTest("testing")
Benjamin Peterson5254c042009-03-23 22:25:03 +00003055 def test_nothing(self): pass
3056 events = []
3057 result = LoggingResult(events)
3058 test = Foo("test_nothing")
3059 test.run(result)
3060 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3061 self.assertEqual(result.skipped, [(test, "testing")])
3062 self.assertEqual(result.testsRun, 1)
3063
3064 def test_skipping_decorators(self):
3065 op_table = ((unittest.skipUnless, False, True),
3066 (unittest.skipIf, True, False))
3067 for deco, do_skip, dont_skip in op_table:
3068 class Foo(unittest.TestCase):
3069 @deco(do_skip, "testing")
3070 def test_skip(self): pass
3071
3072 @deco(dont_skip, "testing")
3073 def test_dont_skip(self): pass
3074 test_do_skip = Foo("test_skip")
3075 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00003076 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003077 events = []
3078 result = LoggingResult(events)
3079 suite.run(result)
3080 self.assertEqual(len(result.skipped), 1)
3081 expected = ['startTest', 'addSkip', 'stopTest',
3082 'startTest', 'addSuccess', 'stopTest']
3083 self.assertEqual(events, expected)
3084 self.assertEqual(result.testsRun, 2)
3085 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
3086 self.assertTrue(result.wasSuccessful())
3087
3088 def test_skip_class(self):
3089 @unittest.skip("testing")
3090 class Foo(unittest.TestCase):
3091 def test_1(self):
3092 record.append(1)
3093 record = []
3094 result = unittest.TestResult()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00003095 test = Foo("test_1")
3096 suite = unittest.TestSuite([test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003097 suite.run(result)
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00003098 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003099 self.assertEqual(record, [])
3100
3101 def test_expected_failure(self):
3102 class Foo(unittest.TestCase):
3103 @unittest.expectedFailure
3104 def test_die(self):
3105 self.fail("help me!")
3106 events = []
3107 result = LoggingResult(events)
3108 test = Foo("test_die")
3109 test.run(result)
3110 self.assertEqual(events,
3111 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Peterson52baa292009-03-24 00:56:30 +00003112 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson5254c042009-03-23 22:25:03 +00003113 self.assertTrue(result.wasSuccessful())
3114
3115 def test_unexpected_success(self):
3116 class Foo(unittest.TestCase):
3117 @unittest.expectedFailure
3118 def test_die(self):
3119 pass
3120 events = []
3121 result = LoggingResult(events)
3122 test = Foo("test_die")
3123 test.run(result)
3124 self.assertEqual(events,
3125 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3126 self.assertFalse(result.failures)
Benjamin Peterson52baa292009-03-24 00:56:30 +00003127 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003128 self.assertTrue(result.wasSuccessful())
3129
Benjamin Peterson847a4112010-03-14 15:04:17 +00003130 def test_skip_doesnt_run_setup(self):
3131 class Foo(unittest.TestCase):
3132 wasSetUp = False
3133 wasTornDown = False
3134 def setUp(self):
3135 Foo.wasSetUp = True
3136 def tornDown(self):
3137 Foo.wasTornDown = True
3138 @unittest.skip('testing')
3139 def test_1(self):
3140 pass
3141
3142 result = unittest.TestResult()
3143 test = Foo("test_1")
3144 suite = unittest.TestSuite([test])
3145 suite.run(result)
3146 self.assertEqual(result.skipped, [(test, "testing")])
3147 self.assertFalse(Foo.wasSetUp)
3148 self.assertFalse(Foo.wasTornDown)
3149
3150 def test_decorated_skip(self):
3151 def decorator(func):
3152 def inner(*a):
3153 return func(*a)
3154 return inner
3155
3156 class Foo(unittest.TestCase):
3157 @decorator
3158 @unittest.skip('testing')
3159 def test_1(self):
3160 pass
3161
3162 result = unittest.TestResult()
3163 test = Foo("test_1")
3164 suite = unittest.TestSuite([test])
3165 suite.run(result)
3166 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003167
3168
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003169class Test_Assertions(TestCase):
3170 def test_AlmostEqual(self):
Benjamin Petersone1759f82009-06-30 23:35:19 +00003171 self.assertAlmostEqual(1.00000001, 1.0)
3172 self.assertNotAlmostEqual(1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003173 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003174 self.assertAlmostEqual, 1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003175 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003176 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003177
Benjamin Petersone1759f82009-06-30 23:35:19 +00003178 self.assertAlmostEqual(1.1, 1.0, places=0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003179 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003180 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003181
Benjamin Petersone1759f82009-06-30 23:35:19 +00003182 self.assertAlmostEqual(0, .1+.1j, places=0)
3183 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003184 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003185 self.assertAlmostEqual, 0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003186 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003187 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003188
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003189 self.assertAlmostEqual(float('inf'), float('inf'))
3190 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3191 float('inf'), float('inf'))
3192
3193
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003194 def test_assertRaises(self):
3195 def _raise(e):
3196 raise e
3197 self.assertRaises(KeyError, _raise, KeyError)
3198 self.assertRaises(KeyError, _raise, KeyError("key"))
3199 try:
3200 self.assertRaises(KeyError, lambda: None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003201 except self.failureException as e:
Ezio Melottib58e0bd2010-01-23 15:40:09 +00003202 self.assertIn("KeyError not raised", str(e))
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003203 else:
3204 self.fail("assertRaises() didn't fail")
3205 try:
3206 self.assertRaises(KeyError, _raise, ValueError)
3207 except ValueError:
3208 pass
3209 else:
3210 self.fail("assertRaises() didn't let exception pass through")
Ezio Melotti49008232010-02-08 21:57:48 +00003211 with self.assertRaises(KeyError) as cm:
3212 try:
3213 raise KeyError
3214 except Exception as e:
3215 exc = e
3216 raise
3217 self.assertIs(cm.exception, exc)
3218
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003219 with self.assertRaises(KeyError):
3220 raise KeyError("key")
3221 try:
3222 with self.assertRaises(KeyError):
3223 pass
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003224 except self.failureException as e:
Ezio Melottib58e0bd2010-01-23 15:40:09 +00003225 self.assertIn("KeyError not raised", str(e))
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003226 else:
3227 self.fail("assertRaises() didn't fail")
3228 try:
3229 with self.assertRaises(KeyError):
3230 raise ValueError
3231 except ValueError:
3232 pass
3233 else:
3234 self.fail("assertRaises() didn't let exception pass through")
3235
3236
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003237class TestLongMessage(TestCase):
3238 """Test that the individual asserts honour longMessage.
3239 This actually tests all the message behaviour for
3240 asserts that use longMessage."""
3241
3242 def setUp(self):
3243 class TestableTestFalse(TestCase):
3244 longMessage = False
3245 failureException = self.failureException
3246
3247 def testTest(self):
3248 pass
3249
3250 class TestableTestTrue(TestCase):
3251 longMessage = True
3252 failureException = self.failureException
3253
3254 def testTest(self):
3255 pass
3256
3257 self.testableTrue = TestableTestTrue('testTest')
3258 self.testableFalse = TestableTestFalse('testTest')
3259
3260 def testDefault(self):
3261 self.assertFalse(TestCase.longMessage)
3262
3263 def test_formatMsg(self):
3264 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3265 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3266
3267 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3268 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3269
Benjamin Peterson847a4112010-03-14 15:04:17 +00003270 # This blows up if _formatMessage uses string concatenation
3271 self.testableTrue._formatMessage(object(), 'foo')
3272
3273 def test_formatMessage_unicode_error(self):
3274 with warnings.catch_warnings(record=True):
3275 # This causes a UnicodeWarning due to its craziness
3276 one = ''.join(chr(i) for i in range(255))
3277 # this used to cause a UnicodeDecodeError constructing msg
3278 self.testableTrue._formatMessage(one, '\uFFFD')
3279
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003280 def assertMessages(self, methodName, args, errors):
3281 def getMethod(i):
3282 useTestableFalse = i < 2
3283 if useTestableFalse:
3284 test = self.testableFalse
3285 else:
3286 test = self.testableTrue
3287 return getattr(test, methodName)
3288
3289 for i, expected_regexp in enumerate(errors):
3290 testMethod = getMethod(i)
3291 kwargs = {}
3292 withMsg = i % 2
3293 if withMsg:
3294 kwargs = {"msg": "oops"}
3295
3296 with self.assertRaisesRegexp(self.failureException,
3297 expected_regexp=expected_regexp):
3298 testMethod(*args, **kwargs)
3299
3300 def testAssertTrue(self):
3301 self.assertMessages('assertTrue', (False,),
3302 ["^False is not True$", "^oops$", "^False is not True$",
3303 "^False is not True : oops$"])
3304
3305 def testAssertFalse(self):
3306 self.assertMessages('assertFalse', (True,),
3307 ["^True is not False$", "^oops$", "^True is not False$",
3308 "^True is not False : oops$"])
3309
3310 def testNotEqual(self):
3311 self.assertMessages('assertNotEqual', (1, 1),
3312 ["^1 == 1$", "^oops$", "^1 == 1$",
3313 "^1 == 1 : oops$"])
3314
3315 def testAlmostEqual(self):
3316 self.assertMessages('assertAlmostEqual', (1, 2),
3317 ["^1 != 2 within 7 places$", "^oops$",
3318 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3319
3320 def testNotAlmostEqual(self):
3321 self.assertMessages('assertNotAlmostEqual', (1, 1),
3322 ["^1 == 1 within 7 places$", "^oops$",
3323 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3324
3325 def test_baseAssertEqual(self):
3326 self.assertMessages('_baseAssertEqual', (1, 2),
3327 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3328
3329 def testAssertSequenceEqual(self):
3330 # Error messages are multiline so not testing on full message
3331 # assertTupleEqual and assertListEqual delegate to this method
3332 self.assertMessages('assertSequenceEqual', ([], [None]),
3333 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3334 r"\+ \[None\] : oops$"])
3335
3336 def testAssertSetEqual(self):
3337 self.assertMessages('assertSetEqual', (set(), set([None])),
3338 ["None$", "^oops$", "None$",
3339 "None : oops$"])
3340
3341 def testAssertIn(self):
3342 self.assertMessages('assertIn', (None, []),
3343 ['^None not found in \[\]$', "^oops$",
3344 '^None not found in \[\]$',
3345 '^None not found in \[\] : oops$'])
3346
3347 def testAssertNotIn(self):
3348 self.assertMessages('assertNotIn', (None, [None]),
3349 ['^None unexpectedly found in \[None\]$', "^oops$",
3350 '^None unexpectedly found in \[None\]$',
3351 '^None unexpectedly found in \[None\] : oops$'])
3352
3353 def testAssertDictEqual(self):
3354 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3355 [r"\+ \{'key': 'value'\}$", "^oops$",
3356 "\+ \{'key': 'value'\}$",
3357 "\+ \{'key': 'value'\} : oops$"])
3358
3359 def testAssertDictContainsSubset(self):
3360 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3361 ["^Missing: 'key'$", "^oops$",
3362 "^Missing: 'key'$",
3363 "^Missing: 'key' : oops$"])
3364
Michael Foord8442a602010-03-20 16:58:04 +00003365 def testAssertItemsEqual(self):
3366 self.assertMessages('assertItemsEqual', ([], [None]),
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003367 [r"\[None\]$", "^oops$",
3368 r"\[None\]$",
3369 r"\[None\] : oops$"])
3370
3371 def testAssertMultiLineEqual(self):
3372 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3373 [r"\+ foo$", "^oops$",
3374 r"\+ foo$",
3375 r"\+ foo : oops$"])
3376
3377 def testAssertLess(self):
3378 self.assertMessages('assertLess', (2, 1),
3379 ["^2 not less than 1$", "^oops$",
3380 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3381
3382 def testAssertLessEqual(self):
3383 self.assertMessages('assertLessEqual', (2, 1),
3384 ["^2 not less than or equal to 1$", "^oops$",
3385 "^2 not less than or equal to 1$",
3386 "^2 not less than or equal to 1 : oops$"])
3387
3388 def testAssertGreater(self):
3389 self.assertMessages('assertGreater', (1, 2),
3390 ["^1 not greater than 2$", "^oops$",
3391 "^1 not greater than 2$",
3392 "^1 not greater than 2 : oops$"])
3393
3394 def testAssertGreaterEqual(self):
3395 self.assertMessages('assertGreaterEqual', (1, 2),
3396 ["^1 not greater than or equal to 2$", "^oops$",
3397 "^1 not greater than or equal to 2$",
3398 "^1 not greater than or equal to 2 : oops$"])
3399
3400 def testAssertIsNone(self):
3401 self.assertMessages('assertIsNone', ('not None',),
3402 ["^'not None' is not None$", "^oops$",
3403 "^'not None' is not None$",
3404 "^'not None' is not None : oops$"])
3405
3406 def testAssertIsNotNone(self):
3407 self.assertMessages('assertIsNotNone', (None,),
3408 ["^unexpectedly None$", "^oops$",
3409 "^unexpectedly None$",
3410 "^unexpectedly None : oops$"])
3411
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00003412 def testAssertIs(self):
3413 self.assertMessages('assertIs', (None, 'foo'),
3414 ["^None is not 'foo'$", "^oops$",
3415 "^None is not 'foo'$",
3416 "^None is not 'foo' : oops$"])
3417
3418 def testAssertIsNot(self):
3419 self.assertMessages('assertIsNot', (None, None),
3420 ["^unexpectedly identical: None$", "^oops$",
3421 "^unexpectedly identical: None$",
3422 "^unexpectedly identical: None : oops$"])
3423
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003424
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003425class TestCleanUp(TestCase):
3426
3427 def testCleanUp(self):
3428 class TestableTest(TestCase):
3429 def testNothing(self):
3430 pass
3431
3432 test = TestableTest('testNothing')
3433 self.assertEqual(test._cleanups, [])
3434
3435 cleanups = []
3436
3437 def cleanup1(*args, **kwargs):
3438 cleanups.append((1, args, kwargs))
3439
3440 def cleanup2(*args, **kwargs):
3441 cleanups.append((2, args, kwargs))
3442
3443 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3444 test.addCleanup(cleanup2)
3445
3446 self.assertEqual(test._cleanups,
3447 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3448 (cleanup2, (), {})])
3449
3450 result = test.doCleanups()
3451 self.assertTrue(result)
3452
3453 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3454
3455 def testCleanUpWithErrors(self):
3456 class TestableTest(TestCase):
3457 def testNothing(self):
3458 pass
3459
3460 class MockResult(object):
3461 errors = []
3462 def addError(self, test, exc_info):
3463 self.errors.append((test, exc_info))
3464
3465 result = MockResult()
3466 test = TestableTest('testNothing')
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00003467 test._resultForDoCleanups = result
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003468
3469 exc1 = Exception('foo')
3470 exc2 = Exception('bar')
3471 def cleanup1():
3472 raise exc1
3473
3474 def cleanup2():
3475 raise exc2
3476
3477 test.addCleanup(cleanup1)
3478 test.addCleanup(cleanup2)
3479
3480 self.assertFalse(test.doCleanups())
3481
3482 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3483 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3484 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3485
3486 def testCleanupInRun(self):
3487 blowUp = False
3488 ordering = []
3489
3490 class TestableTest(TestCase):
3491 def setUp(self):
3492 ordering.append('setUp')
3493 if blowUp:
3494 raise Exception('foo')
3495
3496 def testNothing(self):
3497 ordering.append('test')
3498
3499 def tearDown(self):
3500 ordering.append('tearDown')
3501
3502 test = TestableTest('testNothing')
3503
3504 def cleanup1():
3505 ordering.append('cleanup1')
3506 def cleanup2():
3507 ordering.append('cleanup2')
3508 test.addCleanup(cleanup1)
3509 test.addCleanup(cleanup2)
3510
3511 def success(some_test):
3512 self.assertEqual(some_test, test)
3513 ordering.append('success')
3514
3515 result = unittest.TestResult()
3516 result.addSuccess = success
3517
3518 test.run(result)
3519 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3520 'cleanup2', 'cleanup1', 'success'])
3521
3522 blowUp = True
3523 ordering = []
3524 test = TestableTest('testNothing')
3525 test.addCleanup(cleanup1)
3526 test.run(result)
3527 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3528
3529
3530class Test_TestProgram(TestCase):
3531
3532 # Horrible white box test
3533 def testNoExit(self):
3534 result = object()
3535 test = object()
3536
3537 class FakeRunner(object):
3538 def run(self, test):
3539 self.test = test
3540 return result
3541
3542 runner = FakeRunner()
3543
Benjamin Petersond2397752009-06-27 23:45:02 +00003544 oldParseArgs = TestProgram.parseArgs
3545 def restoreParseArgs():
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003546 TestProgram.parseArgs = oldParseArgs
Benjamin Petersond2397752009-06-27 23:45:02 +00003547 TestProgram.parseArgs = lambda *args: None
3548 self.addCleanup(restoreParseArgs)
3549
3550 def removeTest():
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003551 del TestProgram.test
Benjamin Petersond2397752009-06-27 23:45:02 +00003552 TestProgram.test = test
3553 self.addCleanup(removeTest)
3554
3555 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3556
3557 self.assertEqual(program.result, result)
3558 self.assertEqual(runner.test, test)
3559 self.assertEqual(program.verbosity, 2)
3560
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003561 class FooBar(unittest.TestCase):
3562 def testPass(self):
3563 assert True
3564 def testFail(self):
3565 assert False
3566
3567 class FooBarLoader(unittest.TestLoader):
3568 """Test loader that returns a suite containing FooBar."""
3569 def loadTestsFromModule(self, module):
3570 return self.suiteClass(
3571 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3572
3573
3574 def test_NonExit(self):
3575 program = unittest.main(exit=False,
3576 argv=["foobar"],
3577 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3578 testLoader=self.FooBarLoader())
3579 self.assertTrue(hasattr(program, 'result'))
3580
3581
3582 def test_Exit(self):
3583 self.assertRaises(
3584 SystemExit,
3585 unittest.main,
3586 argv=["foobar"],
3587 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3588 exit=True,
3589 testLoader=self.FooBarLoader())
3590
3591
3592 def test_ExitAsDefault(self):
3593 self.assertRaises(
3594 SystemExit,
3595 unittest.main,
3596 argv=["foobar"],
3597 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3598 testLoader=self.FooBarLoader())
3599
3600
3601class Test_TextTestRunner(TestCase):
3602 """Tests for TextTestRunner."""
3603
3604 def test_works_with_result_without_startTestRun_stopTestRun(self):
3605 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3606 separator2 = ''
3607 def printErrors(self):
3608 pass
3609
3610 class Runner(unittest.TextTestRunner):
3611 def __init__(self):
3612 super(Runner, self).__init__(io.StringIO())
3613
3614 def _makeResult(self):
3615 return OldTextResult()
3616
3617 runner = Runner()
3618 runner.run(unittest.TestSuite())
3619
3620 def test_startTestRun_stopTestRun_called(self):
3621 class LoggingTextResult(LoggingResult):
3622 separator2 = ''
3623 def printErrors(self):
3624 pass
3625
3626 class LoggingRunner(unittest.TextTestRunner):
3627 def __init__(self, events):
3628 super(LoggingRunner, self).__init__(io.StringIO())
3629 self._events = events
3630
3631 def _makeResult(self):
3632 return LoggingTextResult(self._events)
3633
3634 events = []
3635 runner = LoggingRunner(events)
3636 runner.run(unittest.TestSuite())
3637 expected = ['startTestRun', 'stopTestRun']
3638 self.assertEqual(events, expected)
3639
Antoine Pitrouc63ecee2009-11-10 21:34:48 +00003640 def test_pickle_unpickle(self):
3641 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3642 # required by test_multiprocessing under Windows (in verbose mode).
3643 stream = io.StringIO("foo")
3644 runner = unittest.TextTestRunner(stream)
3645 for protocol in range(2, pickle.HIGHEST_PROTOCOL + 1):
3646 s = pickle.dumps(runner, protocol)
3647 obj = pickle.loads(s)
3648 # StringIO objects never compare equal, a cheap test instead.
3649 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3650
Michael Foord34c94622010-02-10 15:51:42 +00003651 def test_resultclass(self):
3652 def MockResultClass(*args):
3653 return args
3654 STREAM = object()
3655 DESCRIPTIONS = object()
3656 VERBOSITY = object()
3657 runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY,
3658 resultclass=MockResultClass)
3659 self.assertEqual(runner.resultclass, MockResultClass)
3660
3661 expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY)
3662 self.assertEqual(runner._makeResult(), expectedresult)
3663
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003664
Benjamin Petersond2397752009-06-27 23:45:02 +00003665class TestDiscovery(TestCase):
3666
3667 # Heavily mocked tests so I can avoid hitting the filesystem
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003668 def test_get_name_from_path(self):
Benjamin Petersond2397752009-06-27 23:45:02 +00003669 loader = unittest.TestLoader()
Benjamin Petersond2397752009-06-27 23:45:02 +00003670 loader._top_level_dir = '/foo'
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003671 name = loader._get_name_from_path('/foo/bar/baz.py')
3672 self.assertEqual(name, 'bar.baz')
Benjamin Petersond2397752009-06-27 23:45:02 +00003673
3674 if not __debug__:
3675 # asserts are off
3676 return
3677
3678 with self.assertRaises(AssertionError):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003679 loader._get_name_from_path('/bar/baz.py')
Benjamin Petersond2397752009-06-27 23:45:02 +00003680
3681 def test_find_tests(self):
3682 loader = unittest.TestLoader()
3683
3684 original_listdir = os.listdir
3685 def restore_listdir():
3686 os.listdir = original_listdir
3687 original_isfile = os.path.isfile
3688 def restore_isfile():
3689 os.path.isfile = original_isfile
3690 original_isdir = os.path.isdir
3691 def restore_isdir():
3692 os.path.isdir = original_isdir
3693
3694 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003695 'test.foo', 'test-not-a-module.py', 'another_dir'],
Benjamin Petersond2397752009-06-27 23:45:02 +00003696 ['test3.py', 'test4.py', ]]
3697 os.listdir = lambda path: path_lists.pop(0)
3698 self.addCleanup(restore_listdir)
3699
3700 def isdir(path):
3701 return path.endswith('dir')
3702 os.path.isdir = isdir
3703 self.addCleanup(restore_isdir)
3704
3705 def isfile(path):
3706 # another_dir is not a package and so shouldn't be recursed into
3707 return not path.endswith('dir') and not 'another_dir' in path
3708 os.path.isfile = isfile
3709 self.addCleanup(restore_isfile)
3710
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003711 loader._get_module_from_name = lambda path: path + ' module'
Benjamin Petersond2397752009-06-27 23:45:02 +00003712 loader.loadTestsFromModule = lambda module: module + ' tests'
3713
3714 loader._top_level_dir = '/foo'
3715 suite = list(loader._find_tests('/foo', 'test*.py'))
3716
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003717 expected = [name + ' module tests' for name in
3718 ('test1', 'test2')]
3719 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3720 ('test3', 'test4')])
Benjamin Petersond2397752009-06-27 23:45:02 +00003721 self.assertEqual(suite, expected)
3722
3723 def test_find_tests_with_package(self):
3724 loader = unittest.TestLoader()
3725
3726 original_listdir = os.listdir
3727 def restore_listdir():
3728 os.listdir = original_listdir
3729 original_isfile = os.path.isfile
3730 def restore_isfile():
3731 os.path.isfile = original_isfile
3732 original_isdir = os.path.isdir
3733 def restore_isdir():
3734 os.path.isdir = original_isdir
3735
3736 directories = ['a_directory', 'test_directory', 'test_directory2']
3737 path_lists = [directories, [], [], []]
3738 os.listdir = lambda path: path_lists.pop(0)
3739 self.addCleanup(restore_listdir)
3740
3741 os.path.isdir = lambda path: True
3742 self.addCleanup(restore_isdir)
3743
3744 os.path.isfile = lambda path: os.path.basename(path) not in directories
3745 self.addCleanup(restore_isfile)
3746
3747 class Module(object):
3748 paths = []
3749 load_tests_args = []
3750
3751 def __init__(self, path):
3752 self.path = path
3753 self.paths.append(path)
3754 if os.path.basename(path) == 'test_directory':
3755 def load_tests(loader, tests, pattern):
3756 self.load_tests_args.append((loader, tests, pattern))
3757 return 'load_tests'
3758 self.load_tests = load_tests
3759
3760 def __eq__(self, other):
3761 return self.path == other.path
3762
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003763 loader._get_module_from_name = lambda name: Module(name)
Benjamin Petersond2397752009-06-27 23:45:02 +00003764 def loadTestsFromModule(module, use_load_tests):
3765 if use_load_tests:
3766 raise self.failureException('use_load_tests should be False for packages')
3767 return module.path + ' module tests'
3768 loader.loadTestsFromModule = loadTestsFromModule
3769
3770 loader._top_level_dir = '/foo'
3771 # this time no '.py' on the pattern so that it can match
3772 # a test package
3773 suite = list(loader._find_tests('/foo', 'test*'))
3774
3775 # We should have loaded tests from the test_directory package by calling load_tests
3776 # and directly from the test_directory2 package
3777 self.assertEqual(suite,
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003778 ['load_tests', 'test_directory2' + ' module tests'])
3779 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Benjamin Petersond2397752009-06-27 23:45:02 +00003780
3781 # load_tests should have been called once with loader, tests and pattern
3782 self.assertEqual(Module.load_tests_args,
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003783 [(loader, 'test_directory' + ' module tests', 'test*')])
Benjamin Petersond2397752009-06-27 23:45:02 +00003784
3785 def test_discover(self):
3786 loader = unittest.TestLoader()
3787
3788 original_isfile = os.path.isfile
3789 def restore_isfile():
3790 os.path.isfile = original_isfile
3791
3792 os.path.isfile = lambda path: False
3793 self.addCleanup(restore_isfile)
3794
Nick Coghlan6ead5522009-10-18 13:19:33 +00003795 orig_sys_path = sys.path[:]
3796 def restore_path():
3797 sys.path[:] = orig_sys_path
3798 self.addCleanup(restore_path)
Benjamin Petersond2397752009-06-27 23:45:02 +00003799
Nick Coghlan6ead5522009-10-18 13:19:33 +00003800 full_path = os.path.abspath(os.path.normpath('/foo'))
Benjamin Petersond2397752009-06-27 23:45:02 +00003801 with self.assertRaises(ImportError):
3802 loader.discover('/foo/bar', top_level_dir='/foo')
3803
3804 self.assertEqual(loader._top_level_dir, full_path)
3805 self.assertIn(full_path, sys.path)
3806
3807 os.path.isfile = lambda path: True
3808 _find_tests_args = []
3809 def _find_tests(start_dir, pattern):
3810 _find_tests_args.append((start_dir, pattern))
3811 return ['tests']
3812 loader._find_tests = _find_tests
3813 loader.suiteClass = str
3814
3815 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3816
3817 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3818 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3819 self.assertEqual(suite, "['tests']")
3820 self.assertEqual(loader._top_level_dir, top_level_dir)
3821 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlan6ead5522009-10-18 13:19:33 +00003822 self.assertIn(top_level_dir, sys.path)
Benjamin Petersond2397752009-06-27 23:45:02 +00003823
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003824 def test_discover_with_modules_that_fail_to_import(self):
3825 loader = unittest.TestLoader()
3826
3827 listdir = os.listdir
3828 os.listdir = lambda _: ['test_this_does_not_exist.py']
3829 isfile = os.path.isfile
3830 os.path.isfile = lambda _: True
Nick Coghlan6ead5522009-10-18 13:19:33 +00003831 orig_sys_path = sys.path[:]
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003832 def restore():
3833 os.path.isfile = isfile
3834 os.listdir = listdir
Nick Coghlan6ead5522009-10-18 13:19:33 +00003835 sys.path[:] = orig_sys_path
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003836 self.addCleanup(restore)
3837
3838 suite = loader.discover('.')
Nick Coghlan6ead5522009-10-18 13:19:33 +00003839 self.assertIn(os.getcwd(), sys.path)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003840 self.assertEqual(suite.countTestCases(), 1)
3841 test = list(list(suite)[0])[0] # extract test from suite
3842
3843 with self.assertRaises(ImportError):
3844 test.test_this_does_not_exist()
3845
Benjamin Petersond2397752009-06-27 23:45:02 +00003846 def test_command_line_handling_parseArgs(self):
3847 # Haha - take that uninstantiable class
3848 program = object.__new__(TestProgram)
3849
3850 args = []
3851 def do_discovery(argv):
3852 args.extend(argv)
3853 program._do_discovery = do_discovery
3854 program.parseArgs(['something', 'discover'])
3855 self.assertEqual(args, [])
3856
3857 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3858 self.assertEqual(args, ['foo', 'bar'])
3859
3860 def test_command_line_handling_do_discovery_too_many_arguments(self):
3861 class Stop(Exception):
3862 pass
3863 def usageExit():
3864 raise Stop
3865
3866 program = object.__new__(TestProgram)
3867 program.usageExit = usageExit
3868
3869 with self.assertRaises(Stop):
3870 # too many args
3871 program._do_discovery(['one', 'two', 'three', 'four'])
3872
3873
3874 def test_command_line_handling_do_discovery_calls_loader(self):
3875 program = object.__new__(TestProgram)
3876
3877 class Loader(object):
3878 args = []
3879 def discover(self, start_dir, pattern, top_level_dir):
3880 self.args.append((start_dir, pattern, top_level_dir))
3881 return 'tests'
3882
3883 program._do_discovery(['-v'], Loader=Loader)
3884 self.assertEqual(program.verbosity, 2)
3885 self.assertEqual(program.test, 'tests')
3886 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3887
3888 Loader.args = []
3889 program = object.__new__(TestProgram)
3890 program._do_discovery(['--verbose'], Loader=Loader)
3891 self.assertEqual(program.test, 'tests')
3892 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3893
3894 Loader.args = []
3895 program = object.__new__(TestProgram)
3896 program._do_discovery([], Loader=Loader)
3897 self.assertEqual(program.test, 'tests')
3898 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3899
3900 Loader.args = []
3901 program = object.__new__(TestProgram)
3902 program._do_discovery(['fish'], Loader=Loader)
3903 self.assertEqual(program.test, 'tests')
3904 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3905
3906 Loader.args = []
3907 program = object.__new__(TestProgram)
3908 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3909 self.assertEqual(program.test, 'tests')
3910 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3911
3912 Loader.args = []
3913 program = object.__new__(TestProgram)
3914 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3915 self.assertEqual(program.test, 'tests')
3916 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3917
3918 Loader.args = []
3919 program = object.__new__(TestProgram)
3920 program._do_discovery(['-s', 'fish'], Loader=Loader)
3921 self.assertEqual(program.test, 'tests')
3922 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3923
3924 Loader.args = []
3925 program = object.__new__(TestProgram)
3926 program._do_discovery(['-t', 'fish'], Loader=Loader)
3927 self.assertEqual(program.test, 'tests')
3928 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3929
3930 Loader.args = []
3931 program = object.__new__(TestProgram)
3932 program._do_discovery(['-p', 'fish'], Loader=Loader)
3933 self.assertEqual(program.test, 'tests')
3934 self.assertEqual(Loader.args, [('.', 'fish', None)])
3935
3936 Loader.args = []
3937 program = object.__new__(TestProgram)
3938 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3939 self.assertEqual(program.test, 'tests')
3940 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3941 self.assertEqual(program.verbosity, 2)
3942
3943
Benjamin Peterson847a4112010-03-14 15:04:17 +00003944class TestSetups(unittest.TestCase):
3945
3946 def getRunner(self):
3947 return unittest.TextTestRunner(resultclass=resultFactory,
3948 stream=io.StringIO())
3949 def runTests(self, *cases):
3950 suite = unittest.TestSuite()
3951 for case in cases:
3952 tests = unittest.defaultTestLoader.loadTestsFromTestCase(case)
3953 suite.addTests(tests)
3954
3955 runner = self.getRunner()
3956
3957 # creating a nested suite exposes some potential bugs
3958 realSuite = unittest.TestSuite()
3959 realSuite.addTest(suite)
3960 # adding empty suites to the end exposes potential bugs
3961 suite.addTest(unittest.TestSuite())
3962 realSuite.addTest(unittest.TestSuite())
3963 return runner.run(realSuite)
3964
3965 def test_setup_class(self):
3966 class Test(unittest.TestCase):
3967 setUpCalled = 0
3968 @classmethod
3969 def setUpClass(cls):
3970 Test.setUpCalled += 1
3971 unittest.TestCase.setUpClass()
3972 def test_one(self):
3973 pass
3974 def test_two(self):
3975 pass
3976
3977 result = self.runTests(Test)
3978
3979 self.assertEqual(Test.setUpCalled, 1)
3980 self.assertEqual(result.testsRun, 2)
3981 self.assertEqual(len(result.errors), 0)
3982
3983 def test_teardown_class(self):
3984 class Test(unittest.TestCase):
3985 tearDownCalled = 0
3986 @classmethod
3987 def tearDownClass(cls):
3988 Test.tearDownCalled += 1
3989 unittest.TestCase.tearDownClass()
3990 def test_one(self):
3991 pass
3992 def test_two(self):
3993 pass
3994
3995 result = self.runTests(Test)
3996
3997 self.assertEqual(Test.tearDownCalled, 1)
3998 self.assertEqual(result.testsRun, 2)
3999 self.assertEqual(len(result.errors), 0)
4000
4001 def test_teardown_class_two_classes(self):
4002 class Test(unittest.TestCase):
4003 tearDownCalled = 0
4004 @classmethod
4005 def tearDownClass(cls):
4006 Test.tearDownCalled += 1
4007 unittest.TestCase.tearDownClass()
4008 def test_one(self):
4009 pass
4010 def test_two(self):
4011 pass
4012
4013 class Test2(unittest.TestCase):
4014 tearDownCalled = 0
4015 @classmethod
4016 def tearDownClass(cls):
4017 Test2.tearDownCalled += 1
4018 unittest.TestCase.tearDownClass()
4019 def test_one(self):
4020 pass
4021 def test_two(self):
4022 pass
4023
4024 result = self.runTests(Test, Test2)
4025
4026 self.assertEqual(Test.tearDownCalled, 1)
4027 self.assertEqual(Test2.tearDownCalled, 1)
4028 self.assertEqual(result.testsRun, 4)
4029 self.assertEqual(len(result.errors), 0)
4030
4031 def test_error_in_setupclass(self):
4032 class BrokenTest(unittest.TestCase):
4033 @classmethod
4034 def setUpClass(cls):
4035 raise TypeError('foo')
4036 def test_one(self):
4037 pass
4038 def test_two(self):
4039 pass
4040
4041 result = self.runTests(BrokenTest)
4042
4043 self.assertEqual(result.testsRun, 0)
4044 self.assertEqual(len(result.errors), 1)
4045 error, _ = result.errors[0]
4046 self.assertEqual(str(error),
4047 'classSetUp (%s.BrokenTest)' % __name__)
4048
4049 def test_error_in_teardown_class(self):
4050 class Test(unittest.TestCase):
4051 tornDown = 0
4052 @classmethod
4053 def tearDownClass(cls):
4054 Test.tornDown += 1
4055 raise TypeError('foo')
4056 def test_one(self):
4057 pass
4058 def test_two(self):
4059 pass
4060
4061 class Test2(unittest.TestCase):
4062 tornDown = 0
4063 @classmethod
4064 def tearDownClass(cls):
4065 Test2.tornDown += 1
4066 raise TypeError('foo')
4067 def test_one(self):
4068 pass
4069 def test_two(self):
4070 pass
4071
4072 result = self.runTests(Test, Test2)
4073 self.assertEqual(result.testsRun, 4)
4074 self.assertEqual(len(result.errors), 2)
4075 self.assertEqual(Test.tornDown, 1)
4076 self.assertEqual(Test2.tornDown, 1)
4077
4078 error, _ = result.errors[0]
4079 self.assertEqual(str(error),
4080 'classTearDown (%s.Test)' % __name__)
4081
4082 def test_class_not_torndown_when_setup_fails(self):
4083 class Test(unittest.TestCase):
4084 tornDown = False
4085 @classmethod
4086 def setUpClass(cls):
4087 raise TypeError
4088 @classmethod
4089 def tearDownClass(cls):
4090 Test.tornDown = True
4091 raise TypeError('foo')
4092 def test_one(self):
4093 pass
4094
4095 self.runTests(Test)
4096 self.assertFalse(Test.tornDown)
4097
4098 def test_class_not_setup_or_torndown_when_skipped(self):
4099 class Test(unittest.TestCase):
4100 classSetUp = False
4101 tornDown = False
4102 @classmethod
4103 def setUpClass(cls):
4104 Test.classSetUp = True
4105 @classmethod
4106 def tearDownClass(cls):
4107 Test.tornDown = True
4108 def test_one(self):
4109 pass
4110
4111 Test = unittest.skip("hop")(Test)
4112 self.runTests(Test)
4113 self.assertFalse(Test.classSetUp)
4114 self.assertFalse(Test.tornDown)
4115
4116 def test_setup_teardown_order_with_pathological_suite(self):
4117 results = []
4118
4119 class Module1(object):
4120 @staticmethod
4121 def setUpModule():
4122 results.append('Module1.setUpModule')
4123 @staticmethod
4124 def tearDownModule():
4125 results.append('Module1.tearDownModule')
4126
4127 class Module2(object):
4128 @staticmethod
4129 def setUpModule():
4130 results.append('Module2.setUpModule')
4131 @staticmethod
4132 def tearDownModule():
4133 results.append('Module2.tearDownModule')
4134
4135 class Test1(unittest.TestCase):
4136 @classmethod
4137 def setUpClass(cls):
4138 results.append('setup 1')
4139 @classmethod
4140 def tearDownClass(cls):
4141 results.append('teardown 1')
4142 def testOne(self):
4143 results.append('Test1.testOne')
4144 def testTwo(self):
4145 results.append('Test1.testTwo')
4146
4147 class Test2(unittest.TestCase):
4148 @classmethod
4149 def setUpClass(cls):
4150 results.append('setup 2')
4151 @classmethod
4152 def tearDownClass(cls):
4153 results.append('teardown 2')
4154 def testOne(self):
4155 results.append('Test2.testOne')
4156 def testTwo(self):
4157 results.append('Test2.testTwo')
4158
4159 class Test3(unittest.TestCase):
4160 @classmethod
4161 def setUpClass(cls):
4162 results.append('setup 3')
4163 @classmethod
4164 def tearDownClass(cls):
4165 results.append('teardown 3')
4166 def testOne(self):
4167 results.append('Test3.testOne')
4168 def testTwo(self):
4169 results.append('Test3.testTwo')
4170
4171 Test1.__module__ = Test2.__module__ = 'Module'
4172 Test3.__module__ = 'Module2'
4173 sys.modules['Module'] = Module1
4174 sys.modules['Module2'] = Module2
4175
4176 first = unittest.TestSuite((Test1('testOne'),))
4177 second = unittest.TestSuite((Test1('testTwo'),))
4178 third = unittest.TestSuite((Test2('testOne'),))
4179 fourth = unittest.TestSuite((Test2('testTwo'),))
4180 fifth = unittest.TestSuite((Test3('testOne'),))
4181 sixth = unittest.TestSuite((Test3('testTwo'),))
4182 suite = unittest.TestSuite((first, second, third, fourth, fifth, sixth))
4183
4184 runner = self.getRunner()
4185 result = runner.run(suite)
4186 self.assertEqual(result.testsRun, 6)
4187 self.assertEqual(len(result.errors), 0)
4188
4189 self.assertEqual(results,
4190 ['Module1.setUpModule', 'setup 1',
4191 'Test1.testOne', 'Test1.testTwo', 'teardown 1',
4192 'setup 2', 'Test2.testOne', 'Test2.testTwo',
4193 'teardown 2', 'Module1.tearDownModule',
4194 'Module2.setUpModule', 'setup 3',
4195 'Test3.testOne', 'Test3.testTwo',
4196 'teardown 3', 'Module2.tearDownModule'])
4197
4198 def test_setup_module(self):
4199 class Module(object):
4200 moduleSetup = 0
4201 @staticmethod
4202 def setUpModule():
4203 Module.moduleSetup += 1
4204
4205 class Test(unittest.TestCase):
4206 def test_one(self):
4207 pass
4208 def test_two(self):
4209 pass
4210 Test.__module__ = 'Module'
4211 sys.modules['Module'] = Module
4212
4213 result = self.runTests(Test)
4214 self.assertEqual(Module.moduleSetup, 1)
4215 self.assertEqual(result.testsRun, 2)
4216 self.assertEqual(len(result.errors), 0)
4217
4218 def test_error_in_setup_module(self):
4219 class Module(object):
4220 moduleSetup = 0
4221 moduleTornDown = 0
4222 @staticmethod
4223 def setUpModule():
4224 Module.moduleSetup += 1
4225 raise TypeError('foo')
4226 @staticmethod
4227 def tearDownModule():
4228 Module.moduleTornDown += 1
4229
4230 class Test(unittest.TestCase):
4231 classSetUp = False
4232 classTornDown = False
4233 @classmethod
4234 def setUpClass(cls):
4235 Test.classSetUp = True
4236 @classmethod
4237 def tearDownClass(cls):
4238 Test.classTornDown = True
4239 def test_one(self):
4240 pass
4241 def test_two(self):
4242 pass
4243
4244 class Test2(unittest.TestCase):
4245 def test_one(self):
4246 pass
4247 def test_two(self):
4248 pass
4249 Test.__module__ = 'Module'
4250 Test2.__module__ = 'Module'
4251 sys.modules['Module'] = Module
4252
4253 result = self.runTests(Test, Test2)
4254 self.assertEqual(Module.moduleSetup, 1)
4255 self.assertEqual(Module.moduleTornDown, 0)
4256 self.assertEqual(result.testsRun, 0)
4257 self.assertFalse(Test.classSetUp)
4258 self.assertFalse(Test.classTornDown)
4259 self.assertEqual(len(result.errors), 1)
4260 error, _ = result.errors[0]
4261 self.assertEqual(str(error), 'setUpModule (Module)')
4262
4263 def test_testcase_with_missing_module(self):
4264 class Test(unittest.TestCase):
4265 def test_one(self):
4266 pass
4267 def test_two(self):
4268 pass
4269 Test.__module__ = 'Module'
4270 sys.modules.pop('Module', None)
4271
4272 result = self.runTests(Test)
4273 self.assertEqual(result.testsRun, 2)
4274
4275 def test_teardown_module(self):
4276 class Module(object):
4277 moduleTornDown = 0
4278 @staticmethod
4279 def tearDownModule():
4280 Module.moduleTornDown += 1
4281
4282 class Test(unittest.TestCase):
4283 def test_one(self):
4284 pass
4285 def test_two(self):
4286 pass
4287 Test.__module__ = 'Module'
4288 sys.modules['Module'] = Module
4289
4290 result = self.runTests(Test)
4291 self.assertEqual(Module.moduleTornDown, 1)
4292 self.assertEqual(result.testsRun, 2)
4293 self.assertEqual(len(result.errors), 0)
4294
4295 def test_error_in_teardown_module(self):
4296 class Module(object):
4297 moduleTornDown = 0
4298 @staticmethod
4299 def tearDownModule():
4300 Module.moduleTornDown += 1
4301 raise TypeError('foo')
4302
4303 class Test(unittest.TestCase):
4304 classSetUp = False
4305 classTornDown = False
4306 @classmethod
4307 def setUpClass(cls):
4308 Test.classSetUp = True
4309 @classmethod
4310 def tearDownClass(cls):
4311 Test.classTornDown = True
4312 def test_one(self):
4313 pass
4314 def test_two(self):
4315 pass
4316
4317 class Test2(unittest.TestCase):
4318 def test_one(self):
4319 pass
4320 def test_two(self):
4321 pass
4322 Test.__module__ = 'Module'
4323 Test2.__module__ = 'Module'
4324 sys.modules['Module'] = Module
4325
4326 result = self.runTests(Test, Test2)
4327 self.assertEqual(Module.moduleTornDown, 1)
4328 self.assertEqual(result.testsRun, 4)
4329 self.assertTrue(Test.classSetUp)
4330 self.assertTrue(Test.classTornDown)
4331 self.assertEqual(len(result.errors), 1)
4332 error, _ = result.errors[0]
4333 self.assertEqual(str(error), 'tearDownModule (Module)')
4334
Jim Fultonfafd8742004-08-28 15:22:12 +00004335######################################################################
4336## Main
4337######################################################################
4338
4339def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004340 support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00004341 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Benjamin Peterson25c95f12009-05-08 20:42:26 +00004342 Test_TestSkipping, Test_Assertions, TestLongMessage,
Benjamin Peterson847a4112010-03-14 15:04:17 +00004343 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner,
4344 Test_OldTestResult, TestSetups)
Jim Fultonfafd8742004-08-28 15:22:12 +00004345
Guido van Rossumd8faa362007-04-27 19:54:29 +00004346if __name__ == "__main__":
Jim Fultonfafd8742004-08-28 15:22:12 +00004347 test_main()