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