blob: 991740c6ff0cbe7dde7010a4b251b167c06992e9 [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 Petersond2397752009-06-27 23:45:02 +00009import os
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000010import re
Benjamin Petersond2397752009-06-27 23:45:02 +000011import sys
Benjamin Peterson6bcbad52009-06-30 23:45:41 +000012import warnings
Benjamin Petersonee8712c2008-05-20 21:35:26 +000013from test import support
Jim Fultonfafd8742004-08-28 15:22:12 +000014import unittest
Benjamin Peterson25c95f12009-05-08 20:42:26 +000015from unittest import TestCase, TestProgram
Christian Heimes45f9af32007-11-27 21:50:00 +000016import types
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000017from copy import deepcopy
Benjamin Peterson25c95f12009-05-08 20:42:26 +000018import io
Jim Fultonfafd8742004-08-28 15:22:12 +000019
Guido van Rossumd8faa362007-04-27 19:54:29 +000020### Support code
21################################################################
Jim Fultonfafd8742004-08-28 15:22:12 +000022
Guido van Rossumd8faa362007-04-27 19:54:29 +000023class LoggingResult(unittest.TestResult):
24 def __init__(self, log):
25 self._events = log
Guido van Rossumcd16bf62007-06-13 18:07:49 +000026 super().__init__()
Guido van Rossumd8faa362007-04-27 19:54:29 +000027
28 def startTest(self, test):
29 self._events.append('startTest')
Guido van Rossumcd16bf62007-06-13 18:07:49 +000030 super().startTest(test)
Guido van Rossumd8faa362007-04-27 19:54:29 +000031
Benjamin Peterson25c95f12009-05-08 20:42:26 +000032 def startTestRun(self):
33 self._events.append('startTestRun')
34 super(LoggingResult, self).startTestRun()
35
Guido van Rossumd8faa362007-04-27 19:54:29 +000036 def stopTest(self, test):
37 self._events.append('stopTest')
Guido van Rossumcd16bf62007-06-13 18:07:49 +000038 super().stopTest(test)
Guido van Rossumd8faa362007-04-27 19:54:29 +000039
Benjamin Peterson25c95f12009-05-08 20:42:26 +000040 def stopTestRun(self):
41 self._events.append('stopTestRun')
42 super(LoggingResult, self).stopTestRun()
43
Guido van Rossumd8faa362007-04-27 19:54:29 +000044 def addFailure(self, *args):
45 self._events.append('addFailure')
Guido van Rossumcd16bf62007-06-13 18:07:49 +000046 super().addFailure(*args)
Guido van Rossumd8faa362007-04-27 19:54:29 +000047
Benjamin Peterson5254c042009-03-23 22:25:03 +000048 def addSuccess(self, *args):
49 self._events.append('addSuccess')
50 super(LoggingResult, self).addSuccess(*args)
51
Guido van Rossumd8faa362007-04-27 19:54:29 +000052 def addError(self, *args):
53 self._events.append('addError')
Guido van Rossumcd16bf62007-06-13 18:07:49 +000054 super().addError(*args)
Guido van Rossumd8faa362007-04-27 19:54:29 +000055
Benjamin Peterson5254c042009-03-23 22:25:03 +000056 def addSkip(self, *args):
57 self._events.append('addSkip')
58 super(LoggingResult, self).addSkip(*args)
59
60 def addExpectedFailure(self, *args):
61 self._events.append('addExpectedFailure')
62 super(LoggingResult, self).addExpectedFailure(*args)
63
64 def addUnexpectedSuccess(self, *args):
65 self._events.append('addUnexpectedSuccess')
66 super(LoggingResult, self).addUnexpectedSuccess(*args)
67
68
Guido van Rossumd8faa362007-04-27 19:54:29 +000069class TestEquality(object):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000070 """Used as a mixin for TestCase"""
71
Guido van Rossumd8faa362007-04-27 19:54:29 +000072 # Check for a valid __eq__ implementation
73 def test_eq(self):
74 for obj_1, obj_2 in self.eq_pairs:
75 self.assertEqual(obj_1, obj_2)
76 self.assertEqual(obj_2, obj_1)
77
78 # Check for a valid __ne__ implementation
79 def test_ne(self):
80 for obj_1, obj_2 in self.ne_pairs:
Benjamin Petersone1759f82009-06-30 23:35:19 +000081 self.assertNotEqual(obj_1, obj_2)
82 self.assertNotEqual(obj_2, obj_1)
Guido van Rossumd8faa362007-04-27 19:54:29 +000083
84class TestHashing(object):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000085 """Used as a mixin for TestCase"""
86
Guido van Rossumd8faa362007-04-27 19:54:29 +000087 # Check for a valid __hash__ implementation
88 def test_hash(self):
89 for obj_1, obj_2 in self.eq_pairs:
90 try:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000091 if not hash(obj_1) == hash(obj_2):
92 self.fail("%r and %r do not hash equal" % (obj_1, obj_2))
Guido van Rossumd8faa362007-04-27 19:54:29 +000093 except KeyboardInterrupt:
94 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +000095 except Exception as e:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000096 self.fail("Problem hashing %r and %r: %s" % (obj_1, obj_2, e))
Guido van Rossumd8faa362007-04-27 19:54:29 +000097
98 for obj_1, obj_2 in self.ne_pairs:
99 try:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000100 if hash(obj_1) == hash(obj_2):
101 self.fail("%s and %s hash equal, but shouldn't" %
102 (obj_1, obj_2))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000103 except KeyboardInterrupt:
104 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +0000105 except Exception as e:
106 self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e))
107
108
Benjamin Peterson5254c042009-03-23 22:25:03 +0000109# List subclass we can add attributes to.
110class MyClassSuite(list):
111
Benjamin Peterson14a3dd72009-05-25 00:51:58 +0000112 def __init__(self, tests):
Benjamin Peterson5254c042009-03-23 22:25:03 +0000113 super(MyClassSuite, self).__init__(tests)
114
115
Guido van Rossumd8faa362007-04-27 19:54:29 +0000116################################################################
117### /Support code
118
119class Test_TestLoader(TestCase):
120
121 ### Tests for TestLoader.loadTestsFromTestCase
122 ################################################################
123
124 # "Return a suite of all tests cases contained in the TestCase-derived
125 # class testCaseClass"
126 def test_loadTestsFromTestCase(self):
127 class Foo(unittest.TestCase):
128 def test_1(self): pass
129 def test_2(self): pass
130 def foo_bar(self): pass
131
132 tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
133
134 loader = unittest.TestLoader()
135 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
136
137 # "Return a suite of all tests cases contained in the TestCase-derived
138 # class testCaseClass"
139 #
140 # Make sure it does the right thing even if no tests were found
141 def test_loadTestsFromTestCase__no_matches(self):
142 class Foo(unittest.TestCase):
143 def foo_bar(self): pass
144
145 empty_suite = unittest.TestSuite()
146
147 loader = unittest.TestLoader()
148 self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite)
149
150 # "Return a suite of all tests cases contained in the TestCase-derived
151 # class testCaseClass"
152 #
153 # What happens if loadTestsFromTestCase() is given an object
154 # that isn't a subclass of TestCase? Specifically, what happens
155 # if testCaseClass is a subclass of TestSuite?
156 #
157 # This is checked for specifically in the code, so we better add a
158 # test for it.
159 def test_loadTestsFromTestCase__TestSuite_subclass(self):
160 class NotATestCase(unittest.TestSuite):
161 pass
162
163 loader = unittest.TestLoader()
164 try:
165 loader.loadTestsFromTestCase(NotATestCase)
166 except TypeError:
167 pass
168 else:
169 self.fail('Should raise TypeError')
170
171 # "Return a suite of all tests cases contained in the TestCase-derived
172 # class testCaseClass"
173 #
174 # Make sure loadTestsFromTestCase() picks up the default test method
175 # name (as specified by TestCase), even though the method name does
176 # not match the default TestLoader.testMethodPrefix string
177 def test_loadTestsFromTestCase__default_method_name(self):
178 class Foo(unittest.TestCase):
179 def runTest(self):
180 pass
181
182 loader = unittest.TestLoader()
183 # This has to be false for the test to succeed
Benjamin Petersone1759f82009-06-30 23:35:19 +0000184 self.assertFalse('runTest'.startswith(loader.testMethodPrefix))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000185
186 suite = loader.loadTestsFromTestCase(Foo)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000187 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000188 self.assertEqual(list(suite), [Foo('runTest')])
189
190 ################################################################
191 ### /Tests for TestLoader.loadTestsFromTestCase
192
193 ### Tests for TestLoader.loadTestsFromModule
194 ################################################################
195
196 # "This method searches `module` for classes derived from TestCase"
197 def test_loadTestsFromModule__TestCase_subclass(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000198 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000199 class MyTestCase(unittest.TestCase):
200 def test(self):
201 pass
202 m.testcase_1 = MyTestCase
203
204 loader = unittest.TestLoader()
205 suite = loader.loadTestsFromModule(m)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000206 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000207
208 expected = [loader.suiteClass([MyTestCase('test')])]
209 self.assertEqual(list(suite), expected)
210
211 # "This method searches `module` for classes derived from TestCase"
212 #
213 # What happens if no tests are found (no TestCase instances)?
214 def test_loadTestsFromModule__no_TestCase_instances(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000215 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000216
217 loader = unittest.TestLoader()
218 suite = loader.loadTestsFromModule(m)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000219 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000220 self.assertEqual(list(suite), [])
221
222 # "This method searches `module` for classes derived from TestCase"
223 #
224 # What happens if no tests are found (TestCases instances, but no tests)?
225 def test_loadTestsFromModule__no_TestCase_tests(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000226 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000227 class MyTestCase(unittest.TestCase):
228 pass
229 m.testcase_1 = MyTestCase
230
231 loader = unittest.TestLoader()
232 suite = loader.loadTestsFromModule(m)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000233 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000234
235 self.assertEqual(list(suite), [loader.suiteClass()])
236
237 # "This method searches `module` for classes derived from TestCase"s
238 #
239 # What happens if loadTestsFromModule() is given something other
240 # than a module?
241 #
242 # XXX Currently, it succeeds anyway. This flexibility
243 # should either be documented or loadTestsFromModule() should
244 # raise a TypeError
245 #
246 # XXX Certain people are using this behaviour. We'll add a test for it
247 def test_loadTestsFromModule__not_a_module(self):
248 class MyTestCase(unittest.TestCase):
249 def test(self):
250 pass
251
252 class NotAModule(object):
253 test_2 = MyTestCase
254
255 loader = unittest.TestLoader()
256 suite = loader.loadTestsFromModule(NotAModule)
257
258 reference = [unittest.TestSuite([MyTestCase('test')])]
259 self.assertEqual(list(suite), reference)
260
Benjamin Petersond2397752009-06-27 23:45:02 +0000261
262 # Check that loadTestsFromModule honors (or not) a module
263 # with a load_tests function.
264 def test_loadTestsFromModule__load_tests(self):
265 m = types.ModuleType('m')
266 class MyTestCase(unittest.TestCase):
267 def test(self):
268 pass
269 m.testcase_1 = MyTestCase
270
271 load_tests_args = []
272 def load_tests(loader, tests, pattern):
273 load_tests_args.extend((loader, tests, pattern))
274 return tests
275 m.load_tests = load_tests
276
277 loader = unittest.TestLoader()
278 suite = loader.loadTestsFromModule(m)
279 self.assertEquals(load_tests_args, [loader, suite, None])
280
281 load_tests_args = []
282 suite = loader.loadTestsFromModule(m, use_load_tests=False)
283 self.assertEquals(load_tests_args, [])
284
Guido van Rossumd8faa362007-04-27 19:54:29 +0000285 ################################################################
286 ### /Tests for TestLoader.loadTestsFromModule()
287
288 ### Tests for TestLoader.loadTestsFromName()
289 ################################################################
290
291 # "The specifier name is a ``dotted name'' that may resolve either to
292 # a module, a test case class, a TestSuite instance, a test method
293 # within a test case class, or a callable object which returns a
294 # TestCase or TestSuite instance."
295 #
296 # Is ValueError raised in response to an empty name?
297 def test_loadTestsFromName__empty_name(self):
298 loader = unittest.TestLoader()
299
300 try:
301 loader.loadTestsFromName('')
302 except ValueError as e:
303 self.assertEqual(str(e), "Empty module name")
304 else:
305 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
306
307 # "The specifier name is a ``dotted name'' that may resolve either to
308 # a module, a test case class, a TestSuite instance, a test method
309 # within a test case class, or a callable object which returns a
310 # TestCase or TestSuite instance."
311 #
312 # What happens when the name contains invalid characters?
313 def test_loadTestsFromName__malformed_name(self):
314 loader = unittest.TestLoader()
315
316 # XXX Should this raise ValueError or ImportError?
317 try:
318 loader.loadTestsFromName('abc () //')
319 except ValueError:
320 pass
321 except ImportError:
322 pass
323 else:
324 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
325
326 # "The specifier name is a ``dotted name'' that may resolve ... to a
327 # module"
328 #
329 # What happens when a module by that name can't be found?
330 def test_loadTestsFromName__unknown_module_name(self):
331 loader = unittest.TestLoader()
332
333 try:
334 loader.loadTestsFromName('sdasfasfasdf')
335 except ImportError as e:
336 self.assertEqual(str(e), "No module named sdasfasfasdf")
337 else:
338 self.fail("TestLoader.loadTestsFromName failed to raise ImportError")
339
340 # "The specifier name is a ``dotted name'' that may resolve either to
341 # a module, a test case class, a TestSuite instance, a test method
342 # within a test case class, or a callable object which returns a
343 # TestCase or TestSuite instance."
344 #
345 # What happens when the module is found, but the attribute can't?
346 def test_loadTestsFromName__unknown_attr_name(self):
347 loader = unittest.TestLoader()
348
349 try:
350 loader.loadTestsFromName('unittest.sdasfasfasdf')
351 except AttributeError as e:
352 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
353 else:
354 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
355
356 # "The specifier name is a ``dotted name'' that may resolve either to
357 # a module, a test case class, a TestSuite instance, a test method
358 # within a test case class, or a callable object which returns a
359 # TestCase or TestSuite instance."
360 #
361 # What happens when we provide the module, but the attribute can't be
362 # found?
363 def test_loadTestsFromName__relative_unknown_name(self):
364 loader = unittest.TestLoader()
365
366 try:
367 loader.loadTestsFromName('sdasfasfasdf', unittest)
368 except AttributeError as e:
369 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
370 else:
371 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
372
373 # "The specifier name is a ``dotted name'' that may resolve either to
374 # a module, a test case class, a TestSuite instance, a test method
375 # within a test case class, or a callable object which returns a
376 # TestCase or TestSuite instance."
377 # ...
378 # "The method optionally resolves name relative to the given module"
379 #
380 # Does loadTestsFromName raise ValueError when passed an empty
381 # name relative to a provided module?
382 #
383 # XXX Should probably raise a ValueError instead of an AttributeError
384 def test_loadTestsFromName__relative_empty_name(self):
385 loader = unittest.TestLoader()
386
387 try:
388 loader.loadTestsFromName('', unittest)
389 except AttributeError as e:
390 pass
391 else:
392 self.fail("Failed to raise AttributeError")
393
394 # "The specifier name is a ``dotted name'' that may resolve either to
395 # a module, a test case class, a TestSuite instance, a test method
396 # within a test case class, or a callable object which returns a
397 # TestCase or TestSuite instance."
398 # ...
399 # "The method optionally resolves name relative to the given module"
400 #
401 # What happens when an impossible name is given, relative to the provided
402 # `module`?
403 def test_loadTestsFromName__relative_malformed_name(self):
404 loader = unittest.TestLoader()
405
406 # XXX Should this raise AttributeError or ValueError?
407 try:
408 loader.loadTestsFromName('abc () //', unittest)
409 except ValueError:
410 pass
411 except AttributeError:
412 pass
413 else:
414 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
415
416 # "The method optionally resolves name relative to the given module"
417 #
418 # Does loadTestsFromName raise TypeError when the `module` argument
419 # isn't a module object?
420 #
421 # XXX Accepts the not-a-module object, ignorning the object's type
422 # This should raise an exception or the method name should be changed
423 #
424 # XXX Some people are relying on this, so keep it for now
425 def test_loadTestsFromName__relative_not_a_module(self):
426 class MyTestCase(unittest.TestCase):
427 def test(self):
428 pass
429
430 class NotAModule(object):
431 test_2 = MyTestCase
432
433 loader = unittest.TestLoader()
434 suite = loader.loadTestsFromName('test_2', NotAModule)
435
436 reference = [MyTestCase('test')]
437 self.assertEqual(list(suite), reference)
438
439 # "The specifier name is a ``dotted name'' that may resolve either to
440 # a module, a test case class, a TestSuite instance, a test method
441 # within a test case class, or a callable object which returns a
442 # TestCase or TestSuite instance."
443 #
444 # Does it raise an exception if the name resolves to an invalid
445 # object?
446 def test_loadTestsFromName__relative_bad_object(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000447 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000448 m.testcase_1 = object()
449
450 loader = unittest.TestLoader()
451 try:
452 loader.loadTestsFromName('testcase_1', m)
453 except TypeError:
454 pass
455 else:
456 self.fail("Should have raised TypeError")
457
458 # "The specifier name is a ``dotted name'' that may
459 # resolve either to ... a test case class"
460 def test_loadTestsFromName__relative_TestCase_subclass(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000461 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000462 class MyTestCase(unittest.TestCase):
463 def test(self):
464 pass
465 m.testcase_1 = MyTestCase
466
467 loader = unittest.TestLoader()
468 suite = loader.loadTestsFromName('testcase_1', m)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000469 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000470 self.assertEqual(list(suite), [MyTestCase('test')])
471
472 # "The specifier name is a ``dotted name'' that may resolve either to
473 # a module, a test case class, a TestSuite instance, a test method
474 # within a test case class, or a callable object which returns a
475 # TestCase or TestSuite instance."
476 def test_loadTestsFromName__relative_TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000477 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000478 class MyTestCase(unittest.TestCase):
479 def test(self):
480 pass
481 m.testsuite = unittest.TestSuite([MyTestCase('test')])
482
483 loader = unittest.TestLoader()
484 suite = loader.loadTestsFromName('testsuite', m)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000485 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000486
487 self.assertEqual(list(suite), [MyTestCase('test')])
488
489 # "The specifier name is a ``dotted name'' that may resolve ... to
490 # ... a test method within a test case class"
491 def test_loadTestsFromName__relative_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000492 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000493 class MyTestCase(unittest.TestCase):
494 def test(self):
495 pass
496 m.testcase_1 = MyTestCase
497
498 loader = unittest.TestLoader()
499 suite = loader.loadTestsFromName('testcase_1.test', m)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000500 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000501
502 self.assertEqual(list(suite), [MyTestCase('test')])
503
504 # "The specifier name is a ``dotted name'' that may resolve either to
505 # a module, a test case class, a TestSuite instance, a test method
506 # within a test case class, or a callable object which returns a
507 # TestCase or TestSuite instance."
508 #
509 # Does loadTestsFromName() raise the proper exception when trying to
510 # resolve "a test method within a test case class" that doesn't exist
511 # for the given name (relative to a provided module)?
512 def test_loadTestsFromName__relative_invalid_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000513 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000514 class MyTestCase(unittest.TestCase):
515 def test(self):
516 pass
517 m.testcase_1 = MyTestCase
518
519 loader = unittest.TestLoader()
520 try:
521 loader.loadTestsFromName('testcase_1.testfoo', m)
522 except AttributeError as e:
523 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
524 else:
525 self.fail("Failed to raise AttributeError")
526
527 # "The specifier name is a ``dotted name'' that may resolve ... to
528 # ... a callable object which returns a ... TestSuite instance"
529 def test_loadTestsFromName__callable__TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000530 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000531 testcase_1 = unittest.FunctionTestCase(lambda: None)
532 testcase_2 = unittest.FunctionTestCase(lambda: None)
533 def return_TestSuite():
534 return unittest.TestSuite([testcase_1, testcase_2])
535 m.return_TestSuite = return_TestSuite
536
537 loader = unittest.TestLoader()
538 suite = loader.loadTestsFromName('return_TestSuite', m)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000539 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000540 self.assertEqual(list(suite), [testcase_1, testcase_2])
541
542 # "The specifier name is a ``dotted name'' that may resolve ... to
543 # ... a callable object which returns a TestCase ... instance"
544 def test_loadTestsFromName__callable__TestCase_instance(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000545 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000546 testcase_1 = unittest.FunctionTestCase(lambda: None)
547 def return_TestCase():
548 return testcase_1
549 m.return_TestCase = return_TestCase
550
551 loader = unittest.TestLoader()
552 suite = loader.loadTestsFromName('return_TestCase', m)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000553 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000554 self.assertEqual(list(suite), [testcase_1])
555
556 # "The specifier name is a ``dotted name'' that may resolve ... to
557 # ... a callable object which returns a TestCase or TestSuite instance"
558 #
559 # What happens if the callable returns something else?
560 def test_loadTestsFromName__callable__wrong_type(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000561 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000562 def return_wrong():
563 return 6
564 m.return_wrong = return_wrong
565
566 loader = unittest.TestLoader()
567 try:
568 suite = loader.loadTestsFromName('return_wrong', m)
569 except TypeError:
570 pass
571 else:
572 self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
573
574 # "The specifier can refer to modules and packages which have not been
575 # imported; they will be imported as a side-effect"
576 def test_loadTestsFromName__module_not_loaded(self):
577 # We're going to try to load this module as a side-effect, so it
578 # better not be loaded before we try.
579 #
580 # Why pick audioop? Google shows it isn't used very often, so there's
581 # a good chance that it won't be imported when this test is run
582 module_name = 'audioop'
583
584 import sys
585 if module_name in sys.modules:
586 del sys.modules[module_name]
587
588 loader = unittest.TestLoader()
589 try:
590 suite = loader.loadTestsFromName(module_name)
591
Benjamin Petersone1759f82009-06-30 23:35:19 +0000592 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000593 self.assertEqual(list(suite), [])
594
595 # audioop should now be loaded, thanks to loadTestsFromName()
Benjamin Petersone1759f82009-06-30 23:35:19 +0000596 self.assertTrue(module_name in sys.modules)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000597 finally:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000598 if module_name in sys.modules:
599 del sys.modules[module_name]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000600
601 ################################################################
602 ### Tests for TestLoader.loadTestsFromName()
603
604 ### Tests for TestLoader.loadTestsFromNames()
605 ################################################################
606
607 # "Similar to loadTestsFromName(), but takes a sequence of names rather
608 # than a single name."
609 #
610 # What happens if that sequence of names is empty?
611 def test_loadTestsFromNames__empty_name_list(self):
612 loader = unittest.TestLoader()
613
614 suite = loader.loadTestsFromNames([])
Benjamin Petersone1759f82009-06-30 23:35:19 +0000615 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000616 self.assertEqual(list(suite), [])
617
618 # "Similar to loadTestsFromName(), but takes a sequence of names rather
619 # than a single name."
620 # ...
621 # "The method optionally resolves name relative to the given module"
622 #
623 # What happens if that sequence of names is empty?
624 #
625 # XXX Should this raise a ValueError or just return an empty TestSuite?
626 def test_loadTestsFromNames__relative_empty_name_list(self):
627 loader = unittest.TestLoader()
628
629 suite = loader.loadTestsFromNames([], unittest)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000630 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000631 self.assertEqual(list(suite), [])
632
633 # "The specifier name is a ``dotted name'' that may resolve either to
634 # a module, a test case class, a TestSuite instance, a test method
635 # within a test case class, or a callable object which returns a
636 # TestCase or TestSuite instance."
637 #
638 # Is ValueError raised in response to an empty name?
639 def test_loadTestsFromNames__empty_name(self):
640 loader = unittest.TestLoader()
641
642 try:
643 loader.loadTestsFromNames([''])
644 except ValueError as e:
645 self.assertEqual(str(e), "Empty module name")
646 else:
647 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
648
649 # "The specifier name is a ``dotted name'' that may resolve either to
650 # a module, a test case class, a TestSuite instance, a test method
651 # within a test case class, or a callable object which returns a
652 # TestCase or TestSuite instance."
653 #
654 # What happens when presented with an impossible module name?
655 def test_loadTestsFromNames__malformed_name(self):
656 loader = unittest.TestLoader()
657
658 # XXX Should this raise ValueError or ImportError?
659 try:
660 loader.loadTestsFromNames(['abc () //'])
661 except ValueError:
662 pass
663 except ImportError:
664 pass
665 else:
666 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
667
668 # "The specifier name is a ``dotted name'' that may resolve either to
669 # a module, a test case class, a TestSuite instance, a test method
670 # within a test case class, or a callable object which returns a
671 # TestCase or TestSuite instance."
672 #
673 # What happens when no module can be found for the given name?
674 def test_loadTestsFromNames__unknown_module_name(self):
675 loader = unittest.TestLoader()
676
677 try:
678 loader.loadTestsFromNames(['sdasfasfasdf'])
679 except ImportError as e:
680 self.assertEqual(str(e), "No module named sdasfasfasdf")
681 else:
682 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
683
684 # "The specifier name is a ``dotted name'' that may resolve either to
685 # a module, a test case class, a TestSuite instance, a test method
686 # within a test case class, or a callable object which returns a
687 # TestCase or TestSuite instance."
688 #
689 # What happens when the module can be found, but not the attribute?
690 def test_loadTestsFromNames__unknown_attr_name(self):
691 loader = unittest.TestLoader()
692
693 try:
694 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
695 except AttributeError as e:
696 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
697 else:
698 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
699
700 # "The specifier name is a ``dotted name'' that may resolve either to
701 # a module, a test case class, a TestSuite instance, a test method
702 # within a test case class, or a callable object which returns a
703 # TestCase or TestSuite instance."
704 # ...
705 # "The method optionally resolves name relative to the given module"
706 #
707 # What happens when given an unknown attribute on a specified `module`
708 # argument?
709 def test_loadTestsFromNames__unknown_name_relative_1(self):
710 loader = unittest.TestLoader()
711
712 try:
713 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
714 except AttributeError as e:
715 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
716 else:
717 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
718
719 # "The specifier name is a ``dotted name'' that may resolve either to
720 # a module, a test case class, a TestSuite instance, a test method
721 # within a test case class, or a callable object which returns a
722 # TestCase or TestSuite instance."
723 # ...
724 # "The method optionally resolves name relative to the given module"
725 #
726 # Do unknown attributes (relative to a provided module) still raise an
727 # exception even in the presence of valid attribute names?
728 def test_loadTestsFromNames__unknown_name_relative_2(self):
729 loader = unittest.TestLoader()
730
731 try:
732 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
733 except AttributeError as e:
734 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
735 else:
736 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
737
738 # "The specifier name is a ``dotted name'' that may resolve either to
739 # a module, a test case class, a TestSuite instance, a test method
740 # within a test case class, or a callable object which returns a
741 # TestCase or TestSuite instance."
742 # ...
743 # "The method optionally resolves name relative to the given module"
744 #
745 # What happens when faced with the empty string?
746 #
747 # XXX This currently raises AttributeError, though ValueError is probably
748 # more appropriate
749 def test_loadTestsFromNames__relative_empty_name(self):
750 loader = unittest.TestLoader()
751
752 try:
753 loader.loadTestsFromNames([''], unittest)
754 except AttributeError:
755 pass
756 else:
757 self.fail("Failed to raise ValueError")
758
759 # "The specifier name is a ``dotted name'' that may resolve either to
760 # a module, a test case class, a TestSuite instance, a test method
761 # within a test case class, or a callable object which returns a
762 # TestCase or TestSuite instance."
763 # ...
764 # "The method optionally resolves name relative to the given module"
765 #
766 # What happens when presented with an impossible attribute name?
767 def test_loadTestsFromNames__relative_malformed_name(self):
768 loader = unittest.TestLoader()
769
770 # XXX Should this raise AttributeError or ValueError?
771 try:
772 loader.loadTestsFromNames(['abc () //'], unittest)
773 except AttributeError:
774 pass
775 except ValueError:
776 pass
777 else:
778 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
779
780 # "The method optionally resolves name relative to the given module"
781 #
782 # Does loadTestsFromNames() make sure the provided `module` is in fact
783 # a module?
784 #
785 # XXX This validation is currently not done. This flexibility should
786 # either be documented or a TypeError should be raised.
787 def test_loadTestsFromNames__relative_not_a_module(self):
788 class MyTestCase(unittest.TestCase):
789 def test(self):
790 pass
791
792 class NotAModule(object):
793 test_2 = MyTestCase
794
795 loader = unittest.TestLoader()
796 suite = loader.loadTestsFromNames(['test_2'], NotAModule)
797
798 reference = [unittest.TestSuite([MyTestCase('test')])]
799 self.assertEqual(list(suite), reference)
800
801 # "The specifier name is a ``dotted name'' that may resolve either to
802 # a module, a test case class, a TestSuite instance, a test method
803 # within a test case class, or a callable object which returns a
804 # TestCase or TestSuite instance."
805 #
806 # Does it raise an exception if the name resolves to an invalid
807 # object?
808 def test_loadTestsFromNames__relative_bad_object(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000809 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000810 m.testcase_1 = object()
811
812 loader = unittest.TestLoader()
813 try:
814 loader.loadTestsFromNames(['testcase_1'], m)
815 except TypeError:
816 pass
817 else:
818 self.fail("Should have raised TypeError")
819
820 # "The specifier name is a ``dotted name'' that may resolve ... to
821 # ... a test case class"
822 def test_loadTestsFromNames__relative_TestCase_subclass(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000823 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000824 class MyTestCase(unittest.TestCase):
825 def test(self):
826 pass
827 m.testcase_1 = MyTestCase
828
829 loader = unittest.TestLoader()
830 suite = loader.loadTestsFromNames(['testcase_1'], m)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000831 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000832
833 expected = loader.suiteClass([MyTestCase('test')])
834 self.assertEqual(list(suite), [expected])
835
836 # "The specifier name is a ``dotted name'' that may resolve ... to
837 # ... a TestSuite instance"
838 def test_loadTestsFromNames__relative_TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000839 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000840 class MyTestCase(unittest.TestCase):
841 def test(self):
842 pass
843 m.testsuite = unittest.TestSuite([MyTestCase('test')])
844
845 loader = unittest.TestLoader()
846 suite = loader.loadTestsFromNames(['testsuite'], m)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000847 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000848
849 self.assertEqual(list(suite), [m.testsuite])
850
851 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
852 # test method within a test case class"
853 def test_loadTestsFromNames__relative_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000854 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000855 class MyTestCase(unittest.TestCase):
856 def test(self):
857 pass
858 m.testcase_1 = MyTestCase
859
860 loader = unittest.TestLoader()
861 suite = loader.loadTestsFromNames(['testcase_1.test'], m)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000862 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000863
864 ref_suite = unittest.TestSuite([MyTestCase('test')])
865 self.assertEqual(list(suite), [ref_suite])
866
867 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
868 # test method within a test case class"
869 #
870 # Does the method gracefully handle names that initially look like they
871 # resolve to "a test method within a test case class" but don't?
872 def test_loadTestsFromNames__relative_invalid_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000873 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000874 class MyTestCase(unittest.TestCase):
875 def test(self):
876 pass
877 m.testcase_1 = MyTestCase
878
879 loader = unittest.TestLoader()
880 try:
881 loader.loadTestsFromNames(['testcase_1.testfoo'], m)
882 except AttributeError as e:
883 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
884 else:
885 self.fail("Failed to raise AttributeError")
886
887 # "The specifier name is a ``dotted name'' that may resolve ... to
888 # ... a callable object which returns a ... TestSuite instance"
889 def test_loadTestsFromNames__callable__TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000890 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000891 testcase_1 = unittest.FunctionTestCase(lambda: None)
892 testcase_2 = unittest.FunctionTestCase(lambda: None)
893 def return_TestSuite():
894 return unittest.TestSuite([testcase_1, testcase_2])
895 m.return_TestSuite = return_TestSuite
896
897 loader = unittest.TestLoader()
898 suite = loader.loadTestsFromNames(['return_TestSuite'], m)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000899 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000900
901 expected = unittest.TestSuite([testcase_1, testcase_2])
902 self.assertEqual(list(suite), [expected])
903
904 # "The specifier name is a ``dotted name'' that may resolve ... to
905 # ... a callable object which returns a TestCase ... instance"
906 def test_loadTestsFromNames__callable__TestCase_instance(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000907 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000908 testcase_1 = unittest.FunctionTestCase(lambda: None)
909 def return_TestCase():
910 return testcase_1
911 m.return_TestCase = return_TestCase
912
913 loader = unittest.TestLoader()
914 suite = loader.loadTestsFromNames(['return_TestCase'], m)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000915 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000916
917 ref_suite = unittest.TestSuite([testcase_1])
918 self.assertEqual(list(suite), [ref_suite])
919
920 # "The specifier name is a ``dotted name'' that may resolve ... to
921 # ... a callable object which returns a TestCase or TestSuite instance"
922 #
923 # Are staticmethods handled correctly?
924 def test_loadTestsFromNames__callable__call_staticmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000925 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000926 class Test1(unittest.TestCase):
927 def test(self):
928 pass
929
930 testcase_1 = Test1('test')
931 class Foo(unittest.TestCase):
932 @staticmethod
933 def foo():
934 return testcase_1
935 m.Foo = Foo
936
937 loader = unittest.TestLoader()
938 suite = loader.loadTestsFromNames(['Foo.foo'], m)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000939 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000940
941 ref_suite = unittest.TestSuite([testcase_1])
942 self.assertEqual(list(suite), [ref_suite])
943
944 # "The specifier name is a ``dotted name'' that may resolve ... to
945 # ... a callable object which returns a TestCase or TestSuite instance"
946 #
947 # What happens when the callable returns something else?
948 def test_loadTestsFromNames__callable__wrong_type(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000949 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000950 def return_wrong():
951 return 6
952 m.return_wrong = return_wrong
953
954 loader = unittest.TestLoader()
955 try:
956 suite = loader.loadTestsFromNames(['return_wrong'], m)
957 except TypeError:
958 pass
959 else:
960 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
961
962 # "The specifier can refer to modules and packages which have not been
963 # imported; they will be imported as a side-effect"
964 def test_loadTestsFromNames__module_not_loaded(self):
965 # We're going to try to load this module as a side-effect, so it
966 # better not be loaded before we try.
967 #
968 # Why pick audioop? Google shows it isn't used very often, so there's
969 # a good chance that it won't be imported when this test is run
970 module_name = 'audioop'
971
972 import sys
973 if module_name in sys.modules:
974 del sys.modules[module_name]
975
976 loader = unittest.TestLoader()
977 try:
978 suite = loader.loadTestsFromNames([module_name])
979
Benjamin Petersone1759f82009-06-30 23:35:19 +0000980 self.assertTrue(isinstance(suite, loader.suiteClass))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000981 self.assertEqual(list(suite), [unittest.TestSuite()])
982
983 # audioop should now be loaded, thanks to loadTestsFromName()
Benjamin Petersone1759f82009-06-30 23:35:19 +0000984 self.assertTrue(module_name in sys.modules)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000985 finally:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000986 if module_name in sys.modules:
987 del sys.modules[module_name]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000988
989 ################################################################
990 ### /Tests for TestLoader.loadTestsFromNames()
991
992 ### Tests for TestLoader.getTestCaseNames()
993 ################################################################
994
995 # "Return a sorted sequence of method names found within testCaseClass"
996 #
997 # Test.foobar is defined to make sure getTestCaseNames() respects
998 # loader.testMethodPrefix
999 def test_getTestCaseNames(self):
1000 class Test(unittest.TestCase):
1001 def test_1(self): pass
1002 def test_2(self): pass
1003 def foobar(self): pass
1004
1005 loader = unittest.TestLoader()
1006
1007 self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])
1008
1009 # "Return a sorted sequence of method names found within testCaseClass"
1010 #
1011 # Does getTestCaseNames() behave appropriately if no tests are found?
1012 def test_getTestCaseNames__no_tests(self):
1013 class Test(unittest.TestCase):
1014 def foobar(self): pass
1015
1016 loader = unittest.TestLoader()
1017
1018 self.assertEqual(loader.getTestCaseNames(Test), [])
1019
1020 # "Return a sorted sequence of method names found within testCaseClass"
1021 #
1022 # Are not-TestCases handled gracefully?
1023 #
1024 # XXX This should raise a TypeError, not return a list
1025 #
1026 # XXX It's too late in the 2.5 release cycle to fix this, but it should
1027 # probably be revisited for 2.6
1028 def test_getTestCaseNames__not_a_TestCase(self):
1029 class BadCase(int):
1030 def test_foo(self):
1031 pass
1032
1033 loader = unittest.TestLoader()
1034 names = loader.getTestCaseNames(BadCase)
1035
1036 self.assertEqual(names, ['test_foo'])
1037
1038 # "Return a sorted sequence of method names found within testCaseClass"
1039 #
1040 # Make sure inherited names are handled.
1041 #
1042 # TestP.foobar is defined to make sure getTestCaseNames() respects
1043 # loader.testMethodPrefix
1044 def test_getTestCaseNames__inheritance(self):
1045 class TestP(unittest.TestCase):
1046 def test_1(self): pass
1047 def test_2(self): pass
1048 def foobar(self): pass
1049
1050 class TestC(TestP):
1051 def test_1(self): pass
1052 def test_3(self): pass
1053
1054 loader = unittest.TestLoader()
1055
1056 names = ['test_1', 'test_2', 'test_3']
1057 self.assertEqual(loader.getTestCaseNames(TestC), names)
1058
1059 ################################################################
1060 ### /Tests for TestLoader.getTestCaseNames()
1061
1062 ### Tests for TestLoader.testMethodPrefix
1063 ################################################################
1064
1065 # "String giving the prefix of method names which will be interpreted as
1066 # test methods"
1067 #
1068 # Implicit in the documentation is that testMethodPrefix is respected by
1069 # all loadTestsFrom* methods.
1070 def test_testMethodPrefix__loadTestsFromTestCase(self):
1071 class Foo(unittest.TestCase):
1072 def test_1(self): pass
1073 def test_2(self): pass
1074 def foo_bar(self): pass
1075
1076 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1077 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1078
1079 loader = unittest.TestLoader()
1080 loader.testMethodPrefix = 'foo'
1081 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
1082
1083 loader.testMethodPrefix = 'test'
1084 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
1085
1086 # "String giving the prefix of method names which will be interpreted as
1087 # test methods"
1088 #
1089 # Implicit in the documentation is that testMethodPrefix is respected by
1090 # all loadTestsFrom* methods.
1091 def test_testMethodPrefix__loadTestsFromModule(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001092 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001093 class Foo(unittest.TestCase):
1094 def test_1(self): pass
1095 def test_2(self): pass
1096 def foo_bar(self): pass
1097 m.Foo = Foo
1098
1099 tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
1100 tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]
1101
1102 loader = unittest.TestLoader()
1103 loader.testMethodPrefix = 'foo'
1104 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
1105
1106 loader.testMethodPrefix = 'test'
1107 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
1108
1109 # "String giving the prefix of method names which will be interpreted as
1110 # test methods"
1111 #
1112 # Implicit in the documentation is that testMethodPrefix is respected by
1113 # all loadTestsFrom* methods.
1114 def test_testMethodPrefix__loadTestsFromName(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001115 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001116 class Foo(unittest.TestCase):
1117 def test_1(self): pass
1118 def test_2(self): pass
1119 def foo_bar(self): pass
1120 m.Foo = Foo
1121
1122 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1123 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1124
1125 loader = unittest.TestLoader()
1126 loader.testMethodPrefix = 'foo'
1127 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
1128
1129 loader.testMethodPrefix = 'test'
1130 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
1131
1132 # "String giving the prefix of method names which will be interpreted as
1133 # test methods"
1134 #
1135 # Implicit in the documentation is that testMethodPrefix is respected by
1136 # all loadTestsFrom* methods.
1137 def test_testMethodPrefix__loadTestsFromNames(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001138 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001139 class Foo(unittest.TestCase):
1140 def test_1(self): pass
1141 def test_2(self): pass
1142 def foo_bar(self): pass
1143 m.Foo = Foo
1144
1145 tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
1146 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1147 tests_2 = unittest.TestSuite([tests_2])
1148
1149 loader = unittest.TestLoader()
1150 loader.testMethodPrefix = 'foo'
1151 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)
1152
1153 loader.testMethodPrefix = 'test'
1154 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)
1155
1156 # "The default value is 'test'"
1157 def test_testMethodPrefix__default_value(self):
1158 loader = unittest.TestLoader()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001159 self.assertEqual(loader.testMethodPrefix, 'test')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001160
1161 ################################################################
1162 ### /Tests for TestLoader.testMethodPrefix
1163
1164 ### Tests for TestLoader.sortTestMethodsUsing
1165 ################################################################
1166
1167 # "Function to be used to compare method names when sorting them in
1168 # getTestCaseNames() and all the loadTestsFromX() methods"
1169 def test_sortTestMethodsUsing__loadTestsFromTestCase(self):
1170 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001171 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001172
1173 class Foo(unittest.TestCase):
1174 def test_1(self): pass
1175 def test_2(self): pass
1176
1177 loader = unittest.TestLoader()
1178 loader.sortTestMethodsUsing = reversed_cmp
1179
1180 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1181 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
1182
1183 # "Function to be used to compare method names when sorting them in
1184 # getTestCaseNames() and all the loadTestsFromX() methods"
1185 def test_sortTestMethodsUsing__loadTestsFromModule(self):
1186 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001187 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001188
Christian Heimes45f9af32007-11-27 21:50:00 +00001189 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001190 class Foo(unittest.TestCase):
1191 def test_1(self): pass
1192 def test_2(self): pass
1193 m.Foo = Foo
1194
1195 loader = unittest.TestLoader()
1196 loader.sortTestMethodsUsing = reversed_cmp
1197
1198 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1199 self.assertEqual(list(loader.loadTestsFromModule(m)), tests)
1200
1201 # "Function to be used to compare method names when sorting them in
1202 # getTestCaseNames() and all the loadTestsFromX() methods"
1203 def test_sortTestMethodsUsing__loadTestsFromName(self):
1204 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001205 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001206
Christian Heimes45f9af32007-11-27 21:50:00 +00001207 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001208 class Foo(unittest.TestCase):
1209 def test_1(self): pass
1210 def test_2(self): pass
1211 m.Foo = Foo
1212
1213 loader = unittest.TestLoader()
1214 loader.sortTestMethodsUsing = reversed_cmp
1215
1216 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1217 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
1218
1219 # "Function to be used to compare method names when sorting them in
1220 # getTestCaseNames() and all the loadTestsFromX() methods"
1221 def test_sortTestMethodsUsing__loadTestsFromNames(self):
1222 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001223 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001224
Christian Heimes45f9af32007-11-27 21:50:00 +00001225 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001226 class Foo(unittest.TestCase):
1227 def test_1(self): pass
1228 def test_2(self): pass
1229 m.Foo = Foo
1230
1231 loader = unittest.TestLoader()
1232 loader.sortTestMethodsUsing = reversed_cmp
1233
1234 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1235 self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)
1236
1237 # "Function to be used to compare method names when sorting them in
1238 # getTestCaseNames()"
1239 #
1240 # Does it actually affect getTestCaseNames()?
1241 def test_sortTestMethodsUsing__getTestCaseNames(self):
1242 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001243 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001244
1245 class Foo(unittest.TestCase):
1246 def test_1(self): pass
1247 def test_2(self): pass
1248
1249 loader = unittest.TestLoader()
1250 loader.sortTestMethodsUsing = reversed_cmp
1251
1252 test_names = ['test_2', 'test_1']
1253 self.assertEqual(loader.getTestCaseNames(Foo), test_names)
1254
1255 # "The default value is the built-in cmp() function"
Mark Dickinsona56c4672009-01-27 18:17:45 +00001256 # Since cmp is now defunct, we simply verify that the results
1257 # occur in the same order as they would with the default sort.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001258 def test_sortTestMethodsUsing__default_value(self):
1259 loader = unittest.TestLoader()
Mark Dickinsona56c4672009-01-27 18:17:45 +00001260
1261 class Foo(unittest.TestCase):
1262 def test_2(self): pass
1263 def test_3(self): pass
1264 def test_1(self): pass
1265
1266 test_names = ['test_2', 'test_3', 'test_1']
1267 self.assertEqual(loader.getTestCaseNames(Foo), sorted(test_names))
1268
Guido van Rossumd8faa362007-04-27 19:54:29 +00001269
1270 # "it can be set to None to disable the sort."
1271 #
1272 # XXX How is this different from reassigning cmp? Are the tests returned
1273 # in a random order or something? This behaviour should die
1274 def test_sortTestMethodsUsing__None(self):
1275 class Foo(unittest.TestCase):
1276 def test_1(self): pass
1277 def test_2(self): pass
1278
1279 loader = unittest.TestLoader()
1280 loader.sortTestMethodsUsing = None
1281
1282 test_names = ['test_2', 'test_1']
1283 self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))
1284
1285 ################################################################
1286 ### /Tests for TestLoader.sortTestMethodsUsing
1287
1288 ### Tests for TestLoader.suiteClass
1289 ################################################################
1290
1291 # "Callable object that constructs a test suite from a list of tests."
1292 def test_suiteClass__loadTestsFromTestCase(self):
1293 class Foo(unittest.TestCase):
1294 def test_1(self): pass
1295 def test_2(self): pass
1296 def foo_bar(self): pass
1297
1298 tests = [Foo('test_1'), Foo('test_2')]
1299
1300 loader = unittest.TestLoader()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001301 loader.suiteClass = list
Guido van Rossumd8faa362007-04-27 19:54:29 +00001302 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
1303
1304 # It is implicit in the documentation for TestLoader.suiteClass that
1305 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
1306 def test_suiteClass__loadTestsFromModule(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001307 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001308 class Foo(unittest.TestCase):
1309 def test_1(self): pass
1310 def test_2(self): pass
1311 def foo_bar(self): pass
1312 m.Foo = Foo
1313
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001314 tests = [[Foo('test_1'), Foo('test_2')]]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001315
1316 loader = unittest.TestLoader()
1317 loader.suiteClass = list
1318 self.assertEqual(loader.loadTestsFromModule(m), tests)
1319
1320 # It is implicit in the documentation for TestLoader.suiteClass that
1321 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
1322 def test_suiteClass__loadTestsFromName(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001323 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001324 class Foo(unittest.TestCase):
1325 def test_1(self): pass
1326 def test_2(self): pass
1327 def foo_bar(self): pass
1328 m.Foo = Foo
1329
1330 tests = [Foo('test_1'), Foo('test_2')]
1331
1332 loader = unittest.TestLoader()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001333 loader.suiteClass = list
Guido van Rossumd8faa362007-04-27 19:54:29 +00001334 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
1335
1336 # It is implicit in the documentation for TestLoader.suiteClass that
1337 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
1338 def test_suiteClass__loadTestsFromNames(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001339 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001340 class Foo(unittest.TestCase):
1341 def test_1(self): pass
1342 def test_2(self): pass
1343 def foo_bar(self): pass
1344 m.Foo = Foo
1345
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001346 tests = [[Foo('test_1'), Foo('test_2')]]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001347
1348 loader = unittest.TestLoader()
1349 loader.suiteClass = list
1350 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)
1351
1352 # "The default value is the TestSuite class"
1353 def test_suiteClass__default_value(self):
1354 loader = unittest.TestLoader()
Benjamin Petersone1759f82009-06-30 23:35:19 +00001355 self.assertTrue(loader.suiteClass is unittest.TestSuite)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001356
1357 ################################################################
1358 ### /Tests for TestLoader.suiteClass
1359
1360### Support code for Test_TestSuite
1361################################################################
1362
1363class Foo(unittest.TestCase):
1364 def test_1(self): pass
1365 def test_2(self): pass
1366 def test_3(self): pass
1367 def runTest(self): pass
1368
1369def _mk_TestSuite(*names):
1370 return unittest.TestSuite(Foo(n) for n in names)
1371
1372################################################################
1373### /Support code for Test_TestSuite
1374
1375class Test_TestSuite(TestCase, TestEquality):
1376
1377 ### Set up attributes needed by inherited tests
1378 ################################################################
1379
1380 # Used by TestEquality.test_eq
1381 eq_pairs = [(unittest.TestSuite(), unittest.TestSuite())
1382 ,(unittest.TestSuite(), unittest.TestSuite([]))
1383 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]
1384
1385 # Used by TestEquality.test_ne
1386 ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1'))
1387 ,(unittest.TestSuite([]), _mk_TestSuite('test_1'))
1388 ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3'))
1389 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]
1390
1391 ################################################################
1392 ### /Set up attributes needed by inherited tests
1393
1394 ### Tests for TestSuite.__init__
1395 ################################################################
1396
1397 # "class TestSuite([tests])"
1398 #
1399 # The tests iterable should be optional
1400 def test_init__tests_optional(self):
1401 suite = unittest.TestSuite()
1402
1403 self.assertEqual(suite.countTestCases(), 0)
1404
1405 # "class TestSuite([tests])"
1406 # ...
1407 # "If tests is given, it must be an iterable of individual test cases
1408 # or other test suites that will be used to build the suite initially"
1409 #
1410 # TestSuite should deal with empty tests iterables by allowing the
1411 # creation of an empty suite
1412 def test_init__empty_tests(self):
1413 suite = unittest.TestSuite([])
1414
1415 self.assertEqual(suite.countTestCases(), 0)
1416
1417 # "class TestSuite([tests])"
1418 # ...
1419 # "If tests is given, it must be an iterable of individual test cases
1420 # or other test suites that will be used to build the suite initially"
1421 #
1422 # TestSuite should allow any iterable to provide tests
1423 def test_init__tests_from_any_iterable(self):
1424 def tests():
1425 yield unittest.FunctionTestCase(lambda: None)
1426 yield unittest.FunctionTestCase(lambda: None)
1427
1428 suite_1 = unittest.TestSuite(tests())
1429 self.assertEqual(suite_1.countTestCases(), 2)
1430
1431 suite_2 = unittest.TestSuite(suite_1)
1432 self.assertEqual(suite_2.countTestCases(), 2)
1433
1434 suite_3 = unittest.TestSuite(set(suite_1))
1435 self.assertEqual(suite_3.countTestCases(), 2)
1436
1437 # "class TestSuite([tests])"
1438 # ...
1439 # "If tests is given, it must be an iterable of individual test cases
1440 # or other test suites that will be used to build the suite initially"
1441 #
1442 # Does TestSuite() also allow other TestSuite() instances to be present
1443 # in the tests iterable?
1444 def test_init__TestSuite_instances_in_tests(self):
1445 def tests():
1446 ftc = unittest.FunctionTestCase(lambda: None)
1447 yield unittest.TestSuite([ftc])
1448 yield unittest.FunctionTestCase(lambda: None)
1449
1450 suite = unittest.TestSuite(tests())
1451 self.assertEqual(suite.countTestCases(), 2)
1452
1453 ################################################################
1454 ### /Tests for TestSuite.__init__
1455
1456 # Container types should support the iter protocol
1457 def test_iter(self):
1458 test1 = unittest.FunctionTestCase(lambda: None)
1459 test2 = unittest.FunctionTestCase(lambda: None)
1460 suite = unittest.TestSuite((test1, test2))
1461
1462 self.assertEqual(list(suite), [test1, test2])
1463
1464 # "Return the number of tests represented by the this test object.
1465 # ...this method is also implemented by the TestSuite class, which can
1466 # return larger [greater than 1] values"
1467 #
1468 # Presumably an empty TestSuite returns 0?
1469 def test_countTestCases_zero_simple(self):
1470 suite = unittest.TestSuite()
1471
1472 self.assertEqual(suite.countTestCases(), 0)
1473
1474 # "Return the number of tests represented by the this test object.
1475 # ...this method is also implemented by the TestSuite class, which can
1476 # return larger [greater than 1] values"
1477 #
1478 # Presumably an empty TestSuite (even if it contains other empty
1479 # TestSuite instances) returns 0?
1480 def test_countTestCases_zero_nested(self):
1481 class Test1(unittest.TestCase):
1482 def test(self):
1483 pass
1484
1485 suite = unittest.TestSuite([unittest.TestSuite()])
1486
1487 self.assertEqual(suite.countTestCases(), 0)
1488
1489 # "Return the number of tests represented by the this test object.
1490 # ...this method is also implemented by the TestSuite class, which can
1491 # return larger [greater than 1] values"
1492 def test_countTestCases_simple(self):
1493 test1 = unittest.FunctionTestCase(lambda: None)
1494 test2 = unittest.FunctionTestCase(lambda: None)
1495 suite = unittest.TestSuite((test1, test2))
1496
1497 self.assertEqual(suite.countTestCases(), 2)
1498
1499 # "Return the number of tests represented by the this test object.
1500 # ...this method is also implemented by the TestSuite class, which can
1501 # return larger [greater than 1] values"
1502 #
1503 # Make sure this holds for nested TestSuite instances, too
1504 def test_countTestCases_nested(self):
1505 class Test1(unittest.TestCase):
1506 def test1(self): pass
1507 def test2(self): pass
1508
1509 test2 = unittest.FunctionTestCase(lambda: None)
1510 test3 = unittest.FunctionTestCase(lambda: None)
1511 child = unittest.TestSuite((Test1('test2'), test2))
1512 parent = unittest.TestSuite((test3, child, Test1('test1')))
1513
1514 self.assertEqual(parent.countTestCases(), 4)
1515
1516 # "Run the tests associated with this suite, collecting the result into
1517 # the test result object passed as result."
1518 #
1519 # And if there are no tests? What then?
1520 def test_run__empty_suite(self):
1521 events = []
1522 result = LoggingResult(events)
1523
1524 suite = unittest.TestSuite()
1525
1526 suite.run(result)
1527
1528 self.assertEqual(events, [])
1529
1530 # "Note that unlike TestCase.run(), TestSuite.run() requires the
1531 # "result object to be passed in."
1532 def test_run__requires_result(self):
1533 suite = unittest.TestSuite()
1534
1535 try:
1536 suite.run()
1537 except TypeError:
1538 pass
1539 else:
1540 self.fail("Failed to raise TypeError")
1541
1542 # "Run the tests associated with this suite, collecting the result into
1543 # the test result object passed as result."
1544 def test_run(self):
1545 events = []
1546 result = LoggingResult(events)
1547
1548 class LoggingCase(unittest.TestCase):
1549 def run(self, result):
1550 events.append('run %s' % self._testMethodName)
1551
1552 def test1(self): pass
1553 def test2(self): pass
1554
1555 tests = [LoggingCase('test1'), LoggingCase('test2')]
1556
1557 unittest.TestSuite(tests).run(result)
1558
1559 self.assertEqual(events, ['run test1', 'run test2'])
1560
1561 # "Add a TestCase ... to the suite"
1562 def test_addTest__TestCase(self):
1563 class Foo(unittest.TestCase):
1564 def test(self): pass
1565
1566 test = Foo('test')
1567 suite = unittest.TestSuite()
1568
1569 suite.addTest(test)
1570
1571 self.assertEqual(suite.countTestCases(), 1)
1572 self.assertEqual(list(suite), [test])
1573
1574 # "Add a ... TestSuite to the suite"
1575 def test_addTest__TestSuite(self):
1576 class Foo(unittest.TestCase):
1577 def test(self): pass
1578
1579 suite_2 = unittest.TestSuite([Foo('test')])
1580
1581 suite = unittest.TestSuite()
1582 suite.addTest(suite_2)
1583
1584 self.assertEqual(suite.countTestCases(), 1)
1585 self.assertEqual(list(suite), [suite_2])
1586
1587 # "Add all the tests from an iterable of TestCase and TestSuite
1588 # instances to this test suite."
1589 #
1590 # "This is equivalent to iterating over tests, calling addTest() for
1591 # each element"
1592 def test_addTests(self):
1593 class Foo(unittest.TestCase):
1594 def test_1(self): pass
1595 def test_2(self): pass
1596
1597 test_1 = Foo('test_1')
1598 test_2 = Foo('test_2')
1599 inner_suite = unittest.TestSuite([test_2])
1600
1601 def gen():
1602 yield test_1
1603 yield test_2
1604 yield inner_suite
1605
1606 suite_1 = unittest.TestSuite()
1607 suite_1.addTests(gen())
1608
1609 self.assertEqual(list(suite_1), list(gen()))
1610
1611 # "This is equivalent to iterating over tests, calling addTest() for
1612 # each element"
1613 suite_2 = unittest.TestSuite()
1614 for t in gen():
1615 suite_2.addTest(t)
1616
1617 self.assertEqual(suite_1, suite_2)
1618
1619 # "Add all the tests from an iterable of TestCase and TestSuite
1620 # instances to this test suite."
1621 #
1622 # What happens if it doesn't get an iterable?
1623 def test_addTest__noniterable(self):
1624 suite = unittest.TestSuite()
1625
1626 try:
1627 suite.addTests(5)
1628 except TypeError:
1629 pass
1630 else:
1631 self.fail("Failed to raise TypeError")
1632
1633 def test_addTest__noncallable(self):
1634 suite = unittest.TestSuite()
1635 self.assertRaises(TypeError, suite.addTest, 5)
1636
1637 def test_addTest__casesuiteclass(self):
1638 suite = unittest.TestSuite()
1639 self.assertRaises(TypeError, suite.addTest, Test_TestSuite)
1640 self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)
1641
1642 def test_addTests__string(self):
1643 suite = unittest.TestSuite()
1644 self.assertRaises(TypeError, suite.addTests, "foo")
1645
1646
1647class Test_FunctionTestCase(TestCase):
1648
1649 # "Return the number of tests represented by the this test object. For
1650 # TestCase instances, this will always be 1"
1651 def test_countTestCases(self):
1652 test = unittest.FunctionTestCase(lambda: None)
1653
1654 self.assertEqual(test.countTestCases(), 1)
1655
1656 # "When a setUp() method is defined, the test runner will run that method
1657 # prior to each test. Likewise, if a tearDown() method is defined, the
1658 # test runner will invoke that method after each test. In the example,
1659 # setUp() was used to create a fresh sequence for each test."
1660 #
1661 # Make sure the proper call order is maintained, even if setUp() raises
1662 # an exception.
1663 def test_run_call_order__error_in_setUp(self):
1664 events = []
1665 result = LoggingResult(events)
1666
1667 def setUp():
1668 events.append('setUp')
1669 raise RuntimeError('raised by setUp')
1670
1671 def test():
1672 events.append('test')
1673
1674 def tearDown():
1675 events.append('tearDown')
1676
1677 expected = ['startTest', 'setUp', 'addError', 'stopTest']
1678 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1679 self.assertEqual(events, expected)
1680
1681 # "When a setUp() method is defined, the test runner will run that method
1682 # prior to each test. Likewise, if a tearDown() method is defined, the
1683 # test runner will invoke that method after each test. In the example,
1684 # setUp() was used to create a fresh sequence for each test."
1685 #
1686 # Make sure the proper call order is maintained, even if the test raises
1687 # an error (as opposed to a failure).
1688 def test_run_call_order__error_in_test(self):
1689 events = []
1690 result = LoggingResult(events)
1691
1692 def setUp():
1693 events.append('setUp')
1694
1695 def test():
1696 events.append('test')
1697 raise RuntimeError('raised by test')
1698
1699 def tearDown():
1700 events.append('tearDown')
1701
1702 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
1703 'stopTest']
1704 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1705 self.assertEqual(events, expected)
1706
1707 # "When a setUp() method is defined, the test runner will run that method
1708 # prior to each test. Likewise, if a tearDown() method is defined, the
1709 # test runner will invoke that method after each test. In the example,
1710 # setUp() was used to create a fresh sequence for each test."
1711 #
1712 # Make sure the proper call order is maintained, even if the test signals
1713 # a failure (as opposed to an error).
1714 def test_run_call_order__failure_in_test(self):
1715 events = []
1716 result = LoggingResult(events)
1717
1718 def setUp():
1719 events.append('setUp')
1720
1721 def test():
1722 events.append('test')
1723 self.fail('raised by test')
1724
1725 def tearDown():
1726 events.append('tearDown')
1727
1728 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
1729 'stopTest']
1730 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1731 self.assertEqual(events, expected)
1732
1733 # "When a setUp() method is defined, the test runner will run that method
1734 # prior to each test. Likewise, if a tearDown() method is defined, the
1735 # test runner will invoke that method after each test. In the example,
1736 # setUp() was used to create a fresh sequence for each test."
1737 #
1738 # Make sure the proper call order is maintained, even if tearDown() raises
1739 # an exception.
1740 def test_run_call_order__error_in_tearDown(self):
1741 events = []
1742 result = LoggingResult(events)
1743
1744 def setUp():
1745 events.append('setUp')
1746
1747 def test():
1748 events.append('test')
1749
1750 def tearDown():
1751 events.append('tearDown')
1752 raise RuntimeError('raised by tearDown')
1753
1754 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
1755 'stopTest']
1756 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1757 self.assertEqual(events, expected)
1758
1759 # "Return a string identifying the specific test case."
1760 #
1761 # Because of the vague nature of the docs, I'm not going to lock this
1762 # test down too much. Really all that can be asserted is that the id()
1763 # will be a string (either 8-byte or unicode -- again, because the docs
1764 # just say "string")
1765 def test_id(self):
1766 test = unittest.FunctionTestCase(lambda: None)
1767
Benjamin Petersone1759f82009-06-30 23:35:19 +00001768 self.assertTrue(isinstance(test.id(), str))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001769
1770 # "Returns a one-line description of the test, or None if no description
1771 # has been provided. The default implementation of this method returns
1772 # the first line of the test method's docstring, if available, or None."
1773 def test_shortDescription__no_docstring(self):
1774 test = unittest.FunctionTestCase(lambda: None)
1775
1776 self.assertEqual(test.shortDescription(), None)
1777
1778 # "Returns a one-line description of the test, or None if no description
1779 # has been provided. The default implementation of this method returns
1780 # the first line of the test method's docstring, if available, or None."
1781 def test_shortDescription__singleline_docstring(self):
1782 desc = "this tests foo"
1783 test = unittest.FunctionTestCase(lambda: None, description=desc)
1784
1785 self.assertEqual(test.shortDescription(), "this tests foo")
1786
1787class Test_TestResult(TestCase):
1788 # Note: there are not separate tests for TestResult.wasSuccessful(),
1789 # TestResult.errors, TestResult.failures, TestResult.testsRun or
1790 # TestResult.shouldStop because these only have meaning in terms of
1791 # other TestResult methods.
1792 #
1793 # Accordingly, tests for the aforenamed attributes are incorporated
1794 # in with the tests for the defining methods.
1795 ################################################################
1796
1797 def test_init(self):
1798 result = unittest.TestResult()
1799
Benjamin Petersone1759f82009-06-30 23:35:19 +00001800 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001801 self.assertEqual(len(result.errors), 0)
1802 self.assertEqual(len(result.failures), 0)
1803 self.assertEqual(result.testsRun, 0)
1804 self.assertEqual(result.shouldStop, False)
1805
1806 # "This method can be called to signal that the set of tests being
1807 # run should be aborted by setting the TestResult's shouldStop
1808 # attribute to True."
1809 def test_stop(self):
1810 result = unittest.TestResult()
1811
1812 result.stop()
1813
1814 self.assertEqual(result.shouldStop, True)
1815
1816 # "Called when the test case test is about to be run. The default
1817 # implementation simply increments the instance's testsRun counter."
1818 def test_startTest(self):
1819 class Foo(unittest.TestCase):
1820 def test_1(self):
1821 pass
1822
1823 test = Foo('test_1')
1824
1825 result = unittest.TestResult()
1826
1827 result.startTest(test)
1828
Benjamin Petersone1759f82009-06-30 23:35:19 +00001829 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001830 self.assertEqual(len(result.errors), 0)
1831 self.assertEqual(len(result.failures), 0)
1832 self.assertEqual(result.testsRun, 1)
1833 self.assertEqual(result.shouldStop, False)
1834
1835 result.stopTest(test)
1836
1837 # "Called after the test case test has been executed, regardless of
1838 # the outcome. The default implementation does nothing."
1839 def test_stopTest(self):
1840 class Foo(unittest.TestCase):
1841 def test_1(self):
1842 pass
1843
1844 test = Foo('test_1')
1845
1846 result = unittest.TestResult()
1847
1848 result.startTest(test)
1849
Benjamin Petersone1759f82009-06-30 23:35:19 +00001850 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001851 self.assertEqual(len(result.errors), 0)
1852 self.assertEqual(len(result.failures), 0)
1853 self.assertEqual(result.testsRun, 1)
1854 self.assertEqual(result.shouldStop, False)
1855
1856 result.stopTest(test)
1857
1858 # Same tests as above; make sure nothing has changed
Benjamin Petersone1759f82009-06-30 23:35:19 +00001859 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001860 self.assertEqual(len(result.errors), 0)
1861 self.assertEqual(len(result.failures), 0)
1862 self.assertEqual(result.testsRun, 1)
1863 self.assertEqual(result.shouldStop, False)
1864
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001865 # "Called before and after tests are run. The default implementation does nothing."
1866 def test_startTestRun_stopTestRun(self):
1867 result = unittest.TestResult()
1868 result.startTestRun()
1869 result.stopTestRun()
1870
Guido van Rossumd8faa362007-04-27 19:54:29 +00001871 # "addSuccess(test)"
1872 # ...
1873 # "Called when the test case test succeeds"
1874 # ...
1875 # "wasSuccessful() - Returns True if all tests run so far have passed,
1876 # otherwise returns False"
1877 # ...
1878 # "testsRun - The total number of tests run so far."
1879 # ...
1880 # "errors - A list containing 2-tuples of TestCase instances and
1881 # formatted tracebacks. Each tuple represents a test which raised an
1882 # unexpected exception. Contains formatted
1883 # tracebacks instead of sys.exc_info() results."
1884 # ...
1885 # "failures - A list containing 2-tuples of TestCase instances and
1886 # formatted tracebacks. Each tuple represents a test where a failure was
1887 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1888 # methods. Contains formatted tracebacks instead
1889 # of sys.exc_info() results."
1890 def test_addSuccess(self):
1891 class Foo(unittest.TestCase):
1892 def test_1(self):
1893 pass
1894
1895 test = Foo('test_1')
1896
1897 result = unittest.TestResult()
1898
1899 result.startTest(test)
1900 result.addSuccess(test)
1901 result.stopTest(test)
1902
Benjamin Petersone1759f82009-06-30 23:35:19 +00001903 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001904 self.assertEqual(len(result.errors), 0)
1905 self.assertEqual(len(result.failures), 0)
1906 self.assertEqual(result.testsRun, 1)
1907 self.assertEqual(result.shouldStop, False)
1908
1909 # "addFailure(test, err)"
1910 # ...
1911 # "Called when the test case test signals a failure. err is a tuple of
1912 # the form returned by sys.exc_info(): (type, value, traceback)"
1913 # ...
1914 # "wasSuccessful() - Returns True if all tests run so far have passed,
1915 # otherwise returns False"
1916 # ...
1917 # "testsRun - The total number of tests run so far."
1918 # ...
1919 # "errors - A list containing 2-tuples of TestCase instances and
1920 # formatted tracebacks. Each tuple represents a test which raised an
1921 # unexpected exception. Contains formatted
1922 # tracebacks instead of sys.exc_info() results."
1923 # ...
1924 # "failures - A list containing 2-tuples of TestCase instances and
1925 # formatted tracebacks. Each tuple represents a test where a failure was
1926 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1927 # methods. Contains formatted tracebacks instead
1928 # of sys.exc_info() results."
1929 def test_addFailure(self):
1930 import sys
1931
1932 class Foo(unittest.TestCase):
1933 def test_1(self):
1934 pass
1935
1936 test = Foo('test_1')
1937 try:
1938 test.fail("foo")
1939 except:
1940 exc_info_tuple = sys.exc_info()
1941
1942 result = unittest.TestResult()
1943
1944 result.startTest(test)
1945 result.addFailure(test, exc_info_tuple)
1946 result.stopTest(test)
1947
Benjamin Petersone1759f82009-06-30 23:35:19 +00001948 self.assertFalse(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001949 self.assertEqual(len(result.errors), 0)
1950 self.assertEqual(len(result.failures), 1)
1951 self.assertEqual(result.testsRun, 1)
1952 self.assertEqual(result.shouldStop, False)
1953
1954 test_case, formatted_exc = result.failures[0]
Benjamin Petersone1759f82009-06-30 23:35:19 +00001955 self.assertTrue(test_case is test)
1956 self.assertTrue(isinstance(formatted_exc, str))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001957
1958 # "addError(test, err)"
1959 # ...
1960 # "Called when the test case test raises an unexpected exception err
1961 # is a tuple of the form returned by sys.exc_info():
1962 # (type, value, traceback)"
1963 # ...
1964 # "wasSuccessful() - Returns True if all tests run so far have passed,
1965 # otherwise returns False"
1966 # ...
1967 # "testsRun - The total number of tests run so far."
1968 # ...
1969 # "errors - A list containing 2-tuples of TestCase instances and
1970 # formatted tracebacks. Each tuple represents a test which raised an
1971 # unexpected exception. Contains formatted
1972 # tracebacks instead of sys.exc_info() results."
1973 # ...
1974 # "failures - A list containing 2-tuples of TestCase instances and
1975 # formatted tracebacks. Each tuple represents a test where a failure was
1976 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1977 # methods. Contains formatted tracebacks instead
1978 # of sys.exc_info() results."
1979 def test_addError(self):
1980 import sys
1981
1982 class Foo(unittest.TestCase):
1983 def test_1(self):
1984 pass
1985
1986 test = Foo('test_1')
1987 try:
1988 raise TypeError()
1989 except:
1990 exc_info_tuple = sys.exc_info()
1991
1992 result = unittest.TestResult()
1993
1994 result.startTest(test)
1995 result.addError(test, exc_info_tuple)
1996 result.stopTest(test)
1997
Benjamin Petersone1759f82009-06-30 23:35:19 +00001998 self.assertFalse(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001999 self.assertEqual(len(result.errors), 1)
2000 self.assertEqual(len(result.failures), 0)
2001 self.assertEqual(result.testsRun, 1)
2002 self.assertEqual(result.shouldStop, False)
2003
2004 test_case, formatted_exc = result.errors[0]
Benjamin Petersone1759f82009-06-30 23:35:19 +00002005 self.assertTrue(test_case is test)
2006 self.assertTrue(isinstance(formatted_exc, str))
Guido van Rossumd8faa362007-04-27 19:54:29 +00002007
2008### Support code for Test_TestCase
2009################################################################
2010
2011class Foo(unittest.TestCase):
2012 def runTest(self): pass
2013 def test1(self): pass
2014
2015class Bar(Foo):
2016 def test2(self): pass
2017
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002018class LoggingTestCase(unittest.TestCase):
2019 """A test case which logs its calls."""
2020
2021 def __init__(self, events):
2022 super(LoggingTestCase, self).__init__('test')
2023 self.events = events
2024
2025 def setUp(self):
2026 self.events.append('setUp')
2027
2028 def test(self):
2029 self.events.append('test')
2030
2031 def tearDown(self):
2032 self.events.append('tearDown')
2033
2034class ResultWithNoStartTestRunStopTestRun(object):
2035 """An object honouring TestResult before startTestRun/stopTestRun."""
2036
2037 def __init__(self):
2038 self.failures = []
2039 self.errors = []
2040 self.testsRun = 0
2041 self.skipped = []
2042 self.expectedFailures = []
2043 self.unexpectedSuccesses = []
2044 self.shouldStop = False
2045
2046 def startTest(self, test):
2047 pass
2048
2049 def stopTest(self, test):
2050 pass
2051
2052 def addError(self, test):
2053 pass
2054
2055 def addFailure(self, test):
2056 pass
2057
2058 def addSuccess(self, test):
2059 pass
2060
2061 def wasSuccessful(self):
2062 return True
2063
2064
Guido van Rossumd8faa362007-04-27 19:54:29 +00002065################################################################
2066### /Support code for Test_TestCase
2067
2068class Test_TestCase(TestCase, TestEquality, TestHashing):
2069
2070 ### Set up attributes used by inherited tests
2071 ################################################################
2072
2073 # Used by TestHashing.test_hash and TestEquality.test_eq
2074 eq_pairs = [(Foo('test1'), Foo('test1'))]
2075
2076 # Used by TestEquality.test_ne
2077 ne_pairs = [(Foo('test1'), Foo('runTest'))
2078 ,(Foo('test1'), Bar('test1'))
2079 ,(Foo('test1'), Bar('test2'))]
2080
2081 ################################################################
2082 ### /Set up attributes used by inherited tests
2083
2084
2085 # "class TestCase([methodName])"
2086 # ...
2087 # "Each instance of TestCase will run a single test method: the
2088 # method named methodName."
2089 # ...
2090 # "methodName defaults to "runTest"."
2091 #
2092 # Make sure it really is optional, and that it defaults to the proper
2093 # thing.
2094 def test_init__no_test_name(self):
2095 class Test(unittest.TestCase):
2096 def runTest(self): raise MyException()
2097 def test(self): pass
2098
2099 self.assertEqual(Test().id()[-13:], '.Test.runTest')
2100
2101 # "class TestCase([methodName])"
2102 # ...
2103 # "Each instance of TestCase will run a single test method: the
2104 # method named methodName."
2105 def test_init__test_name__valid(self):
2106 class Test(unittest.TestCase):
2107 def runTest(self): raise MyException()
2108 def test(self): pass
2109
2110 self.assertEqual(Test('test').id()[-10:], '.Test.test')
2111
2112 # "class TestCase([methodName])"
2113 # ...
2114 # "Each instance of TestCase will run a single test method: the
2115 # method named methodName."
2116 def test_init__test_name__invalid(self):
2117 class Test(unittest.TestCase):
2118 def runTest(self): raise MyException()
2119 def test(self): pass
2120
2121 try:
2122 Test('testfoo')
2123 except ValueError:
2124 pass
2125 else:
2126 self.fail("Failed to raise ValueError")
2127
2128 # "Return the number of tests represented by the this test object. For
2129 # TestCase instances, this will always be 1"
2130 def test_countTestCases(self):
2131 class Foo(unittest.TestCase):
2132 def test(self): pass
2133
2134 self.assertEqual(Foo('test').countTestCases(), 1)
2135
2136 # "Return the default type of test result object to be used to run this
2137 # test. For TestCase instances, this will always be
2138 # unittest.TestResult; subclasses of TestCase should
2139 # override this as necessary."
2140 def test_defaultTestResult(self):
2141 class Foo(unittest.TestCase):
2142 def runTest(self):
2143 pass
2144
2145 result = Foo().defaultTestResult()
2146 self.assertEqual(type(result), unittest.TestResult)
2147
2148 # "When a setUp() method is defined, the test runner will run that method
2149 # prior to each test. Likewise, if a tearDown() method is defined, the
2150 # test runner will invoke that method after each test. In the example,
2151 # setUp() was used to create a fresh sequence for each test."
2152 #
2153 # Make sure the proper call order is maintained, even if setUp() raises
2154 # an exception.
2155 def test_run_call_order__error_in_setUp(self):
2156 events = []
2157 result = LoggingResult(events)
2158
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002159 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002160 def setUp(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002161 super(Foo, self).setUp()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002162 raise RuntimeError('raised by Foo.setUp')
2163
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002164 Foo(events).run(result)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002165 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2166 self.assertEqual(events, expected)
2167
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002168 # "With a temporary result stopTestRun is called when setUp errors.
2169 def test_run_call_order__error_in_setUp_default_result(self):
2170 events = []
2171
2172 class Foo(LoggingTestCase):
2173 def defaultTestResult(self):
2174 return LoggingResult(self.events)
2175
2176 def setUp(self):
2177 super(Foo, self).setUp()
2178 raise RuntimeError('raised by Foo.setUp')
2179
2180 Foo(events).run()
2181 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2182 'stopTest', 'stopTestRun']
2183 self.assertEqual(events, expected)
2184
Guido van Rossumd8faa362007-04-27 19:54:29 +00002185 # "When a setUp() method is defined, the test runner will run that method
2186 # prior to each test. Likewise, if a tearDown() method is defined, the
2187 # test runner will invoke that method after each test. In the example,
2188 # setUp() was used to create a fresh sequence for each test."
2189 #
2190 # Make sure the proper call order is maintained, even if the test raises
2191 # an error (as opposed to a failure).
2192 def test_run_call_order__error_in_test(self):
2193 events = []
2194 result = LoggingResult(events)
2195
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002196 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002197 def test(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002198 super(Foo, self).test()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002199 raise RuntimeError('raised by Foo.test')
2200
Guido van Rossumd8faa362007-04-27 19:54:29 +00002201 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2202 'stopTest']
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002203 Foo(events).run(result)
2204 self.assertEqual(events, expected)
2205
2206 # "With a default result, an error in the test still results in stopTestRun
2207 # being called."
2208 def test_run_call_order__error_in_test_default_result(self):
2209 events = []
2210
2211 class Foo(LoggingTestCase):
2212 def defaultTestResult(self):
2213 return LoggingResult(self.events)
2214
2215 def test(self):
2216 super(Foo, self).test()
2217 raise RuntimeError('raised by Foo.test')
2218
2219 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2220 'tearDown', 'stopTest', 'stopTestRun']
2221 Foo(events).run()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002222 self.assertEqual(events, expected)
2223
2224 # "When a setUp() method is defined, the test runner will run that method
2225 # prior to each test. Likewise, if a tearDown() method is defined, the
2226 # test runner will invoke that method after each test. In the example,
2227 # setUp() was used to create a fresh sequence for each test."
2228 #
2229 # Make sure the proper call order is maintained, even if the test signals
2230 # a failure (as opposed to an error).
2231 def test_run_call_order__failure_in_test(self):
2232 events = []
2233 result = LoggingResult(events)
2234
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002235 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002236 def test(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002237 super(Foo, self).test()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002238 self.fail('raised by Foo.test')
2239
Guido van Rossumd8faa362007-04-27 19:54:29 +00002240 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2241 'stopTest']
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002242 Foo(events).run(result)
2243 self.assertEqual(events, expected)
2244
2245 # "When a test fails with a default result stopTestRun is still called."
2246 def test_run_call_order__failure_in_test_default_result(self):
2247
2248 class Foo(LoggingTestCase):
2249 def defaultTestResult(self):
2250 return LoggingResult(self.events)
2251 def test(self):
2252 super(Foo, self).test()
2253 self.fail('raised by Foo.test')
2254
2255 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2256 'tearDown', 'stopTest', 'stopTestRun']
2257 events = []
2258 Foo(events).run()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002259 self.assertEqual(events, expected)
2260
2261 # "When a setUp() method is defined, the test runner will run that method
2262 # prior to each test. Likewise, if a tearDown() method is defined, the
2263 # test runner will invoke that method after each test. In the example,
2264 # setUp() was used to create a fresh sequence for each test."
2265 #
2266 # Make sure the proper call order is maintained, even if tearDown() raises
2267 # an exception.
2268 def test_run_call_order__error_in_tearDown(self):
2269 events = []
2270 result = LoggingResult(events)
2271
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002272 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002273 def tearDown(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002274 super(Foo, self).tearDown()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002275 raise RuntimeError('raised by Foo.tearDown')
2276
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002277 Foo(events).run(result)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002278 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2279 'stopTest']
2280 self.assertEqual(events, expected)
2281
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002282 # "When tearDown errors with a default result stopTestRun is still called."
2283 def test_run_call_order__error_in_tearDown_default_result(self):
2284
2285 class Foo(LoggingTestCase):
2286 def defaultTestResult(self):
2287 return LoggingResult(self.events)
2288 def tearDown(self):
2289 super(Foo, self).tearDown()
2290 raise RuntimeError('raised by Foo.tearDown')
2291
2292 events = []
2293 Foo(events).run()
2294 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2295 'addError', 'stopTest', 'stopTestRun']
2296 self.assertEqual(events, expected)
2297
2298 # "TestCase.run() still works when the defaultTestResult is a TestResult
2299 # that does not support startTestRun and stopTestRun.
2300 def test_run_call_order_default_result(self):
2301
2302 class Foo(unittest.TestCase):
2303 def defaultTestResult(self):
2304 return ResultWithNoStartTestRunStopTestRun()
2305 def test(self):
2306 pass
2307
2308 Foo('test').run()
2309
Guido van Rossumd8faa362007-04-27 19:54:29 +00002310 # "This class attribute gives the exception raised by the test() method.
2311 # If a test framework needs to use a specialized exception, possibly to
2312 # carry additional information, it must subclass this exception in
2313 # order to ``play fair'' with the framework. The initial value of this
2314 # attribute is AssertionError"
2315 def test_failureException__default(self):
2316 class Foo(unittest.TestCase):
2317 def test(self):
2318 pass
2319
Benjamin Petersone1759f82009-06-30 23:35:19 +00002320 self.assertTrue(Foo('test').failureException is AssertionError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002321
2322 # "This class attribute gives the exception raised by the test() method.
2323 # If a test framework needs to use a specialized exception, possibly to
2324 # carry additional information, it must subclass this exception in
2325 # order to ``play fair'' with the framework."
2326 #
2327 # Make sure TestCase.run() respects the designated failureException
2328 def test_failureException__subclassing__explicit_raise(self):
2329 events = []
2330 result = LoggingResult(events)
2331
2332 class Foo(unittest.TestCase):
2333 def test(self):
2334 raise RuntimeError()
2335
2336 failureException = RuntimeError
2337
Benjamin Petersone1759f82009-06-30 23:35:19 +00002338 self.assertTrue(Foo('test').failureException is RuntimeError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002339
2340
2341 Foo('test').run(result)
2342 expected = ['startTest', 'addFailure', 'stopTest']
2343 self.assertEqual(events, expected)
2344
2345 # "This class attribute gives the exception raised by the test() method.
2346 # If a test framework needs to use a specialized exception, possibly to
2347 # carry additional information, it must subclass this exception in
2348 # order to ``play fair'' with the framework."
2349 #
2350 # Make sure TestCase.run() respects the designated failureException
2351 def test_failureException__subclassing__implicit_raise(self):
2352 events = []
2353 result = LoggingResult(events)
2354
2355 class Foo(unittest.TestCase):
2356 def test(self):
2357 self.fail("foo")
2358
2359 failureException = RuntimeError
2360
Benjamin Petersone1759f82009-06-30 23:35:19 +00002361 self.assertTrue(Foo('test').failureException is RuntimeError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002362
2363
2364 Foo('test').run(result)
2365 expected = ['startTest', 'addFailure', 'stopTest']
2366 self.assertEqual(events, expected)
2367
2368 # "The default implementation does nothing."
2369 def test_setUp(self):
2370 class Foo(unittest.TestCase):
2371 def runTest(self):
2372 pass
2373
2374 # ... and nothing should happen
2375 Foo().setUp()
2376
2377 # "The default implementation does nothing."
2378 def test_tearDown(self):
2379 class Foo(unittest.TestCase):
2380 def runTest(self):
2381 pass
2382
2383 # ... and nothing should happen
2384 Foo().tearDown()
2385
2386 # "Return a string identifying the specific test case."
2387 #
2388 # Because of the vague nature of the docs, I'm not going to lock this
2389 # test down too much. Really all that can be asserted is that the id()
2390 # will be a string (either 8-byte or unicode -- again, because the docs
2391 # just say "string")
2392 def test_id(self):
2393 class Foo(unittest.TestCase):
2394 def runTest(self):
2395 pass
2396
Benjamin Petersone1759f82009-06-30 23:35:19 +00002397 self.assertTrue(isinstance(Foo().id(), str))
Guido van Rossumd8faa362007-04-27 19:54:29 +00002398
Guido van Rossumd8faa362007-04-27 19:54:29 +00002399 # "If result is omitted or None, a temporary result object is created
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002400 # and used, but is not made available to the caller. As TestCase owns the
2401 # temporary result startTestRun and stopTestRun are called.
2402
Guido van Rossumd8faa362007-04-27 19:54:29 +00002403 def test_run__uses_defaultTestResult(self):
2404 events = []
2405
2406 class Foo(unittest.TestCase):
2407 def test(self):
2408 events.append('test')
2409
2410 def defaultTestResult(self):
2411 return LoggingResult(events)
2412
2413 # Make run() find a result object on its own
2414 Foo('test').run()
2415
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002416 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2417 'stopTest', 'stopTestRun']
Guido van Rossumd8faa362007-04-27 19:54:29 +00002418 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002419
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002420 def testShortDescriptionWithoutDocstring(self):
2421 self.assertEqual(
2422 self.shortDescription(),
2423 'testShortDescriptionWithoutDocstring (' + __name__ +
2424 '.Test_TestCase)')
2425
2426 def testShortDescriptionWithOneLineDocstring(self):
2427 """Tests shortDescription() for a method with a docstring."""
2428 self.assertEqual(
2429 self.shortDescription(),
2430 ('testShortDescriptionWithOneLineDocstring '
2431 '(' + __name__ + '.Test_TestCase)\n'
2432 'Tests shortDescription() for a method with a docstring.'))
2433
2434 def testShortDescriptionWithMultiLineDocstring(self):
2435 """Tests shortDescription() for a method with a longer docstring.
2436
2437 This method ensures that only the first line of a docstring is
2438 returned used in the short description, no matter how long the
2439 whole thing is.
2440 """
2441 self.assertEqual(
2442 self.shortDescription(),
2443 ('testShortDescriptionWithMultiLineDocstring '
2444 '(' + __name__ + '.Test_TestCase)\n'
2445 'Tests shortDescription() for a method with a longer '
2446 'docstring.'))
2447
2448 def testAddTypeEqualityFunc(self):
2449 class SadSnake(object):
2450 """Dummy class for test_addTypeEqualityFunc."""
2451 s1, s2 = SadSnake(), SadSnake()
2452 self.assertFalse(s1 == s2)
2453 def AllSnakesCreatedEqual(a, b, msg=None):
2454 return type(a) == type(b) == SadSnake
2455 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2456 self.assertEqual(s1, s2)
2457 # No this doesn't clean up and remove the SadSnake equality func
2458 # from this TestCase instance but since its a local nothing else
2459 # will ever notice that.
2460
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00002461 def testAssertIs(self):
2462 thing = object()
2463 self.assertIs(thing, thing)
2464 self.assertRaises(self.failureException, self.assertIs, thing, object())
2465
2466 def testAssertIsNot(self):
2467 thing = object()
2468 self.assertIsNot(thing, object())
2469 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2470
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002471 def testAssertIn(self):
2472 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2473
2474 self.assertIn('a', 'abc')
2475 self.assertIn(2, [1, 2, 3])
2476 self.assertIn('monkey', animals)
2477
2478 self.assertNotIn('d', 'abc')
2479 self.assertNotIn(0, [1, 2, 3])
2480 self.assertNotIn('otter', animals)
2481
2482 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2483 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2484 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2485 animals)
2486
2487 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2488 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2489 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2490 animals)
2491
2492 def testAssertDictContainsSubset(self):
2493 self.assertDictContainsSubset({}, {})
2494 self.assertDictContainsSubset({}, {'a': 1})
2495 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2496 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2497 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2498
2499 self.assertRaises(unittest.TestCase.failureException,
2500 self.assertDictContainsSubset, {'a': 2}, {'a': 1},
2501 '.*Mismatched values:.*')
2502
2503 self.assertRaises(unittest.TestCase.failureException,
2504 self.assertDictContainsSubset, {'c': 1}, {'a': 1},
2505 '.*Missing:.*')
2506
2507 self.assertRaises(unittest.TestCase.failureException,
2508 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2509 {'a': 1}, '.*Missing:.*')
2510
2511 self.assertRaises(unittest.TestCase.failureException,
2512 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2513 {'a': 1}, '.*Missing:.*Mismatched values:.*')
2514
2515 def testAssertEqual(self):
2516 equal_pairs = [
2517 ((), ()),
2518 ({}, {}),
2519 ([], []),
2520 (set(), set()),
2521 (frozenset(), frozenset())]
2522 for a, b in equal_pairs:
2523 # This mess of try excepts is to test the assertEqual behavior
2524 # itself.
2525 try:
2526 self.assertEqual(a, b)
2527 except self.failureException:
2528 self.fail('assertEqual(%r, %r) failed' % (a, b))
2529 try:
2530 self.assertEqual(a, b, msg='foo')
2531 except self.failureException:
2532 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2533 try:
2534 self.assertEqual(a, b, 'foo')
2535 except self.failureException:
2536 self.fail('assertEqual(%r, %r) with third parameter failed' %
2537 (a, b))
2538
2539 unequal_pairs = [
2540 ((), []),
2541 ({}, set()),
2542 (set([4,1]), frozenset([4,2])),
2543 (frozenset([4,5]), set([2,3])),
2544 (set([3,4]), set([5,4]))]
2545 for a, b in unequal_pairs:
2546 self.assertRaises(self.failureException, self.assertEqual, a, b)
2547 self.assertRaises(self.failureException, self.assertEqual, a, b,
2548 'foo')
2549 self.assertRaises(self.failureException, self.assertEqual, a, b,
2550 msg='foo')
2551
2552 def testEquality(self):
2553 self.assertListEqual([], [])
2554 self.assertTupleEqual((), ())
2555 self.assertSequenceEqual([], ())
2556
2557 a = [0, 'a', []]
2558 b = []
2559 self.assertRaises(unittest.TestCase.failureException,
2560 self.assertListEqual, a, b)
2561 self.assertRaises(unittest.TestCase.failureException,
2562 self.assertListEqual, tuple(a), tuple(b))
2563 self.assertRaises(unittest.TestCase.failureException,
2564 self.assertSequenceEqual, a, tuple(b))
2565
2566 b.extend(a)
2567 self.assertListEqual(a, b)
2568 self.assertTupleEqual(tuple(a), tuple(b))
2569 self.assertSequenceEqual(a, tuple(b))
2570 self.assertSequenceEqual(tuple(a), b)
2571
2572 self.assertRaises(self.failureException, self.assertListEqual,
2573 a, tuple(b))
2574 self.assertRaises(self.failureException, self.assertTupleEqual,
2575 tuple(a), b)
2576 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2577 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2578 tuple(b))
2579 self.assertRaises(self.failureException, self.assertSequenceEqual,
2580 None, tuple(b))
2581 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2582 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2583 self.assertRaises(self.failureException, self.assertSequenceEqual,
2584 1, 1)
2585
2586 self.assertDictEqual({}, {})
2587
2588 c = { 'x': 1 }
2589 d = {}
2590 self.assertRaises(unittest.TestCase.failureException,
2591 self.assertDictEqual, c, d)
2592
2593 d.update(c)
2594 self.assertDictEqual(c, d)
2595
2596 d['x'] = 0
2597 self.assertRaises(unittest.TestCase.failureException,
2598 self.assertDictEqual, c, d, 'These are unequal')
2599
2600 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2601 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2602 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2603
2604 self.assertSameElements([1, 2, 3], [3, 2, 1])
2605 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2606 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2607 self.assertRaises(self.failureException, self.assertSameElements,
2608 [10], [10, 11])
2609 self.assertRaises(self.failureException, self.assertSameElements,
2610 [10, 11], [10])
2611
2612 # Test that sequences of unhashable objects can be tested for sameness:
2613 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00002614
Benjamin Peterson3bb6b7a2009-04-04 16:46:24 +00002615 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002616 self.assertRaises(self.failureException, self.assertSameElements,
2617 [[1]], [[2]])
Michael Foorda5809c82009-04-04 18:55:09 +00002618 self.assertRaises(self.failureException, self.assertSameElements,
2619 [{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 2}])
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002620
2621 def testAssertSetEqual(self):
2622 set1 = set()
2623 set2 = set()
2624 self.assertSetEqual(set1, set2)
2625
2626 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2627 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2628 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2629 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2630
2631 set1 = set(['a'])
2632 set2 = set()
2633 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2634
2635 set1 = set(['a'])
2636 set2 = set(['a'])
2637 self.assertSetEqual(set1, set2)
2638
2639 set1 = set(['a'])
2640 set2 = set(['a', 'b'])
2641 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2642
2643 set1 = set(['a'])
2644 set2 = frozenset(['a', 'b'])
2645 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2646
2647 set1 = set(['a', 'b'])
2648 set2 = frozenset(['a', 'b'])
2649 self.assertSetEqual(set1, set2)
2650
2651 set1 = set()
2652 set2 = "foo"
2653 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2654 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2655
2656 # make sure any string formatting is tuple-safe
2657 set1 = set([(0, 1), (2, 3)])
2658 set2 = set([(4, 5)])
2659 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2660
2661 def testInequality(self):
2662 # Try ints
2663 self.assertGreater(2, 1)
2664 self.assertGreaterEqual(2, 1)
2665 self.assertGreaterEqual(1, 1)
2666 self.assertLess(1, 2)
2667 self.assertLessEqual(1, 2)
2668 self.assertLessEqual(1, 1)
2669 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2670 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2671 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2672 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2673 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2674 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2675
2676 # Try Floats
2677 self.assertGreater(1.1, 1.0)
2678 self.assertGreaterEqual(1.1, 1.0)
2679 self.assertGreaterEqual(1.0, 1.0)
2680 self.assertLess(1.0, 1.1)
2681 self.assertLessEqual(1.0, 1.1)
2682 self.assertLessEqual(1.0, 1.0)
2683 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2684 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2685 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2686 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2687 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2688 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2689
2690 # Try Strings
2691 self.assertGreater('bug', 'ant')
2692 self.assertGreaterEqual('bug', 'ant')
2693 self.assertGreaterEqual('ant', 'ant')
2694 self.assertLess('ant', 'bug')
2695 self.assertLessEqual('ant', 'bug')
2696 self.assertLessEqual('ant', 'ant')
2697 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2698 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2699 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2700 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2701 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2702 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2703
2704 # Try bytes
2705 self.assertGreater(b'bug', b'ant')
2706 self.assertGreaterEqual(b'bug', b'ant')
2707 self.assertGreaterEqual(b'ant', b'ant')
2708 self.assertLess(b'ant', b'bug')
2709 self.assertLessEqual(b'ant', b'bug')
2710 self.assertLessEqual(b'ant', b'ant')
2711 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'bug')
2712 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'ant')
2713 self.assertRaises(self.failureException, self.assertGreaterEqual, b'ant',
2714 b'bug')
2715 self.assertRaises(self.failureException, self.assertLess, b'bug', b'ant')
2716 self.assertRaises(self.failureException, self.assertLess, b'ant', b'ant')
2717 self.assertRaises(self.failureException, self.assertLessEqual, b'bug', b'ant')
2718
2719 def testAssertMultiLineEqual(self):
2720 sample_text = """\
2721http://www.python.org/doc/2.3/lib/module-unittest.html
2722test case
2723 A test case is the smallest unit of testing. [...]
2724"""
2725 revised_sample_text = """\
2726http://www.python.org/doc/2.4.1/lib/module-unittest.html
2727test case
2728 A test case is the smallest unit of testing. [...] You may provide your
2729 own implementation that does not subclass from TestCase, of course.
2730"""
2731 sample_text_error = """
2732- http://www.python.org/doc/2.3/lib/module-unittest.html
2733? ^
2734+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2735? ^^^
2736 test case
2737- A test case is the smallest unit of testing. [...]
2738+ A test case is the smallest unit of testing. [...] You may provide your
2739? +++++++++++++++++++++
2740+ own implementation that does not subclass from TestCase, of course.
2741"""
2742
2743 try:
2744 self.assertMultiLineEqual(sample_text, revised_sample_text)
2745 except self.failureException as e:
2746 # no fair testing ourself with ourself, use assertEqual..
2747 self.assertEqual(sample_text_error, str(e))
2748
2749 def testAssertIsNone(self):
2750 self.assertIsNone(None)
2751 self.assertRaises(self.failureException, self.assertIsNone, False)
2752 self.assertIsNotNone('DjZoPloGears on Rails')
2753 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2754
2755 def testAssertRegexpMatches(self):
2756 self.assertRegexpMatches('asdfabasdf', r'ab+')
2757 self.assertRaises(self.failureException, self.assertRegexpMatches,
2758 'saaas', r'aaaa')
2759
2760 def testAssertRaisesRegexp(self):
2761 class ExceptionMock(Exception):
2762 pass
2763
2764 def Stub():
2765 raise ExceptionMock('We expect')
2766
2767 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2768 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2769
2770 def testAssertNotRaisesRegexp(self):
2771 self.assertRaisesRegexp(
Benjamin Peterson4f75b642009-04-04 16:39:09 +00002772 self.failureException, '^Exception not raised by <lambda>$',
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002773 self.assertRaisesRegexp, Exception, re.compile('x'),
2774 lambda: None)
2775 self.assertRaisesRegexp(
Benjamin Peterson4f75b642009-04-04 16:39:09 +00002776 self.failureException, '^Exception not raised by <lambda>$',
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002777 self.assertRaisesRegexp, Exception, 'x',
2778 lambda: None)
2779
2780 def testAssertRaisesRegexpMismatch(self):
2781 def Stub():
2782 raise Exception('Unexpected')
2783
2784 self.assertRaisesRegexp(
2785 self.failureException,
2786 r'"\^Expected\$" does not match "Unexpected"',
2787 self.assertRaisesRegexp, Exception, '^Expected$',
2788 Stub)
2789 self.assertRaisesRegexp(
2790 self.failureException,
2791 r'"\^Expected\$" does not match "Unexpected"',
2792 self.assertRaisesRegexp, Exception,
2793 re.compile('^Expected$'), Stub)
2794
2795 def testSynonymAssertMethodNames(self):
2796 """Test undocumented method name synonyms.
2797
2798 Please do not use these methods names in your own code.
2799
2800 This test confirms their continued existence and functionality
2801 in order to avoid breaking existing code.
2802 """
2803 self.assertNotEquals(3, 5)
2804 self.assertEquals(3, 3)
2805 self.assertAlmostEquals(2.0, 2.0)
2806 self.assertNotAlmostEquals(3.0, 5.0)
2807 self.assert_(True)
2808
2809 def testPendingDeprecationMethodNames(self):
2810 """Test fail* methods pending deprecation, they will warn in 3.2.
2811
2812 Do not use these methods. They will go away in 3.3.
2813 """
Benjamin Peterson6bcbad52009-06-30 23:45:41 +00002814 old = (
2815 (self.failIfEqual, (3, 5)),
2816 (self.failUnlessEqual, (3, 3)),
2817 (self.failUnlessAlmostEqual, (2.0, 2.0)),
2818 (self.failIfAlmostEqual, (3.0, 5.0)),
2819 (self.failUnless, (True,)),
2820 (self.failUnlessRaises, (TypeError, lambda _: 3.14 + 'spam')),
2821 (self.failIf, (False,))
2822 )
2823 for meth, args in old:
2824 with warnings.catch_warnings(record=True) as w:
2825 meth(*args)
2826 self.assertEqual(len(w), 1)
2827 self.assertIs(w[0].category, DeprecationWarning)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002828
2829 def testDeepcopy(self):
2830 # Issue: 5660
2831 class TestableTest(TestCase):
2832 def testNothing(self):
2833 pass
2834
2835 test = TestableTest('testNothing')
2836
2837 # This shouldn't blow up
2838 deepcopy(test)
2839
Benjamin Peterson5254c042009-03-23 22:25:03 +00002840
2841class Test_TestSkipping(TestCase):
2842
2843 def test_skipping(self):
2844 class Foo(unittest.TestCase):
2845 def test_skip_me(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00002846 self.skipTest("skip")
Benjamin Peterson5254c042009-03-23 22:25:03 +00002847 events = []
2848 result = LoggingResult(events)
2849 test = Foo("test_skip_me")
2850 test.run(result)
2851 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2852 self.assertEqual(result.skipped, [(test, "skip")])
2853
2854 # Try letting setUp skip the test now.
2855 class Foo(unittest.TestCase):
2856 def setUp(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00002857 self.skipTest("testing")
Benjamin Peterson5254c042009-03-23 22:25:03 +00002858 def test_nothing(self): pass
2859 events = []
2860 result = LoggingResult(events)
2861 test = Foo("test_nothing")
2862 test.run(result)
2863 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2864 self.assertEqual(result.skipped, [(test, "testing")])
2865 self.assertEqual(result.testsRun, 1)
2866
2867 def test_skipping_decorators(self):
2868 op_table = ((unittest.skipUnless, False, True),
2869 (unittest.skipIf, True, False))
2870 for deco, do_skip, dont_skip in op_table:
2871 class Foo(unittest.TestCase):
2872 @deco(do_skip, "testing")
2873 def test_skip(self): pass
2874
2875 @deco(dont_skip, "testing")
2876 def test_dont_skip(self): pass
2877 test_do_skip = Foo("test_skip")
2878 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002879 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002880 events = []
2881 result = LoggingResult(events)
2882 suite.run(result)
2883 self.assertEqual(len(result.skipped), 1)
2884 expected = ['startTest', 'addSkip', 'stopTest',
2885 'startTest', 'addSuccess', 'stopTest']
2886 self.assertEqual(events, expected)
2887 self.assertEqual(result.testsRun, 2)
2888 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
2889 self.assertTrue(result.wasSuccessful())
2890
2891 def test_skip_class(self):
2892 @unittest.skip("testing")
2893 class Foo(unittest.TestCase):
2894 def test_1(self):
2895 record.append(1)
2896 record = []
2897 result = unittest.TestResult()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002898 test = Foo("test_1")
2899 suite = unittest.TestSuite([test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002900 suite.run(result)
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002901 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002902 self.assertEqual(record, [])
2903
2904 def test_expected_failure(self):
2905 class Foo(unittest.TestCase):
2906 @unittest.expectedFailure
2907 def test_die(self):
2908 self.fail("help me!")
2909 events = []
2910 result = LoggingResult(events)
2911 test = Foo("test_die")
2912 test.run(result)
2913 self.assertEqual(events,
2914 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Peterson52baa292009-03-24 00:56:30 +00002915 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson5254c042009-03-23 22:25:03 +00002916 self.assertTrue(result.wasSuccessful())
2917
2918 def test_unexpected_success(self):
2919 class Foo(unittest.TestCase):
2920 @unittest.expectedFailure
2921 def test_die(self):
2922 pass
2923 events = []
2924 result = LoggingResult(events)
2925 test = Foo("test_die")
2926 test.run(result)
2927 self.assertEqual(events,
2928 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
2929 self.assertFalse(result.failures)
Benjamin Peterson52baa292009-03-24 00:56:30 +00002930 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002931 self.assertTrue(result.wasSuccessful())
2932
2933
2934
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00002935class Test_Assertions(TestCase):
2936 def test_AlmostEqual(self):
Benjamin Petersone1759f82009-06-30 23:35:19 +00002937 self.assertAlmostEqual(1.00000001, 1.0)
2938 self.assertNotAlmostEqual(1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002939 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00002940 self.assertAlmostEqual, 1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002941 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00002942 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00002943
Benjamin Petersone1759f82009-06-30 23:35:19 +00002944 self.assertAlmostEqual(1.1, 1.0, places=0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002945 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00002946 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00002947
Benjamin Petersone1759f82009-06-30 23:35:19 +00002948 self.assertAlmostEqual(0, .1+.1j, places=0)
2949 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002950 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00002951 self.assertAlmostEqual, 0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002952 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00002953 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00002954
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00002955 def test_assertRaises(self):
2956 def _raise(e):
2957 raise e
2958 self.assertRaises(KeyError, _raise, KeyError)
2959 self.assertRaises(KeyError, _raise, KeyError("key"))
2960 try:
2961 self.assertRaises(KeyError, lambda: None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002962 except self.failureException as e:
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00002963 self.assert_("KeyError not raised" in str(e), str(e))
2964 else:
2965 self.fail("assertRaises() didn't fail")
2966 try:
2967 self.assertRaises(KeyError, _raise, ValueError)
2968 except ValueError:
2969 pass
2970 else:
2971 self.fail("assertRaises() didn't let exception pass through")
2972 with self.assertRaises(KeyError):
2973 raise KeyError
2974 with self.assertRaises(KeyError):
2975 raise KeyError("key")
2976 try:
2977 with self.assertRaises(KeyError):
2978 pass
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002979 except self.failureException as e:
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00002980 self.assert_("KeyError not raised" in str(e), str(e))
2981 else:
2982 self.fail("assertRaises() didn't fail")
2983 try:
2984 with self.assertRaises(KeyError):
2985 raise ValueError
2986 except ValueError:
2987 pass
2988 else:
2989 self.fail("assertRaises() didn't let exception pass through")
2990
2991
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002992class TestLongMessage(TestCase):
2993 """Test that the individual asserts honour longMessage.
2994 This actually tests all the message behaviour for
2995 asserts that use longMessage."""
2996
2997 def setUp(self):
2998 class TestableTestFalse(TestCase):
2999 longMessage = False
3000 failureException = self.failureException
3001
3002 def testTest(self):
3003 pass
3004
3005 class TestableTestTrue(TestCase):
3006 longMessage = True
3007 failureException = self.failureException
3008
3009 def testTest(self):
3010 pass
3011
3012 self.testableTrue = TestableTestTrue('testTest')
3013 self.testableFalse = TestableTestFalse('testTest')
3014
3015 def testDefault(self):
3016 self.assertFalse(TestCase.longMessage)
3017
3018 def test_formatMsg(self):
3019 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3020 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3021
3022 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3023 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3024
3025 def assertMessages(self, methodName, args, errors):
3026 def getMethod(i):
3027 useTestableFalse = i < 2
3028 if useTestableFalse:
3029 test = self.testableFalse
3030 else:
3031 test = self.testableTrue
3032 return getattr(test, methodName)
3033
3034 for i, expected_regexp in enumerate(errors):
3035 testMethod = getMethod(i)
3036 kwargs = {}
3037 withMsg = i % 2
3038 if withMsg:
3039 kwargs = {"msg": "oops"}
3040
3041 with self.assertRaisesRegexp(self.failureException,
3042 expected_regexp=expected_regexp):
3043 testMethod(*args, **kwargs)
3044
3045 def testAssertTrue(self):
3046 self.assertMessages('assertTrue', (False,),
3047 ["^False is not True$", "^oops$", "^False is not True$",
3048 "^False is not True : oops$"])
3049
3050 def testAssertFalse(self):
3051 self.assertMessages('assertFalse', (True,),
3052 ["^True is not False$", "^oops$", "^True is not False$",
3053 "^True is not False : oops$"])
3054
3055 def testNotEqual(self):
3056 self.assertMessages('assertNotEqual', (1, 1),
3057 ["^1 == 1$", "^oops$", "^1 == 1$",
3058 "^1 == 1 : oops$"])
3059
3060 def testAlmostEqual(self):
3061 self.assertMessages('assertAlmostEqual', (1, 2),
3062 ["^1 != 2 within 7 places$", "^oops$",
3063 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3064
3065 def testNotAlmostEqual(self):
3066 self.assertMessages('assertNotAlmostEqual', (1, 1),
3067 ["^1 == 1 within 7 places$", "^oops$",
3068 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3069
3070 def test_baseAssertEqual(self):
3071 self.assertMessages('_baseAssertEqual', (1, 2),
3072 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3073
3074 def testAssertSequenceEqual(self):
3075 # Error messages are multiline so not testing on full message
3076 # assertTupleEqual and assertListEqual delegate to this method
3077 self.assertMessages('assertSequenceEqual', ([], [None]),
3078 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3079 r"\+ \[None\] : oops$"])
3080
3081 def testAssertSetEqual(self):
3082 self.assertMessages('assertSetEqual', (set(), set([None])),
3083 ["None$", "^oops$", "None$",
3084 "None : oops$"])
3085
3086 def testAssertIn(self):
3087 self.assertMessages('assertIn', (None, []),
3088 ['^None not found in \[\]$', "^oops$",
3089 '^None not found in \[\]$',
3090 '^None not found in \[\] : oops$'])
3091
3092 def testAssertNotIn(self):
3093 self.assertMessages('assertNotIn', (None, [None]),
3094 ['^None unexpectedly found in \[None\]$', "^oops$",
3095 '^None unexpectedly found in \[None\]$',
3096 '^None unexpectedly found in \[None\] : oops$'])
3097
3098 def testAssertDictEqual(self):
3099 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3100 [r"\+ \{'key': 'value'\}$", "^oops$",
3101 "\+ \{'key': 'value'\}$",
3102 "\+ \{'key': 'value'\} : oops$"])
3103
3104 def testAssertDictContainsSubset(self):
3105 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3106 ["^Missing: 'key'$", "^oops$",
3107 "^Missing: 'key'$",
3108 "^Missing: 'key' : oops$"])
3109
3110 def testAssertSameElements(self):
3111 self.assertMessages('assertSameElements', ([], [None]),
3112 [r"\[None\]$", "^oops$",
3113 r"\[None\]$",
3114 r"\[None\] : oops$"])
3115
3116 def testAssertMultiLineEqual(self):
3117 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3118 [r"\+ foo$", "^oops$",
3119 r"\+ foo$",
3120 r"\+ foo : oops$"])
3121
3122 def testAssertLess(self):
3123 self.assertMessages('assertLess', (2, 1),
3124 ["^2 not less than 1$", "^oops$",
3125 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3126
3127 def testAssertLessEqual(self):
3128 self.assertMessages('assertLessEqual', (2, 1),
3129 ["^2 not less than or equal to 1$", "^oops$",
3130 "^2 not less than or equal to 1$",
3131 "^2 not less than or equal to 1 : oops$"])
3132
3133 def testAssertGreater(self):
3134 self.assertMessages('assertGreater', (1, 2),
3135 ["^1 not greater than 2$", "^oops$",
3136 "^1 not greater than 2$",
3137 "^1 not greater than 2 : oops$"])
3138
3139 def testAssertGreaterEqual(self):
3140 self.assertMessages('assertGreaterEqual', (1, 2),
3141 ["^1 not greater than or equal to 2$", "^oops$",
3142 "^1 not greater than or equal to 2$",
3143 "^1 not greater than or equal to 2 : oops$"])
3144
3145 def testAssertIsNone(self):
3146 self.assertMessages('assertIsNone', ('not None',),
3147 ["^'not None' is not None$", "^oops$",
3148 "^'not None' is not None$",
3149 "^'not None' is not None : oops$"])
3150
3151 def testAssertIsNotNone(self):
3152 self.assertMessages('assertIsNotNone', (None,),
3153 ["^unexpectedly None$", "^oops$",
3154 "^unexpectedly None$",
3155 "^unexpectedly None : oops$"])
3156
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00003157 def testAssertIs(self):
3158 self.assertMessages('assertIs', (None, 'foo'),
3159 ["^None is not 'foo'$", "^oops$",
3160 "^None is not 'foo'$",
3161 "^None is not 'foo' : oops$"])
3162
3163 def testAssertIsNot(self):
3164 self.assertMessages('assertIsNot', (None, None),
3165 ["^unexpectedly identical: None$", "^oops$",
3166 "^unexpectedly identical: None$",
3167 "^unexpectedly identical: None : oops$"])
3168
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003169
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003170class TestCleanUp(TestCase):
3171
3172 def testCleanUp(self):
3173 class TestableTest(TestCase):
3174 def testNothing(self):
3175 pass
3176
3177 test = TestableTest('testNothing')
3178 self.assertEqual(test._cleanups, [])
3179
3180 cleanups = []
3181
3182 def cleanup1(*args, **kwargs):
3183 cleanups.append((1, args, kwargs))
3184
3185 def cleanup2(*args, **kwargs):
3186 cleanups.append((2, args, kwargs))
3187
3188 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3189 test.addCleanup(cleanup2)
3190
3191 self.assertEqual(test._cleanups,
3192 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3193 (cleanup2, (), {})])
3194
3195 result = test.doCleanups()
3196 self.assertTrue(result)
3197
3198 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3199
3200 def testCleanUpWithErrors(self):
3201 class TestableTest(TestCase):
3202 def testNothing(self):
3203 pass
3204
3205 class MockResult(object):
3206 errors = []
3207 def addError(self, test, exc_info):
3208 self.errors.append((test, exc_info))
3209
3210 result = MockResult()
3211 test = TestableTest('testNothing')
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00003212 test._resultForDoCleanups = result
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003213
3214 exc1 = Exception('foo')
3215 exc2 = Exception('bar')
3216 def cleanup1():
3217 raise exc1
3218
3219 def cleanup2():
3220 raise exc2
3221
3222 test.addCleanup(cleanup1)
3223 test.addCleanup(cleanup2)
3224
3225 self.assertFalse(test.doCleanups())
3226
3227 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3228 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3229 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3230
3231 def testCleanupInRun(self):
3232 blowUp = False
3233 ordering = []
3234
3235 class TestableTest(TestCase):
3236 def setUp(self):
3237 ordering.append('setUp')
3238 if blowUp:
3239 raise Exception('foo')
3240
3241 def testNothing(self):
3242 ordering.append('test')
3243
3244 def tearDown(self):
3245 ordering.append('tearDown')
3246
3247 test = TestableTest('testNothing')
3248
3249 def cleanup1():
3250 ordering.append('cleanup1')
3251 def cleanup2():
3252 ordering.append('cleanup2')
3253 test.addCleanup(cleanup1)
3254 test.addCleanup(cleanup2)
3255
3256 def success(some_test):
3257 self.assertEqual(some_test, test)
3258 ordering.append('success')
3259
3260 result = unittest.TestResult()
3261 result.addSuccess = success
3262
3263 test.run(result)
3264 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3265 'cleanup2', 'cleanup1', 'success'])
3266
3267 blowUp = True
3268 ordering = []
3269 test = TestableTest('testNothing')
3270 test.addCleanup(cleanup1)
3271 test.run(result)
3272 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3273
3274
3275class Test_TestProgram(TestCase):
3276
3277 # Horrible white box test
3278 def testNoExit(self):
3279 result = object()
3280 test = object()
3281
3282 class FakeRunner(object):
3283 def run(self, test):
3284 self.test = test
3285 return result
3286
3287 runner = FakeRunner()
3288
Benjamin Petersond2397752009-06-27 23:45:02 +00003289 oldParseArgs = TestProgram.parseArgs
3290 def restoreParseArgs():
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003291 TestProgram.parseArgs = oldParseArgs
Benjamin Petersond2397752009-06-27 23:45:02 +00003292 TestProgram.parseArgs = lambda *args: None
3293 self.addCleanup(restoreParseArgs)
3294
3295 def removeTest():
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003296 del TestProgram.test
Benjamin Petersond2397752009-06-27 23:45:02 +00003297 TestProgram.test = test
3298 self.addCleanup(removeTest)
3299
3300 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3301
3302 self.assertEqual(program.result, result)
3303 self.assertEqual(runner.test, test)
3304 self.assertEqual(program.verbosity, 2)
3305
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003306 class FooBar(unittest.TestCase):
3307 def testPass(self):
3308 assert True
3309 def testFail(self):
3310 assert False
3311
3312 class FooBarLoader(unittest.TestLoader):
3313 """Test loader that returns a suite containing FooBar."""
3314 def loadTestsFromModule(self, module):
3315 return self.suiteClass(
3316 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3317
3318
3319 def test_NonExit(self):
3320 program = unittest.main(exit=False,
3321 argv=["foobar"],
3322 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3323 testLoader=self.FooBarLoader())
3324 self.assertTrue(hasattr(program, 'result'))
3325
3326
3327 def test_Exit(self):
3328 self.assertRaises(
3329 SystemExit,
3330 unittest.main,
3331 argv=["foobar"],
3332 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3333 exit=True,
3334 testLoader=self.FooBarLoader())
3335
3336
3337 def test_ExitAsDefault(self):
3338 self.assertRaises(
3339 SystemExit,
3340 unittest.main,
3341 argv=["foobar"],
3342 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3343 testLoader=self.FooBarLoader())
3344
3345
3346class Test_TextTestRunner(TestCase):
3347 """Tests for TextTestRunner."""
3348
3349 def test_works_with_result_without_startTestRun_stopTestRun(self):
3350 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3351 separator2 = ''
3352 def printErrors(self):
3353 pass
3354
3355 class Runner(unittest.TextTestRunner):
3356 def __init__(self):
3357 super(Runner, self).__init__(io.StringIO())
3358
3359 def _makeResult(self):
3360 return OldTextResult()
3361
3362 runner = Runner()
3363 runner.run(unittest.TestSuite())
3364
3365 def test_startTestRun_stopTestRun_called(self):
3366 class LoggingTextResult(LoggingResult):
3367 separator2 = ''
3368 def printErrors(self):
3369 pass
3370
3371 class LoggingRunner(unittest.TextTestRunner):
3372 def __init__(self, events):
3373 super(LoggingRunner, self).__init__(io.StringIO())
3374 self._events = events
3375
3376 def _makeResult(self):
3377 return LoggingTextResult(self._events)
3378
3379 events = []
3380 runner = LoggingRunner(events)
3381 runner.run(unittest.TestSuite())
3382 expected = ['startTestRun', 'stopTestRun']
3383 self.assertEqual(events, expected)
3384
3385
Benjamin Petersond2397752009-06-27 23:45:02 +00003386class TestDiscovery(TestCase):
3387
3388 # Heavily mocked tests so I can avoid hitting the filesystem
3389 def test_get_module_from_path(self):
3390 loader = unittest.TestLoader()
3391
3392 def restore_import():
3393 unittest.__import__ = __import__
3394 unittest.__import__ = lambda *_: None
3395 self.addCleanup(restore_import)
3396
3397 expected_module = object()
3398 def del_module():
3399 del sys.modules['bar.baz']
3400 sys.modules['bar.baz'] = expected_module
3401 self.addCleanup(del_module)
3402
3403 loader._top_level_dir = '/foo'
3404 module = loader._get_module_from_path('/foo/bar/baz.py')
3405 self.assertEqual(module, expected_module)
3406
3407 if not __debug__:
3408 # asserts are off
3409 return
3410
3411 with self.assertRaises(AssertionError):
3412 loader._get_module_from_path('/bar/baz.py')
3413
3414 def test_find_tests(self):
3415 loader = unittest.TestLoader()
3416
3417 original_listdir = os.listdir
3418 def restore_listdir():
3419 os.listdir = original_listdir
3420 original_isfile = os.path.isfile
3421 def restore_isfile():
3422 os.path.isfile = original_isfile
3423 original_isdir = os.path.isdir
3424 def restore_isdir():
3425 os.path.isdir = original_isdir
3426
3427 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
3428 'test.foo', 'another_dir'],
3429 ['test3.py', 'test4.py', ]]
3430 os.listdir = lambda path: path_lists.pop(0)
3431 self.addCleanup(restore_listdir)
3432
3433 def isdir(path):
3434 return path.endswith('dir')
3435 os.path.isdir = isdir
3436 self.addCleanup(restore_isdir)
3437
3438 def isfile(path):
3439 # another_dir is not a package and so shouldn't be recursed into
3440 return not path.endswith('dir') and not 'another_dir' in path
3441 os.path.isfile = isfile
3442 self.addCleanup(restore_isfile)
3443
3444 loader._get_module_from_path = lambda path: path + ' module'
3445 loader.loadTestsFromModule = lambda module: module + ' tests'
3446
3447 loader._top_level_dir = '/foo'
3448 suite = list(loader._find_tests('/foo', 'test*.py'))
3449
3450 expected = [os.path.join('/foo', name) + ' module tests' for name in
3451 ('test1.py', 'test2.py')]
3452 expected.extend([os.path.join('/foo', 'test_dir', name) + ' module tests' for name in
3453 ('test3.py', 'test4.py')])
3454 self.assertEqual(suite, expected)
3455
3456 def test_find_tests_with_package(self):
3457 loader = unittest.TestLoader()
3458
3459 original_listdir = os.listdir
3460 def restore_listdir():
3461 os.listdir = original_listdir
3462 original_isfile = os.path.isfile
3463 def restore_isfile():
3464 os.path.isfile = original_isfile
3465 original_isdir = os.path.isdir
3466 def restore_isdir():
3467 os.path.isdir = original_isdir
3468
3469 directories = ['a_directory', 'test_directory', 'test_directory2']
3470 path_lists = [directories, [], [], []]
3471 os.listdir = lambda path: path_lists.pop(0)
3472 self.addCleanup(restore_listdir)
3473
3474 os.path.isdir = lambda path: True
3475 self.addCleanup(restore_isdir)
3476
3477 os.path.isfile = lambda path: os.path.basename(path) not in directories
3478 self.addCleanup(restore_isfile)
3479
3480 class Module(object):
3481 paths = []
3482 load_tests_args = []
3483
3484 def __init__(self, path):
3485 self.path = path
3486 self.paths.append(path)
3487 if os.path.basename(path) == 'test_directory':
3488 def load_tests(loader, tests, pattern):
3489 self.load_tests_args.append((loader, tests, pattern))
3490 return 'load_tests'
3491 self.load_tests = load_tests
3492
3493 def __eq__(self, other):
3494 return self.path == other.path
3495
3496 loader._get_module_from_path = lambda path: Module(path)
3497 def loadTestsFromModule(module, use_load_tests):
3498 if use_load_tests:
3499 raise self.failureException('use_load_tests should be False for packages')
3500 return module.path + ' module tests'
3501 loader.loadTestsFromModule = loadTestsFromModule
3502
3503 loader._top_level_dir = '/foo'
3504 # this time no '.py' on the pattern so that it can match
3505 # a test package
3506 suite = list(loader._find_tests('/foo', 'test*'))
3507
3508 # We should have loaded tests from the test_directory package by calling load_tests
3509 # and directly from the test_directory2 package
3510 self.assertEqual(suite,
3511 ['load_tests',
3512 os.path.join('/foo', 'test_directory2') + ' module tests'])
3513 self.assertEqual(Module.paths, [os.path.join('/foo', 'test_directory'),
3514 os.path.join('/foo', 'test_directory2')])
3515
3516 # load_tests should have been called once with loader, tests and pattern
3517 self.assertEqual(Module.load_tests_args,
3518 [(loader, os.path.join('/foo', 'test_directory') + ' module tests',
3519 'test*')])
3520
3521 def test_discover(self):
3522 loader = unittest.TestLoader()
3523
3524 original_isfile = os.path.isfile
3525 def restore_isfile():
3526 os.path.isfile = original_isfile
3527
3528 os.path.isfile = lambda path: False
3529 self.addCleanup(restore_isfile)
3530
3531 full_path = os.path.abspath(os.path.normpath('/foo'))
3532 def clean_path():
3533 if sys.path[-1] == full_path:
3534 sys.path.pop(-1)
3535 self.addCleanup(clean_path)
3536
3537 with self.assertRaises(ImportError):
3538 loader.discover('/foo/bar', top_level_dir='/foo')
3539
3540 self.assertEqual(loader._top_level_dir, full_path)
3541 self.assertIn(full_path, sys.path)
3542
3543 os.path.isfile = lambda path: True
3544 _find_tests_args = []
3545 def _find_tests(start_dir, pattern):
3546 _find_tests_args.append((start_dir, pattern))
3547 return ['tests']
3548 loader._find_tests = _find_tests
3549 loader.suiteClass = str
3550
3551 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3552
3553 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3554 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3555 self.assertEqual(suite, "['tests']")
3556 self.assertEqual(loader._top_level_dir, top_level_dir)
3557 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
3558
3559 def test_command_line_handling_parseArgs(self):
3560 # Haha - take that uninstantiable class
3561 program = object.__new__(TestProgram)
3562
3563 args = []
3564 def do_discovery(argv):
3565 args.extend(argv)
3566 program._do_discovery = do_discovery
3567 program.parseArgs(['something', 'discover'])
3568 self.assertEqual(args, [])
3569
3570 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3571 self.assertEqual(args, ['foo', 'bar'])
3572
3573 def test_command_line_handling_do_discovery_too_many_arguments(self):
3574 class Stop(Exception):
3575 pass
3576 def usageExit():
3577 raise Stop
3578
3579 program = object.__new__(TestProgram)
3580 program.usageExit = usageExit
3581
3582 with self.assertRaises(Stop):
3583 # too many args
3584 program._do_discovery(['one', 'two', 'three', 'four'])
3585
3586
3587 def test_command_line_handling_do_discovery_calls_loader(self):
3588 program = object.__new__(TestProgram)
3589
3590 class Loader(object):
3591 args = []
3592 def discover(self, start_dir, pattern, top_level_dir):
3593 self.args.append((start_dir, pattern, top_level_dir))
3594 return 'tests'
3595
3596 program._do_discovery(['-v'], Loader=Loader)
3597 self.assertEqual(program.verbosity, 2)
3598 self.assertEqual(program.test, 'tests')
3599 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3600
3601 Loader.args = []
3602 program = object.__new__(TestProgram)
3603 program._do_discovery(['--verbose'], Loader=Loader)
3604 self.assertEqual(program.test, 'tests')
3605 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3606
3607 Loader.args = []
3608 program = object.__new__(TestProgram)
3609 program._do_discovery([], Loader=Loader)
3610 self.assertEqual(program.test, 'tests')
3611 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3612
3613 Loader.args = []
3614 program = object.__new__(TestProgram)
3615 program._do_discovery(['fish'], Loader=Loader)
3616 self.assertEqual(program.test, 'tests')
3617 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3618
3619 Loader.args = []
3620 program = object.__new__(TestProgram)
3621 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3622 self.assertEqual(program.test, 'tests')
3623 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3624
3625 Loader.args = []
3626 program = object.__new__(TestProgram)
3627 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3628 self.assertEqual(program.test, 'tests')
3629 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3630
3631 Loader.args = []
3632 program = object.__new__(TestProgram)
3633 program._do_discovery(['-s', 'fish'], Loader=Loader)
3634 self.assertEqual(program.test, 'tests')
3635 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3636
3637 Loader.args = []
3638 program = object.__new__(TestProgram)
3639 program._do_discovery(['-t', 'fish'], Loader=Loader)
3640 self.assertEqual(program.test, 'tests')
3641 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3642
3643 Loader.args = []
3644 program = object.__new__(TestProgram)
3645 program._do_discovery(['-p', 'fish'], Loader=Loader)
3646 self.assertEqual(program.test, 'tests')
3647 self.assertEqual(Loader.args, [('.', 'fish', None)])
3648
3649 Loader.args = []
3650 program = object.__new__(TestProgram)
3651 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3652 self.assertEqual(program.test, 'tests')
3653 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3654 self.assertEqual(program.verbosity, 2)
3655
3656
Jim Fultonfafd8742004-08-28 15:22:12 +00003657######################################################################
3658## Main
3659######################################################################
3660
3661def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003662 support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003663 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003664 Test_TestSkipping, Test_Assertions, TestLongMessage,
Benjamin Petersond2397752009-06-27 23:45:02 +00003665 Test_TestProgram, TestCleanUp, TestDiscovery)
Jim Fultonfafd8742004-08-28 15:22:12 +00003666
Guido van Rossumd8faa362007-04-27 19:54:29 +00003667if __name__ == "__main__":
Jim Fultonfafd8742004-08-28 15:22:12 +00003668 test_main()