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