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