blob: d59bf8a3aec767d9ac59367bc3d0d8303e927534 [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 Peterson7fe73a12009-04-04 16:35:46 +00009import re
Benjamin Petersonee8712c2008-05-20 21:35:26 +000010from test import support
Jim Fultonfafd8742004-08-28 15:22:12 +000011import unittest
Benjamin Peterson25c95f12009-05-08 20:42:26 +000012from unittest import TestCase, TestProgram
Christian Heimes45f9af32007-11-27 21:50:00 +000013import types
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000014from copy import deepcopy
Benjamin Peterson25c95f12009-05-08 20:42:26 +000015import io
Jim Fultonfafd8742004-08-28 15:22:12 +000016
Guido van Rossumd8faa362007-04-27 19:54:29 +000017### Support code
18################################################################
Jim Fultonfafd8742004-08-28 15:22:12 +000019
Guido van Rossumd8faa362007-04-27 19:54:29 +000020class LoggingResult(unittest.TestResult):
21 def __init__(self, log):
22 self._events = log
Guido van Rossumcd16bf62007-06-13 18:07:49 +000023 super().__init__()
Guido van Rossumd8faa362007-04-27 19:54:29 +000024
25 def startTest(self, test):
26 self._events.append('startTest')
Guido van Rossumcd16bf62007-06-13 18:07:49 +000027 super().startTest(test)
Guido van Rossumd8faa362007-04-27 19:54:29 +000028
Benjamin Peterson25c95f12009-05-08 20:42:26 +000029 def startTestRun(self):
30 self._events.append('startTestRun')
31 super(LoggingResult, self).startTestRun()
32
Guido van Rossumd8faa362007-04-27 19:54:29 +000033 def stopTest(self, test):
34 self._events.append('stopTest')
Guido van Rossumcd16bf62007-06-13 18:07:49 +000035 super().stopTest(test)
Guido van Rossumd8faa362007-04-27 19:54:29 +000036
Benjamin Peterson25c95f12009-05-08 20:42:26 +000037 def stopTestRun(self):
38 self._events.append('stopTestRun')
39 super(LoggingResult, self).stopTestRun()
40
Guido van Rossumd8faa362007-04-27 19:54:29 +000041 def addFailure(self, *args):
42 self._events.append('addFailure')
Guido van Rossumcd16bf62007-06-13 18:07:49 +000043 super().addFailure(*args)
Guido van Rossumd8faa362007-04-27 19:54:29 +000044
Benjamin Peterson5254c042009-03-23 22:25:03 +000045 def addSuccess(self, *args):
46 self._events.append('addSuccess')
47 super(LoggingResult, self).addSuccess(*args)
48
Guido van Rossumd8faa362007-04-27 19:54:29 +000049 def addError(self, *args):
50 self._events.append('addError')
Guido van Rossumcd16bf62007-06-13 18:07:49 +000051 super().addError(*args)
Guido van Rossumd8faa362007-04-27 19:54:29 +000052
Benjamin Peterson5254c042009-03-23 22:25:03 +000053 def addSkip(self, *args):
54 self._events.append('addSkip')
55 super(LoggingResult, self).addSkip(*args)
56
57 def addExpectedFailure(self, *args):
58 self._events.append('addExpectedFailure')
59 super(LoggingResult, self).addExpectedFailure(*args)
60
61 def addUnexpectedSuccess(self, *args):
62 self._events.append('addUnexpectedSuccess')
63 super(LoggingResult, self).addUnexpectedSuccess(*args)
64
65
Guido van Rossumd8faa362007-04-27 19:54:29 +000066class TestEquality(object):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000067 """Used as a mixin for TestCase"""
68
Guido van Rossumd8faa362007-04-27 19:54:29 +000069 # Check for a valid __eq__ implementation
70 def test_eq(self):
71 for obj_1, obj_2 in self.eq_pairs:
72 self.assertEqual(obj_1, obj_2)
73 self.assertEqual(obj_2, obj_1)
74
75 # Check for a valid __ne__ implementation
76 def test_ne(self):
77 for obj_1, obj_2 in self.ne_pairs:
Georg Brandlfe5f11c2009-08-13 08:52:53 +000078 self.assertNotEqual(obj_1, obj_2)
79 self.assertNotEqual(obj_2, obj_1)
Guido van Rossumd8faa362007-04-27 19:54:29 +000080
81class TestHashing(object):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000082 """Used as a mixin for TestCase"""
83
Guido van Rossumd8faa362007-04-27 19:54:29 +000084 # Check for a valid __hash__ implementation
85 def test_hash(self):
86 for obj_1, obj_2 in self.eq_pairs:
87 try:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000088 if not hash(obj_1) == hash(obj_2):
89 self.fail("%r and %r do not hash equal" % (obj_1, obj_2))
Guido van Rossumd8faa362007-04-27 19:54:29 +000090 except KeyboardInterrupt:
91 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +000092 except Exception as e:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000093 self.fail("Problem hashing %r and %r: %s" % (obj_1, obj_2, e))
Guido van Rossumd8faa362007-04-27 19:54:29 +000094
95 for obj_1, obj_2 in self.ne_pairs:
96 try:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000097 if hash(obj_1) == hash(obj_2):
98 self.fail("%s and %s hash equal, but shouldn't" %
99 (obj_1, obj_2))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000100 except KeyboardInterrupt:
101 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +0000102 except Exception as e:
103 self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e))
104
105
Benjamin Peterson5254c042009-03-23 22:25:03 +0000106# List subclass we can add attributes to.
107class MyClassSuite(list):
108
Benjamin Peterson14a3dd72009-05-25 00:51:58 +0000109 def __init__(self, tests):
Benjamin Peterson5254c042009-03-23 22:25:03 +0000110 super(MyClassSuite, self).__init__(tests)
111
112
Guido van Rossumd8faa362007-04-27 19:54:29 +0000113################################################################
114### /Support code
115
116class Test_TestLoader(TestCase):
117
118 ### Tests for TestLoader.loadTestsFromTestCase
119 ################################################################
120
121 # "Return a suite of all tests cases contained in the TestCase-derived
122 # class testCaseClass"
123 def test_loadTestsFromTestCase(self):
124 class Foo(unittest.TestCase):
125 def test_1(self): pass
126 def test_2(self): pass
127 def foo_bar(self): pass
128
129 tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
130
131 loader = unittest.TestLoader()
132 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
133
134 # "Return a suite of all tests cases contained in the TestCase-derived
135 # class testCaseClass"
136 #
137 # Make sure it does the right thing even if no tests were found
138 def test_loadTestsFromTestCase__no_matches(self):
139 class Foo(unittest.TestCase):
140 def foo_bar(self): pass
141
142 empty_suite = unittest.TestSuite()
143
144 loader = unittest.TestLoader()
145 self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite)
146
147 # "Return a suite of all tests cases contained in the TestCase-derived
148 # class testCaseClass"
149 #
150 # What happens if loadTestsFromTestCase() is given an object
151 # that isn't a subclass of TestCase? Specifically, what happens
152 # if testCaseClass is a subclass of TestSuite?
153 #
154 # This is checked for specifically in the code, so we better add a
155 # test for it.
156 def test_loadTestsFromTestCase__TestSuite_subclass(self):
157 class NotATestCase(unittest.TestSuite):
158 pass
159
160 loader = unittest.TestLoader()
161 try:
162 loader.loadTestsFromTestCase(NotATestCase)
163 except TypeError:
164 pass
165 else:
166 self.fail('Should raise TypeError')
167
168 # "Return a suite of all tests cases contained in the TestCase-derived
169 # class testCaseClass"
170 #
171 # Make sure loadTestsFromTestCase() picks up the default test method
172 # name (as specified by TestCase), even though the method name does
173 # not match the default TestLoader.testMethodPrefix string
174 def test_loadTestsFromTestCase__default_method_name(self):
175 class Foo(unittest.TestCase):
176 def runTest(self):
177 pass
178
179 loader = unittest.TestLoader()
180 # This has to be false for the test to succeed
Georg Brandlfe5f11c2009-08-13 08:52:53 +0000181 self.assertFalse('runTest'.startswith(loader.testMethodPrefix))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000182
183 suite = loader.loadTestsFromTestCase(Foo)
Georg Brandlfe5f11c2009-08-13 08:52:53 +0000184 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000185 self.assertEqual(list(suite), [Foo('runTest')])
186
187 ################################################################
188 ### /Tests for TestLoader.loadTestsFromTestCase
189
190 ### Tests for TestLoader.loadTestsFromModule
191 ################################################################
192
193 # "This method searches `module` for classes derived from TestCase"
194 def test_loadTestsFromModule__TestCase_subclass(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000195 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000196 class MyTestCase(unittest.TestCase):
197 def test(self):
198 pass
199 m.testcase_1 = MyTestCase
200
201 loader = unittest.TestLoader()
202 suite = loader.loadTestsFromModule(m)
Georg Brandlfe5f11c2009-08-13 08:52:53 +0000203 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000204
205 expected = [loader.suiteClass([MyTestCase('test')])]
206 self.assertEqual(list(suite), expected)
207
208 # "This method searches `module` for classes derived from TestCase"
209 #
210 # What happens if no tests are found (no TestCase instances)?
211 def test_loadTestsFromModule__no_TestCase_instances(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000212 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000213
214 loader = unittest.TestLoader()
215 suite = loader.loadTestsFromModule(m)
Georg Brandlfe5f11c2009-08-13 08:52:53 +0000216 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000217 self.assertEqual(list(suite), [])
218
219 # "This method searches `module` for classes derived from TestCase"
220 #
221 # What happens if no tests are found (TestCases instances, but no tests)?
222 def test_loadTestsFromModule__no_TestCase_tests(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000223 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000224 class MyTestCase(unittest.TestCase):
225 pass
226 m.testcase_1 = MyTestCase
227
228 loader = unittest.TestLoader()
229 suite = loader.loadTestsFromModule(m)
Georg Brandlfe5f11c2009-08-13 08:52:53 +0000230 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000231
232 self.assertEqual(list(suite), [loader.suiteClass()])
233
234 # "This method searches `module` for classes derived from TestCase"s
235 #
236 # What happens if loadTestsFromModule() is given something other
237 # than a module?
238 #
239 # XXX Currently, it succeeds anyway. This flexibility
240 # should either be documented or loadTestsFromModule() should
241 # raise a TypeError
242 #
243 # XXX Certain people are using this behaviour. We'll add a test for it
244 def test_loadTestsFromModule__not_a_module(self):
245 class MyTestCase(unittest.TestCase):
246 def test(self):
247 pass
248
249 class NotAModule(object):
250 test_2 = MyTestCase
251
252 loader = unittest.TestLoader()
253 suite = loader.loadTestsFromModule(NotAModule)
254
255 reference = [unittest.TestSuite([MyTestCase('test')])]
256 self.assertEqual(list(suite), reference)
257
258 ################################################################
259 ### /Tests for TestLoader.loadTestsFromModule()
260
261 ### Tests for TestLoader.loadTestsFromName()
262 ################################################################
263
264 # "The specifier name is a ``dotted name'' that may resolve either to
265 # a module, a test case class, a TestSuite instance, a test method
266 # within a test case class, or a callable object which returns a
267 # TestCase or TestSuite instance."
268 #
269 # Is ValueError raised in response to an empty name?
270 def test_loadTestsFromName__empty_name(self):
271 loader = unittest.TestLoader()
272
273 try:
274 loader.loadTestsFromName('')
275 except ValueError as e:
276 self.assertEqual(str(e), "Empty module name")
277 else:
278 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
279
280 # "The specifier name is a ``dotted name'' that may resolve either to
281 # a module, a test case class, a TestSuite instance, a test method
282 # within a test case class, or a callable object which returns a
283 # TestCase or TestSuite instance."
284 #
285 # What happens when the name contains invalid characters?
286 def test_loadTestsFromName__malformed_name(self):
287 loader = unittest.TestLoader()
288
289 # XXX Should this raise ValueError or ImportError?
290 try:
291 loader.loadTestsFromName('abc () //')
292 except ValueError:
293 pass
294 except ImportError:
295 pass
296 else:
297 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
298
299 # "The specifier name is a ``dotted name'' that may resolve ... to a
300 # module"
301 #
302 # What happens when a module by that name can't be found?
303 def test_loadTestsFromName__unknown_module_name(self):
304 loader = unittest.TestLoader()
305
306 try:
307 loader.loadTestsFromName('sdasfasfasdf')
308 except ImportError as e:
309 self.assertEqual(str(e), "No module named sdasfasfasdf")
310 else:
311 self.fail("TestLoader.loadTestsFromName failed to raise ImportError")
312
313 # "The specifier name is a ``dotted name'' that may resolve either to
314 # a module, a test case class, a TestSuite instance, a test method
315 # within a test case class, or a callable object which returns a
316 # TestCase or TestSuite instance."
317 #
318 # What happens when the module is found, but the attribute can't?
319 def test_loadTestsFromName__unknown_attr_name(self):
320 loader = unittest.TestLoader()
321
322 try:
323 loader.loadTestsFromName('unittest.sdasfasfasdf')
324 except AttributeError as e:
325 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
326 else:
327 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
328
329 # "The specifier name is a ``dotted name'' that may resolve either to
330 # a module, a test case class, a TestSuite instance, a test method
331 # within a test case class, or a callable object which returns a
332 # TestCase or TestSuite instance."
333 #
334 # What happens when we provide the module, but the attribute can't be
335 # found?
336 def test_loadTestsFromName__relative_unknown_name(self):
337 loader = unittest.TestLoader()
338
339 try:
340 loader.loadTestsFromName('sdasfasfasdf', unittest)
341 except AttributeError as e:
342 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
343 else:
344 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
345
346 # "The specifier name is a ``dotted name'' that may resolve either to
347 # a module, a test case class, a TestSuite instance, a test method
348 # within a test case class, or a callable object which returns a
349 # TestCase or TestSuite instance."
350 # ...
351 # "The method optionally resolves name relative to the given module"
352 #
353 # Does loadTestsFromName raise ValueError when passed an empty
354 # name relative to a provided module?
355 #
356 # XXX Should probably raise a ValueError instead of an AttributeError
357 def test_loadTestsFromName__relative_empty_name(self):
358 loader = unittest.TestLoader()
359
360 try:
361 loader.loadTestsFromName('', unittest)
362 except AttributeError as e:
363 pass
364 else:
365 self.fail("Failed to raise AttributeError")
366
367 # "The specifier name is a ``dotted name'' that may resolve either to
368 # a module, a test case class, a TestSuite instance, a test method
369 # within a test case class, or a callable object which returns a
370 # TestCase or TestSuite instance."
371 # ...
372 # "The method optionally resolves name relative to the given module"
373 #
374 # What happens when an impossible name is given, relative to the provided
375 # `module`?
376 def test_loadTestsFromName__relative_malformed_name(self):
377 loader = unittest.TestLoader()
378
379 # XXX Should this raise AttributeError or ValueError?
380 try:
381 loader.loadTestsFromName('abc () //', unittest)
382 except ValueError:
383 pass
384 except AttributeError:
385 pass
386 else:
387 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
388
389 # "The method optionally resolves name relative to the given module"
390 #
391 # Does loadTestsFromName raise TypeError when the `module` argument
392 # isn't a module object?
393 #
394 # XXX Accepts the not-a-module object, ignorning the object's type
395 # This should raise an exception or the method name should be changed
396 #
397 # XXX Some people are relying on this, so keep it for now
398 def test_loadTestsFromName__relative_not_a_module(self):
399 class MyTestCase(unittest.TestCase):
400 def test(self):
401 pass
402
403 class NotAModule(object):
404 test_2 = MyTestCase
405
406 loader = unittest.TestLoader()
407 suite = loader.loadTestsFromName('test_2', NotAModule)
408
409 reference = [MyTestCase('test')]
410 self.assertEqual(list(suite), reference)
411
412 # "The specifier name is a ``dotted name'' that may resolve either to
413 # a module, a test case class, a TestSuite instance, a test method
414 # within a test case class, or a callable object which returns a
415 # TestCase or TestSuite instance."
416 #
417 # Does it raise an exception if the name resolves to an invalid
418 # object?
419 def test_loadTestsFromName__relative_bad_object(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000420 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000421 m.testcase_1 = object()
422
423 loader = unittest.TestLoader()
424 try:
425 loader.loadTestsFromName('testcase_1', m)
426 except TypeError:
427 pass
428 else:
429 self.fail("Should have raised TypeError")
430
431 # "The specifier name is a ``dotted name'' that may
432 # resolve either to ... a test case class"
433 def test_loadTestsFromName__relative_TestCase_subclass(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000434 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000435 class MyTestCase(unittest.TestCase):
436 def test(self):
437 pass
438 m.testcase_1 = MyTestCase
439
440 loader = unittest.TestLoader()
441 suite = loader.loadTestsFromName('testcase_1', m)
Georg Brandlfe5f11c2009-08-13 08:52:53 +0000442 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000443 self.assertEqual(list(suite), [MyTestCase('test')])
444
445 # "The specifier name is a ``dotted name'' that may resolve either to
446 # a module, a test case class, a TestSuite instance, a test method
447 # within a test case class, or a callable object which returns a
448 # TestCase or TestSuite instance."
449 def test_loadTestsFromName__relative_TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000450 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000451 class MyTestCase(unittest.TestCase):
452 def test(self):
453 pass
454 m.testsuite = unittest.TestSuite([MyTestCase('test')])
455
456 loader = unittest.TestLoader()
457 suite = loader.loadTestsFromName('testsuite', m)
Georg Brandlfe5f11c2009-08-13 08:52:53 +0000458 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000459
460 self.assertEqual(list(suite), [MyTestCase('test')])
461
462 # "The specifier name is a ``dotted name'' that may resolve ... to
463 # ... a test method within a test case class"
464 def test_loadTestsFromName__relative_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000465 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000466 class MyTestCase(unittest.TestCase):
467 def test(self):
468 pass
469 m.testcase_1 = MyTestCase
470
471 loader = unittest.TestLoader()
472 suite = loader.loadTestsFromName('testcase_1.test', m)
Georg Brandlfe5f11c2009-08-13 08:52:53 +0000473 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000474
475 self.assertEqual(list(suite), [MyTestCase('test')])
476
477 # "The specifier name is a ``dotted name'' that may resolve either to
478 # a module, a test case class, a TestSuite instance, a test method
479 # within a test case class, or a callable object which returns a
480 # TestCase or TestSuite instance."
481 #
482 # Does loadTestsFromName() raise the proper exception when trying to
483 # resolve "a test method within a test case class" that doesn't exist
484 # for the given name (relative to a provided module)?
485 def test_loadTestsFromName__relative_invalid_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000486 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000487 class MyTestCase(unittest.TestCase):
488 def test(self):
489 pass
490 m.testcase_1 = MyTestCase
491
492 loader = unittest.TestLoader()
493 try:
494 loader.loadTestsFromName('testcase_1.testfoo', m)
495 except AttributeError as e:
496 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
497 else:
498 self.fail("Failed to raise AttributeError")
499
500 # "The specifier name is a ``dotted name'' that may resolve ... to
501 # ... a callable object which returns a ... TestSuite instance"
502 def test_loadTestsFromName__callable__TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000503 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000504 testcase_1 = unittest.FunctionTestCase(lambda: None)
505 testcase_2 = unittest.FunctionTestCase(lambda: None)
506 def return_TestSuite():
507 return unittest.TestSuite([testcase_1, testcase_2])
508 m.return_TestSuite = return_TestSuite
509
510 loader = unittest.TestLoader()
511 suite = loader.loadTestsFromName('return_TestSuite', m)
Georg Brandlfe5f11c2009-08-13 08:52:53 +0000512 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000513 self.assertEqual(list(suite), [testcase_1, testcase_2])
514
515 # "The specifier name is a ``dotted name'' that may resolve ... to
516 # ... a callable object which returns a TestCase ... instance"
517 def test_loadTestsFromName__callable__TestCase_instance(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000518 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000519 testcase_1 = unittest.FunctionTestCase(lambda: None)
520 def return_TestCase():
521 return testcase_1
522 m.return_TestCase = return_TestCase
523
524 loader = unittest.TestLoader()
525 suite = loader.loadTestsFromName('return_TestCase', m)
Georg Brandlfe5f11c2009-08-13 08:52:53 +0000526 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000527 self.assertEqual(list(suite), [testcase_1])
528
529 # "The specifier name is a ``dotted name'' that may resolve ... to
530 # ... a callable object which returns a TestCase or TestSuite instance"
531 #
532 # What happens if the callable returns something else?
533 def test_loadTestsFromName__callable__wrong_type(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000534 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000535 def return_wrong():
536 return 6
537 m.return_wrong = return_wrong
538
539 loader = unittest.TestLoader()
540 try:
541 suite = loader.loadTestsFromName('return_wrong', m)
542 except TypeError:
543 pass
544 else:
545 self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
546
547 # "The specifier can refer to modules and packages which have not been
548 # imported; they will be imported as a side-effect"
549 def test_loadTestsFromName__module_not_loaded(self):
550 # We're going to try to load this module as a side-effect, so it
551 # better not be loaded before we try.
552 #
553 # Why pick audioop? Google shows it isn't used very often, so there's
554 # a good chance that it won't be imported when this test is run
555 module_name = 'audioop'
556
557 import sys
558 if module_name in sys.modules:
559 del sys.modules[module_name]
560
561 loader = unittest.TestLoader()
562 try:
563 suite = loader.loadTestsFromName(module_name)
564
Georg Brandlfe5f11c2009-08-13 08:52:53 +0000565 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000566 self.assertEqual(list(suite), [])
567
568 # audioop should now be loaded, thanks to loadTestsFromName()
Georg Brandlfe5f11c2009-08-13 08:52:53 +0000569 self.assertTrue(module_name in sys.modules)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000570 finally:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000571 if module_name in sys.modules:
572 del sys.modules[module_name]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000573
574 ################################################################
575 ### Tests for TestLoader.loadTestsFromName()
576
577 ### Tests for TestLoader.loadTestsFromNames()
578 ################################################################
579
580 # "Similar to loadTestsFromName(), but takes a sequence of names rather
581 # than a single name."
582 #
583 # What happens if that sequence of names is empty?
584 def test_loadTestsFromNames__empty_name_list(self):
585 loader = unittest.TestLoader()
586
587 suite = loader.loadTestsFromNames([])
Georg Brandlfe5f11c2009-08-13 08:52:53 +0000588 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000589 self.assertEqual(list(suite), [])
590
591 # "Similar to loadTestsFromName(), but takes a sequence of names rather
592 # than a single name."
593 # ...
594 # "The method optionally resolves name relative to the given module"
595 #
596 # What happens if that sequence of names is empty?
597 #
598 # XXX Should this raise a ValueError or just return an empty TestSuite?
599 def test_loadTestsFromNames__relative_empty_name_list(self):
600 loader = unittest.TestLoader()
601
602 suite = loader.loadTestsFromNames([], unittest)
Georg Brandlfe5f11c2009-08-13 08:52:53 +0000603 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000604 self.assertEqual(list(suite), [])
605
606 # "The specifier name is a ``dotted name'' that may resolve either to
607 # a module, a test case class, a TestSuite instance, a test method
608 # within a test case class, or a callable object which returns a
609 # TestCase or TestSuite instance."
610 #
611 # Is ValueError raised in response to an empty name?
612 def test_loadTestsFromNames__empty_name(self):
613 loader = unittest.TestLoader()
614
615 try:
616 loader.loadTestsFromNames([''])
617 except ValueError as e:
618 self.assertEqual(str(e), "Empty module name")
619 else:
620 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
621
622 # "The specifier name is a ``dotted name'' that may resolve either to
623 # a module, a test case class, a TestSuite instance, a test method
624 # within a test case class, or a callable object which returns a
625 # TestCase or TestSuite instance."
626 #
627 # What happens when presented with an impossible module name?
628 def test_loadTestsFromNames__malformed_name(self):
629 loader = unittest.TestLoader()
630
631 # XXX Should this raise ValueError or ImportError?
632 try:
633 loader.loadTestsFromNames(['abc () //'])
634 except ValueError:
635 pass
636 except ImportError:
637 pass
638 else:
639 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
640
641 # "The specifier name is a ``dotted name'' that may resolve either to
642 # a module, a test case class, a TestSuite instance, a test method
643 # within a test case class, or a callable object which returns a
644 # TestCase or TestSuite instance."
645 #
646 # What happens when no module can be found for the given name?
647 def test_loadTestsFromNames__unknown_module_name(self):
648 loader = unittest.TestLoader()
649
650 try:
651 loader.loadTestsFromNames(['sdasfasfasdf'])
652 except ImportError as e:
653 self.assertEqual(str(e), "No module named sdasfasfasdf")
654 else:
655 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
656
657 # "The specifier name is a ``dotted name'' that may resolve either to
658 # a module, a test case class, a TestSuite instance, a test method
659 # within a test case class, or a callable object which returns a
660 # TestCase or TestSuite instance."
661 #
662 # What happens when the module can be found, but not the attribute?
663 def test_loadTestsFromNames__unknown_attr_name(self):
664 loader = unittest.TestLoader()
665
666 try:
667 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
668 except AttributeError as e:
669 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
670 else:
671 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
672
673 # "The specifier name is a ``dotted name'' that may resolve either to
674 # a module, a test case class, a TestSuite instance, a test method
675 # within a test case class, or a callable object which returns a
676 # TestCase or TestSuite instance."
677 # ...
678 # "The method optionally resolves name relative to the given module"
679 #
680 # What happens when given an unknown attribute on a specified `module`
681 # argument?
682 def test_loadTestsFromNames__unknown_name_relative_1(self):
683 loader = unittest.TestLoader()
684
685 try:
686 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
687 except AttributeError as e:
688 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
689 else:
690 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
691
692 # "The specifier name is a ``dotted name'' that may resolve either to
693 # a module, a test case class, a TestSuite instance, a test method
694 # within a test case class, or a callable object which returns a
695 # TestCase or TestSuite instance."
696 # ...
697 # "The method optionally resolves name relative to the given module"
698 #
699 # Do unknown attributes (relative to a provided module) still raise an
700 # exception even in the presence of valid attribute names?
701 def test_loadTestsFromNames__unknown_name_relative_2(self):
702 loader = unittest.TestLoader()
703
704 try:
705 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
706 except AttributeError as e:
707 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
708 else:
709 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
710
711 # "The specifier name is a ``dotted name'' that may resolve either to
712 # a module, a test case class, a TestSuite instance, a test method
713 # within a test case class, or a callable object which returns a
714 # TestCase or TestSuite instance."
715 # ...
716 # "The method optionally resolves name relative to the given module"
717 #
718 # What happens when faced with the empty string?
719 #
720 # XXX This currently raises AttributeError, though ValueError is probably
721 # more appropriate
722 def test_loadTestsFromNames__relative_empty_name(self):
723 loader = unittest.TestLoader()
724
725 try:
726 loader.loadTestsFromNames([''], unittest)
727 except AttributeError:
728 pass
729 else:
730 self.fail("Failed to raise ValueError")
731
732 # "The specifier name is a ``dotted name'' that may resolve either to
733 # a module, a test case class, a TestSuite instance, a test method
734 # within a test case class, or a callable object which returns a
735 # TestCase or TestSuite instance."
736 # ...
737 # "The method optionally resolves name relative to the given module"
738 #
739 # What happens when presented with an impossible attribute name?
740 def test_loadTestsFromNames__relative_malformed_name(self):
741 loader = unittest.TestLoader()
742
743 # XXX Should this raise AttributeError or ValueError?
744 try:
745 loader.loadTestsFromNames(['abc () //'], unittest)
746 except AttributeError:
747 pass
748 except ValueError:
749 pass
750 else:
751 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
752
753 # "The method optionally resolves name relative to the given module"
754 #
755 # Does loadTestsFromNames() make sure the provided `module` is in fact
756 # a module?
757 #
758 # XXX This validation is currently not done. This flexibility should
759 # either be documented or a TypeError should be raised.
760 def test_loadTestsFromNames__relative_not_a_module(self):
761 class MyTestCase(unittest.TestCase):
762 def test(self):
763 pass
764
765 class NotAModule(object):
766 test_2 = MyTestCase
767
768 loader = unittest.TestLoader()
769 suite = loader.loadTestsFromNames(['test_2'], NotAModule)
770
771 reference = [unittest.TestSuite([MyTestCase('test')])]
772 self.assertEqual(list(suite), reference)
773
774 # "The specifier name is a ``dotted name'' that may resolve either to
775 # a module, a test case class, a TestSuite instance, a test method
776 # within a test case class, or a callable object which returns a
777 # TestCase or TestSuite instance."
778 #
779 # Does it raise an exception if the name resolves to an invalid
780 # object?
781 def test_loadTestsFromNames__relative_bad_object(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000782 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000783 m.testcase_1 = object()
784
785 loader = unittest.TestLoader()
786 try:
787 loader.loadTestsFromNames(['testcase_1'], m)
788 except TypeError:
789 pass
790 else:
791 self.fail("Should have raised TypeError")
792
793 # "The specifier name is a ``dotted name'' that may resolve ... to
794 # ... a test case class"
795 def test_loadTestsFromNames__relative_TestCase_subclass(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000796 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000797 class MyTestCase(unittest.TestCase):
798 def test(self):
799 pass
800 m.testcase_1 = MyTestCase
801
802 loader = unittest.TestLoader()
803 suite = loader.loadTestsFromNames(['testcase_1'], m)
Georg Brandlfe5f11c2009-08-13 08:52:53 +0000804 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000805
806 expected = loader.suiteClass([MyTestCase('test')])
807 self.assertEqual(list(suite), [expected])
808
809 # "The specifier name is a ``dotted name'' that may resolve ... to
810 # ... a TestSuite instance"
811 def test_loadTestsFromNames__relative_TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000812 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000813 class MyTestCase(unittest.TestCase):
814 def test(self):
815 pass
816 m.testsuite = unittest.TestSuite([MyTestCase('test')])
817
818 loader = unittest.TestLoader()
819 suite = loader.loadTestsFromNames(['testsuite'], m)
Georg Brandlfe5f11c2009-08-13 08:52:53 +0000820 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000821
822 self.assertEqual(list(suite), [m.testsuite])
823
824 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
825 # test method within a test case class"
826 def test_loadTestsFromNames__relative_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000827 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000828 class MyTestCase(unittest.TestCase):
829 def test(self):
830 pass
831 m.testcase_1 = MyTestCase
832
833 loader = unittest.TestLoader()
834 suite = loader.loadTestsFromNames(['testcase_1.test'], m)
Georg Brandlfe5f11c2009-08-13 08:52:53 +0000835 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000836
837 ref_suite = unittest.TestSuite([MyTestCase('test')])
838 self.assertEqual(list(suite), [ref_suite])
839
840 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
841 # test method within a test case class"
842 #
843 # Does the method gracefully handle names that initially look like they
844 # resolve to "a test method within a test case class" but don't?
845 def test_loadTestsFromNames__relative_invalid_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000846 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000847 class MyTestCase(unittest.TestCase):
848 def test(self):
849 pass
850 m.testcase_1 = MyTestCase
851
852 loader = unittest.TestLoader()
853 try:
854 loader.loadTestsFromNames(['testcase_1.testfoo'], m)
855 except AttributeError as e:
856 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
857 else:
858 self.fail("Failed to raise AttributeError")
859
860 # "The specifier name is a ``dotted name'' that may resolve ... to
861 # ... a callable object which returns a ... TestSuite instance"
862 def test_loadTestsFromNames__callable__TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000863 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000864 testcase_1 = unittest.FunctionTestCase(lambda: None)
865 testcase_2 = unittest.FunctionTestCase(lambda: None)
866 def return_TestSuite():
867 return unittest.TestSuite([testcase_1, testcase_2])
868 m.return_TestSuite = return_TestSuite
869
870 loader = unittest.TestLoader()
871 suite = loader.loadTestsFromNames(['return_TestSuite'], m)
Georg Brandlfe5f11c2009-08-13 08:52:53 +0000872 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000873
874 expected = unittest.TestSuite([testcase_1, testcase_2])
875 self.assertEqual(list(suite), [expected])
876
877 # "The specifier name is a ``dotted name'' that may resolve ... to
878 # ... a callable object which returns a TestCase ... instance"
879 def test_loadTestsFromNames__callable__TestCase_instance(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000880 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000881 testcase_1 = unittest.FunctionTestCase(lambda: None)
882 def return_TestCase():
883 return testcase_1
884 m.return_TestCase = return_TestCase
885
886 loader = unittest.TestLoader()
887 suite = loader.loadTestsFromNames(['return_TestCase'], m)
Georg Brandlfe5f11c2009-08-13 08:52:53 +0000888 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000889
890 ref_suite = unittest.TestSuite([testcase_1])
891 self.assertEqual(list(suite), [ref_suite])
892
893 # "The specifier name is a ``dotted name'' that may resolve ... to
894 # ... a callable object which returns a TestCase or TestSuite instance"
895 #
896 # Are staticmethods handled correctly?
897 def test_loadTestsFromNames__callable__call_staticmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000898 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000899 class Test1(unittest.TestCase):
900 def test(self):
901 pass
902
903 testcase_1 = Test1('test')
904 class Foo(unittest.TestCase):
905 @staticmethod
906 def foo():
907 return testcase_1
908 m.Foo = Foo
909
910 loader = unittest.TestLoader()
911 suite = loader.loadTestsFromNames(['Foo.foo'], m)
Georg Brandlfe5f11c2009-08-13 08:52:53 +0000912 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000913
914 ref_suite = unittest.TestSuite([testcase_1])
915 self.assertEqual(list(suite), [ref_suite])
916
917 # "The specifier name is a ``dotted name'' that may resolve ... to
918 # ... a callable object which returns a TestCase or TestSuite instance"
919 #
920 # What happens when the callable returns something else?
921 def test_loadTestsFromNames__callable__wrong_type(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000922 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000923 def return_wrong():
924 return 6
925 m.return_wrong = return_wrong
926
927 loader = unittest.TestLoader()
928 try:
929 suite = loader.loadTestsFromNames(['return_wrong'], m)
930 except TypeError:
931 pass
932 else:
933 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
934
935 # "The specifier can refer to modules and packages which have not been
936 # imported; they will be imported as a side-effect"
937 def test_loadTestsFromNames__module_not_loaded(self):
938 # We're going to try to load this module as a side-effect, so it
939 # better not be loaded before we try.
940 #
941 # Why pick audioop? Google shows it isn't used very often, so there's
942 # a good chance that it won't be imported when this test is run
943 module_name = 'audioop'
944
945 import sys
946 if module_name in sys.modules:
947 del sys.modules[module_name]
948
949 loader = unittest.TestLoader()
950 try:
951 suite = loader.loadTestsFromNames([module_name])
952
Georg Brandlfe5f11c2009-08-13 08:52:53 +0000953 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000954 self.assertEqual(list(suite), [unittest.TestSuite()])
955
956 # audioop should now be loaded, thanks to loadTestsFromName()
Georg Brandlfe5f11c2009-08-13 08:52:53 +0000957 self.assertTrue(module_name in sys.modules)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000958 finally:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000959 if module_name in sys.modules:
960 del sys.modules[module_name]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000961
962 ################################################################
963 ### /Tests for TestLoader.loadTestsFromNames()
964
965 ### Tests for TestLoader.getTestCaseNames()
966 ################################################################
967
968 # "Return a sorted sequence of method names found within testCaseClass"
969 #
970 # Test.foobar is defined to make sure getTestCaseNames() respects
971 # loader.testMethodPrefix
972 def test_getTestCaseNames(self):
973 class Test(unittest.TestCase):
974 def test_1(self): pass
975 def test_2(self): pass
976 def foobar(self): pass
977
978 loader = unittest.TestLoader()
979
980 self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])
981
982 # "Return a sorted sequence of method names found within testCaseClass"
983 #
984 # Does getTestCaseNames() behave appropriately if no tests are found?
985 def test_getTestCaseNames__no_tests(self):
986 class Test(unittest.TestCase):
987 def foobar(self): pass
988
989 loader = unittest.TestLoader()
990
991 self.assertEqual(loader.getTestCaseNames(Test), [])
992
993 # "Return a sorted sequence of method names found within testCaseClass"
994 #
995 # Are not-TestCases handled gracefully?
996 #
997 # XXX This should raise a TypeError, not return a list
998 #
999 # XXX It's too late in the 2.5 release cycle to fix this, but it should
1000 # probably be revisited for 2.6
1001 def test_getTestCaseNames__not_a_TestCase(self):
1002 class BadCase(int):
1003 def test_foo(self):
1004 pass
1005
1006 loader = unittest.TestLoader()
1007 names = loader.getTestCaseNames(BadCase)
1008
1009 self.assertEqual(names, ['test_foo'])
1010
1011 # "Return a sorted sequence of method names found within testCaseClass"
1012 #
1013 # Make sure inherited names are handled.
1014 #
1015 # TestP.foobar is defined to make sure getTestCaseNames() respects
1016 # loader.testMethodPrefix
1017 def test_getTestCaseNames__inheritance(self):
1018 class TestP(unittest.TestCase):
1019 def test_1(self): pass
1020 def test_2(self): pass
1021 def foobar(self): pass
1022
1023 class TestC(TestP):
1024 def test_1(self): pass
1025 def test_3(self): pass
1026
1027 loader = unittest.TestLoader()
1028
1029 names = ['test_1', 'test_2', 'test_3']
1030 self.assertEqual(loader.getTestCaseNames(TestC), names)
1031
1032 ################################################################
1033 ### /Tests for TestLoader.getTestCaseNames()
1034
1035 ### Tests for TestLoader.testMethodPrefix
1036 ################################################################
1037
1038 # "String giving the prefix of method names which will be interpreted as
1039 # test methods"
1040 #
1041 # Implicit in the documentation is that testMethodPrefix is respected by
1042 # all loadTestsFrom* methods.
1043 def test_testMethodPrefix__loadTestsFromTestCase(self):
1044 class Foo(unittest.TestCase):
1045 def test_1(self): pass
1046 def test_2(self): pass
1047 def foo_bar(self): pass
1048
1049 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1050 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1051
1052 loader = unittest.TestLoader()
1053 loader.testMethodPrefix = 'foo'
1054 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
1055
1056 loader.testMethodPrefix = 'test'
1057 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
1058
1059 # "String giving the prefix of method names which will be interpreted as
1060 # test methods"
1061 #
1062 # Implicit in the documentation is that testMethodPrefix is respected by
1063 # all loadTestsFrom* methods.
1064 def test_testMethodPrefix__loadTestsFromModule(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001065 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001066 class Foo(unittest.TestCase):
1067 def test_1(self): pass
1068 def test_2(self): pass
1069 def foo_bar(self): pass
1070 m.Foo = Foo
1071
1072 tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
1073 tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]
1074
1075 loader = unittest.TestLoader()
1076 loader.testMethodPrefix = 'foo'
1077 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
1078
1079 loader.testMethodPrefix = 'test'
1080 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
1081
1082 # "String giving the prefix of method names which will be interpreted as
1083 # test methods"
1084 #
1085 # Implicit in the documentation is that testMethodPrefix is respected by
1086 # all loadTestsFrom* methods.
1087 def test_testMethodPrefix__loadTestsFromName(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001088 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001089 class Foo(unittest.TestCase):
1090 def test_1(self): pass
1091 def test_2(self): pass
1092 def foo_bar(self): pass
1093 m.Foo = Foo
1094
1095 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1096 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1097
1098 loader = unittest.TestLoader()
1099 loader.testMethodPrefix = 'foo'
1100 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
1101
1102 loader.testMethodPrefix = 'test'
1103 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
1104
1105 # "String giving the prefix of method names which will be interpreted as
1106 # test methods"
1107 #
1108 # Implicit in the documentation is that testMethodPrefix is respected by
1109 # all loadTestsFrom* methods.
1110 def test_testMethodPrefix__loadTestsFromNames(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001111 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001112 class Foo(unittest.TestCase):
1113 def test_1(self): pass
1114 def test_2(self): pass
1115 def foo_bar(self): pass
1116 m.Foo = Foo
1117
1118 tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
1119 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1120 tests_2 = unittest.TestSuite([tests_2])
1121
1122 loader = unittest.TestLoader()
1123 loader.testMethodPrefix = 'foo'
1124 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)
1125
1126 loader.testMethodPrefix = 'test'
1127 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)
1128
1129 # "The default value is 'test'"
1130 def test_testMethodPrefix__default_value(self):
1131 loader = unittest.TestLoader()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001132 self.assertEqual(loader.testMethodPrefix, 'test')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001133
1134 ################################################################
1135 ### /Tests for TestLoader.testMethodPrefix
1136
1137 ### Tests for TestLoader.sortTestMethodsUsing
1138 ################################################################
1139
1140 # "Function to be used to compare method names when sorting them in
1141 # getTestCaseNames() and all the loadTestsFromX() methods"
1142 def test_sortTestMethodsUsing__loadTestsFromTestCase(self):
1143 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001144 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001145
1146 class Foo(unittest.TestCase):
1147 def test_1(self): pass
1148 def test_2(self): pass
1149
1150 loader = unittest.TestLoader()
1151 loader.sortTestMethodsUsing = reversed_cmp
1152
1153 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1154 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
1155
1156 # "Function to be used to compare method names when sorting them in
1157 # getTestCaseNames() and all the loadTestsFromX() methods"
1158 def test_sortTestMethodsUsing__loadTestsFromModule(self):
1159 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001160 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001161
Christian Heimes45f9af32007-11-27 21:50:00 +00001162 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001163 class Foo(unittest.TestCase):
1164 def test_1(self): pass
1165 def test_2(self): pass
1166 m.Foo = Foo
1167
1168 loader = unittest.TestLoader()
1169 loader.sortTestMethodsUsing = reversed_cmp
1170
1171 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1172 self.assertEqual(list(loader.loadTestsFromModule(m)), tests)
1173
1174 # "Function to be used to compare method names when sorting them in
1175 # getTestCaseNames() and all the loadTestsFromX() methods"
1176 def test_sortTestMethodsUsing__loadTestsFromName(self):
1177 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001178 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001179
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 m.Foo = Foo
1185
1186 loader = unittest.TestLoader()
1187 loader.sortTestMethodsUsing = reversed_cmp
1188
1189 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1190 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
1191
1192 # "Function to be used to compare method names when sorting them in
1193 # getTestCaseNames() and all the loadTestsFromX() methods"
1194 def test_sortTestMethodsUsing__loadTestsFromNames(self):
1195 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001196 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001197
Christian Heimes45f9af32007-11-27 21:50:00 +00001198 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001199 class Foo(unittest.TestCase):
1200 def test_1(self): pass
1201 def test_2(self): pass
1202 m.Foo = Foo
1203
1204 loader = unittest.TestLoader()
1205 loader.sortTestMethodsUsing = reversed_cmp
1206
1207 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1208 self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)
1209
1210 # "Function to be used to compare method names when sorting them in
1211 # getTestCaseNames()"
1212 #
1213 # Does it actually affect getTestCaseNames()?
1214 def test_sortTestMethodsUsing__getTestCaseNames(self):
1215 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001216 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001217
1218 class Foo(unittest.TestCase):
1219 def test_1(self): pass
1220 def test_2(self): pass
1221
1222 loader = unittest.TestLoader()
1223 loader.sortTestMethodsUsing = reversed_cmp
1224
1225 test_names = ['test_2', 'test_1']
1226 self.assertEqual(loader.getTestCaseNames(Foo), test_names)
1227
1228 # "The default value is the built-in cmp() function"
Mark Dickinsona56c4672009-01-27 18:17:45 +00001229 # Since cmp is now defunct, we simply verify that the results
1230 # occur in the same order as they would with the default sort.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001231 def test_sortTestMethodsUsing__default_value(self):
1232 loader = unittest.TestLoader()
Mark Dickinsona56c4672009-01-27 18:17:45 +00001233
1234 class Foo(unittest.TestCase):
1235 def test_2(self): pass
1236 def test_3(self): pass
1237 def test_1(self): pass
1238
1239 test_names = ['test_2', 'test_3', 'test_1']
1240 self.assertEqual(loader.getTestCaseNames(Foo), sorted(test_names))
1241
Guido van Rossumd8faa362007-04-27 19:54:29 +00001242
1243 # "it can be set to None to disable the sort."
1244 #
1245 # XXX How is this different from reassigning cmp? Are the tests returned
1246 # in a random order or something? This behaviour should die
1247 def test_sortTestMethodsUsing__None(self):
1248 class Foo(unittest.TestCase):
1249 def test_1(self): pass
1250 def test_2(self): pass
1251
1252 loader = unittest.TestLoader()
1253 loader.sortTestMethodsUsing = None
1254
1255 test_names = ['test_2', 'test_1']
1256 self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))
1257
1258 ################################################################
1259 ### /Tests for TestLoader.sortTestMethodsUsing
1260
1261 ### Tests for TestLoader.suiteClass
1262 ################################################################
1263
1264 # "Callable object that constructs a test suite from a list of tests."
1265 def test_suiteClass__loadTestsFromTestCase(self):
1266 class Foo(unittest.TestCase):
1267 def test_1(self): pass
1268 def test_2(self): pass
1269 def foo_bar(self): pass
1270
1271 tests = [Foo('test_1'), Foo('test_2')]
1272
1273 loader = unittest.TestLoader()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001274 loader.suiteClass = list
Guido van Rossumd8faa362007-04-27 19:54:29 +00001275 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
1276
1277 # It is implicit in the documentation for TestLoader.suiteClass that
1278 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
1279 def test_suiteClass__loadTestsFromModule(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001280 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001281 class Foo(unittest.TestCase):
1282 def test_1(self): pass
1283 def test_2(self): pass
1284 def foo_bar(self): pass
1285 m.Foo = Foo
1286
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001287 tests = [[Foo('test_1'), Foo('test_2')]]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001288
1289 loader = unittest.TestLoader()
1290 loader.suiteClass = list
1291 self.assertEqual(loader.loadTestsFromModule(m), tests)
1292
1293 # It is implicit in the documentation for TestLoader.suiteClass that
1294 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
1295 def test_suiteClass__loadTestsFromName(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001296 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001297 class Foo(unittest.TestCase):
1298 def test_1(self): pass
1299 def test_2(self): pass
1300 def foo_bar(self): pass
1301 m.Foo = Foo
1302
1303 tests = [Foo('test_1'), Foo('test_2')]
1304
1305 loader = unittest.TestLoader()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001306 loader.suiteClass = list
Guido van Rossumd8faa362007-04-27 19:54:29 +00001307 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
1308
1309 # It is implicit in the documentation for TestLoader.suiteClass that
1310 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
1311 def test_suiteClass__loadTestsFromNames(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001312 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001313 class Foo(unittest.TestCase):
1314 def test_1(self): pass
1315 def test_2(self): pass
1316 def foo_bar(self): pass
1317 m.Foo = Foo
1318
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001319 tests = [[Foo('test_1'), Foo('test_2')]]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001320
1321 loader = unittest.TestLoader()
1322 loader.suiteClass = list
1323 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)
1324
1325 # "The default value is the TestSuite class"
1326 def test_suiteClass__default_value(self):
1327 loader = unittest.TestLoader()
Georg Brandlfe5f11c2009-08-13 08:52:53 +00001328 self.assertTrue(loader.suiteClass is unittest.TestSuite)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001329
1330 ################################################################
1331 ### /Tests for TestLoader.suiteClass
1332
1333### Support code for Test_TestSuite
1334################################################################
1335
1336class Foo(unittest.TestCase):
1337 def test_1(self): pass
1338 def test_2(self): pass
1339 def test_3(self): pass
1340 def runTest(self): pass
1341
1342def _mk_TestSuite(*names):
1343 return unittest.TestSuite(Foo(n) for n in names)
1344
1345################################################################
1346### /Support code for Test_TestSuite
1347
1348class Test_TestSuite(TestCase, TestEquality):
1349
1350 ### Set up attributes needed by inherited tests
1351 ################################################################
1352
1353 # Used by TestEquality.test_eq
1354 eq_pairs = [(unittest.TestSuite(), unittest.TestSuite())
1355 ,(unittest.TestSuite(), unittest.TestSuite([]))
1356 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]
1357
1358 # Used by TestEquality.test_ne
1359 ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1'))
1360 ,(unittest.TestSuite([]), _mk_TestSuite('test_1'))
1361 ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3'))
1362 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]
1363
1364 ################################################################
1365 ### /Set up attributes needed by inherited tests
1366
1367 ### Tests for TestSuite.__init__
1368 ################################################################
1369
1370 # "class TestSuite([tests])"
1371 #
1372 # The tests iterable should be optional
1373 def test_init__tests_optional(self):
1374 suite = unittest.TestSuite()
1375
1376 self.assertEqual(suite.countTestCases(), 0)
1377
1378 # "class TestSuite([tests])"
1379 # ...
1380 # "If tests is given, it must be an iterable of individual test cases
1381 # or other test suites that will be used to build the suite initially"
1382 #
1383 # TestSuite should deal with empty tests iterables by allowing the
1384 # creation of an empty suite
1385 def test_init__empty_tests(self):
1386 suite = unittest.TestSuite([])
1387
1388 self.assertEqual(suite.countTestCases(), 0)
1389
1390 # "class TestSuite([tests])"
1391 # ...
1392 # "If tests is given, it must be an iterable of individual test cases
1393 # or other test suites that will be used to build the suite initially"
1394 #
1395 # TestSuite should allow any iterable to provide tests
1396 def test_init__tests_from_any_iterable(self):
1397 def tests():
1398 yield unittest.FunctionTestCase(lambda: None)
1399 yield unittest.FunctionTestCase(lambda: None)
1400
1401 suite_1 = unittest.TestSuite(tests())
1402 self.assertEqual(suite_1.countTestCases(), 2)
1403
1404 suite_2 = unittest.TestSuite(suite_1)
1405 self.assertEqual(suite_2.countTestCases(), 2)
1406
1407 suite_3 = unittest.TestSuite(set(suite_1))
1408 self.assertEqual(suite_3.countTestCases(), 2)
1409
1410 # "class TestSuite([tests])"
1411 # ...
1412 # "If tests is given, it must be an iterable of individual test cases
1413 # or other test suites that will be used to build the suite initially"
1414 #
1415 # Does TestSuite() also allow other TestSuite() instances to be present
1416 # in the tests iterable?
1417 def test_init__TestSuite_instances_in_tests(self):
1418 def tests():
1419 ftc = unittest.FunctionTestCase(lambda: None)
1420 yield unittest.TestSuite([ftc])
1421 yield unittest.FunctionTestCase(lambda: None)
1422
1423 suite = unittest.TestSuite(tests())
1424 self.assertEqual(suite.countTestCases(), 2)
1425
1426 ################################################################
1427 ### /Tests for TestSuite.__init__
1428
1429 # Container types should support the iter protocol
1430 def test_iter(self):
1431 test1 = unittest.FunctionTestCase(lambda: None)
1432 test2 = unittest.FunctionTestCase(lambda: None)
1433 suite = unittest.TestSuite((test1, test2))
1434
1435 self.assertEqual(list(suite), [test1, test2])
1436
1437 # "Return the number of tests represented by the this test object.
1438 # ...this method is also implemented by the TestSuite class, which can
1439 # return larger [greater than 1] values"
1440 #
1441 # Presumably an empty TestSuite returns 0?
1442 def test_countTestCases_zero_simple(self):
1443 suite = unittest.TestSuite()
1444
1445 self.assertEqual(suite.countTestCases(), 0)
1446
1447 # "Return the number of tests represented by the this test object.
1448 # ...this method is also implemented by the TestSuite class, which can
1449 # return larger [greater than 1] values"
1450 #
1451 # Presumably an empty TestSuite (even if it contains other empty
1452 # TestSuite instances) returns 0?
1453 def test_countTestCases_zero_nested(self):
1454 class Test1(unittest.TestCase):
1455 def test(self):
1456 pass
1457
1458 suite = unittest.TestSuite([unittest.TestSuite()])
1459
1460 self.assertEqual(suite.countTestCases(), 0)
1461
1462 # "Return the number of tests represented by the this test object.
1463 # ...this method is also implemented by the TestSuite class, which can
1464 # return larger [greater than 1] values"
1465 def test_countTestCases_simple(self):
1466 test1 = unittest.FunctionTestCase(lambda: None)
1467 test2 = unittest.FunctionTestCase(lambda: None)
1468 suite = unittest.TestSuite((test1, test2))
1469
1470 self.assertEqual(suite.countTestCases(), 2)
1471
1472 # "Return the number of tests represented by the this test object.
1473 # ...this method is also implemented by the TestSuite class, which can
1474 # return larger [greater than 1] values"
1475 #
1476 # Make sure this holds for nested TestSuite instances, too
1477 def test_countTestCases_nested(self):
1478 class Test1(unittest.TestCase):
1479 def test1(self): pass
1480 def test2(self): pass
1481
1482 test2 = unittest.FunctionTestCase(lambda: None)
1483 test3 = unittest.FunctionTestCase(lambda: None)
1484 child = unittest.TestSuite((Test1('test2'), test2))
1485 parent = unittest.TestSuite((test3, child, Test1('test1')))
1486
1487 self.assertEqual(parent.countTestCases(), 4)
1488
1489 # "Run the tests associated with this suite, collecting the result into
1490 # the test result object passed as result."
1491 #
1492 # And if there are no tests? What then?
1493 def test_run__empty_suite(self):
1494 events = []
1495 result = LoggingResult(events)
1496
1497 suite = unittest.TestSuite()
1498
1499 suite.run(result)
1500
1501 self.assertEqual(events, [])
1502
1503 # "Note that unlike TestCase.run(), TestSuite.run() requires the
1504 # "result object to be passed in."
1505 def test_run__requires_result(self):
1506 suite = unittest.TestSuite()
1507
1508 try:
1509 suite.run()
1510 except TypeError:
1511 pass
1512 else:
1513 self.fail("Failed to raise TypeError")
1514
1515 # "Run the tests associated with this suite, collecting the result into
1516 # the test result object passed as result."
1517 def test_run(self):
1518 events = []
1519 result = LoggingResult(events)
1520
1521 class LoggingCase(unittest.TestCase):
1522 def run(self, result):
1523 events.append('run %s' % self._testMethodName)
1524
1525 def test1(self): pass
1526 def test2(self): pass
1527
1528 tests = [LoggingCase('test1'), LoggingCase('test2')]
1529
1530 unittest.TestSuite(tests).run(result)
1531
1532 self.assertEqual(events, ['run test1', 'run test2'])
1533
1534 # "Add a TestCase ... to the suite"
1535 def test_addTest__TestCase(self):
1536 class Foo(unittest.TestCase):
1537 def test(self): pass
1538
1539 test = Foo('test')
1540 suite = unittest.TestSuite()
1541
1542 suite.addTest(test)
1543
1544 self.assertEqual(suite.countTestCases(), 1)
1545 self.assertEqual(list(suite), [test])
1546
1547 # "Add a ... TestSuite to the suite"
1548 def test_addTest__TestSuite(self):
1549 class Foo(unittest.TestCase):
1550 def test(self): pass
1551
1552 suite_2 = unittest.TestSuite([Foo('test')])
1553
1554 suite = unittest.TestSuite()
1555 suite.addTest(suite_2)
1556
1557 self.assertEqual(suite.countTestCases(), 1)
1558 self.assertEqual(list(suite), [suite_2])
1559
1560 # "Add all the tests from an iterable of TestCase and TestSuite
1561 # instances to this test suite."
1562 #
1563 # "This is equivalent to iterating over tests, calling addTest() for
1564 # each element"
1565 def test_addTests(self):
1566 class Foo(unittest.TestCase):
1567 def test_1(self): pass
1568 def test_2(self): pass
1569
1570 test_1 = Foo('test_1')
1571 test_2 = Foo('test_2')
1572 inner_suite = unittest.TestSuite([test_2])
1573
1574 def gen():
1575 yield test_1
1576 yield test_2
1577 yield inner_suite
1578
1579 suite_1 = unittest.TestSuite()
1580 suite_1.addTests(gen())
1581
1582 self.assertEqual(list(suite_1), list(gen()))
1583
1584 # "This is equivalent to iterating over tests, calling addTest() for
1585 # each element"
1586 suite_2 = unittest.TestSuite()
1587 for t in gen():
1588 suite_2.addTest(t)
1589
1590 self.assertEqual(suite_1, suite_2)
1591
1592 # "Add all the tests from an iterable of TestCase and TestSuite
1593 # instances to this test suite."
1594 #
1595 # What happens if it doesn't get an iterable?
1596 def test_addTest__noniterable(self):
1597 suite = unittest.TestSuite()
1598
1599 try:
1600 suite.addTests(5)
1601 except TypeError:
1602 pass
1603 else:
1604 self.fail("Failed to raise TypeError")
1605
1606 def test_addTest__noncallable(self):
1607 suite = unittest.TestSuite()
1608 self.assertRaises(TypeError, suite.addTest, 5)
1609
1610 def test_addTest__casesuiteclass(self):
1611 suite = unittest.TestSuite()
1612 self.assertRaises(TypeError, suite.addTest, Test_TestSuite)
1613 self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)
1614
1615 def test_addTests__string(self):
1616 suite = unittest.TestSuite()
1617 self.assertRaises(TypeError, suite.addTests, "foo")
1618
1619
1620class Test_FunctionTestCase(TestCase):
1621
1622 # "Return the number of tests represented by the this test object. For
1623 # TestCase instances, this will always be 1"
1624 def test_countTestCases(self):
1625 test = unittest.FunctionTestCase(lambda: None)
1626
1627 self.assertEqual(test.countTestCases(), 1)
1628
1629 # "When a setUp() method is defined, the test runner will run that method
1630 # prior to each test. Likewise, if a tearDown() method is defined, the
1631 # test runner will invoke that method after each test. In the example,
1632 # setUp() was used to create a fresh sequence for each test."
1633 #
1634 # Make sure the proper call order is maintained, even if setUp() raises
1635 # an exception.
1636 def test_run_call_order__error_in_setUp(self):
1637 events = []
1638 result = LoggingResult(events)
1639
1640 def setUp():
1641 events.append('setUp')
1642 raise RuntimeError('raised by setUp')
1643
1644 def test():
1645 events.append('test')
1646
1647 def tearDown():
1648 events.append('tearDown')
1649
1650 expected = ['startTest', 'setUp', 'addError', 'stopTest']
1651 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1652 self.assertEqual(events, expected)
1653
1654 # "When a setUp() method is defined, the test runner will run that method
1655 # prior to each test. Likewise, if a tearDown() method is defined, the
1656 # test runner will invoke that method after each test. In the example,
1657 # setUp() was used to create a fresh sequence for each test."
1658 #
1659 # Make sure the proper call order is maintained, even if the test raises
1660 # an error (as opposed to a failure).
1661 def test_run_call_order__error_in_test(self):
1662 events = []
1663 result = LoggingResult(events)
1664
1665 def setUp():
1666 events.append('setUp')
1667
1668 def test():
1669 events.append('test')
1670 raise RuntimeError('raised by test')
1671
1672 def tearDown():
1673 events.append('tearDown')
1674
1675 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
1676 'stopTest']
1677 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1678 self.assertEqual(events, expected)
1679
1680 # "When a setUp() method is defined, the test runner will run that method
1681 # prior to each test. Likewise, if a tearDown() method is defined, the
1682 # test runner will invoke that method after each test. In the example,
1683 # setUp() was used to create a fresh sequence for each test."
1684 #
1685 # Make sure the proper call order is maintained, even if the test signals
1686 # a failure (as opposed to an error).
1687 def test_run_call_order__failure_in_test(self):
1688 events = []
1689 result = LoggingResult(events)
1690
1691 def setUp():
1692 events.append('setUp')
1693
1694 def test():
1695 events.append('test')
1696 self.fail('raised by test')
1697
1698 def tearDown():
1699 events.append('tearDown')
1700
1701 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
1702 'stopTest']
1703 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1704 self.assertEqual(events, expected)
1705
1706 # "When a setUp() method is defined, the test runner will run that method
1707 # prior to each test. Likewise, if a tearDown() method is defined, the
1708 # test runner will invoke that method after each test. In the example,
1709 # setUp() was used to create a fresh sequence for each test."
1710 #
1711 # Make sure the proper call order is maintained, even if tearDown() raises
1712 # an exception.
1713 def test_run_call_order__error_in_tearDown(self):
1714 events = []
1715 result = LoggingResult(events)
1716
1717 def setUp():
1718 events.append('setUp')
1719
1720 def test():
1721 events.append('test')
1722
1723 def tearDown():
1724 events.append('tearDown')
1725 raise RuntimeError('raised by tearDown')
1726
1727 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
1728 'stopTest']
1729 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1730 self.assertEqual(events, expected)
1731
1732 # "Return a string identifying the specific test case."
1733 #
1734 # Because of the vague nature of the docs, I'm not going to lock this
1735 # test down too much. Really all that can be asserted is that the id()
1736 # will be a string (either 8-byte or unicode -- again, because the docs
1737 # just say "string")
1738 def test_id(self):
1739 test = unittest.FunctionTestCase(lambda: None)
1740
Georg Brandlfe5f11c2009-08-13 08:52:53 +00001741 self.assertTrue(isinstance(test.id(), str))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001742
1743 # "Returns a one-line description of the test, or None if no description
1744 # has been provided. The default implementation of this method returns
1745 # the first line of the test method's docstring, if available, or None."
1746 def test_shortDescription__no_docstring(self):
1747 test = unittest.FunctionTestCase(lambda: None)
1748
1749 self.assertEqual(test.shortDescription(), None)
1750
1751 # "Returns a one-line description of the test, or None if no description
1752 # has been provided. The default implementation of this method returns
1753 # the first line of the test method's docstring, if available, or None."
1754 def test_shortDescription__singleline_docstring(self):
1755 desc = "this tests foo"
1756 test = unittest.FunctionTestCase(lambda: None, description=desc)
1757
1758 self.assertEqual(test.shortDescription(), "this tests foo")
1759
1760class Test_TestResult(TestCase):
1761 # Note: there are not separate tests for TestResult.wasSuccessful(),
1762 # TestResult.errors, TestResult.failures, TestResult.testsRun or
1763 # TestResult.shouldStop because these only have meaning in terms of
1764 # other TestResult methods.
1765 #
1766 # Accordingly, tests for the aforenamed attributes are incorporated
1767 # in with the tests for the defining methods.
1768 ################################################################
1769
1770 def test_init(self):
1771 result = unittest.TestResult()
1772
Georg Brandlfe5f11c2009-08-13 08:52:53 +00001773 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001774 self.assertEqual(len(result.errors), 0)
1775 self.assertEqual(len(result.failures), 0)
1776 self.assertEqual(result.testsRun, 0)
1777 self.assertEqual(result.shouldStop, False)
1778
1779 # "This method can be called to signal that the set of tests being
1780 # run should be aborted by setting the TestResult's shouldStop
1781 # attribute to True."
1782 def test_stop(self):
1783 result = unittest.TestResult()
1784
1785 result.stop()
1786
1787 self.assertEqual(result.shouldStop, True)
1788
1789 # "Called when the test case test is about to be run. The default
1790 # implementation simply increments the instance's testsRun counter."
1791 def test_startTest(self):
1792 class Foo(unittest.TestCase):
1793 def test_1(self):
1794 pass
1795
1796 test = Foo('test_1')
1797
1798 result = unittest.TestResult()
1799
1800 result.startTest(test)
1801
Georg Brandlfe5f11c2009-08-13 08:52:53 +00001802 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001803 self.assertEqual(len(result.errors), 0)
1804 self.assertEqual(len(result.failures), 0)
1805 self.assertEqual(result.testsRun, 1)
1806 self.assertEqual(result.shouldStop, False)
1807
1808 result.stopTest(test)
1809
1810 # "Called after the test case test has been executed, regardless of
1811 # the outcome. The default implementation does nothing."
1812 def test_stopTest(self):
1813 class Foo(unittest.TestCase):
1814 def test_1(self):
1815 pass
1816
1817 test = Foo('test_1')
1818
1819 result = unittest.TestResult()
1820
1821 result.startTest(test)
1822
Georg Brandlfe5f11c2009-08-13 08:52:53 +00001823 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001824 self.assertEqual(len(result.errors), 0)
1825 self.assertEqual(len(result.failures), 0)
1826 self.assertEqual(result.testsRun, 1)
1827 self.assertEqual(result.shouldStop, False)
1828
1829 result.stopTest(test)
1830
1831 # Same tests as above; make sure nothing has changed
Georg Brandlfe5f11c2009-08-13 08:52:53 +00001832 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001833 self.assertEqual(len(result.errors), 0)
1834 self.assertEqual(len(result.failures), 0)
1835 self.assertEqual(result.testsRun, 1)
1836 self.assertEqual(result.shouldStop, False)
1837
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001838 # "Called before and after tests are run. The default implementation does nothing."
1839 def test_startTestRun_stopTestRun(self):
1840 result = unittest.TestResult()
1841 result.startTestRun()
1842 result.stopTestRun()
1843
Guido van Rossumd8faa362007-04-27 19:54:29 +00001844 # "addSuccess(test)"
1845 # ...
1846 # "Called when the test case test succeeds"
1847 # ...
1848 # "wasSuccessful() - Returns True if all tests run so far have passed,
1849 # otherwise returns False"
1850 # ...
1851 # "testsRun - The total number of tests run so far."
1852 # ...
1853 # "errors - A list containing 2-tuples of TestCase instances and
1854 # formatted tracebacks. Each tuple represents a test which raised an
1855 # unexpected exception. Contains formatted
1856 # tracebacks instead of sys.exc_info() results."
1857 # ...
1858 # "failures - A list containing 2-tuples of TestCase instances and
1859 # formatted tracebacks. Each tuple represents a test where a failure was
1860 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1861 # methods. Contains formatted tracebacks instead
1862 # of sys.exc_info() results."
1863 def test_addSuccess(self):
1864 class Foo(unittest.TestCase):
1865 def test_1(self):
1866 pass
1867
1868 test = Foo('test_1')
1869
1870 result = unittest.TestResult()
1871
1872 result.startTest(test)
1873 result.addSuccess(test)
1874 result.stopTest(test)
1875
Georg Brandlfe5f11c2009-08-13 08:52:53 +00001876 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001877 self.assertEqual(len(result.errors), 0)
1878 self.assertEqual(len(result.failures), 0)
1879 self.assertEqual(result.testsRun, 1)
1880 self.assertEqual(result.shouldStop, False)
1881
1882 # "addFailure(test, err)"
1883 # ...
1884 # "Called when the test case test signals a failure. err is a tuple of
1885 # the form returned by sys.exc_info(): (type, value, traceback)"
1886 # ...
1887 # "wasSuccessful() - Returns True if all tests run so far have passed,
1888 # otherwise returns False"
1889 # ...
1890 # "testsRun - The total number of tests run so far."
1891 # ...
1892 # "errors - A list containing 2-tuples of TestCase instances and
1893 # formatted tracebacks. Each tuple represents a test which raised an
1894 # unexpected exception. Contains formatted
1895 # tracebacks instead of sys.exc_info() results."
1896 # ...
1897 # "failures - A list containing 2-tuples of TestCase instances and
1898 # formatted tracebacks. Each tuple represents a test where a failure was
1899 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1900 # methods. Contains formatted tracebacks instead
1901 # of sys.exc_info() results."
1902 def test_addFailure(self):
1903 import sys
1904
1905 class Foo(unittest.TestCase):
1906 def test_1(self):
1907 pass
1908
1909 test = Foo('test_1')
1910 try:
1911 test.fail("foo")
1912 except:
1913 exc_info_tuple = sys.exc_info()
1914
1915 result = unittest.TestResult()
1916
1917 result.startTest(test)
1918 result.addFailure(test, exc_info_tuple)
1919 result.stopTest(test)
1920
Georg Brandlfe5f11c2009-08-13 08:52:53 +00001921 self.assertFalse(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001922 self.assertEqual(len(result.errors), 0)
1923 self.assertEqual(len(result.failures), 1)
1924 self.assertEqual(result.testsRun, 1)
1925 self.assertEqual(result.shouldStop, False)
1926
1927 test_case, formatted_exc = result.failures[0]
Georg Brandlfe5f11c2009-08-13 08:52:53 +00001928 self.assertTrue(test_case is test)
1929 self.assertTrue(isinstance(formatted_exc, str))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001930
1931 # "addError(test, err)"
1932 # ...
1933 # "Called when the test case test raises an unexpected exception err
1934 # is a tuple of the form returned by sys.exc_info():
1935 # (type, value, traceback)"
1936 # ...
1937 # "wasSuccessful() - Returns True if all tests run so far have passed,
1938 # otherwise returns False"
1939 # ...
1940 # "testsRun - The total number of tests run so far."
1941 # ...
1942 # "errors - A list containing 2-tuples of TestCase instances and
1943 # formatted tracebacks. Each tuple represents a test which raised an
1944 # unexpected exception. Contains formatted
1945 # tracebacks instead of sys.exc_info() results."
1946 # ...
1947 # "failures - A list containing 2-tuples of TestCase instances and
1948 # formatted tracebacks. Each tuple represents a test where a failure was
1949 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1950 # methods. Contains formatted tracebacks instead
1951 # of sys.exc_info() results."
1952 def test_addError(self):
1953 import sys
1954
1955 class Foo(unittest.TestCase):
1956 def test_1(self):
1957 pass
1958
1959 test = Foo('test_1')
1960 try:
1961 raise TypeError()
1962 except:
1963 exc_info_tuple = sys.exc_info()
1964
1965 result = unittest.TestResult()
1966
1967 result.startTest(test)
1968 result.addError(test, exc_info_tuple)
1969 result.stopTest(test)
1970
Georg Brandlfe5f11c2009-08-13 08:52:53 +00001971 self.assertFalse(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001972 self.assertEqual(len(result.errors), 1)
1973 self.assertEqual(len(result.failures), 0)
1974 self.assertEqual(result.testsRun, 1)
1975 self.assertEqual(result.shouldStop, False)
1976
1977 test_case, formatted_exc = result.errors[0]
Georg Brandlfe5f11c2009-08-13 08:52:53 +00001978 self.assertTrue(test_case is test)
1979 self.assertTrue(isinstance(formatted_exc, str))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001980
1981### Support code for Test_TestCase
1982################################################################
1983
1984class Foo(unittest.TestCase):
1985 def runTest(self): pass
1986 def test1(self): pass
1987
1988class Bar(Foo):
1989 def test2(self): pass
1990
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001991class LoggingTestCase(unittest.TestCase):
1992 """A test case which logs its calls."""
1993
1994 def __init__(self, events):
1995 super(LoggingTestCase, self).__init__('test')
1996 self.events = events
1997
1998 def setUp(self):
1999 self.events.append('setUp')
2000
2001 def test(self):
2002 self.events.append('test')
2003
2004 def tearDown(self):
2005 self.events.append('tearDown')
2006
2007class ResultWithNoStartTestRunStopTestRun(object):
2008 """An object honouring TestResult before startTestRun/stopTestRun."""
2009
2010 def __init__(self):
2011 self.failures = []
2012 self.errors = []
2013 self.testsRun = 0
2014 self.skipped = []
2015 self.expectedFailures = []
2016 self.unexpectedSuccesses = []
2017 self.shouldStop = False
2018
2019 def startTest(self, test):
2020 pass
2021
2022 def stopTest(self, test):
2023 pass
2024
2025 def addError(self, test):
2026 pass
2027
2028 def addFailure(self, test):
2029 pass
2030
2031 def addSuccess(self, test):
2032 pass
2033
2034 def wasSuccessful(self):
2035 return True
2036
2037
Guido van Rossumd8faa362007-04-27 19:54:29 +00002038################################################################
2039### /Support code for Test_TestCase
2040
2041class Test_TestCase(TestCase, TestEquality, TestHashing):
2042
2043 ### Set up attributes used by inherited tests
2044 ################################################################
2045
2046 # Used by TestHashing.test_hash and TestEquality.test_eq
2047 eq_pairs = [(Foo('test1'), Foo('test1'))]
2048
2049 # Used by TestEquality.test_ne
2050 ne_pairs = [(Foo('test1'), Foo('runTest'))
2051 ,(Foo('test1'), Bar('test1'))
2052 ,(Foo('test1'), Bar('test2'))]
2053
2054 ################################################################
2055 ### /Set up attributes used by inherited tests
2056
2057
2058 # "class TestCase([methodName])"
2059 # ...
2060 # "Each instance of TestCase will run a single test method: the
2061 # method named methodName."
2062 # ...
2063 # "methodName defaults to "runTest"."
2064 #
2065 # Make sure it really is optional, and that it defaults to the proper
2066 # thing.
2067 def test_init__no_test_name(self):
2068 class Test(unittest.TestCase):
2069 def runTest(self): raise MyException()
2070 def test(self): pass
2071
2072 self.assertEqual(Test().id()[-13:], '.Test.runTest')
2073
2074 # "class TestCase([methodName])"
2075 # ...
2076 # "Each instance of TestCase will run a single test method: the
2077 # method named methodName."
2078 def test_init__test_name__valid(self):
2079 class Test(unittest.TestCase):
2080 def runTest(self): raise MyException()
2081 def test(self): pass
2082
2083 self.assertEqual(Test('test').id()[-10:], '.Test.test')
2084
2085 # "class TestCase([methodName])"
2086 # ...
2087 # "Each instance of TestCase will run a single test method: the
2088 # method named methodName."
2089 def test_init__test_name__invalid(self):
2090 class Test(unittest.TestCase):
2091 def runTest(self): raise MyException()
2092 def test(self): pass
2093
2094 try:
2095 Test('testfoo')
2096 except ValueError:
2097 pass
2098 else:
2099 self.fail("Failed to raise ValueError")
2100
2101 # "Return the number of tests represented by the this test object. For
2102 # TestCase instances, this will always be 1"
2103 def test_countTestCases(self):
2104 class Foo(unittest.TestCase):
2105 def test(self): pass
2106
2107 self.assertEqual(Foo('test').countTestCases(), 1)
2108
2109 # "Return the default type of test result object to be used to run this
2110 # test. For TestCase instances, this will always be
2111 # unittest.TestResult; subclasses of TestCase should
2112 # override this as necessary."
2113 def test_defaultTestResult(self):
2114 class Foo(unittest.TestCase):
2115 def runTest(self):
2116 pass
2117
2118 result = Foo().defaultTestResult()
2119 self.assertEqual(type(result), unittest.TestResult)
2120
2121 # "When a setUp() method is defined, the test runner will run that method
2122 # prior to each test. Likewise, if a tearDown() method is defined, the
2123 # test runner will invoke that method after each test. In the example,
2124 # setUp() was used to create a fresh sequence for each test."
2125 #
2126 # Make sure the proper call order is maintained, even if setUp() raises
2127 # an exception.
2128 def test_run_call_order__error_in_setUp(self):
2129 events = []
2130 result = LoggingResult(events)
2131
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002132 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002133 def setUp(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002134 super(Foo, self).setUp()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002135 raise RuntimeError('raised by Foo.setUp')
2136
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002137 Foo(events).run(result)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002138 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2139 self.assertEqual(events, expected)
2140
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002141 # "With a temporary result stopTestRun is called when setUp errors.
2142 def test_run_call_order__error_in_setUp_default_result(self):
2143 events = []
2144
2145 class Foo(LoggingTestCase):
2146 def defaultTestResult(self):
2147 return LoggingResult(self.events)
2148
2149 def setUp(self):
2150 super(Foo, self).setUp()
2151 raise RuntimeError('raised by Foo.setUp')
2152
2153 Foo(events).run()
2154 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2155 'stopTest', 'stopTestRun']
2156 self.assertEqual(events, expected)
2157
Guido van Rossumd8faa362007-04-27 19:54:29 +00002158 # "When a setUp() method is defined, the test runner will run that method
2159 # prior to each test. Likewise, if a tearDown() method is defined, the
2160 # test runner will invoke that method after each test. In the example,
2161 # setUp() was used to create a fresh sequence for each test."
2162 #
2163 # Make sure the proper call order is maintained, even if the test raises
2164 # an error (as opposed to a failure).
2165 def test_run_call_order__error_in_test(self):
2166 events = []
2167 result = LoggingResult(events)
2168
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002169 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002170 def test(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002171 super(Foo, self).test()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002172 raise RuntimeError('raised by Foo.test')
2173
Guido van Rossumd8faa362007-04-27 19:54:29 +00002174 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2175 'stopTest']
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002176 Foo(events).run(result)
2177 self.assertEqual(events, expected)
2178
2179 # "With a default result, an error in the test still results in stopTestRun
2180 # being called."
2181 def test_run_call_order__error_in_test_default_result(self):
2182 events = []
2183
2184 class Foo(LoggingTestCase):
2185 def defaultTestResult(self):
2186 return LoggingResult(self.events)
2187
2188 def test(self):
2189 super(Foo, self).test()
2190 raise RuntimeError('raised by Foo.test')
2191
2192 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2193 'tearDown', 'stopTest', 'stopTestRun']
2194 Foo(events).run()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002195 self.assertEqual(events, expected)
2196
2197 # "When a setUp() method is defined, the test runner will run that method
2198 # prior to each test. Likewise, if a tearDown() method is defined, the
2199 # test runner will invoke that method after each test. In the example,
2200 # setUp() was used to create a fresh sequence for each test."
2201 #
2202 # Make sure the proper call order is maintained, even if the test signals
2203 # a failure (as opposed to an error).
2204 def test_run_call_order__failure_in_test(self):
2205 events = []
2206 result = LoggingResult(events)
2207
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002208 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002209 def test(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002210 super(Foo, self).test()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002211 self.fail('raised by Foo.test')
2212
Guido van Rossumd8faa362007-04-27 19:54:29 +00002213 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2214 'stopTest']
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002215 Foo(events).run(result)
2216 self.assertEqual(events, expected)
2217
2218 # "When a test fails with a default result stopTestRun is still called."
2219 def test_run_call_order__failure_in_test_default_result(self):
2220
2221 class Foo(LoggingTestCase):
2222 def defaultTestResult(self):
2223 return LoggingResult(self.events)
2224 def test(self):
2225 super(Foo, self).test()
2226 self.fail('raised by Foo.test')
2227
2228 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2229 'tearDown', 'stopTest', 'stopTestRun']
2230 events = []
2231 Foo(events).run()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002232 self.assertEqual(events, expected)
2233
2234 # "When a setUp() method is defined, the test runner will run that method
2235 # prior to each test. Likewise, if a tearDown() method is defined, the
2236 # test runner will invoke that method after each test. In the example,
2237 # setUp() was used to create a fresh sequence for each test."
2238 #
2239 # Make sure the proper call order is maintained, even if tearDown() raises
2240 # an exception.
2241 def test_run_call_order__error_in_tearDown(self):
2242 events = []
2243 result = LoggingResult(events)
2244
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002245 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002246 def tearDown(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002247 super(Foo, self).tearDown()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002248 raise RuntimeError('raised by Foo.tearDown')
2249
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002250 Foo(events).run(result)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002251 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2252 'stopTest']
2253 self.assertEqual(events, expected)
2254
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002255 # "When tearDown errors with a default result stopTestRun is still called."
2256 def test_run_call_order__error_in_tearDown_default_result(self):
2257
2258 class Foo(LoggingTestCase):
2259 def defaultTestResult(self):
2260 return LoggingResult(self.events)
2261 def tearDown(self):
2262 super(Foo, self).tearDown()
2263 raise RuntimeError('raised by Foo.tearDown')
2264
2265 events = []
2266 Foo(events).run()
2267 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2268 'addError', 'stopTest', 'stopTestRun']
2269 self.assertEqual(events, expected)
2270
2271 # "TestCase.run() still works when the defaultTestResult is a TestResult
2272 # that does not support startTestRun and stopTestRun.
2273 def test_run_call_order_default_result(self):
2274
2275 class Foo(unittest.TestCase):
2276 def defaultTestResult(self):
2277 return ResultWithNoStartTestRunStopTestRun()
2278 def test(self):
2279 pass
2280
2281 Foo('test').run()
2282
Guido van Rossumd8faa362007-04-27 19:54:29 +00002283 # "This class attribute gives the exception raised by the test() method.
2284 # If a test framework needs to use a specialized exception, possibly to
2285 # carry additional information, it must subclass this exception in
2286 # order to ``play fair'' with the framework. The initial value of this
2287 # attribute is AssertionError"
2288 def test_failureException__default(self):
2289 class Foo(unittest.TestCase):
2290 def test(self):
2291 pass
2292
Georg Brandlfe5f11c2009-08-13 08:52:53 +00002293 self.assertTrue(Foo('test').failureException is AssertionError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002294
2295 # "This class attribute gives the exception raised by the test() method.
2296 # If a test framework needs to use a specialized exception, possibly to
2297 # carry additional information, it must subclass this exception in
2298 # order to ``play fair'' with the framework."
2299 #
2300 # Make sure TestCase.run() respects the designated failureException
2301 def test_failureException__subclassing__explicit_raise(self):
2302 events = []
2303 result = LoggingResult(events)
2304
2305 class Foo(unittest.TestCase):
2306 def test(self):
2307 raise RuntimeError()
2308
2309 failureException = RuntimeError
2310
Georg Brandlfe5f11c2009-08-13 08:52:53 +00002311 self.assertTrue(Foo('test').failureException is RuntimeError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002312
2313
2314 Foo('test').run(result)
2315 expected = ['startTest', 'addFailure', 'stopTest']
2316 self.assertEqual(events, expected)
2317
2318 # "This class attribute gives the exception raised by the test() method.
2319 # If a test framework needs to use a specialized exception, possibly to
2320 # carry additional information, it must subclass this exception in
2321 # order to ``play fair'' with the framework."
2322 #
2323 # Make sure TestCase.run() respects the designated failureException
2324 def test_failureException__subclassing__implicit_raise(self):
2325 events = []
2326 result = LoggingResult(events)
2327
2328 class Foo(unittest.TestCase):
2329 def test(self):
2330 self.fail("foo")
2331
2332 failureException = RuntimeError
2333
Georg Brandlfe5f11c2009-08-13 08:52:53 +00002334 self.assertTrue(Foo('test').failureException is RuntimeError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002335
2336
2337 Foo('test').run(result)
2338 expected = ['startTest', 'addFailure', 'stopTest']
2339 self.assertEqual(events, expected)
2340
2341 # "The default implementation does nothing."
2342 def test_setUp(self):
2343 class Foo(unittest.TestCase):
2344 def runTest(self):
2345 pass
2346
2347 # ... and nothing should happen
2348 Foo().setUp()
2349
2350 # "The default implementation does nothing."
2351 def test_tearDown(self):
2352 class Foo(unittest.TestCase):
2353 def runTest(self):
2354 pass
2355
2356 # ... and nothing should happen
2357 Foo().tearDown()
2358
2359 # "Return a string identifying the specific test case."
2360 #
2361 # Because of the vague nature of the docs, I'm not going to lock this
2362 # test down too much. Really all that can be asserted is that the id()
2363 # will be a string (either 8-byte or unicode -- again, because the docs
2364 # just say "string")
2365 def test_id(self):
2366 class Foo(unittest.TestCase):
2367 def runTest(self):
2368 pass
2369
Georg Brandlfe5f11c2009-08-13 08:52:53 +00002370 self.assertTrue(isinstance(Foo().id(), str))
Guido van Rossumd8faa362007-04-27 19:54:29 +00002371
Guido van Rossumd8faa362007-04-27 19:54:29 +00002372 # "If result is omitted or None, a temporary result object is created
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002373 # and used, but is not made available to the caller. As TestCase owns the
2374 # temporary result startTestRun and stopTestRun are called.
2375
Guido van Rossumd8faa362007-04-27 19:54:29 +00002376 def test_run__uses_defaultTestResult(self):
2377 events = []
2378
2379 class Foo(unittest.TestCase):
2380 def test(self):
2381 events.append('test')
2382
2383 def defaultTestResult(self):
2384 return LoggingResult(events)
2385
2386 # Make run() find a result object on its own
2387 Foo('test').run()
2388
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002389 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2390 'stopTest', 'stopTestRun']
Guido van Rossumd8faa362007-04-27 19:54:29 +00002391 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002392
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002393 def testShortDescriptionWithoutDocstring(self):
2394 self.assertEqual(
2395 self.shortDescription(),
2396 'testShortDescriptionWithoutDocstring (' + __name__ +
2397 '.Test_TestCase)')
2398
2399 def testShortDescriptionWithOneLineDocstring(self):
2400 """Tests shortDescription() for a method with a docstring."""
2401 self.assertEqual(
2402 self.shortDescription(),
2403 ('testShortDescriptionWithOneLineDocstring '
2404 '(' + __name__ + '.Test_TestCase)\n'
2405 'Tests shortDescription() for a method with a docstring.'))
2406
2407 def testShortDescriptionWithMultiLineDocstring(self):
2408 """Tests shortDescription() for a method with a longer docstring.
2409
2410 This method ensures that only the first line of a docstring is
2411 returned used in the short description, no matter how long the
2412 whole thing is.
2413 """
2414 self.assertEqual(
2415 self.shortDescription(),
2416 ('testShortDescriptionWithMultiLineDocstring '
2417 '(' + __name__ + '.Test_TestCase)\n'
2418 'Tests shortDescription() for a method with a longer '
2419 'docstring.'))
2420
2421 def testAddTypeEqualityFunc(self):
2422 class SadSnake(object):
2423 """Dummy class for test_addTypeEqualityFunc."""
2424 s1, s2 = SadSnake(), SadSnake()
2425 self.assertFalse(s1 == s2)
2426 def AllSnakesCreatedEqual(a, b, msg=None):
2427 return type(a) == type(b) == SadSnake
2428 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2429 self.assertEqual(s1, s2)
2430 # No this doesn't clean up and remove the SadSnake equality func
2431 # from this TestCase instance but since its a local nothing else
2432 # will ever notice that.
2433
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00002434 def testAssertIs(self):
2435 thing = object()
2436 self.assertIs(thing, thing)
2437 self.assertRaises(self.failureException, self.assertIs, thing, object())
2438
2439 def testAssertIsNot(self):
2440 thing = object()
2441 self.assertIsNot(thing, object())
2442 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2443
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002444 def testAssertIn(self):
2445 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2446
2447 self.assertIn('a', 'abc')
2448 self.assertIn(2, [1, 2, 3])
2449 self.assertIn('monkey', animals)
2450
2451 self.assertNotIn('d', 'abc')
2452 self.assertNotIn(0, [1, 2, 3])
2453 self.assertNotIn('otter', animals)
2454
2455 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2456 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2457 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2458 animals)
2459
2460 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2461 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2462 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2463 animals)
2464
2465 def testAssertDictContainsSubset(self):
2466 self.assertDictContainsSubset({}, {})
2467 self.assertDictContainsSubset({}, {'a': 1})
2468 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2469 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2470 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2471
2472 self.assertRaises(unittest.TestCase.failureException,
2473 self.assertDictContainsSubset, {'a': 2}, {'a': 1},
2474 '.*Mismatched values:.*')
2475
2476 self.assertRaises(unittest.TestCase.failureException,
2477 self.assertDictContainsSubset, {'c': 1}, {'a': 1},
2478 '.*Missing:.*')
2479
2480 self.assertRaises(unittest.TestCase.failureException,
2481 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2482 {'a': 1}, '.*Missing:.*')
2483
2484 self.assertRaises(unittest.TestCase.failureException,
2485 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2486 {'a': 1}, '.*Missing:.*Mismatched values:.*')
2487
2488 def testAssertEqual(self):
2489 equal_pairs = [
2490 ((), ()),
2491 ({}, {}),
2492 ([], []),
2493 (set(), set()),
2494 (frozenset(), frozenset())]
2495 for a, b in equal_pairs:
2496 # This mess of try excepts is to test the assertEqual behavior
2497 # itself.
2498 try:
2499 self.assertEqual(a, b)
2500 except self.failureException:
2501 self.fail('assertEqual(%r, %r) failed' % (a, b))
2502 try:
2503 self.assertEqual(a, b, msg='foo')
2504 except self.failureException:
2505 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2506 try:
2507 self.assertEqual(a, b, 'foo')
2508 except self.failureException:
2509 self.fail('assertEqual(%r, %r) with third parameter failed' %
2510 (a, b))
2511
2512 unequal_pairs = [
2513 ((), []),
2514 ({}, set()),
2515 (set([4,1]), frozenset([4,2])),
2516 (frozenset([4,5]), set([2,3])),
2517 (set([3,4]), set([5,4]))]
2518 for a, b in unequal_pairs:
2519 self.assertRaises(self.failureException, self.assertEqual, a, b)
2520 self.assertRaises(self.failureException, self.assertEqual, a, b,
2521 'foo')
2522 self.assertRaises(self.failureException, self.assertEqual, a, b,
2523 msg='foo')
2524
2525 def testEquality(self):
2526 self.assertListEqual([], [])
2527 self.assertTupleEqual((), ())
2528 self.assertSequenceEqual([], ())
2529
2530 a = [0, 'a', []]
2531 b = []
2532 self.assertRaises(unittest.TestCase.failureException,
2533 self.assertListEqual, a, b)
2534 self.assertRaises(unittest.TestCase.failureException,
2535 self.assertListEqual, tuple(a), tuple(b))
2536 self.assertRaises(unittest.TestCase.failureException,
2537 self.assertSequenceEqual, a, tuple(b))
2538
2539 b.extend(a)
2540 self.assertListEqual(a, b)
2541 self.assertTupleEqual(tuple(a), tuple(b))
2542 self.assertSequenceEqual(a, tuple(b))
2543 self.assertSequenceEqual(tuple(a), b)
2544
2545 self.assertRaises(self.failureException, self.assertListEqual,
2546 a, tuple(b))
2547 self.assertRaises(self.failureException, self.assertTupleEqual,
2548 tuple(a), b)
2549 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2550 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2551 tuple(b))
2552 self.assertRaises(self.failureException, self.assertSequenceEqual,
2553 None, tuple(b))
2554 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2555 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2556 self.assertRaises(self.failureException, self.assertSequenceEqual,
2557 1, 1)
2558
2559 self.assertDictEqual({}, {})
2560
2561 c = { 'x': 1 }
2562 d = {}
2563 self.assertRaises(unittest.TestCase.failureException,
2564 self.assertDictEqual, c, d)
2565
2566 d.update(c)
2567 self.assertDictEqual(c, d)
2568
2569 d['x'] = 0
2570 self.assertRaises(unittest.TestCase.failureException,
2571 self.assertDictEqual, c, d, 'These are unequal')
2572
2573 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2574 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2575 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2576
2577 self.assertSameElements([1, 2, 3], [3, 2, 1])
2578 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2579 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2580 self.assertRaises(self.failureException, self.assertSameElements,
2581 [10], [10, 11])
2582 self.assertRaises(self.failureException, self.assertSameElements,
2583 [10, 11], [10])
2584
2585 # Test that sequences of unhashable objects can be tested for sameness:
2586 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00002587
Benjamin Peterson3bb6b7a2009-04-04 16:46:24 +00002588 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002589 self.assertRaises(self.failureException, self.assertSameElements,
2590 [[1]], [[2]])
Michael Foorda5809c82009-04-04 18:55:09 +00002591 self.assertRaises(self.failureException, self.assertSameElements,
2592 [{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 2}])
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002593
2594 def testAssertSetEqual(self):
2595 set1 = set()
2596 set2 = set()
2597 self.assertSetEqual(set1, set2)
2598
2599 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2600 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2601 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2602 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2603
2604 set1 = set(['a'])
2605 set2 = set()
2606 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2607
2608 set1 = set(['a'])
2609 set2 = set(['a'])
2610 self.assertSetEqual(set1, set2)
2611
2612 set1 = set(['a'])
2613 set2 = set(['a', 'b'])
2614 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2615
2616 set1 = set(['a'])
2617 set2 = frozenset(['a', 'b'])
2618 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2619
2620 set1 = set(['a', 'b'])
2621 set2 = frozenset(['a', 'b'])
2622 self.assertSetEqual(set1, set2)
2623
2624 set1 = set()
2625 set2 = "foo"
2626 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2627 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2628
2629 # make sure any string formatting is tuple-safe
2630 set1 = set([(0, 1), (2, 3)])
2631 set2 = set([(4, 5)])
2632 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2633
2634 def testInequality(self):
2635 # Try ints
2636 self.assertGreater(2, 1)
2637 self.assertGreaterEqual(2, 1)
2638 self.assertGreaterEqual(1, 1)
2639 self.assertLess(1, 2)
2640 self.assertLessEqual(1, 2)
2641 self.assertLessEqual(1, 1)
2642 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2643 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2644 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2645 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2646 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2647 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2648
2649 # Try Floats
2650 self.assertGreater(1.1, 1.0)
2651 self.assertGreaterEqual(1.1, 1.0)
2652 self.assertGreaterEqual(1.0, 1.0)
2653 self.assertLess(1.0, 1.1)
2654 self.assertLessEqual(1.0, 1.1)
2655 self.assertLessEqual(1.0, 1.0)
2656 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2657 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2658 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2659 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2660 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2661 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2662
2663 # Try Strings
2664 self.assertGreater('bug', 'ant')
2665 self.assertGreaterEqual('bug', 'ant')
2666 self.assertGreaterEqual('ant', 'ant')
2667 self.assertLess('ant', 'bug')
2668 self.assertLessEqual('ant', 'bug')
2669 self.assertLessEqual('ant', 'ant')
2670 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2671 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2672 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2673 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2674 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2675 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2676
2677 # Try bytes
2678 self.assertGreater(b'bug', b'ant')
2679 self.assertGreaterEqual(b'bug', b'ant')
2680 self.assertGreaterEqual(b'ant', b'ant')
2681 self.assertLess(b'ant', b'bug')
2682 self.assertLessEqual(b'ant', b'bug')
2683 self.assertLessEqual(b'ant', b'ant')
2684 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'bug')
2685 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'ant')
2686 self.assertRaises(self.failureException, self.assertGreaterEqual, b'ant',
2687 b'bug')
2688 self.assertRaises(self.failureException, self.assertLess, b'bug', b'ant')
2689 self.assertRaises(self.failureException, self.assertLess, b'ant', b'ant')
2690 self.assertRaises(self.failureException, self.assertLessEqual, b'bug', b'ant')
2691
2692 def testAssertMultiLineEqual(self):
2693 sample_text = """\
2694http://www.python.org/doc/2.3/lib/module-unittest.html
2695test case
2696 A test case is the smallest unit of testing. [...]
2697"""
2698 revised_sample_text = """\
2699http://www.python.org/doc/2.4.1/lib/module-unittest.html
2700test case
2701 A test case is the smallest unit of testing. [...] You may provide your
2702 own implementation that does not subclass from TestCase, of course.
2703"""
2704 sample_text_error = """
2705- http://www.python.org/doc/2.3/lib/module-unittest.html
2706? ^
2707+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2708? ^^^
2709 test case
2710- A test case is the smallest unit of testing. [...]
2711+ A test case is the smallest unit of testing. [...] You may provide your
2712? +++++++++++++++++++++
2713+ own implementation that does not subclass from TestCase, of course.
2714"""
2715
2716 try:
2717 self.assertMultiLineEqual(sample_text, revised_sample_text)
2718 except self.failureException as e:
2719 # no fair testing ourself with ourself, use assertEqual..
2720 self.assertEqual(sample_text_error, str(e))
2721
2722 def testAssertIsNone(self):
2723 self.assertIsNone(None)
2724 self.assertRaises(self.failureException, self.assertIsNone, False)
2725 self.assertIsNotNone('DjZoPloGears on Rails')
2726 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2727
2728 def testAssertRegexpMatches(self):
2729 self.assertRegexpMatches('asdfabasdf', r'ab+')
2730 self.assertRaises(self.failureException, self.assertRegexpMatches,
2731 'saaas', r'aaaa')
2732
2733 def testAssertRaisesRegexp(self):
2734 class ExceptionMock(Exception):
2735 pass
2736
2737 def Stub():
2738 raise ExceptionMock('We expect')
2739
2740 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2741 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2742
2743 def testAssertNotRaisesRegexp(self):
2744 self.assertRaisesRegexp(
Benjamin Peterson4f75b642009-04-04 16:39:09 +00002745 self.failureException, '^Exception not raised by <lambda>$',
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002746 self.assertRaisesRegexp, Exception, re.compile('x'),
2747 lambda: None)
2748 self.assertRaisesRegexp(
Benjamin Peterson4f75b642009-04-04 16:39:09 +00002749 self.failureException, '^Exception not raised by <lambda>$',
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002750 self.assertRaisesRegexp, Exception, 'x',
2751 lambda: None)
2752
2753 def testAssertRaisesRegexpMismatch(self):
2754 def Stub():
2755 raise Exception('Unexpected')
2756
2757 self.assertRaisesRegexp(
2758 self.failureException,
2759 r'"\^Expected\$" does not match "Unexpected"',
2760 self.assertRaisesRegexp, Exception, '^Expected$',
2761 Stub)
2762 self.assertRaisesRegexp(
2763 self.failureException,
2764 r'"\^Expected\$" does not match "Unexpected"',
2765 self.assertRaisesRegexp, Exception,
2766 re.compile('^Expected$'), Stub)
2767
2768 def testSynonymAssertMethodNames(self):
2769 """Test undocumented method name synonyms.
2770
2771 Please do not use these methods names in your own code.
2772
2773 This test confirms their continued existence and functionality
2774 in order to avoid breaking existing code.
2775 """
2776 self.assertNotEquals(3, 5)
2777 self.assertEquals(3, 3)
2778 self.assertAlmostEquals(2.0, 2.0)
2779 self.assertNotAlmostEquals(3.0, 5.0)
2780 self.assert_(True)
2781
2782 def testPendingDeprecationMethodNames(self):
2783 """Test fail* methods pending deprecation, they will warn in 3.2.
2784
2785 Do not use these methods. They will go away in 3.3.
2786 """
2787 self.failIfEqual(3, 5)
2788 self.failUnlessEqual(3, 3)
2789 self.failUnlessAlmostEqual(2.0, 2.0)
2790 self.failIfAlmostEqual(3.0, 5.0)
2791 self.failUnless(True)
2792 self.failUnlessRaises(TypeError, lambda _: 3.14 + 'spam')
2793 self.failIf(False)
2794
2795 def testDeepcopy(self):
2796 # Issue: 5660
2797 class TestableTest(TestCase):
2798 def testNothing(self):
2799 pass
2800
2801 test = TestableTest('testNothing')
2802
2803 # This shouldn't blow up
2804 deepcopy(test)
2805
Benjamin Peterson5254c042009-03-23 22:25:03 +00002806
2807class Test_TestSkipping(TestCase):
2808
2809 def test_skipping(self):
2810 class Foo(unittest.TestCase):
2811 def test_skip_me(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00002812 self.skipTest("skip")
Benjamin Peterson5254c042009-03-23 22:25:03 +00002813 events = []
2814 result = LoggingResult(events)
2815 test = Foo("test_skip_me")
2816 test.run(result)
2817 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2818 self.assertEqual(result.skipped, [(test, "skip")])
2819
2820 # Try letting setUp skip the test now.
2821 class Foo(unittest.TestCase):
2822 def setUp(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00002823 self.skipTest("testing")
Benjamin Peterson5254c042009-03-23 22:25:03 +00002824 def test_nothing(self): pass
2825 events = []
2826 result = LoggingResult(events)
2827 test = Foo("test_nothing")
2828 test.run(result)
2829 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2830 self.assertEqual(result.skipped, [(test, "testing")])
2831 self.assertEqual(result.testsRun, 1)
2832
2833 def test_skipping_decorators(self):
2834 op_table = ((unittest.skipUnless, False, True),
2835 (unittest.skipIf, True, False))
2836 for deco, do_skip, dont_skip in op_table:
2837 class Foo(unittest.TestCase):
2838 @deco(do_skip, "testing")
2839 def test_skip(self): pass
2840
2841 @deco(dont_skip, "testing")
2842 def test_dont_skip(self): pass
2843 test_do_skip = Foo("test_skip")
2844 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002845 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002846 events = []
2847 result = LoggingResult(events)
2848 suite.run(result)
2849 self.assertEqual(len(result.skipped), 1)
2850 expected = ['startTest', 'addSkip', 'stopTest',
2851 'startTest', 'addSuccess', 'stopTest']
2852 self.assertEqual(events, expected)
2853 self.assertEqual(result.testsRun, 2)
2854 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
2855 self.assertTrue(result.wasSuccessful())
2856
2857 def test_skip_class(self):
2858 @unittest.skip("testing")
2859 class Foo(unittest.TestCase):
2860 def test_1(self):
2861 record.append(1)
2862 record = []
2863 result = unittest.TestResult()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002864 test = Foo("test_1")
2865 suite = unittest.TestSuite([test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002866 suite.run(result)
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002867 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002868 self.assertEqual(record, [])
2869
2870 def test_expected_failure(self):
2871 class Foo(unittest.TestCase):
2872 @unittest.expectedFailure
2873 def test_die(self):
2874 self.fail("help me!")
2875 events = []
2876 result = LoggingResult(events)
2877 test = Foo("test_die")
2878 test.run(result)
2879 self.assertEqual(events,
2880 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Peterson52baa292009-03-24 00:56:30 +00002881 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson5254c042009-03-23 22:25:03 +00002882 self.assertTrue(result.wasSuccessful())
2883
2884 def test_unexpected_success(self):
2885 class Foo(unittest.TestCase):
2886 @unittest.expectedFailure
2887 def test_die(self):
2888 pass
2889 events = []
2890 result = LoggingResult(events)
2891 test = Foo("test_die")
2892 test.run(result)
2893 self.assertEqual(events,
2894 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
2895 self.assertFalse(result.failures)
Benjamin Peterson52baa292009-03-24 00:56:30 +00002896 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002897 self.assertTrue(result.wasSuccessful())
2898
2899
2900
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00002901class Test_Assertions(TestCase):
2902 def test_AlmostEqual(self):
Georg Brandlfe5f11c2009-08-13 08:52:53 +00002903 self.assertAlmostEqual(1.00000001, 1.0)
2904 self.assertNotAlmostEqual(1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002905 self.assertRaises(self.failureException,
Georg Brandlfe5f11c2009-08-13 08:52:53 +00002906 self.assertAlmostEqual, 1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002907 self.assertRaises(self.failureException,
Georg Brandlfe5f11c2009-08-13 08:52:53 +00002908 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00002909
Georg Brandlfe5f11c2009-08-13 08:52:53 +00002910 self.assertAlmostEqual(1.1, 1.0, places=0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002911 self.assertRaises(self.failureException,
Georg Brandlfe5f11c2009-08-13 08:52:53 +00002912 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00002913
Georg Brandlfe5f11c2009-08-13 08:52:53 +00002914 self.assertAlmostEqual(0, .1+.1j, places=0)
2915 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002916 self.assertRaises(self.failureException,
Georg Brandlfe5f11c2009-08-13 08:52:53 +00002917 self.assertAlmostEqual, 0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002918 self.assertRaises(self.failureException,
Georg Brandlfe5f11c2009-08-13 08:52:53 +00002919 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00002920
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00002921 def test_assertRaises(self):
2922 def _raise(e):
2923 raise e
2924 self.assertRaises(KeyError, _raise, KeyError)
2925 self.assertRaises(KeyError, _raise, KeyError("key"))
2926 try:
2927 self.assertRaises(KeyError, lambda: None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002928 except self.failureException as e:
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00002929 self.assert_("KeyError not raised" in str(e), str(e))
2930 else:
2931 self.fail("assertRaises() didn't fail")
2932 try:
2933 self.assertRaises(KeyError, _raise, ValueError)
2934 except ValueError:
2935 pass
2936 else:
2937 self.fail("assertRaises() didn't let exception pass through")
2938 with self.assertRaises(KeyError):
2939 raise KeyError
2940 with self.assertRaises(KeyError):
2941 raise KeyError("key")
2942 try:
2943 with self.assertRaises(KeyError):
2944 pass
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002945 except self.failureException as e:
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00002946 self.assert_("KeyError not raised" in str(e), str(e))
2947 else:
2948 self.fail("assertRaises() didn't fail")
2949 try:
2950 with self.assertRaises(KeyError):
2951 raise ValueError
2952 except ValueError:
2953 pass
2954 else:
2955 self.fail("assertRaises() didn't let exception pass through")
2956
2957
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002958class TestLongMessage(TestCase):
2959 """Test that the individual asserts honour longMessage.
2960 This actually tests all the message behaviour for
2961 asserts that use longMessage."""
2962
2963 def setUp(self):
2964 class TestableTestFalse(TestCase):
2965 longMessage = False
2966 failureException = self.failureException
2967
2968 def testTest(self):
2969 pass
2970
2971 class TestableTestTrue(TestCase):
2972 longMessage = True
2973 failureException = self.failureException
2974
2975 def testTest(self):
2976 pass
2977
2978 self.testableTrue = TestableTestTrue('testTest')
2979 self.testableFalse = TestableTestFalse('testTest')
2980
2981 def testDefault(self):
2982 self.assertFalse(TestCase.longMessage)
2983
2984 def test_formatMsg(self):
2985 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
2986 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
2987
2988 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
2989 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
2990
2991 def assertMessages(self, methodName, args, errors):
2992 def getMethod(i):
2993 useTestableFalse = i < 2
2994 if useTestableFalse:
2995 test = self.testableFalse
2996 else:
2997 test = self.testableTrue
2998 return getattr(test, methodName)
2999
3000 for i, expected_regexp in enumerate(errors):
3001 testMethod = getMethod(i)
3002 kwargs = {}
3003 withMsg = i % 2
3004 if withMsg:
3005 kwargs = {"msg": "oops"}
3006
3007 with self.assertRaisesRegexp(self.failureException,
3008 expected_regexp=expected_regexp):
3009 testMethod(*args, **kwargs)
3010
3011 def testAssertTrue(self):
3012 self.assertMessages('assertTrue', (False,),
3013 ["^False is not True$", "^oops$", "^False is not True$",
3014 "^False is not True : oops$"])
3015
3016 def testAssertFalse(self):
3017 self.assertMessages('assertFalse', (True,),
3018 ["^True is not False$", "^oops$", "^True is not False$",
3019 "^True is not False : oops$"])
3020
3021 def testNotEqual(self):
3022 self.assertMessages('assertNotEqual', (1, 1),
3023 ["^1 == 1$", "^oops$", "^1 == 1$",
3024 "^1 == 1 : oops$"])
3025
3026 def testAlmostEqual(self):
3027 self.assertMessages('assertAlmostEqual', (1, 2),
3028 ["^1 != 2 within 7 places$", "^oops$",
3029 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3030
3031 def testNotAlmostEqual(self):
3032 self.assertMessages('assertNotAlmostEqual', (1, 1),
3033 ["^1 == 1 within 7 places$", "^oops$",
3034 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3035
3036 def test_baseAssertEqual(self):
3037 self.assertMessages('_baseAssertEqual', (1, 2),
3038 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3039
3040 def testAssertSequenceEqual(self):
3041 # Error messages are multiline so not testing on full message
3042 # assertTupleEqual and assertListEqual delegate to this method
3043 self.assertMessages('assertSequenceEqual', ([], [None]),
3044 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3045 r"\+ \[None\] : oops$"])
3046
3047 def testAssertSetEqual(self):
3048 self.assertMessages('assertSetEqual', (set(), set([None])),
3049 ["None$", "^oops$", "None$",
3050 "None : oops$"])
3051
3052 def testAssertIn(self):
3053 self.assertMessages('assertIn', (None, []),
3054 ['^None not found in \[\]$', "^oops$",
3055 '^None not found in \[\]$',
3056 '^None not found in \[\] : oops$'])
3057
3058 def testAssertNotIn(self):
3059 self.assertMessages('assertNotIn', (None, [None]),
3060 ['^None unexpectedly found in \[None\]$', "^oops$",
3061 '^None unexpectedly found in \[None\]$',
3062 '^None unexpectedly found in \[None\] : oops$'])
3063
3064 def testAssertDictEqual(self):
3065 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3066 [r"\+ \{'key': 'value'\}$", "^oops$",
3067 "\+ \{'key': 'value'\}$",
3068 "\+ \{'key': 'value'\} : oops$"])
3069
3070 def testAssertDictContainsSubset(self):
3071 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3072 ["^Missing: 'key'$", "^oops$",
3073 "^Missing: 'key'$",
3074 "^Missing: 'key' : oops$"])
3075
3076 def testAssertSameElements(self):
3077 self.assertMessages('assertSameElements', ([], [None]),
3078 [r"\[None\]$", "^oops$",
3079 r"\[None\]$",
3080 r"\[None\] : oops$"])
3081
3082 def testAssertMultiLineEqual(self):
3083 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3084 [r"\+ foo$", "^oops$",
3085 r"\+ foo$",
3086 r"\+ foo : oops$"])
3087
3088 def testAssertLess(self):
3089 self.assertMessages('assertLess', (2, 1),
3090 ["^2 not less than 1$", "^oops$",
3091 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3092
3093 def testAssertLessEqual(self):
3094 self.assertMessages('assertLessEqual', (2, 1),
3095 ["^2 not less than or equal to 1$", "^oops$",
3096 "^2 not less than or equal to 1$",
3097 "^2 not less than or equal to 1 : oops$"])
3098
3099 def testAssertGreater(self):
3100 self.assertMessages('assertGreater', (1, 2),
3101 ["^1 not greater than 2$", "^oops$",
3102 "^1 not greater than 2$",
3103 "^1 not greater than 2 : oops$"])
3104
3105 def testAssertGreaterEqual(self):
3106 self.assertMessages('assertGreaterEqual', (1, 2),
3107 ["^1 not greater than or equal to 2$", "^oops$",
3108 "^1 not greater than or equal to 2$",
3109 "^1 not greater than or equal to 2 : oops$"])
3110
3111 def testAssertIsNone(self):
3112 self.assertMessages('assertIsNone', ('not None',),
3113 ["^'not None' is not None$", "^oops$",
3114 "^'not None' is not None$",
3115 "^'not None' is not None : oops$"])
3116
3117 def testAssertIsNotNone(self):
3118 self.assertMessages('assertIsNotNone', (None,),
3119 ["^unexpectedly None$", "^oops$",
3120 "^unexpectedly None$",
3121 "^unexpectedly None : oops$"])
3122
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00003123 def testAssertIs(self):
3124 self.assertMessages('assertIs', (None, 'foo'),
3125 ["^None is not 'foo'$", "^oops$",
3126 "^None is not 'foo'$",
3127 "^None is not 'foo' : oops$"])
3128
3129 def testAssertIsNot(self):
3130 self.assertMessages('assertIsNot', (None, None),
3131 ["^unexpectedly identical: None$", "^oops$",
3132 "^unexpectedly identical: None$",
3133 "^unexpectedly identical: None : oops$"])
3134
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003135
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003136class TestCleanUp(TestCase):
3137
3138 def testCleanUp(self):
3139 class TestableTest(TestCase):
3140 def testNothing(self):
3141 pass
3142
3143 test = TestableTest('testNothing')
3144 self.assertEqual(test._cleanups, [])
3145
3146 cleanups = []
3147
3148 def cleanup1(*args, **kwargs):
3149 cleanups.append((1, args, kwargs))
3150
3151 def cleanup2(*args, **kwargs):
3152 cleanups.append((2, args, kwargs))
3153
3154 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3155 test.addCleanup(cleanup2)
3156
3157 self.assertEqual(test._cleanups,
3158 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3159 (cleanup2, (), {})])
3160
3161 result = test.doCleanups()
3162 self.assertTrue(result)
3163
3164 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3165
3166 def testCleanUpWithErrors(self):
3167 class TestableTest(TestCase):
3168 def testNothing(self):
3169 pass
3170
3171 class MockResult(object):
3172 errors = []
3173 def addError(self, test, exc_info):
3174 self.errors.append((test, exc_info))
3175
3176 result = MockResult()
3177 test = TestableTest('testNothing')
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00003178 test._resultForDoCleanups = result
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003179
3180 exc1 = Exception('foo')
3181 exc2 = Exception('bar')
3182 def cleanup1():
3183 raise exc1
3184
3185 def cleanup2():
3186 raise exc2
3187
3188 test.addCleanup(cleanup1)
3189 test.addCleanup(cleanup2)
3190
3191 self.assertFalse(test.doCleanups())
3192
3193 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3194 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3195 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3196
3197 def testCleanupInRun(self):
3198 blowUp = False
3199 ordering = []
3200
3201 class TestableTest(TestCase):
3202 def setUp(self):
3203 ordering.append('setUp')
3204 if blowUp:
3205 raise Exception('foo')
3206
3207 def testNothing(self):
3208 ordering.append('test')
3209
3210 def tearDown(self):
3211 ordering.append('tearDown')
3212
3213 test = TestableTest('testNothing')
3214
3215 def cleanup1():
3216 ordering.append('cleanup1')
3217 def cleanup2():
3218 ordering.append('cleanup2')
3219 test.addCleanup(cleanup1)
3220 test.addCleanup(cleanup2)
3221
3222 def success(some_test):
3223 self.assertEqual(some_test, test)
3224 ordering.append('success')
3225
3226 result = unittest.TestResult()
3227 result.addSuccess = success
3228
3229 test.run(result)
3230 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3231 'cleanup2', 'cleanup1', 'success'])
3232
3233 blowUp = True
3234 ordering = []
3235 test = TestableTest('testNothing')
3236 test.addCleanup(cleanup1)
3237 test.run(result)
3238 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3239
3240
3241class Test_TestProgram(TestCase):
3242
3243 # Horrible white box test
3244 def testNoExit(self):
3245 result = object()
3246 test = object()
3247
3248 class FakeRunner(object):
3249 def run(self, test):
3250 self.test = test
3251 return result
3252
3253 runner = FakeRunner()
3254
3255 try:
3256 oldParseArgs = TestProgram.parseArgs
3257 TestProgram.parseArgs = lambda *args: None
3258 TestProgram.test = test
3259
3260 program = TestProgram(testRunner=runner, exit=False)
3261
3262 self.assertEqual(program.result, result)
3263 self.assertEqual(runner.test, test)
3264
3265 finally:
3266 TestProgram.parseArgs = oldParseArgs
3267 del TestProgram.test
3268
3269
3270 class FooBar(unittest.TestCase):
3271 def testPass(self):
3272 assert True
3273 def testFail(self):
3274 assert False
3275
3276 class FooBarLoader(unittest.TestLoader):
3277 """Test loader that returns a suite containing FooBar."""
3278 def loadTestsFromModule(self, module):
3279 return self.suiteClass(
3280 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3281
3282
3283 def test_NonExit(self):
3284 program = unittest.main(exit=False,
3285 argv=["foobar"],
3286 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3287 testLoader=self.FooBarLoader())
3288 self.assertTrue(hasattr(program, 'result'))
3289
3290
3291 def test_Exit(self):
3292 self.assertRaises(
3293 SystemExit,
3294 unittest.main,
3295 argv=["foobar"],
3296 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3297 exit=True,
3298 testLoader=self.FooBarLoader())
3299
3300
3301 def test_ExitAsDefault(self):
3302 self.assertRaises(
3303 SystemExit,
3304 unittest.main,
3305 argv=["foobar"],
3306 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3307 testLoader=self.FooBarLoader())
3308
3309
3310class Test_TextTestRunner(TestCase):
3311 """Tests for TextTestRunner."""
3312
3313 def test_works_with_result_without_startTestRun_stopTestRun(self):
3314 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3315 separator2 = ''
3316 def printErrors(self):
3317 pass
3318
3319 class Runner(unittest.TextTestRunner):
3320 def __init__(self):
3321 super(Runner, self).__init__(io.StringIO())
3322
3323 def _makeResult(self):
3324 return OldTextResult()
3325
3326 runner = Runner()
3327 runner.run(unittest.TestSuite())
3328
3329 def test_startTestRun_stopTestRun_called(self):
3330 class LoggingTextResult(LoggingResult):
3331 separator2 = ''
3332 def printErrors(self):
3333 pass
3334
3335 class LoggingRunner(unittest.TextTestRunner):
3336 def __init__(self, events):
3337 super(LoggingRunner, self).__init__(io.StringIO())
3338 self._events = events
3339
3340 def _makeResult(self):
3341 return LoggingTextResult(self._events)
3342
3343 events = []
3344 runner = LoggingRunner(events)
3345 runner.run(unittest.TestSuite())
3346 expected = ['startTestRun', 'stopTestRun']
3347 self.assertEqual(events, expected)
3348
3349
Jim Fultonfafd8742004-08-28 15:22:12 +00003350######################################################################
3351## Main
3352######################################################################
3353
3354def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003355 support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003356 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003357 Test_TestSkipping, Test_Assertions, TestLongMessage,
3358 Test_TestProgram, TestCleanUp)
Jim Fultonfafd8742004-08-28 15:22:12 +00003359
Guido van Rossumd8faa362007-04-27 19:54:29 +00003360if __name__ == "__main__":
Jim Fultonfafd8742004-08-28 15:22:12 +00003361 test_main()