blob: b6100b15147e15374261280211d199b5ea672489 [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
2849 def testSynonymAssertMethodNames(self):
2850 """Test undocumented method name synonyms.
2851
2852 Please do not use these methods names in your own code.
2853
2854 This test confirms their continued existence and functionality
2855 in order to avoid breaking existing code.
2856 """
2857 self.assertNotEquals(3, 5)
2858 self.assertEquals(3, 3)
2859 self.assertAlmostEquals(2.0, 2.0)
2860 self.assertNotAlmostEquals(3.0, 5.0)
2861 self.assert_(True)
2862
2863 def testPendingDeprecationMethodNames(self):
2864 """Test fail* methods pending deprecation, they will warn in 3.2.
2865
2866 Do not use these methods. They will go away in 3.3.
2867 """
Benjamin Peterson6bcbad52009-06-30 23:45:41 +00002868 old = (
2869 (self.failIfEqual, (3, 5)),
2870 (self.failUnlessEqual, (3, 3)),
2871 (self.failUnlessAlmostEqual, (2.0, 2.0)),
2872 (self.failIfAlmostEqual, (3.0, 5.0)),
2873 (self.failUnless, (True,)),
2874 (self.failUnlessRaises, (TypeError, lambda _: 3.14 + 'spam')),
2875 (self.failIf, (False,))
2876 )
2877 for meth, args in old:
2878 with warnings.catch_warnings(record=True) as w:
2879 meth(*args)
2880 self.assertEqual(len(w), 1)
2881 self.assertIs(w[0].category, DeprecationWarning)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002882
2883 def testDeepcopy(self):
2884 # Issue: 5660
2885 class TestableTest(TestCase):
2886 def testNothing(self):
2887 pass
2888
2889 test = TestableTest('testNothing')
2890
2891 # This shouldn't blow up
2892 deepcopy(test)
2893
Benjamin Peterson5254c042009-03-23 22:25:03 +00002894
2895class Test_TestSkipping(TestCase):
2896
2897 def test_skipping(self):
2898 class Foo(unittest.TestCase):
2899 def test_skip_me(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00002900 self.skipTest("skip")
Benjamin Peterson5254c042009-03-23 22:25:03 +00002901 events = []
2902 result = LoggingResult(events)
2903 test = Foo("test_skip_me")
2904 test.run(result)
2905 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2906 self.assertEqual(result.skipped, [(test, "skip")])
2907
2908 # Try letting setUp skip the test now.
2909 class Foo(unittest.TestCase):
2910 def setUp(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00002911 self.skipTest("testing")
Benjamin Peterson5254c042009-03-23 22:25:03 +00002912 def test_nothing(self): pass
2913 events = []
2914 result = LoggingResult(events)
2915 test = Foo("test_nothing")
2916 test.run(result)
2917 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2918 self.assertEqual(result.skipped, [(test, "testing")])
2919 self.assertEqual(result.testsRun, 1)
2920
2921 def test_skipping_decorators(self):
2922 op_table = ((unittest.skipUnless, False, True),
2923 (unittest.skipIf, True, False))
2924 for deco, do_skip, dont_skip in op_table:
2925 class Foo(unittest.TestCase):
2926 @deco(do_skip, "testing")
2927 def test_skip(self): pass
2928
2929 @deco(dont_skip, "testing")
2930 def test_dont_skip(self): pass
2931 test_do_skip = Foo("test_skip")
2932 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002933 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002934 events = []
2935 result = LoggingResult(events)
2936 suite.run(result)
2937 self.assertEqual(len(result.skipped), 1)
2938 expected = ['startTest', 'addSkip', 'stopTest',
2939 'startTest', 'addSuccess', 'stopTest']
2940 self.assertEqual(events, expected)
2941 self.assertEqual(result.testsRun, 2)
2942 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
2943 self.assertTrue(result.wasSuccessful())
2944
2945 def test_skip_class(self):
2946 @unittest.skip("testing")
2947 class Foo(unittest.TestCase):
2948 def test_1(self):
2949 record.append(1)
2950 record = []
2951 result = unittest.TestResult()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002952 test = Foo("test_1")
2953 suite = unittest.TestSuite([test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002954 suite.run(result)
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002955 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002956 self.assertEqual(record, [])
2957
2958 def test_expected_failure(self):
2959 class Foo(unittest.TestCase):
2960 @unittest.expectedFailure
2961 def test_die(self):
2962 self.fail("help me!")
2963 events = []
2964 result = LoggingResult(events)
2965 test = Foo("test_die")
2966 test.run(result)
2967 self.assertEqual(events,
2968 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Peterson52baa292009-03-24 00:56:30 +00002969 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson5254c042009-03-23 22:25:03 +00002970 self.assertTrue(result.wasSuccessful())
2971
2972 def test_unexpected_success(self):
2973 class Foo(unittest.TestCase):
2974 @unittest.expectedFailure
2975 def test_die(self):
2976 pass
2977 events = []
2978 result = LoggingResult(events)
2979 test = Foo("test_die")
2980 test.run(result)
2981 self.assertEqual(events,
2982 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
2983 self.assertFalse(result.failures)
Benjamin Peterson52baa292009-03-24 00:56:30 +00002984 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002985 self.assertTrue(result.wasSuccessful())
2986
2987
2988
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00002989class Test_Assertions(TestCase):
2990 def test_AlmostEqual(self):
Benjamin Petersone1759f82009-06-30 23:35:19 +00002991 self.assertAlmostEqual(1.00000001, 1.0)
2992 self.assertNotAlmostEqual(1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002993 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00002994 self.assertAlmostEqual, 1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002995 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00002996 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00002997
Benjamin Petersone1759f82009-06-30 23:35:19 +00002998 self.assertAlmostEqual(1.1, 1.0, places=0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002999 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003000 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003001
Benjamin Petersone1759f82009-06-30 23:35:19 +00003002 self.assertAlmostEqual(0, .1+.1j, places=0)
3003 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003004 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003005 self.assertAlmostEqual, 0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003006 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003007 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003008
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003009 self.assertAlmostEqual(float('inf'), float('inf'))
3010 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3011 float('inf'), float('inf'))
3012
3013
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003014 def test_assertRaises(self):
3015 def _raise(e):
3016 raise e
3017 self.assertRaises(KeyError, _raise, KeyError)
3018 self.assertRaises(KeyError, _raise, KeyError("key"))
3019 try:
3020 self.assertRaises(KeyError, lambda: None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003021 except self.failureException as e:
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003022 self.assert_("KeyError not raised" in str(e), str(e))
3023 else:
3024 self.fail("assertRaises() didn't fail")
3025 try:
3026 self.assertRaises(KeyError, _raise, ValueError)
3027 except ValueError:
3028 pass
3029 else:
3030 self.fail("assertRaises() didn't let exception pass through")
3031 with self.assertRaises(KeyError):
3032 raise KeyError
3033 with self.assertRaises(KeyError):
3034 raise KeyError("key")
3035 try:
3036 with self.assertRaises(KeyError):
3037 pass
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003038 except self.failureException as e:
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003039 self.assert_("KeyError not raised" in str(e), str(e))
3040 else:
3041 self.fail("assertRaises() didn't fail")
3042 try:
3043 with self.assertRaises(KeyError):
3044 raise ValueError
3045 except ValueError:
3046 pass
3047 else:
3048 self.fail("assertRaises() didn't let exception pass through")
3049
3050
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003051class TestLongMessage(TestCase):
3052 """Test that the individual asserts honour longMessage.
3053 This actually tests all the message behaviour for
3054 asserts that use longMessage."""
3055
3056 def setUp(self):
3057 class TestableTestFalse(TestCase):
3058 longMessage = False
3059 failureException = self.failureException
3060
3061 def testTest(self):
3062 pass
3063
3064 class TestableTestTrue(TestCase):
3065 longMessage = True
3066 failureException = self.failureException
3067
3068 def testTest(self):
3069 pass
3070
3071 self.testableTrue = TestableTestTrue('testTest')
3072 self.testableFalse = TestableTestFalse('testTest')
3073
3074 def testDefault(self):
3075 self.assertFalse(TestCase.longMessage)
3076
3077 def test_formatMsg(self):
3078 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3079 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3080
3081 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3082 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3083
3084 def assertMessages(self, methodName, args, errors):
3085 def getMethod(i):
3086 useTestableFalse = i < 2
3087 if useTestableFalse:
3088 test = self.testableFalse
3089 else:
3090 test = self.testableTrue
3091 return getattr(test, methodName)
3092
3093 for i, expected_regexp in enumerate(errors):
3094 testMethod = getMethod(i)
3095 kwargs = {}
3096 withMsg = i % 2
3097 if withMsg:
3098 kwargs = {"msg": "oops"}
3099
3100 with self.assertRaisesRegexp(self.failureException,
3101 expected_regexp=expected_regexp):
3102 testMethod(*args, **kwargs)
3103
3104 def testAssertTrue(self):
3105 self.assertMessages('assertTrue', (False,),
3106 ["^False is not True$", "^oops$", "^False is not True$",
3107 "^False is not True : oops$"])
3108
3109 def testAssertFalse(self):
3110 self.assertMessages('assertFalse', (True,),
3111 ["^True is not False$", "^oops$", "^True is not False$",
3112 "^True is not False : oops$"])
3113
3114 def testNotEqual(self):
3115 self.assertMessages('assertNotEqual', (1, 1),
3116 ["^1 == 1$", "^oops$", "^1 == 1$",
3117 "^1 == 1 : oops$"])
3118
3119 def testAlmostEqual(self):
3120 self.assertMessages('assertAlmostEqual', (1, 2),
3121 ["^1 != 2 within 7 places$", "^oops$",
3122 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3123
3124 def testNotAlmostEqual(self):
3125 self.assertMessages('assertNotAlmostEqual', (1, 1),
3126 ["^1 == 1 within 7 places$", "^oops$",
3127 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3128
3129 def test_baseAssertEqual(self):
3130 self.assertMessages('_baseAssertEqual', (1, 2),
3131 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3132
3133 def testAssertSequenceEqual(self):
3134 # Error messages are multiline so not testing on full message
3135 # assertTupleEqual and assertListEqual delegate to this method
3136 self.assertMessages('assertSequenceEqual', ([], [None]),
3137 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3138 r"\+ \[None\] : oops$"])
3139
3140 def testAssertSetEqual(self):
3141 self.assertMessages('assertSetEqual', (set(), set([None])),
3142 ["None$", "^oops$", "None$",
3143 "None : oops$"])
3144
3145 def testAssertIn(self):
3146 self.assertMessages('assertIn', (None, []),
3147 ['^None not found in \[\]$', "^oops$",
3148 '^None not found in \[\]$',
3149 '^None not found in \[\] : oops$'])
3150
3151 def testAssertNotIn(self):
3152 self.assertMessages('assertNotIn', (None, [None]),
3153 ['^None unexpectedly found in \[None\]$', "^oops$",
3154 '^None unexpectedly found in \[None\]$',
3155 '^None unexpectedly found in \[None\] : oops$'])
3156
3157 def testAssertDictEqual(self):
3158 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3159 [r"\+ \{'key': 'value'\}$", "^oops$",
3160 "\+ \{'key': 'value'\}$",
3161 "\+ \{'key': 'value'\} : oops$"])
3162
3163 def testAssertDictContainsSubset(self):
3164 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3165 ["^Missing: 'key'$", "^oops$",
3166 "^Missing: 'key'$",
3167 "^Missing: 'key' : oops$"])
3168
3169 def testAssertSameElements(self):
3170 self.assertMessages('assertSameElements', ([], [None]),
3171 [r"\[None\]$", "^oops$",
3172 r"\[None\]$",
3173 r"\[None\] : oops$"])
3174
3175 def testAssertMultiLineEqual(self):
3176 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3177 [r"\+ foo$", "^oops$",
3178 r"\+ foo$",
3179 r"\+ foo : oops$"])
3180
3181 def testAssertLess(self):
3182 self.assertMessages('assertLess', (2, 1),
3183 ["^2 not less than 1$", "^oops$",
3184 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3185
3186 def testAssertLessEqual(self):
3187 self.assertMessages('assertLessEqual', (2, 1),
3188 ["^2 not less than or equal to 1$", "^oops$",
3189 "^2 not less than or equal to 1$",
3190 "^2 not less than or equal to 1 : oops$"])
3191
3192 def testAssertGreater(self):
3193 self.assertMessages('assertGreater', (1, 2),
3194 ["^1 not greater than 2$", "^oops$",
3195 "^1 not greater than 2$",
3196 "^1 not greater than 2 : oops$"])
3197
3198 def testAssertGreaterEqual(self):
3199 self.assertMessages('assertGreaterEqual', (1, 2),
3200 ["^1 not greater than or equal to 2$", "^oops$",
3201 "^1 not greater than or equal to 2$",
3202 "^1 not greater than or equal to 2 : oops$"])
3203
3204 def testAssertIsNone(self):
3205 self.assertMessages('assertIsNone', ('not None',),
3206 ["^'not None' is not None$", "^oops$",
3207 "^'not None' is not None$",
3208 "^'not None' is not None : oops$"])
3209
3210 def testAssertIsNotNone(self):
3211 self.assertMessages('assertIsNotNone', (None,),
3212 ["^unexpectedly None$", "^oops$",
3213 "^unexpectedly None$",
3214 "^unexpectedly None : oops$"])
3215
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00003216 def testAssertIs(self):
3217 self.assertMessages('assertIs', (None, 'foo'),
3218 ["^None is not 'foo'$", "^oops$",
3219 "^None is not 'foo'$",
3220 "^None is not 'foo' : oops$"])
3221
3222 def testAssertIsNot(self):
3223 self.assertMessages('assertIsNot', (None, None),
3224 ["^unexpectedly identical: None$", "^oops$",
3225 "^unexpectedly identical: None$",
3226 "^unexpectedly identical: None : oops$"])
3227
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003228
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003229class TestCleanUp(TestCase):
3230
3231 def testCleanUp(self):
3232 class TestableTest(TestCase):
3233 def testNothing(self):
3234 pass
3235
3236 test = TestableTest('testNothing')
3237 self.assertEqual(test._cleanups, [])
3238
3239 cleanups = []
3240
3241 def cleanup1(*args, **kwargs):
3242 cleanups.append((1, args, kwargs))
3243
3244 def cleanup2(*args, **kwargs):
3245 cleanups.append((2, args, kwargs))
3246
3247 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3248 test.addCleanup(cleanup2)
3249
3250 self.assertEqual(test._cleanups,
3251 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3252 (cleanup2, (), {})])
3253
3254 result = test.doCleanups()
3255 self.assertTrue(result)
3256
3257 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3258
3259 def testCleanUpWithErrors(self):
3260 class TestableTest(TestCase):
3261 def testNothing(self):
3262 pass
3263
3264 class MockResult(object):
3265 errors = []
3266 def addError(self, test, exc_info):
3267 self.errors.append((test, exc_info))
3268
3269 result = MockResult()
3270 test = TestableTest('testNothing')
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00003271 test._resultForDoCleanups = result
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003272
3273 exc1 = Exception('foo')
3274 exc2 = Exception('bar')
3275 def cleanup1():
3276 raise exc1
3277
3278 def cleanup2():
3279 raise exc2
3280
3281 test.addCleanup(cleanup1)
3282 test.addCleanup(cleanup2)
3283
3284 self.assertFalse(test.doCleanups())
3285
3286 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3287 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3288 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3289
3290 def testCleanupInRun(self):
3291 blowUp = False
3292 ordering = []
3293
3294 class TestableTest(TestCase):
3295 def setUp(self):
3296 ordering.append('setUp')
3297 if blowUp:
3298 raise Exception('foo')
3299
3300 def testNothing(self):
3301 ordering.append('test')
3302
3303 def tearDown(self):
3304 ordering.append('tearDown')
3305
3306 test = TestableTest('testNothing')
3307
3308 def cleanup1():
3309 ordering.append('cleanup1')
3310 def cleanup2():
3311 ordering.append('cleanup2')
3312 test.addCleanup(cleanup1)
3313 test.addCleanup(cleanup2)
3314
3315 def success(some_test):
3316 self.assertEqual(some_test, test)
3317 ordering.append('success')
3318
3319 result = unittest.TestResult()
3320 result.addSuccess = success
3321
3322 test.run(result)
3323 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3324 'cleanup2', 'cleanup1', 'success'])
3325
3326 blowUp = True
3327 ordering = []
3328 test = TestableTest('testNothing')
3329 test.addCleanup(cleanup1)
3330 test.run(result)
3331 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3332
3333
3334class Test_TestProgram(TestCase):
3335
3336 # Horrible white box test
3337 def testNoExit(self):
3338 result = object()
3339 test = object()
3340
3341 class FakeRunner(object):
3342 def run(self, test):
3343 self.test = test
3344 return result
3345
3346 runner = FakeRunner()
3347
Benjamin Petersond2397752009-06-27 23:45:02 +00003348 oldParseArgs = TestProgram.parseArgs
3349 def restoreParseArgs():
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003350 TestProgram.parseArgs = oldParseArgs
Benjamin Petersond2397752009-06-27 23:45:02 +00003351 TestProgram.parseArgs = lambda *args: None
3352 self.addCleanup(restoreParseArgs)
3353
3354 def removeTest():
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003355 del TestProgram.test
Benjamin Petersond2397752009-06-27 23:45:02 +00003356 TestProgram.test = test
3357 self.addCleanup(removeTest)
3358
3359 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3360
3361 self.assertEqual(program.result, result)
3362 self.assertEqual(runner.test, test)
3363 self.assertEqual(program.verbosity, 2)
3364
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003365 class FooBar(unittest.TestCase):
3366 def testPass(self):
3367 assert True
3368 def testFail(self):
3369 assert False
3370
3371 class FooBarLoader(unittest.TestLoader):
3372 """Test loader that returns a suite containing FooBar."""
3373 def loadTestsFromModule(self, module):
3374 return self.suiteClass(
3375 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3376
3377
3378 def test_NonExit(self):
3379 program = unittest.main(exit=False,
3380 argv=["foobar"],
3381 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3382 testLoader=self.FooBarLoader())
3383 self.assertTrue(hasattr(program, 'result'))
3384
3385
3386 def test_Exit(self):
3387 self.assertRaises(
3388 SystemExit,
3389 unittest.main,
3390 argv=["foobar"],
3391 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3392 exit=True,
3393 testLoader=self.FooBarLoader())
3394
3395
3396 def test_ExitAsDefault(self):
3397 self.assertRaises(
3398 SystemExit,
3399 unittest.main,
3400 argv=["foobar"],
3401 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3402 testLoader=self.FooBarLoader())
3403
3404
3405class Test_TextTestRunner(TestCase):
3406 """Tests for TextTestRunner."""
3407
3408 def test_works_with_result_without_startTestRun_stopTestRun(self):
3409 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3410 separator2 = ''
3411 def printErrors(self):
3412 pass
3413
3414 class Runner(unittest.TextTestRunner):
3415 def __init__(self):
3416 super(Runner, self).__init__(io.StringIO())
3417
3418 def _makeResult(self):
3419 return OldTextResult()
3420
3421 runner = Runner()
3422 runner.run(unittest.TestSuite())
3423
3424 def test_startTestRun_stopTestRun_called(self):
3425 class LoggingTextResult(LoggingResult):
3426 separator2 = ''
3427 def printErrors(self):
3428 pass
3429
3430 class LoggingRunner(unittest.TextTestRunner):
3431 def __init__(self, events):
3432 super(LoggingRunner, self).__init__(io.StringIO())
3433 self._events = events
3434
3435 def _makeResult(self):
3436 return LoggingTextResult(self._events)
3437
3438 events = []
3439 runner = LoggingRunner(events)
3440 runner.run(unittest.TestSuite())
3441 expected = ['startTestRun', 'stopTestRun']
3442 self.assertEqual(events, expected)
3443
3444
Benjamin Petersond2397752009-06-27 23:45:02 +00003445class TestDiscovery(TestCase):
3446
3447 # Heavily mocked tests so I can avoid hitting the filesystem
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003448 def test_get_name_from_path(self):
Benjamin Petersond2397752009-06-27 23:45:02 +00003449 loader = unittest.TestLoader()
Benjamin Petersond2397752009-06-27 23:45:02 +00003450 loader._top_level_dir = '/foo'
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003451 name = loader._get_name_from_path('/foo/bar/baz.py')
3452 self.assertEqual(name, 'bar.baz')
Benjamin Petersond2397752009-06-27 23:45:02 +00003453
3454 if not __debug__:
3455 # asserts are off
3456 return
3457
3458 with self.assertRaises(AssertionError):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003459 loader._get_name_from_path('/bar/baz.py')
Benjamin Petersond2397752009-06-27 23:45:02 +00003460
3461 def test_find_tests(self):
3462 loader = unittest.TestLoader()
3463
3464 original_listdir = os.listdir
3465 def restore_listdir():
3466 os.listdir = original_listdir
3467 original_isfile = os.path.isfile
3468 def restore_isfile():
3469 os.path.isfile = original_isfile
3470 original_isdir = os.path.isdir
3471 def restore_isdir():
3472 os.path.isdir = original_isdir
3473
3474 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003475 'test.foo', 'test-not-a-module.py', 'another_dir'],
Benjamin Petersond2397752009-06-27 23:45:02 +00003476 ['test3.py', 'test4.py', ]]
3477 os.listdir = lambda path: path_lists.pop(0)
3478 self.addCleanup(restore_listdir)
3479
3480 def isdir(path):
3481 return path.endswith('dir')
3482 os.path.isdir = isdir
3483 self.addCleanup(restore_isdir)
3484
3485 def isfile(path):
3486 # another_dir is not a package and so shouldn't be recursed into
3487 return not path.endswith('dir') and not 'another_dir' in path
3488 os.path.isfile = isfile
3489 self.addCleanup(restore_isfile)
3490
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003491 loader._get_module_from_name = lambda path: path + ' module'
Benjamin Petersond2397752009-06-27 23:45:02 +00003492 loader.loadTestsFromModule = lambda module: module + ' tests'
3493
3494 loader._top_level_dir = '/foo'
3495 suite = list(loader._find_tests('/foo', 'test*.py'))
3496
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003497 expected = [name + ' module tests' for name in
3498 ('test1', 'test2')]
3499 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3500 ('test3', 'test4')])
Benjamin Petersond2397752009-06-27 23:45:02 +00003501 self.assertEqual(suite, expected)
3502
3503 def test_find_tests_with_package(self):
3504 loader = unittest.TestLoader()
3505
3506 original_listdir = os.listdir
3507 def restore_listdir():
3508 os.listdir = original_listdir
3509 original_isfile = os.path.isfile
3510 def restore_isfile():
3511 os.path.isfile = original_isfile
3512 original_isdir = os.path.isdir
3513 def restore_isdir():
3514 os.path.isdir = original_isdir
3515
3516 directories = ['a_directory', 'test_directory', 'test_directory2']
3517 path_lists = [directories, [], [], []]
3518 os.listdir = lambda path: path_lists.pop(0)
3519 self.addCleanup(restore_listdir)
3520
3521 os.path.isdir = lambda path: True
3522 self.addCleanup(restore_isdir)
3523
3524 os.path.isfile = lambda path: os.path.basename(path) not in directories
3525 self.addCleanup(restore_isfile)
3526
3527 class Module(object):
3528 paths = []
3529 load_tests_args = []
3530
3531 def __init__(self, path):
3532 self.path = path
3533 self.paths.append(path)
3534 if os.path.basename(path) == 'test_directory':
3535 def load_tests(loader, tests, pattern):
3536 self.load_tests_args.append((loader, tests, pattern))
3537 return 'load_tests'
3538 self.load_tests = load_tests
3539
3540 def __eq__(self, other):
3541 return self.path == other.path
3542
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003543 loader._get_module_from_name = lambda name: Module(name)
Benjamin Petersond2397752009-06-27 23:45:02 +00003544 def loadTestsFromModule(module, use_load_tests):
3545 if use_load_tests:
3546 raise self.failureException('use_load_tests should be False for packages')
3547 return module.path + ' module tests'
3548 loader.loadTestsFromModule = loadTestsFromModule
3549
3550 loader._top_level_dir = '/foo'
3551 # this time no '.py' on the pattern so that it can match
3552 # a test package
3553 suite = list(loader._find_tests('/foo', 'test*'))
3554
3555 # We should have loaded tests from the test_directory package by calling load_tests
3556 # and directly from the test_directory2 package
3557 self.assertEqual(suite,
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003558 ['load_tests', 'test_directory2' + ' module tests'])
3559 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Benjamin Petersond2397752009-06-27 23:45:02 +00003560
3561 # load_tests should have been called once with loader, tests and pattern
3562 self.assertEqual(Module.load_tests_args,
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003563 [(loader, 'test_directory' + ' module tests', 'test*')])
Benjamin Petersond2397752009-06-27 23:45:02 +00003564
3565 def test_discover(self):
3566 loader = unittest.TestLoader()
3567
3568 original_isfile = os.path.isfile
3569 def restore_isfile():
3570 os.path.isfile = original_isfile
3571
3572 os.path.isfile = lambda path: False
3573 self.addCleanup(restore_isfile)
3574
Nick Coghlan6ead5522009-10-18 13:19:33 +00003575 orig_sys_path = sys.path[:]
3576 def restore_path():
3577 sys.path[:] = orig_sys_path
3578 self.addCleanup(restore_path)
Benjamin Petersond2397752009-06-27 23:45:02 +00003579
Nick Coghlan6ead5522009-10-18 13:19:33 +00003580 full_path = os.path.abspath(os.path.normpath('/foo'))
Benjamin Petersond2397752009-06-27 23:45:02 +00003581 with self.assertRaises(ImportError):
3582 loader.discover('/foo/bar', top_level_dir='/foo')
3583
3584 self.assertEqual(loader._top_level_dir, full_path)
3585 self.assertIn(full_path, sys.path)
3586
3587 os.path.isfile = lambda path: True
3588 _find_tests_args = []
3589 def _find_tests(start_dir, pattern):
3590 _find_tests_args.append((start_dir, pattern))
3591 return ['tests']
3592 loader._find_tests = _find_tests
3593 loader.suiteClass = str
3594
3595 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3596
3597 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3598 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3599 self.assertEqual(suite, "['tests']")
3600 self.assertEqual(loader._top_level_dir, top_level_dir)
3601 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlan6ead5522009-10-18 13:19:33 +00003602 self.assertIn(top_level_dir, sys.path)
Benjamin Petersond2397752009-06-27 23:45:02 +00003603
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003604 def test_discover_with_modules_that_fail_to_import(self):
3605 loader = unittest.TestLoader()
3606
3607 listdir = os.listdir
3608 os.listdir = lambda _: ['test_this_does_not_exist.py']
3609 isfile = os.path.isfile
3610 os.path.isfile = lambda _: True
Nick Coghlan6ead5522009-10-18 13:19:33 +00003611 orig_sys_path = sys.path[:]
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003612 def restore():
3613 os.path.isfile = isfile
3614 os.listdir = listdir
Nick Coghlan6ead5522009-10-18 13:19:33 +00003615 sys.path[:] = orig_sys_path
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003616 self.addCleanup(restore)
3617
3618 suite = loader.discover('.')
Nick Coghlan6ead5522009-10-18 13:19:33 +00003619 self.assertIn(os.getcwd(), sys.path)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003620 self.assertEqual(suite.countTestCases(), 1)
3621 test = list(list(suite)[0])[0] # extract test from suite
3622
3623 with self.assertRaises(ImportError):
3624 test.test_this_does_not_exist()
3625
Benjamin Petersond2397752009-06-27 23:45:02 +00003626 def test_command_line_handling_parseArgs(self):
3627 # Haha - take that uninstantiable class
3628 program = object.__new__(TestProgram)
3629
3630 args = []
3631 def do_discovery(argv):
3632 args.extend(argv)
3633 program._do_discovery = do_discovery
3634 program.parseArgs(['something', 'discover'])
3635 self.assertEqual(args, [])
3636
3637 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3638 self.assertEqual(args, ['foo', 'bar'])
3639
3640 def test_command_line_handling_do_discovery_too_many_arguments(self):
3641 class Stop(Exception):
3642 pass
3643 def usageExit():
3644 raise Stop
3645
3646 program = object.__new__(TestProgram)
3647 program.usageExit = usageExit
3648
3649 with self.assertRaises(Stop):
3650 # too many args
3651 program._do_discovery(['one', 'two', 'three', 'four'])
3652
3653
3654 def test_command_line_handling_do_discovery_calls_loader(self):
3655 program = object.__new__(TestProgram)
3656
3657 class Loader(object):
3658 args = []
3659 def discover(self, start_dir, pattern, top_level_dir):
3660 self.args.append((start_dir, pattern, top_level_dir))
3661 return 'tests'
3662
3663 program._do_discovery(['-v'], Loader=Loader)
3664 self.assertEqual(program.verbosity, 2)
3665 self.assertEqual(program.test, 'tests')
3666 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3667
3668 Loader.args = []
3669 program = object.__new__(TestProgram)
3670 program._do_discovery(['--verbose'], Loader=Loader)
3671 self.assertEqual(program.test, 'tests')
3672 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3673
3674 Loader.args = []
3675 program = object.__new__(TestProgram)
3676 program._do_discovery([], Loader=Loader)
3677 self.assertEqual(program.test, 'tests')
3678 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3679
3680 Loader.args = []
3681 program = object.__new__(TestProgram)
3682 program._do_discovery(['fish'], Loader=Loader)
3683 self.assertEqual(program.test, 'tests')
3684 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3685
3686 Loader.args = []
3687 program = object.__new__(TestProgram)
3688 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3689 self.assertEqual(program.test, 'tests')
3690 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3691
3692 Loader.args = []
3693 program = object.__new__(TestProgram)
3694 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3695 self.assertEqual(program.test, 'tests')
3696 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3697
3698 Loader.args = []
3699 program = object.__new__(TestProgram)
3700 program._do_discovery(['-s', 'fish'], Loader=Loader)
3701 self.assertEqual(program.test, 'tests')
3702 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3703
3704 Loader.args = []
3705 program = object.__new__(TestProgram)
3706 program._do_discovery(['-t', 'fish'], Loader=Loader)
3707 self.assertEqual(program.test, 'tests')
3708 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3709
3710 Loader.args = []
3711 program = object.__new__(TestProgram)
3712 program._do_discovery(['-p', 'fish'], Loader=Loader)
3713 self.assertEqual(program.test, 'tests')
3714 self.assertEqual(Loader.args, [('.', 'fish', None)])
3715
3716 Loader.args = []
3717 program = object.__new__(TestProgram)
3718 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3719 self.assertEqual(program.test, 'tests')
3720 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3721 self.assertEqual(program.verbosity, 2)
3722
3723
Jim Fultonfafd8742004-08-28 15:22:12 +00003724######################################################################
3725## Main
3726######################################################################
3727
3728def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003729 support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003730 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003731 Test_TestSkipping, Test_Assertions, TestLongMessage,
Benjamin Petersond2397752009-06-27 23:45:02 +00003732 Test_TestProgram, TestCleanUp, TestDiscovery)
Jim Fultonfafd8742004-08-28 15:22:12 +00003733
Guido van Rossumd8faa362007-04-27 19:54:29 +00003734if __name__ == "__main__":
Jim Fultonfafd8742004-08-28 15:22:12 +00003735 test_main()