blob: cf734f7e169b42bb01f2e4aee4fb55e162ea5304 [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
2761 self.assertSameElements([1, 2, 3], [3, 2, 1])
2762 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2763 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2764 self.assertRaises(self.failureException, self.assertSameElements,
2765 [10], [10, 11])
2766 self.assertRaises(self.failureException, self.assertSameElements,
2767 [10, 11], [10])
2768
2769 # Test that sequences of unhashable objects can be tested for sameness:
2770 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00002771
Benjamin Peterson3bb6b7a2009-04-04 16:46:24 +00002772 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002773 self.assertRaises(self.failureException, self.assertSameElements,
2774 [[1]], [[2]])
Michael Foorda5809c82009-04-04 18:55:09 +00002775 self.assertRaises(self.failureException, self.assertSameElements,
2776 [{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 2}])
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002777
Michael Foord8442a602010-03-20 16:58:04 +00002778
2779 def testAssertItemsEqual(self):
2780 a = object()
2781 self.assertItemsEqual([1, 2, 3], [3, 2, 1])
2782 self.assertItemsEqual(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2783 self.assertItemsEqual([a, a, 2, 2, 3], (a, 2, 3, a, 2))
2784 self.assertItemsEqual([1, "2", "a", "a"], ["a", "2", True, "a"])
2785 self.assertRaises(self.failureException, self.assertItemsEqual,
2786 [1, 2] + [3] * 100, [1] * 100 + [2, 3])
2787 self.assertRaises(self.failureException, self.assertItemsEqual,
2788 [1, "2", "a", "a"], ["a", "2", True, 1])
2789 self.assertRaises(self.failureException, self.assertItemsEqual,
2790 [10], [10, 11])
2791 self.assertRaises(self.failureException, self.assertItemsEqual,
2792 [10, 11], [10])
2793 self.assertRaises(self.failureException, self.assertItemsEqual,
2794 [10, 11, 10], [10, 11])
2795
2796 # Test that sequences of unhashable objects can be tested for sameness:
2797 self.assertItemsEqual([[1, 2], [3, 4], 0], [False, [3, 4], [1, 2]])
2798
2799 # hashable types, but not orderable
2800 self.assertRaises(self.failureException, self.assertItemsEqual,
2801 [], [divmod, 'x', 1, 5j, 2j, frozenset()])
2802 # comparing dicts raises a py3k warning
2803 self.assertItemsEqual([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2804 # comparing heterogenous non-hashable sequences raises a py3k warning
2805 self.assertItemsEqual([1, 'x', divmod, []], [divmod, [], 'x', 1])
2806 self.assertRaises(self.failureException, self.assertItemsEqual,
2807 [], [divmod, [], 'x', 1, 5j, 2j, set()])
2808 self.assertRaises(self.failureException, self.assertItemsEqual,
2809 [[1]], [[2]])
2810
2811 # Same elements, but not same sequence length
2812 self.assertRaises(self.failureException, self.assertItemsEqual,
2813 [1, 1, 2], [2, 1])
2814 self.assertRaises(self.failureException, self.assertItemsEqual,
2815 [1, 1, "2", "a", "a"], ["2", "2", True, "a"])
2816 self.assertRaises(self.failureException, self.assertItemsEqual,
2817 [1, {'b': 2}, None, True], [{'b': 2}, True, None])
2818
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002819 def testAssertSetEqual(self):
2820 set1 = set()
2821 set2 = set()
2822 self.assertSetEqual(set1, set2)
2823
2824 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2825 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2826 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2827 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2828
2829 set1 = set(['a'])
2830 set2 = set()
2831 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2832
2833 set1 = set(['a'])
2834 set2 = set(['a'])
2835 self.assertSetEqual(set1, set2)
2836
2837 set1 = set(['a'])
2838 set2 = set(['a', 'b'])
2839 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2840
2841 set1 = set(['a'])
2842 set2 = frozenset(['a', 'b'])
2843 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2844
2845 set1 = set(['a', 'b'])
2846 set2 = frozenset(['a', 'b'])
2847 self.assertSetEqual(set1, set2)
2848
2849 set1 = set()
2850 set2 = "foo"
2851 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2852 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2853
2854 # make sure any string formatting is tuple-safe
2855 set1 = set([(0, 1), (2, 3)])
2856 set2 = set([(4, 5)])
2857 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2858
2859 def testInequality(self):
2860 # Try ints
2861 self.assertGreater(2, 1)
2862 self.assertGreaterEqual(2, 1)
2863 self.assertGreaterEqual(1, 1)
2864 self.assertLess(1, 2)
2865 self.assertLessEqual(1, 2)
2866 self.assertLessEqual(1, 1)
2867 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2868 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2869 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2870 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2871 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2872 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2873
2874 # Try Floats
2875 self.assertGreater(1.1, 1.0)
2876 self.assertGreaterEqual(1.1, 1.0)
2877 self.assertGreaterEqual(1.0, 1.0)
2878 self.assertLess(1.0, 1.1)
2879 self.assertLessEqual(1.0, 1.1)
2880 self.assertLessEqual(1.0, 1.0)
2881 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2882 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2883 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2884 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2885 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2886 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2887
2888 # Try Strings
2889 self.assertGreater('bug', 'ant')
2890 self.assertGreaterEqual('bug', 'ant')
2891 self.assertGreaterEqual('ant', 'ant')
2892 self.assertLess('ant', 'bug')
2893 self.assertLessEqual('ant', 'bug')
2894 self.assertLessEqual('ant', 'ant')
2895 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2896 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2897 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2898 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2899 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2900 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2901
2902 # Try bytes
2903 self.assertGreater(b'bug', b'ant')
2904 self.assertGreaterEqual(b'bug', b'ant')
2905 self.assertGreaterEqual(b'ant', b'ant')
2906 self.assertLess(b'ant', b'bug')
2907 self.assertLessEqual(b'ant', b'bug')
2908 self.assertLessEqual(b'ant', b'ant')
2909 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'bug')
2910 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'ant')
2911 self.assertRaises(self.failureException, self.assertGreaterEqual, b'ant',
2912 b'bug')
2913 self.assertRaises(self.failureException, self.assertLess, b'bug', b'ant')
2914 self.assertRaises(self.failureException, self.assertLess, b'ant', b'ant')
2915 self.assertRaises(self.failureException, self.assertLessEqual, b'bug', b'ant')
2916
2917 def testAssertMultiLineEqual(self):
2918 sample_text = """\
2919http://www.python.org/doc/2.3/lib/module-unittest.html
2920test case
2921 A test case is the smallest unit of testing. [...]
2922"""
2923 revised_sample_text = """\
2924http://www.python.org/doc/2.4.1/lib/module-unittest.html
2925test case
2926 A test case is the smallest unit of testing. [...] You may provide your
2927 own implementation that does not subclass from TestCase, of course.
2928"""
2929 sample_text_error = """
2930- http://www.python.org/doc/2.3/lib/module-unittest.html
2931? ^
2932+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2933? ^^^
2934 test case
2935- A test case is the smallest unit of testing. [...]
2936+ A test case is the smallest unit of testing. [...] You may provide your
2937? +++++++++++++++++++++
2938+ own implementation that does not subclass from TestCase, of course.
2939"""
2940
2941 try:
2942 self.assertMultiLineEqual(sample_text, revised_sample_text)
2943 except self.failureException as e:
Michael Foord02834952010-02-08 23:10:39 +00002944 # no fair testing ourself with ourself, and assertEqual is used for strings
2945 # so can't use assertEqual either. Just use assertTrue.
2946 self.assertTrue(sample_text_error == str(e))
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002947
2948 def testAssertIsNone(self):
2949 self.assertIsNone(None)
2950 self.assertRaises(self.failureException, self.assertIsNone, False)
2951 self.assertIsNotNone('DjZoPloGears on Rails')
2952 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2953
2954 def testAssertRegexpMatches(self):
2955 self.assertRegexpMatches('asdfabasdf', r'ab+')
2956 self.assertRaises(self.failureException, self.assertRegexpMatches,
2957 'saaas', r'aaaa')
2958
2959 def testAssertRaisesRegexp(self):
2960 class ExceptionMock(Exception):
2961 pass
2962
2963 def Stub():
2964 raise ExceptionMock('We expect')
2965
2966 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2967 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2968
2969 def testAssertNotRaisesRegexp(self):
2970 self.assertRaisesRegexp(
Benjamin Peterson4f75b642009-04-04 16:39:09 +00002971 self.failureException, '^Exception not raised by <lambda>$',
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002972 self.assertRaisesRegexp, Exception, re.compile('x'),
2973 lambda: None)
2974 self.assertRaisesRegexp(
Benjamin Peterson4f75b642009-04-04 16:39:09 +00002975 self.failureException, '^Exception not raised by <lambda>$',
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002976 self.assertRaisesRegexp, Exception, 'x',
2977 lambda: None)
2978
2979 def testAssertRaisesRegexpMismatch(self):
2980 def Stub():
2981 raise Exception('Unexpected')
2982
2983 self.assertRaisesRegexp(
2984 self.failureException,
2985 r'"\^Expected\$" does not match "Unexpected"',
2986 self.assertRaisesRegexp, Exception, '^Expected$',
2987 Stub)
2988 self.assertRaisesRegexp(
2989 self.failureException,
2990 r'"\^Expected\$" does not match "Unexpected"',
2991 self.assertRaisesRegexp, Exception,
2992 re.compile('^Expected$'), Stub)
2993
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +00002994 def testAssertRaisesExcValue(self):
2995 class ExceptionMock(Exception):
2996 pass
2997
2998 def Stub(foo):
2999 raise ExceptionMock(foo)
3000 v = "particular value"
3001
3002 ctx = self.assertRaises(ExceptionMock)
3003 with ctx:
3004 Stub(v)
Ezio Melotti49008232010-02-08 21:57:48 +00003005 e = ctx.exception
Ezio Melottie9615932010-01-24 19:26:24 +00003006 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +00003007 self.assertEqual(e.args[0], v)
3008
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003009 def testSynonymAssertMethodNames(self):
3010 """Test undocumented method name synonyms.
3011
3012 Please do not use these methods names in your own code.
3013
3014 This test confirms their continued existence and functionality
3015 in order to avoid breaking existing code.
3016 """
3017 self.assertNotEquals(3, 5)
3018 self.assertEquals(3, 3)
3019 self.assertAlmostEquals(2.0, 2.0)
3020 self.assertNotAlmostEquals(3.0, 5.0)
3021 self.assert_(True)
3022
3023 def testPendingDeprecationMethodNames(self):
3024 """Test fail* methods pending deprecation, they will warn in 3.2.
3025
3026 Do not use these methods. They will go away in 3.3.
3027 """
Benjamin Peterson6bcbad52009-06-30 23:45:41 +00003028 old = (
3029 (self.failIfEqual, (3, 5)),
3030 (self.failUnlessEqual, (3, 3)),
3031 (self.failUnlessAlmostEqual, (2.0, 2.0)),
3032 (self.failIfAlmostEqual, (3.0, 5.0)),
3033 (self.failUnless, (True,)),
3034 (self.failUnlessRaises, (TypeError, lambda _: 3.14 + 'spam')),
3035 (self.failIf, (False,))
3036 )
3037 for meth, args in old:
3038 with warnings.catch_warnings(record=True) as w:
3039 meth(*args)
3040 self.assertEqual(len(w), 1)
3041 self.assertIs(w[0].category, DeprecationWarning)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003042
3043 def testDeepcopy(self):
3044 # Issue: 5660
3045 class TestableTest(TestCase):
3046 def testNothing(self):
3047 pass
3048
3049 test = TestableTest('testNothing')
3050
3051 # This shouldn't blow up
3052 deepcopy(test)
3053
Benjamin Peterson5254c042009-03-23 22:25:03 +00003054
3055class Test_TestSkipping(TestCase):
3056
3057 def test_skipping(self):
3058 class Foo(unittest.TestCase):
3059 def test_skip_me(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00003060 self.skipTest("skip")
Benjamin Peterson5254c042009-03-23 22:25:03 +00003061 events = []
3062 result = LoggingResult(events)
3063 test = Foo("test_skip_me")
3064 test.run(result)
3065 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3066 self.assertEqual(result.skipped, [(test, "skip")])
3067
3068 # Try letting setUp skip the test now.
3069 class Foo(unittest.TestCase):
3070 def setUp(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00003071 self.skipTest("testing")
Benjamin Peterson5254c042009-03-23 22:25:03 +00003072 def test_nothing(self): pass
3073 events = []
3074 result = LoggingResult(events)
3075 test = Foo("test_nothing")
3076 test.run(result)
3077 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3078 self.assertEqual(result.skipped, [(test, "testing")])
3079 self.assertEqual(result.testsRun, 1)
3080
3081 def test_skipping_decorators(self):
3082 op_table = ((unittest.skipUnless, False, True),
3083 (unittest.skipIf, True, False))
3084 for deco, do_skip, dont_skip in op_table:
3085 class Foo(unittest.TestCase):
3086 @deco(do_skip, "testing")
3087 def test_skip(self): pass
3088
3089 @deco(dont_skip, "testing")
3090 def test_dont_skip(self): pass
3091 test_do_skip = Foo("test_skip")
3092 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00003093 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003094 events = []
3095 result = LoggingResult(events)
3096 suite.run(result)
3097 self.assertEqual(len(result.skipped), 1)
3098 expected = ['startTest', 'addSkip', 'stopTest',
3099 'startTest', 'addSuccess', 'stopTest']
3100 self.assertEqual(events, expected)
3101 self.assertEqual(result.testsRun, 2)
3102 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
3103 self.assertTrue(result.wasSuccessful())
3104
3105 def test_skip_class(self):
3106 @unittest.skip("testing")
3107 class Foo(unittest.TestCase):
3108 def test_1(self):
3109 record.append(1)
3110 record = []
3111 result = unittest.TestResult()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00003112 test = Foo("test_1")
3113 suite = unittest.TestSuite([test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003114 suite.run(result)
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00003115 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003116 self.assertEqual(record, [])
3117
3118 def test_expected_failure(self):
3119 class Foo(unittest.TestCase):
3120 @unittest.expectedFailure
3121 def test_die(self):
3122 self.fail("help me!")
3123 events = []
3124 result = LoggingResult(events)
3125 test = Foo("test_die")
3126 test.run(result)
3127 self.assertEqual(events,
3128 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Peterson52baa292009-03-24 00:56:30 +00003129 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson5254c042009-03-23 22:25:03 +00003130 self.assertTrue(result.wasSuccessful())
3131
3132 def test_unexpected_success(self):
3133 class Foo(unittest.TestCase):
3134 @unittest.expectedFailure
3135 def test_die(self):
3136 pass
3137 events = []
3138 result = LoggingResult(events)
3139 test = Foo("test_die")
3140 test.run(result)
3141 self.assertEqual(events,
3142 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3143 self.assertFalse(result.failures)
Benjamin Peterson52baa292009-03-24 00:56:30 +00003144 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003145 self.assertTrue(result.wasSuccessful())
3146
Benjamin Peterson847a4112010-03-14 15:04:17 +00003147 def test_skip_doesnt_run_setup(self):
3148 class Foo(unittest.TestCase):
3149 wasSetUp = False
3150 wasTornDown = False
3151 def setUp(self):
3152 Foo.wasSetUp = True
3153 def tornDown(self):
3154 Foo.wasTornDown = True
3155 @unittest.skip('testing')
3156 def test_1(self):
3157 pass
3158
3159 result = unittest.TestResult()
3160 test = Foo("test_1")
3161 suite = unittest.TestSuite([test])
3162 suite.run(result)
3163 self.assertEqual(result.skipped, [(test, "testing")])
3164 self.assertFalse(Foo.wasSetUp)
3165 self.assertFalse(Foo.wasTornDown)
3166
3167 def test_decorated_skip(self):
3168 def decorator(func):
3169 def inner(*a):
3170 return func(*a)
3171 return inner
3172
3173 class Foo(unittest.TestCase):
3174 @decorator
3175 @unittest.skip('testing')
3176 def test_1(self):
3177 pass
3178
3179 result = unittest.TestResult()
3180 test = Foo("test_1")
3181 suite = unittest.TestSuite([test])
3182 suite.run(result)
3183 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003184
3185
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003186class Test_Assertions(TestCase):
3187 def test_AlmostEqual(self):
Benjamin Petersone1759f82009-06-30 23:35:19 +00003188 self.assertAlmostEqual(1.00000001, 1.0)
3189 self.assertNotAlmostEqual(1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003190 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003191 self.assertAlmostEqual, 1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003192 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003193 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003194
Benjamin Petersone1759f82009-06-30 23:35:19 +00003195 self.assertAlmostEqual(1.1, 1.0, places=0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003196 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003197 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003198
Benjamin Petersone1759f82009-06-30 23:35:19 +00003199 self.assertAlmostEqual(0, .1+.1j, places=0)
3200 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003201 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003202 self.assertAlmostEqual, 0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003203 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003204 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003205
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003206 self.assertAlmostEqual(float('inf'), float('inf'))
3207 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3208 float('inf'), float('inf'))
3209
3210
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003211 def test_assertRaises(self):
3212 def _raise(e):
3213 raise e
3214 self.assertRaises(KeyError, _raise, KeyError)
3215 self.assertRaises(KeyError, _raise, KeyError("key"))
3216 try:
3217 self.assertRaises(KeyError, lambda: None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003218 except self.failureException as e:
Ezio Melottib58e0bd2010-01-23 15:40:09 +00003219 self.assertIn("KeyError not raised", str(e))
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003220 else:
3221 self.fail("assertRaises() didn't fail")
3222 try:
3223 self.assertRaises(KeyError, _raise, ValueError)
3224 except ValueError:
3225 pass
3226 else:
3227 self.fail("assertRaises() didn't let exception pass through")
Ezio Melotti49008232010-02-08 21:57:48 +00003228 with self.assertRaises(KeyError) as cm:
3229 try:
3230 raise KeyError
3231 except Exception as e:
3232 exc = e
3233 raise
3234 self.assertIs(cm.exception, exc)
3235
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003236 with self.assertRaises(KeyError):
3237 raise KeyError("key")
3238 try:
3239 with self.assertRaises(KeyError):
3240 pass
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003241 except self.failureException as e:
Ezio Melottib58e0bd2010-01-23 15:40:09 +00003242 self.assertIn("KeyError not raised", str(e))
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003243 else:
3244 self.fail("assertRaises() didn't fail")
3245 try:
3246 with self.assertRaises(KeyError):
3247 raise ValueError
3248 except ValueError:
3249 pass
3250 else:
3251 self.fail("assertRaises() didn't let exception pass through")
3252
3253
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003254class TestLongMessage(TestCase):
3255 """Test that the individual asserts honour longMessage.
3256 This actually tests all the message behaviour for
3257 asserts that use longMessage."""
3258
3259 def setUp(self):
3260 class TestableTestFalse(TestCase):
3261 longMessage = False
3262 failureException = self.failureException
3263
3264 def testTest(self):
3265 pass
3266
3267 class TestableTestTrue(TestCase):
3268 longMessage = True
3269 failureException = self.failureException
3270
3271 def testTest(self):
3272 pass
3273
3274 self.testableTrue = TestableTestTrue('testTest')
3275 self.testableFalse = TestableTestFalse('testTest')
3276
3277 def testDefault(self):
3278 self.assertFalse(TestCase.longMessage)
3279
3280 def test_formatMsg(self):
3281 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3282 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3283
3284 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3285 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3286
Benjamin Peterson847a4112010-03-14 15:04:17 +00003287 # This blows up if _formatMessage uses string concatenation
3288 self.testableTrue._formatMessage(object(), 'foo')
3289
3290 def test_formatMessage_unicode_error(self):
3291 with warnings.catch_warnings(record=True):
3292 # This causes a UnicodeWarning due to its craziness
3293 one = ''.join(chr(i) for i in range(255))
3294 # this used to cause a UnicodeDecodeError constructing msg
3295 self.testableTrue._formatMessage(one, '\uFFFD')
3296
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003297 def assertMessages(self, methodName, args, errors):
3298 def getMethod(i):
3299 useTestableFalse = i < 2
3300 if useTestableFalse:
3301 test = self.testableFalse
3302 else:
3303 test = self.testableTrue
3304 return getattr(test, methodName)
3305
3306 for i, expected_regexp in enumerate(errors):
3307 testMethod = getMethod(i)
3308 kwargs = {}
3309 withMsg = i % 2
3310 if withMsg:
3311 kwargs = {"msg": "oops"}
3312
3313 with self.assertRaisesRegexp(self.failureException,
3314 expected_regexp=expected_regexp):
3315 testMethod(*args, **kwargs)
3316
3317 def testAssertTrue(self):
3318 self.assertMessages('assertTrue', (False,),
3319 ["^False is not True$", "^oops$", "^False is not True$",
3320 "^False is not True : oops$"])
3321
3322 def testAssertFalse(self):
3323 self.assertMessages('assertFalse', (True,),
3324 ["^True is not False$", "^oops$", "^True is not False$",
3325 "^True is not False : oops$"])
3326
3327 def testNotEqual(self):
3328 self.assertMessages('assertNotEqual', (1, 1),
3329 ["^1 == 1$", "^oops$", "^1 == 1$",
3330 "^1 == 1 : oops$"])
3331
3332 def testAlmostEqual(self):
3333 self.assertMessages('assertAlmostEqual', (1, 2),
3334 ["^1 != 2 within 7 places$", "^oops$",
3335 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3336
3337 def testNotAlmostEqual(self):
3338 self.assertMessages('assertNotAlmostEqual', (1, 1),
3339 ["^1 == 1 within 7 places$", "^oops$",
3340 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3341
3342 def test_baseAssertEqual(self):
3343 self.assertMessages('_baseAssertEqual', (1, 2),
3344 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3345
3346 def testAssertSequenceEqual(self):
3347 # Error messages are multiline so not testing on full message
3348 # assertTupleEqual and assertListEqual delegate to this method
3349 self.assertMessages('assertSequenceEqual', ([], [None]),
3350 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3351 r"\+ \[None\] : oops$"])
3352
3353 def testAssertSetEqual(self):
3354 self.assertMessages('assertSetEqual', (set(), set([None])),
3355 ["None$", "^oops$", "None$",
3356 "None : oops$"])
3357
3358 def testAssertIn(self):
3359 self.assertMessages('assertIn', (None, []),
3360 ['^None not found in \[\]$', "^oops$",
3361 '^None not found in \[\]$',
3362 '^None not found in \[\] : oops$'])
3363
3364 def testAssertNotIn(self):
3365 self.assertMessages('assertNotIn', (None, [None]),
3366 ['^None unexpectedly found in \[None\]$', "^oops$",
3367 '^None unexpectedly found in \[None\]$',
3368 '^None unexpectedly found in \[None\] : oops$'])
3369
3370 def testAssertDictEqual(self):
3371 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3372 [r"\+ \{'key': 'value'\}$", "^oops$",
3373 "\+ \{'key': 'value'\}$",
3374 "\+ \{'key': 'value'\} : oops$"])
3375
3376 def testAssertDictContainsSubset(self):
3377 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3378 ["^Missing: 'key'$", "^oops$",
3379 "^Missing: 'key'$",
3380 "^Missing: 'key' : oops$"])
3381
Michael Foord8442a602010-03-20 16:58:04 +00003382 def testAssertItemsEqual(self):
3383 self.assertMessages('assertItemsEqual', ([], [None]),
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003384 [r"\[None\]$", "^oops$",
3385 r"\[None\]$",
3386 r"\[None\] : oops$"])
3387
3388 def testAssertMultiLineEqual(self):
3389 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3390 [r"\+ foo$", "^oops$",
3391 r"\+ foo$",
3392 r"\+ foo : oops$"])
3393
3394 def testAssertLess(self):
3395 self.assertMessages('assertLess', (2, 1),
3396 ["^2 not less than 1$", "^oops$",
3397 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3398
3399 def testAssertLessEqual(self):
3400 self.assertMessages('assertLessEqual', (2, 1),
3401 ["^2 not less than or equal to 1$", "^oops$",
3402 "^2 not less than or equal to 1$",
3403 "^2 not less than or equal to 1 : oops$"])
3404
3405 def testAssertGreater(self):
3406 self.assertMessages('assertGreater', (1, 2),
3407 ["^1 not greater than 2$", "^oops$",
3408 "^1 not greater than 2$",
3409 "^1 not greater than 2 : oops$"])
3410
3411 def testAssertGreaterEqual(self):
3412 self.assertMessages('assertGreaterEqual', (1, 2),
3413 ["^1 not greater than or equal to 2$", "^oops$",
3414 "^1 not greater than or equal to 2$",
3415 "^1 not greater than or equal to 2 : oops$"])
3416
3417 def testAssertIsNone(self):
3418 self.assertMessages('assertIsNone', ('not None',),
3419 ["^'not None' is not None$", "^oops$",
3420 "^'not None' is not None$",
3421 "^'not None' is not None : oops$"])
3422
3423 def testAssertIsNotNone(self):
3424 self.assertMessages('assertIsNotNone', (None,),
3425 ["^unexpectedly None$", "^oops$",
3426 "^unexpectedly None$",
3427 "^unexpectedly None : oops$"])
3428
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00003429 def testAssertIs(self):
3430 self.assertMessages('assertIs', (None, 'foo'),
3431 ["^None is not 'foo'$", "^oops$",
3432 "^None is not 'foo'$",
3433 "^None is not 'foo' : oops$"])
3434
3435 def testAssertIsNot(self):
3436 self.assertMessages('assertIsNot', (None, None),
3437 ["^unexpectedly identical: None$", "^oops$",
3438 "^unexpectedly identical: None$",
3439 "^unexpectedly identical: None : oops$"])
3440
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003441
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003442class TestCleanUp(TestCase):
3443
3444 def testCleanUp(self):
3445 class TestableTest(TestCase):
3446 def testNothing(self):
3447 pass
3448
3449 test = TestableTest('testNothing')
3450 self.assertEqual(test._cleanups, [])
3451
3452 cleanups = []
3453
3454 def cleanup1(*args, **kwargs):
3455 cleanups.append((1, args, kwargs))
3456
3457 def cleanup2(*args, **kwargs):
3458 cleanups.append((2, args, kwargs))
3459
3460 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3461 test.addCleanup(cleanup2)
3462
3463 self.assertEqual(test._cleanups,
3464 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3465 (cleanup2, (), {})])
3466
3467 result = test.doCleanups()
3468 self.assertTrue(result)
3469
3470 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3471
3472 def testCleanUpWithErrors(self):
3473 class TestableTest(TestCase):
3474 def testNothing(self):
3475 pass
3476
3477 class MockResult(object):
3478 errors = []
3479 def addError(self, test, exc_info):
3480 self.errors.append((test, exc_info))
3481
3482 result = MockResult()
3483 test = TestableTest('testNothing')
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00003484 test._resultForDoCleanups = result
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003485
3486 exc1 = Exception('foo')
3487 exc2 = Exception('bar')
3488 def cleanup1():
3489 raise exc1
3490
3491 def cleanup2():
3492 raise exc2
3493
3494 test.addCleanup(cleanup1)
3495 test.addCleanup(cleanup2)
3496
3497 self.assertFalse(test.doCleanups())
3498
3499 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3500 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3501 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3502
3503 def testCleanupInRun(self):
3504 blowUp = False
3505 ordering = []
3506
3507 class TestableTest(TestCase):
3508 def setUp(self):
3509 ordering.append('setUp')
3510 if blowUp:
3511 raise Exception('foo')
3512
3513 def testNothing(self):
3514 ordering.append('test')
3515
3516 def tearDown(self):
3517 ordering.append('tearDown')
3518
3519 test = TestableTest('testNothing')
3520
3521 def cleanup1():
3522 ordering.append('cleanup1')
3523 def cleanup2():
3524 ordering.append('cleanup2')
3525 test.addCleanup(cleanup1)
3526 test.addCleanup(cleanup2)
3527
3528 def success(some_test):
3529 self.assertEqual(some_test, test)
3530 ordering.append('success')
3531
3532 result = unittest.TestResult()
3533 result.addSuccess = success
3534
3535 test.run(result)
3536 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3537 'cleanup2', 'cleanup1', 'success'])
3538
3539 blowUp = True
3540 ordering = []
3541 test = TestableTest('testNothing')
3542 test.addCleanup(cleanup1)
3543 test.run(result)
3544 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3545
3546
3547class Test_TestProgram(TestCase):
3548
3549 # Horrible white box test
3550 def testNoExit(self):
3551 result = object()
3552 test = object()
3553
3554 class FakeRunner(object):
3555 def run(self, test):
3556 self.test = test
3557 return result
3558
3559 runner = FakeRunner()
3560
Benjamin Petersond2397752009-06-27 23:45:02 +00003561 oldParseArgs = TestProgram.parseArgs
3562 def restoreParseArgs():
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003563 TestProgram.parseArgs = oldParseArgs
Benjamin Petersond2397752009-06-27 23:45:02 +00003564 TestProgram.parseArgs = lambda *args: None
3565 self.addCleanup(restoreParseArgs)
3566
3567 def removeTest():
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003568 del TestProgram.test
Benjamin Petersond2397752009-06-27 23:45:02 +00003569 TestProgram.test = test
3570 self.addCleanup(removeTest)
3571
3572 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3573
3574 self.assertEqual(program.result, result)
3575 self.assertEqual(runner.test, test)
3576 self.assertEqual(program.verbosity, 2)
3577
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003578 class FooBar(unittest.TestCase):
3579 def testPass(self):
3580 assert True
3581 def testFail(self):
3582 assert False
3583
3584 class FooBarLoader(unittest.TestLoader):
3585 """Test loader that returns a suite containing FooBar."""
3586 def loadTestsFromModule(self, module):
3587 return self.suiteClass(
3588 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3589
3590
3591 def test_NonExit(self):
3592 program = unittest.main(exit=False,
3593 argv=["foobar"],
3594 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3595 testLoader=self.FooBarLoader())
3596 self.assertTrue(hasattr(program, 'result'))
3597
3598
3599 def test_Exit(self):
3600 self.assertRaises(
3601 SystemExit,
3602 unittest.main,
3603 argv=["foobar"],
3604 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3605 exit=True,
3606 testLoader=self.FooBarLoader())
3607
3608
3609 def test_ExitAsDefault(self):
3610 self.assertRaises(
3611 SystemExit,
3612 unittest.main,
3613 argv=["foobar"],
3614 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3615 testLoader=self.FooBarLoader())
3616
3617
3618class Test_TextTestRunner(TestCase):
3619 """Tests for TextTestRunner."""
3620
3621 def test_works_with_result_without_startTestRun_stopTestRun(self):
3622 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3623 separator2 = ''
3624 def printErrors(self):
3625 pass
3626
3627 class Runner(unittest.TextTestRunner):
3628 def __init__(self):
3629 super(Runner, self).__init__(io.StringIO())
3630
3631 def _makeResult(self):
3632 return OldTextResult()
3633
3634 runner = Runner()
3635 runner.run(unittest.TestSuite())
3636
3637 def test_startTestRun_stopTestRun_called(self):
3638 class LoggingTextResult(LoggingResult):
3639 separator2 = ''
3640 def printErrors(self):
3641 pass
3642
3643 class LoggingRunner(unittest.TextTestRunner):
3644 def __init__(self, events):
3645 super(LoggingRunner, self).__init__(io.StringIO())
3646 self._events = events
3647
3648 def _makeResult(self):
3649 return LoggingTextResult(self._events)
3650
3651 events = []
3652 runner = LoggingRunner(events)
3653 runner.run(unittest.TestSuite())
3654 expected = ['startTestRun', 'stopTestRun']
3655 self.assertEqual(events, expected)
3656
Antoine Pitrouc63ecee2009-11-10 21:34:48 +00003657 def test_pickle_unpickle(self):
3658 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3659 # required by test_multiprocessing under Windows (in verbose mode).
3660 stream = io.StringIO("foo")
3661 runner = unittest.TextTestRunner(stream)
3662 for protocol in range(2, pickle.HIGHEST_PROTOCOL + 1):
3663 s = pickle.dumps(runner, protocol)
3664 obj = pickle.loads(s)
3665 # StringIO objects never compare equal, a cheap test instead.
3666 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3667
Michael Foord34c94622010-02-10 15:51:42 +00003668 def test_resultclass(self):
3669 def MockResultClass(*args):
3670 return args
3671 STREAM = object()
3672 DESCRIPTIONS = object()
3673 VERBOSITY = object()
3674 runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY,
3675 resultclass=MockResultClass)
3676 self.assertEqual(runner.resultclass, MockResultClass)
3677
3678 expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY)
3679 self.assertEqual(runner._makeResult(), expectedresult)
3680
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003681
Benjamin Petersond2397752009-06-27 23:45:02 +00003682class TestDiscovery(TestCase):
3683
3684 # Heavily mocked tests so I can avoid hitting the filesystem
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003685 def test_get_name_from_path(self):
Benjamin Petersond2397752009-06-27 23:45:02 +00003686 loader = unittest.TestLoader()
Benjamin Petersond2397752009-06-27 23:45:02 +00003687 loader._top_level_dir = '/foo'
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003688 name = loader._get_name_from_path('/foo/bar/baz.py')
3689 self.assertEqual(name, 'bar.baz')
Benjamin Petersond2397752009-06-27 23:45:02 +00003690
3691 if not __debug__:
3692 # asserts are off
3693 return
3694
3695 with self.assertRaises(AssertionError):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003696 loader._get_name_from_path('/bar/baz.py')
Benjamin Petersond2397752009-06-27 23:45:02 +00003697
3698 def test_find_tests(self):
3699 loader = unittest.TestLoader()
3700
3701 original_listdir = os.listdir
3702 def restore_listdir():
3703 os.listdir = original_listdir
3704 original_isfile = os.path.isfile
3705 def restore_isfile():
3706 os.path.isfile = original_isfile
3707 original_isdir = os.path.isdir
3708 def restore_isdir():
3709 os.path.isdir = original_isdir
3710
3711 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003712 'test.foo', 'test-not-a-module.py', 'another_dir'],
Benjamin Petersond2397752009-06-27 23:45:02 +00003713 ['test3.py', 'test4.py', ]]
3714 os.listdir = lambda path: path_lists.pop(0)
3715 self.addCleanup(restore_listdir)
3716
3717 def isdir(path):
3718 return path.endswith('dir')
3719 os.path.isdir = isdir
3720 self.addCleanup(restore_isdir)
3721
3722 def isfile(path):
3723 # another_dir is not a package and so shouldn't be recursed into
3724 return not path.endswith('dir') and not 'another_dir' in path
3725 os.path.isfile = isfile
3726 self.addCleanup(restore_isfile)
3727
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003728 loader._get_module_from_name = lambda path: path + ' module'
Benjamin Petersond2397752009-06-27 23:45:02 +00003729 loader.loadTestsFromModule = lambda module: module + ' tests'
3730
3731 loader._top_level_dir = '/foo'
3732 suite = list(loader._find_tests('/foo', 'test*.py'))
3733
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003734 expected = [name + ' module tests' for name in
3735 ('test1', 'test2')]
3736 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3737 ('test3', 'test4')])
Benjamin Petersond2397752009-06-27 23:45:02 +00003738 self.assertEqual(suite, expected)
3739
3740 def test_find_tests_with_package(self):
3741 loader = unittest.TestLoader()
3742
3743 original_listdir = os.listdir
3744 def restore_listdir():
3745 os.listdir = original_listdir
3746 original_isfile = os.path.isfile
3747 def restore_isfile():
3748 os.path.isfile = original_isfile
3749 original_isdir = os.path.isdir
3750 def restore_isdir():
3751 os.path.isdir = original_isdir
3752
3753 directories = ['a_directory', 'test_directory', 'test_directory2']
3754 path_lists = [directories, [], [], []]
3755 os.listdir = lambda path: path_lists.pop(0)
3756 self.addCleanup(restore_listdir)
3757
3758 os.path.isdir = lambda path: True
3759 self.addCleanup(restore_isdir)
3760
3761 os.path.isfile = lambda path: os.path.basename(path) not in directories
3762 self.addCleanup(restore_isfile)
3763
3764 class Module(object):
3765 paths = []
3766 load_tests_args = []
3767
3768 def __init__(self, path):
3769 self.path = path
3770 self.paths.append(path)
3771 if os.path.basename(path) == 'test_directory':
3772 def load_tests(loader, tests, pattern):
3773 self.load_tests_args.append((loader, tests, pattern))
3774 return 'load_tests'
3775 self.load_tests = load_tests
3776
3777 def __eq__(self, other):
3778 return self.path == other.path
3779
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003780 loader._get_module_from_name = lambda name: Module(name)
Benjamin Petersond2397752009-06-27 23:45:02 +00003781 def loadTestsFromModule(module, use_load_tests):
3782 if use_load_tests:
3783 raise self.failureException('use_load_tests should be False for packages')
3784 return module.path + ' module tests'
3785 loader.loadTestsFromModule = loadTestsFromModule
3786
3787 loader._top_level_dir = '/foo'
3788 # this time no '.py' on the pattern so that it can match
3789 # a test package
3790 suite = list(loader._find_tests('/foo', 'test*'))
3791
3792 # We should have loaded tests from the test_directory package by calling load_tests
3793 # and directly from the test_directory2 package
3794 self.assertEqual(suite,
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003795 ['load_tests', 'test_directory2' + ' module tests'])
3796 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Benjamin Petersond2397752009-06-27 23:45:02 +00003797
3798 # load_tests should have been called once with loader, tests and pattern
3799 self.assertEqual(Module.load_tests_args,
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003800 [(loader, 'test_directory' + ' module tests', 'test*')])
Benjamin Petersond2397752009-06-27 23:45:02 +00003801
3802 def test_discover(self):
3803 loader = unittest.TestLoader()
3804
3805 original_isfile = os.path.isfile
3806 def restore_isfile():
3807 os.path.isfile = original_isfile
3808
3809 os.path.isfile = lambda path: False
3810 self.addCleanup(restore_isfile)
3811
Nick Coghlan6ead5522009-10-18 13:19:33 +00003812 orig_sys_path = sys.path[:]
3813 def restore_path():
3814 sys.path[:] = orig_sys_path
3815 self.addCleanup(restore_path)
Benjamin Petersond2397752009-06-27 23:45:02 +00003816
Nick Coghlan6ead5522009-10-18 13:19:33 +00003817 full_path = os.path.abspath(os.path.normpath('/foo'))
Benjamin Petersond2397752009-06-27 23:45:02 +00003818 with self.assertRaises(ImportError):
3819 loader.discover('/foo/bar', top_level_dir='/foo')
3820
3821 self.assertEqual(loader._top_level_dir, full_path)
3822 self.assertIn(full_path, sys.path)
3823
3824 os.path.isfile = lambda path: True
3825 _find_tests_args = []
3826 def _find_tests(start_dir, pattern):
3827 _find_tests_args.append((start_dir, pattern))
3828 return ['tests']
3829 loader._find_tests = _find_tests
3830 loader.suiteClass = str
3831
3832 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3833
3834 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3835 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3836 self.assertEqual(suite, "['tests']")
3837 self.assertEqual(loader._top_level_dir, top_level_dir)
3838 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlan6ead5522009-10-18 13:19:33 +00003839 self.assertIn(top_level_dir, sys.path)
Benjamin Petersond2397752009-06-27 23:45:02 +00003840
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003841 def test_discover_with_modules_that_fail_to_import(self):
3842 loader = unittest.TestLoader()
3843
3844 listdir = os.listdir
3845 os.listdir = lambda _: ['test_this_does_not_exist.py']
3846 isfile = os.path.isfile
3847 os.path.isfile = lambda _: True
Nick Coghlan6ead5522009-10-18 13:19:33 +00003848 orig_sys_path = sys.path[:]
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003849 def restore():
3850 os.path.isfile = isfile
3851 os.listdir = listdir
Nick Coghlan6ead5522009-10-18 13:19:33 +00003852 sys.path[:] = orig_sys_path
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003853 self.addCleanup(restore)
3854
3855 suite = loader.discover('.')
Nick Coghlan6ead5522009-10-18 13:19:33 +00003856 self.assertIn(os.getcwd(), sys.path)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003857 self.assertEqual(suite.countTestCases(), 1)
3858 test = list(list(suite)[0])[0] # extract test from suite
3859
3860 with self.assertRaises(ImportError):
3861 test.test_this_does_not_exist()
3862
Benjamin Petersond2397752009-06-27 23:45:02 +00003863 def test_command_line_handling_parseArgs(self):
3864 # Haha - take that uninstantiable class
3865 program = object.__new__(TestProgram)
3866
3867 args = []
3868 def do_discovery(argv):
3869 args.extend(argv)
3870 program._do_discovery = do_discovery
3871 program.parseArgs(['something', 'discover'])
3872 self.assertEqual(args, [])
3873
3874 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3875 self.assertEqual(args, ['foo', 'bar'])
3876
3877 def test_command_line_handling_do_discovery_too_many_arguments(self):
3878 class Stop(Exception):
3879 pass
3880 def usageExit():
3881 raise Stop
3882
3883 program = object.__new__(TestProgram)
3884 program.usageExit = usageExit
3885
3886 with self.assertRaises(Stop):
3887 # too many args
3888 program._do_discovery(['one', 'two', 'three', 'four'])
3889
3890
3891 def test_command_line_handling_do_discovery_calls_loader(self):
3892 program = object.__new__(TestProgram)
3893
3894 class Loader(object):
3895 args = []
3896 def discover(self, start_dir, pattern, top_level_dir):
3897 self.args.append((start_dir, pattern, top_level_dir))
3898 return 'tests'
3899
3900 program._do_discovery(['-v'], Loader=Loader)
3901 self.assertEqual(program.verbosity, 2)
3902 self.assertEqual(program.test, 'tests')
3903 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3904
3905 Loader.args = []
3906 program = object.__new__(TestProgram)
3907 program._do_discovery(['--verbose'], Loader=Loader)
3908 self.assertEqual(program.test, 'tests')
3909 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3910
3911 Loader.args = []
3912 program = object.__new__(TestProgram)
3913 program._do_discovery([], Loader=Loader)
3914 self.assertEqual(program.test, 'tests')
3915 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3916
3917 Loader.args = []
3918 program = object.__new__(TestProgram)
3919 program._do_discovery(['fish'], Loader=Loader)
3920 self.assertEqual(program.test, 'tests')
3921 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3922
3923 Loader.args = []
3924 program = object.__new__(TestProgram)
3925 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3926 self.assertEqual(program.test, 'tests')
3927 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3928
3929 Loader.args = []
3930 program = object.__new__(TestProgram)
3931 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3932 self.assertEqual(program.test, 'tests')
3933 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3934
3935 Loader.args = []
3936 program = object.__new__(TestProgram)
3937 program._do_discovery(['-s', 'fish'], Loader=Loader)
3938 self.assertEqual(program.test, 'tests')
3939 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3940
3941 Loader.args = []
3942 program = object.__new__(TestProgram)
3943 program._do_discovery(['-t', 'fish'], Loader=Loader)
3944 self.assertEqual(program.test, 'tests')
3945 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3946
3947 Loader.args = []
3948 program = object.__new__(TestProgram)
3949 program._do_discovery(['-p', 'fish'], Loader=Loader)
3950 self.assertEqual(program.test, 'tests')
3951 self.assertEqual(Loader.args, [('.', 'fish', None)])
3952
3953 Loader.args = []
3954 program = object.__new__(TestProgram)
3955 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3956 self.assertEqual(program.test, 'tests')
3957 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3958 self.assertEqual(program.verbosity, 2)
3959
3960
Benjamin Peterson847a4112010-03-14 15:04:17 +00003961class TestSetups(unittest.TestCase):
3962
3963 def getRunner(self):
3964 return unittest.TextTestRunner(resultclass=resultFactory,
3965 stream=io.StringIO())
3966 def runTests(self, *cases):
3967 suite = unittest.TestSuite()
3968 for case in cases:
3969 tests = unittest.defaultTestLoader.loadTestsFromTestCase(case)
3970 suite.addTests(tests)
3971
3972 runner = self.getRunner()
3973
3974 # creating a nested suite exposes some potential bugs
3975 realSuite = unittest.TestSuite()
3976 realSuite.addTest(suite)
3977 # adding empty suites to the end exposes potential bugs
3978 suite.addTest(unittest.TestSuite())
3979 realSuite.addTest(unittest.TestSuite())
3980 return runner.run(realSuite)
3981
3982 def test_setup_class(self):
3983 class Test(unittest.TestCase):
3984 setUpCalled = 0
3985 @classmethod
3986 def setUpClass(cls):
3987 Test.setUpCalled += 1
3988 unittest.TestCase.setUpClass()
3989 def test_one(self):
3990 pass
3991 def test_two(self):
3992 pass
3993
3994 result = self.runTests(Test)
3995
3996 self.assertEqual(Test.setUpCalled, 1)
3997 self.assertEqual(result.testsRun, 2)
3998 self.assertEqual(len(result.errors), 0)
3999
4000 def test_teardown_class(self):
4001 class Test(unittest.TestCase):
4002 tearDownCalled = 0
4003 @classmethod
4004 def tearDownClass(cls):
4005 Test.tearDownCalled += 1
4006 unittest.TestCase.tearDownClass()
4007 def test_one(self):
4008 pass
4009 def test_two(self):
4010 pass
4011
4012 result = self.runTests(Test)
4013
4014 self.assertEqual(Test.tearDownCalled, 1)
4015 self.assertEqual(result.testsRun, 2)
4016 self.assertEqual(len(result.errors), 0)
4017
4018 def test_teardown_class_two_classes(self):
4019 class Test(unittest.TestCase):
4020 tearDownCalled = 0
4021 @classmethod
4022 def tearDownClass(cls):
4023 Test.tearDownCalled += 1
4024 unittest.TestCase.tearDownClass()
4025 def test_one(self):
4026 pass
4027 def test_two(self):
4028 pass
4029
4030 class Test2(unittest.TestCase):
4031 tearDownCalled = 0
4032 @classmethod
4033 def tearDownClass(cls):
4034 Test2.tearDownCalled += 1
4035 unittest.TestCase.tearDownClass()
4036 def test_one(self):
4037 pass
4038 def test_two(self):
4039 pass
4040
4041 result = self.runTests(Test, Test2)
4042
4043 self.assertEqual(Test.tearDownCalled, 1)
4044 self.assertEqual(Test2.tearDownCalled, 1)
4045 self.assertEqual(result.testsRun, 4)
4046 self.assertEqual(len(result.errors), 0)
4047
4048 def test_error_in_setupclass(self):
4049 class BrokenTest(unittest.TestCase):
4050 @classmethod
4051 def setUpClass(cls):
4052 raise TypeError('foo')
4053 def test_one(self):
4054 pass
4055 def test_two(self):
4056 pass
4057
4058 result = self.runTests(BrokenTest)
4059
4060 self.assertEqual(result.testsRun, 0)
4061 self.assertEqual(len(result.errors), 1)
4062 error, _ = result.errors[0]
4063 self.assertEqual(str(error),
4064 'classSetUp (%s.BrokenTest)' % __name__)
4065
4066 def test_error_in_teardown_class(self):
4067 class Test(unittest.TestCase):
4068 tornDown = 0
4069 @classmethod
4070 def tearDownClass(cls):
4071 Test.tornDown += 1
4072 raise TypeError('foo')
4073 def test_one(self):
4074 pass
4075 def test_two(self):
4076 pass
4077
4078 class Test2(unittest.TestCase):
4079 tornDown = 0
4080 @classmethod
4081 def tearDownClass(cls):
4082 Test2.tornDown += 1
4083 raise TypeError('foo')
4084 def test_one(self):
4085 pass
4086 def test_two(self):
4087 pass
4088
4089 result = self.runTests(Test, Test2)
4090 self.assertEqual(result.testsRun, 4)
4091 self.assertEqual(len(result.errors), 2)
4092 self.assertEqual(Test.tornDown, 1)
4093 self.assertEqual(Test2.tornDown, 1)
4094
4095 error, _ = result.errors[0]
4096 self.assertEqual(str(error),
4097 'classTearDown (%s.Test)' % __name__)
4098
4099 def test_class_not_torndown_when_setup_fails(self):
4100 class Test(unittest.TestCase):
4101 tornDown = False
4102 @classmethod
4103 def setUpClass(cls):
4104 raise TypeError
4105 @classmethod
4106 def tearDownClass(cls):
4107 Test.tornDown = True
4108 raise TypeError('foo')
4109 def test_one(self):
4110 pass
4111
4112 self.runTests(Test)
4113 self.assertFalse(Test.tornDown)
4114
4115 def test_class_not_setup_or_torndown_when_skipped(self):
4116 class Test(unittest.TestCase):
4117 classSetUp = False
4118 tornDown = False
4119 @classmethod
4120 def setUpClass(cls):
4121 Test.classSetUp = True
4122 @classmethod
4123 def tearDownClass(cls):
4124 Test.tornDown = True
4125 def test_one(self):
4126 pass
4127
4128 Test = unittest.skip("hop")(Test)
4129 self.runTests(Test)
4130 self.assertFalse(Test.classSetUp)
4131 self.assertFalse(Test.tornDown)
4132
4133 def test_setup_teardown_order_with_pathological_suite(self):
4134 results = []
4135
4136 class Module1(object):
4137 @staticmethod
4138 def setUpModule():
4139 results.append('Module1.setUpModule')
4140 @staticmethod
4141 def tearDownModule():
4142 results.append('Module1.tearDownModule')
4143
4144 class Module2(object):
4145 @staticmethod
4146 def setUpModule():
4147 results.append('Module2.setUpModule')
4148 @staticmethod
4149 def tearDownModule():
4150 results.append('Module2.tearDownModule')
4151
4152 class Test1(unittest.TestCase):
4153 @classmethod
4154 def setUpClass(cls):
4155 results.append('setup 1')
4156 @classmethod
4157 def tearDownClass(cls):
4158 results.append('teardown 1')
4159 def testOne(self):
4160 results.append('Test1.testOne')
4161 def testTwo(self):
4162 results.append('Test1.testTwo')
4163
4164 class Test2(unittest.TestCase):
4165 @classmethod
4166 def setUpClass(cls):
4167 results.append('setup 2')
4168 @classmethod
4169 def tearDownClass(cls):
4170 results.append('teardown 2')
4171 def testOne(self):
4172 results.append('Test2.testOne')
4173 def testTwo(self):
4174 results.append('Test2.testTwo')
4175
4176 class Test3(unittest.TestCase):
4177 @classmethod
4178 def setUpClass(cls):
4179 results.append('setup 3')
4180 @classmethod
4181 def tearDownClass(cls):
4182 results.append('teardown 3')
4183 def testOne(self):
4184 results.append('Test3.testOne')
4185 def testTwo(self):
4186 results.append('Test3.testTwo')
4187
4188 Test1.__module__ = Test2.__module__ = 'Module'
4189 Test3.__module__ = 'Module2'
4190 sys.modules['Module'] = Module1
4191 sys.modules['Module2'] = Module2
4192
4193 first = unittest.TestSuite((Test1('testOne'),))
4194 second = unittest.TestSuite((Test1('testTwo'),))
4195 third = unittest.TestSuite((Test2('testOne'),))
4196 fourth = unittest.TestSuite((Test2('testTwo'),))
4197 fifth = unittest.TestSuite((Test3('testOne'),))
4198 sixth = unittest.TestSuite((Test3('testTwo'),))
4199 suite = unittest.TestSuite((first, second, third, fourth, fifth, sixth))
4200
4201 runner = self.getRunner()
4202 result = runner.run(suite)
4203 self.assertEqual(result.testsRun, 6)
4204 self.assertEqual(len(result.errors), 0)
4205
4206 self.assertEqual(results,
4207 ['Module1.setUpModule', 'setup 1',
4208 'Test1.testOne', 'Test1.testTwo', 'teardown 1',
4209 'setup 2', 'Test2.testOne', 'Test2.testTwo',
4210 'teardown 2', 'Module1.tearDownModule',
4211 'Module2.setUpModule', 'setup 3',
4212 'Test3.testOne', 'Test3.testTwo',
4213 'teardown 3', 'Module2.tearDownModule'])
4214
4215 def test_setup_module(self):
4216 class Module(object):
4217 moduleSetup = 0
4218 @staticmethod
4219 def setUpModule():
4220 Module.moduleSetup += 1
4221
4222 class Test(unittest.TestCase):
4223 def test_one(self):
4224 pass
4225 def test_two(self):
4226 pass
4227 Test.__module__ = 'Module'
4228 sys.modules['Module'] = Module
4229
4230 result = self.runTests(Test)
4231 self.assertEqual(Module.moduleSetup, 1)
4232 self.assertEqual(result.testsRun, 2)
4233 self.assertEqual(len(result.errors), 0)
4234
4235 def test_error_in_setup_module(self):
4236 class Module(object):
4237 moduleSetup = 0
4238 moduleTornDown = 0
4239 @staticmethod
4240 def setUpModule():
4241 Module.moduleSetup += 1
4242 raise TypeError('foo')
4243 @staticmethod
4244 def tearDownModule():
4245 Module.moduleTornDown += 1
4246
4247 class Test(unittest.TestCase):
4248 classSetUp = False
4249 classTornDown = False
4250 @classmethod
4251 def setUpClass(cls):
4252 Test.classSetUp = True
4253 @classmethod
4254 def tearDownClass(cls):
4255 Test.classTornDown = True
4256 def test_one(self):
4257 pass
4258 def test_two(self):
4259 pass
4260
4261 class Test2(unittest.TestCase):
4262 def test_one(self):
4263 pass
4264 def test_two(self):
4265 pass
4266 Test.__module__ = 'Module'
4267 Test2.__module__ = 'Module'
4268 sys.modules['Module'] = Module
4269
4270 result = self.runTests(Test, Test2)
4271 self.assertEqual(Module.moduleSetup, 1)
4272 self.assertEqual(Module.moduleTornDown, 0)
4273 self.assertEqual(result.testsRun, 0)
4274 self.assertFalse(Test.classSetUp)
4275 self.assertFalse(Test.classTornDown)
4276 self.assertEqual(len(result.errors), 1)
4277 error, _ = result.errors[0]
4278 self.assertEqual(str(error), 'setUpModule (Module)')
4279
4280 def test_testcase_with_missing_module(self):
4281 class Test(unittest.TestCase):
4282 def test_one(self):
4283 pass
4284 def test_two(self):
4285 pass
4286 Test.__module__ = 'Module'
4287 sys.modules.pop('Module', None)
4288
4289 result = self.runTests(Test)
4290 self.assertEqual(result.testsRun, 2)
4291
4292 def test_teardown_module(self):
4293 class Module(object):
4294 moduleTornDown = 0
4295 @staticmethod
4296 def tearDownModule():
4297 Module.moduleTornDown += 1
4298
4299 class Test(unittest.TestCase):
4300 def test_one(self):
4301 pass
4302 def test_two(self):
4303 pass
4304 Test.__module__ = 'Module'
4305 sys.modules['Module'] = Module
4306
4307 result = self.runTests(Test)
4308 self.assertEqual(Module.moduleTornDown, 1)
4309 self.assertEqual(result.testsRun, 2)
4310 self.assertEqual(len(result.errors), 0)
4311
4312 def test_error_in_teardown_module(self):
4313 class Module(object):
4314 moduleTornDown = 0
4315 @staticmethod
4316 def tearDownModule():
4317 Module.moduleTornDown += 1
4318 raise TypeError('foo')
4319
4320 class Test(unittest.TestCase):
4321 classSetUp = False
4322 classTornDown = False
4323 @classmethod
4324 def setUpClass(cls):
4325 Test.classSetUp = True
4326 @classmethod
4327 def tearDownClass(cls):
4328 Test.classTornDown = True
4329 def test_one(self):
4330 pass
4331 def test_two(self):
4332 pass
4333
4334 class Test2(unittest.TestCase):
4335 def test_one(self):
4336 pass
4337 def test_two(self):
4338 pass
4339 Test.__module__ = 'Module'
4340 Test2.__module__ = 'Module'
4341 sys.modules['Module'] = Module
4342
4343 result = self.runTests(Test, Test2)
4344 self.assertEqual(Module.moduleTornDown, 1)
4345 self.assertEqual(result.testsRun, 4)
4346 self.assertTrue(Test.classSetUp)
4347 self.assertTrue(Test.classTornDown)
4348 self.assertEqual(len(result.errors), 1)
4349 error, _ = result.errors[0]
4350 self.assertEqual(str(error), 'tearDownModule (Module)')
4351
Jim Fultonfafd8742004-08-28 15:22:12 +00004352######################################################################
4353## Main
4354######################################################################
4355
4356def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004357 support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00004358 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Benjamin Peterson25c95f12009-05-08 20:42:26 +00004359 Test_TestSkipping, Test_Assertions, TestLongMessage,
Benjamin Peterson847a4112010-03-14 15:04:17 +00004360 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner,
4361 Test_OldTestResult, TestSetups)
Jim Fultonfafd8742004-08-28 15:22:12 +00004362
Guido van Rossumd8faa362007-04-27 19:54:29 +00004363if __name__ == "__main__":
Jim Fultonfafd8742004-08-28 15:22:12 +00004364 test_main()