blob: e58c6b763bcb9e53e85019d3445d9eeddb5bb1d2 [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
Antoine Pitrouc63ecee2009-11-10 21:34:48 +000020import pickle
Jim Fultonfafd8742004-08-28 15:22:12 +000021
Guido van Rossumd8faa362007-04-27 19:54:29 +000022### Support code
23################################################################
Jim Fultonfafd8742004-08-28 15:22:12 +000024
Guido van Rossumd8faa362007-04-27 19:54:29 +000025class LoggingResult(unittest.TestResult):
26 def __init__(self, log):
27 self._events = log
Guido van Rossumcd16bf62007-06-13 18:07:49 +000028 super().__init__()
Guido van Rossumd8faa362007-04-27 19:54:29 +000029
30 def startTest(self, test):
31 self._events.append('startTest')
Guido van Rossumcd16bf62007-06-13 18:07:49 +000032 super().startTest(test)
Guido van Rossumd8faa362007-04-27 19:54:29 +000033
Benjamin Peterson25c95f12009-05-08 20:42:26 +000034 def startTestRun(self):
35 self._events.append('startTestRun')
36 super(LoggingResult, self).startTestRun()
37
Guido van Rossumd8faa362007-04-27 19:54:29 +000038 def stopTest(self, test):
39 self._events.append('stopTest')
Guido van Rossumcd16bf62007-06-13 18:07:49 +000040 super().stopTest(test)
Guido van Rossumd8faa362007-04-27 19:54:29 +000041
Benjamin Peterson25c95f12009-05-08 20:42:26 +000042 def stopTestRun(self):
43 self._events.append('stopTestRun')
44 super(LoggingResult, self).stopTestRun()
45
Guido van Rossumd8faa362007-04-27 19:54:29 +000046 def addFailure(self, *args):
47 self._events.append('addFailure')
Guido van Rossumcd16bf62007-06-13 18:07:49 +000048 super().addFailure(*args)
Guido van Rossumd8faa362007-04-27 19:54:29 +000049
Benjamin Peterson5254c042009-03-23 22:25:03 +000050 def addSuccess(self, *args):
51 self._events.append('addSuccess')
52 super(LoggingResult, self).addSuccess(*args)
53
Guido van Rossumd8faa362007-04-27 19:54:29 +000054 def addError(self, *args):
55 self._events.append('addError')
Guido van Rossumcd16bf62007-06-13 18:07:49 +000056 super().addError(*args)
Guido van Rossumd8faa362007-04-27 19:54:29 +000057
Benjamin Peterson5254c042009-03-23 22:25:03 +000058 def addSkip(self, *args):
59 self._events.append('addSkip')
60 super(LoggingResult, self).addSkip(*args)
61
62 def addExpectedFailure(self, *args):
63 self._events.append('addExpectedFailure')
64 super(LoggingResult, self).addExpectedFailure(*args)
65
66 def addUnexpectedSuccess(self, *args):
67 self._events.append('addUnexpectedSuccess')
68 super(LoggingResult, self).addUnexpectedSuccess(*args)
69
70
Guido van Rossumd8faa362007-04-27 19:54:29 +000071class TestEquality(object):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000072 """Used as a mixin for TestCase"""
73
Guido van Rossumd8faa362007-04-27 19:54:29 +000074 # Check for a valid __eq__ implementation
75 def test_eq(self):
76 for obj_1, obj_2 in self.eq_pairs:
77 self.assertEqual(obj_1, obj_2)
78 self.assertEqual(obj_2, obj_1)
79
80 # Check for a valid __ne__ implementation
81 def test_ne(self):
82 for obj_1, obj_2 in self.ne_pairs:
Benjamin Petersone1759f82009-06-30 23:35:19 +000083 self.assertNotEqual(obj_1, obj_2)
84 self.assertNotEqual(obj_2, obj_1)
Guido van Rossumd8faa362007-04-27 19:54:29 +000085
86class TestHashing(object):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000087 """Used as a mixin for TestCase"""
88
Guido van Rossumd8faa362007-04-27 19:54:29 +000089 # Check for a valid __hash__ implementation
90 def test_hash(self):
91 for obj_1, obj_2 in self.eq_pairs:
92 try:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000093 if not hash(obj_1) == hash(obj_2):
94 self.fail("%r and %r do not hash equal" % (obj_1, obj_2))
Guido van Rossumd8faa362007-04-27 19:54:29 +000095 except KeyboardInterrupt:
96 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +000097 except Exception as e:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000098 self.fail("Problem hashing %r and %r: %s" % (obj_1, obj_2, e))
Guido van Rossumd8faa362007-04-27 19:54:29 +000099
100 for obj_1, obj_2 in self.ne_pairs:
101 try:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000102 if hash(obj_1) == hash(obj_2):
103 self.fail("%s and %s hash equal, but shouldn't" %
104 (obj_1, obj_2))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000105 except KeyboardInterrupt:
106 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +0000107 except Exception as e:
108 self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e))
109
110
Benjamin Peterson5254c042009-03-23 22:25:03 +0000111# List subclass we can add attributes to.
112class MyClassSuite(list):
113
Benjamin Peterson14a3dd72009-05-25 00:51:58 +0000114 def __init__(self, tests):
Benjamin Peterson5254c042009-03-23 22:25:03 +0000115 super(MyClassSuite, self).__init__(tests)
116
117
Guido van Rossumd8faa362007-04-27 19:54:29 +0000118################################################################
119### /Support code
120
121class Test_TestLoader(TestCase):
122
123 ### Tests for TestLoader.loadTestsFromTestCase
124 ################################################################
125
126 # "Return a suite of all tests cases contained in the TestCase-derived
127 # class testCaseClass"
128 def test_loadTestsFromTestCase(self):
129 class Foo(unittest.TestCase):
130 def test_1(self): pass
131 def test_2(self): pass
132 def foo_bar(self): pass
133
134 tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
135
136 loader = unittest.TestLoader()
137 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
138
139 # "Return a suite of all tests cases contained in the TestCase-derived
140 # class testCaseClass"
141 #
142 # Make sure it does the right thing even if no tests were found
143 def test_loadTestsFromTestCase__no_matches(self):
144 class Foo(unittest.TestCase):
145 def foo_bar(self): pass
146
147 empty_suite = unittest.TestSuite()
148
149 loader = unittest.TestLoader()
150 self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite)
151
152 # "Return a suite of all tests cases contained in the TestCase-derived
153 # class testCaseClass"
154 #
155 # What happens if loadTestsFromTestCase() is given an object
156 # that isn't a subclass of TestCase? Specifically, what happens
157 # if testCaseClass is a subclass of TestSuite?
158 #
159 # This is checked for specifically in the code, so we better add a
160 # test for it.
161 def test_loadTestsFromTestCase__TestSuite_subclass(self):
162 class NotATestCase(unittest.TestSuite):
163 pass
164
165 loader = unittest.TestLoader()
166 try:
167 loader.loadTestsFromTestCase(NotATestCase)
168 except TypeError:
169 pass
170 else:
171 self.fail('Should raise TypeError')
172
173 # "Return a suite of all tests cases contained in the TestCase-derived
174 # class testCaseClass"
175 #
176 # Make sure loadTestsFromTestCase() picks up the default test method
177 # name (as specified by TestCase), even though the method name does
178 # not match the default TestLoader.testMethodPrefix string
179 def test_loadTestsFromTestCase__default_method_name(self):
180 class Foo(unittest.TestCase):
181 def runTest(self):
182 pass
183
184 loader = unittest.TestLoader()
185 # This has to be false for the test to succeed
Benjamin Petersone1759f82009-06-30 23:35:19 +0000186 self.assertFalse('runTest'.startswith(loader.testMethodPrefix))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000187
188 suite = loader.loadTestsFromTestCase(Foo)
Ezio Melottie9615932010-01-24 19:26:24 +0000189 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000190 self.assertEqual(list(suite), [Foo('runTest')])
191
192 ################################################################
193 ### /Tests for TestLoader.loadTestsFromTestCase
194
195 ### Tests for TestLoader.loadTestsFromModule
196 ################################################################
197
198 # "This method searches `module` for classes derived from TestCase"
199 def test_loadTestsFromModule__TestCase_subclass(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000200 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000201 class MyTestCase(unittest.TestCase):
202 def test(self):
203 pass
204 m.testcase_1 = MyTestCase
205
206 loader = unittest.TestLoader()
207 suite = loader.loadTestsFromModule(m)
Ezio Melottie9615932010-01-24 19:26:24 +0000208 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000209
210 expected = [loader.suiteClass([MyTestCase('test')])]
211 self.assertEqual(list(suite), expected)
212
213 # "This method searches `module` for classes derived from TestCase"
214 #
215 # What happens if no tests are found (no TestCase instances)?
216 def test_loadTestsFromModule__no_TestCase_instances(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000217 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000218
219 loader = unittest.TestLoader()
220 suite = loader.loadTestsFromModule(m)
Ezio Melottie9615932010-01-24 19:26:24 +0000221 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000222 self.assertEqual(list(suite), [])
223
224 # "This method searches `module` for classes derived from TestCase"
225 #
226 # What happens if no tests are found (TestCases instances, but no tests)?
227 def test_loadTestsFromModule__no_TestCase_tests(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000228 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000229 class MyTestCase(unittest.TestCase):
230 pass
231 m.testcase_1 = MyTestCase
232
233 loader = unittest.TestLoader()
234 suite = loader.loadTestsFromModule(m)
Ezio Melottie9615932010-01-24 19:26:24 +0000235 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000236
237 self.assertEqual(list(suite), [loader.suiteClass()])
238
239 # "This method searches `module` for classes derived from TestCase"s
240 #
241 # What happens if loadTestsFromModule() is given something other
242 # than a module?
243 #
244 # XXX Currently, it succeeds anyway. This flexibility
245 # should either be documented or loadTestsFromModule() should
246 # raise a TypeError
247 #
248 # XXX Certain people are using this behaviour. We'll add a test for it
249 def test_loadTestsFromModule__not_a_module(self):
250 class MyTestCase(unittest.TestCase):
251 def test(self):
252 pass
253
254 class NotAModule(object):
255 test_2 = MyTestCase
256
257 loader = unittest.TestLoader()
258 suite = loader.loadTestsFromModule(NotAModule)
259
260 reference = [unittest.TestSuite([MyTestCase('test')])]
261 self.assertEqual(list(suite), reference)
262
Benjamin Petersond2397752009-06-27 23:45:02 +0000263
264 # Check that loadTestsFromModule honors (or not) a module
265 # with a load_tests function.
266 def test_loadTestsFromModule__load_tests(self):
267 m = types.ModuleType('m')
268 class MyTestCase(unittest.TestCase):
269 def test(self):
270 pass
271 m.testcase_1 = MyTestCase
272
273 load_tests_args = []
274 def load_tests(loader, tests, pattern):
Michael Foord41647d62010-02-06 00:26:13 +0000275 self.assertIsInstance(tests, unittest.TestSuite)
Benjamin Petersond2397752009-06-27 23:45:02 +0000276 load_tests_args.extend((loader, tests, pattern))
277 return tests
278 m.load_tests = load_tests
279
280 loader = unittest.TestLoader()
281 suite = loader.loadTestsFromModule(m)
Michael Foord41647d62010-02-06 00:26:13 +0000282 self.assertIsInstance(suite, unittest.TestSuite)
Benjamin Petersond2397752009-06-27 23:45:02 +0000283 self.assertEquals(load_tests_args, [loader, suite, None])
284
285 load_tests_args = []
286 suite = loader.loadTestsFromModule(m, use_load_tests=False)
287 self.assertEquals(load_tests_args, [])
288
Guido van Rossumd8faa362007-04-27 19:54:29 +0000289 ################################################################
290 ### /Tests for TestLoader.loadTestsFromModule()
291
292 ### Tests for TestLoader.loadTestsFromName()
293 ################################################################
294
295 # "The specifier name is a ``dotted name'' that may resolve either to
296 # a module, a test case class, a TestSuite instance, a test method
297 # within a test case class, or a callable object which returns a
298 # TestCase or TestSuite instance."
299 #
300 # Is ValueError raised in response to an empty name?
301 def test_loadTestsFromName__empty_name(self):
302 loader = unittest.TestLoader()
303
304 try:
305 loader.loadTestsFromName('')
306 except ValueError as e:
307 self.assertEqual(str(e), "Empty module name")
308 else:
309 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
310
311 # "The specifier name is a ``dotted name'' that may resolve either to
312 # a module, a test case class, a TestSuite instance, a test method
313 # within a test case class, or a callable object which returns a
314 # TestCase or TestSuite instance."
315 #
316 # What happens when the name contains invalid characters?
317 def test_loadTestsFromName__malformed_name(self):
318 loader = unittest.TestLoader()
319
320 # XXX Should this raise ValueError or ImportError?
321 try:
322 loader.loadTestsFromName('abc () //')
323 except ValueError:
324 pass
325 except ImportError:
326 pass
327 else:
328 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
329
330 # "The specifier name is a ``dotted name'' that may resolve ... to a
331 # module"
332 #
333 # What happens when a module by that name can't be found?
334 def test_loadTestsFromName__unknown_module_name(self):
335 loader = unittest.TestLoader()
336
337 try:
338 loader.loadTestsFromName('sdasfasfasdf')
339 except ImportError as e:
340 self.assertEqual(str(e), "No module named sdasfasfasdf")
341 else:
342 self.fail("TestLoader.loadTestsFromName failed to raise ImportError")
343
344 # "The specifier name is a ``dotted name'' that may resolve either to
345 # a module, a test case class, a TestSuite instance, a test method
346 # within a test case class, or a callable object which returns a
347 # TestCase or TestSuite instance."
348 #
349 # What happens when the module is found, but the attribute can't?
350 def test_loadTestsFromName__unknown_attr_name(self):
351 loader = unittest.TestLoader()
352
353 try:
354 loader.loadTestsFromName('unittest.sdasfasfasdf')
355 except AttributeError as e:
356 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
357 else:
358 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
359
360 # "The specifier name is a ``dotted name'' that may resolve either to
361 # a module, a test case class, a TestSuite instance, a test method
362 # within a test case class, or a callable object which returns a
363 # TestCase or TestSuite instance."
364 #
365 # What happens when we provide the module, but the attribute can't be
366 # found?
367 def test_loadTestsFromName__relative_unknown_name(self):
368 loader = unittest.TestLoader()
369
370 try:
371 loader.loadTestsFromName('sdasfasfasdf', unittest)
372 except AttributeError as e:
373 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
374 else:
375 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
376
377 # "The specifier name is a ``dotted name'' that may resolve either to
378 # a module, a test case class, a TestSuite instance, a test method
379 # within a test case class, or a callable object which returns a
380 # TestCase or TestSuite instance."
381 # ...
382 # "The method optionally resolves name relative to the given module"
383 #
384 # Does loadTestsFromName raise ValueError when passed an empty
385 # name relative to a provided module?
386 #
387 # XXX Should probably raise a ValueError instead of an AttributeError
388 def test_loadTestsFromName__relative_empty_name(self):
389 loader = unittest.TestLoader()
390
391 try:
392 loader.loadTestsFromName('', unittest)
393 except AttributeError as e:
394 pass
395 else:
396 self.fail("Failed to raise AttributeError")
397
398 # "The specifier name is a ``dotted name'' that may resolve either to
399 # a module, a test case class, a TestSuite instance, a test method
400 # within a test case class, or a callable object which returns a
401 # TestCase or TestSuite instance."
402 # ...
403 # "The method optionally resolves name relative to the given module"
404 #
405 # What happens when an impossible name is given, relative to the provided
406 # `module`?
407 def test_loadTestsFromName__relative_malformed_name(self):
408 loader = unittest.TestLoader()
409
410 # XXX Should this raise AttributeError or ValueError?
411 try:
412 loader.loadTestsFromName('abc () //', unittest)
413 except ValueError:
414 pass
415 except AttributeError:
416 pass
417 else:
418 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
419
420 # "The method optionally resolves name relative to the given module"
421 #
422 # Does loadTestsFromName raise TypeError when the `module` argument
423 # isn't a module object?
424 #
425 # XXX Accepts the not-a-module object, ignorning the object's type
426 # This should raise an exception or the method name should be changed
427 #
428 # XXX Some people are relying on this, so keep it for now
429 def test_loadTestsFromName__relative_not_a_module(self):
430 class MyTestCase(unittest.TestCase):
431 def test(self):
432 pass
433
434 class NotAModule(object):
435 test_2 = MyTestCase
436
437 loader = unittest.TestLoader()
438 suite = loader.loadTestsFromName('test_2', NotAModule)
439
440 reference = [MyTestCase('test')]
441 self.assertEqual(list(suite), reference)
442
443 # "The specifier name is a ``dotted name'' that may resolve either to
444 # a module, a test case class, a TestSuite instance, a test method
445 # within a test case class, or a callable object which returns a
446 # TestCase or TestSuite instance."
447 #
448 # Does it raise an exception if the name resolves to an invalid
449 # object?
450 def test_loadTestsFromName__relative_bad_object(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000451 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000452 m.testcase_1 = object()
453
454 loader = unittest.TestLoader()
455 try:
456 loader.loadTestsFromName('testcase_1', m)
457 except TypeError:
458 pass
459 else:
460 self.fail("Should have raised TypeError")
461
462 # "The specifier name is a ``dotted name'' that may
463 # resolve either to ... a test case class"
464 def test_loadTestsFromName__relative_TestCase_subclass(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000465 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000466 class MyTestCase(unittest.TestCase):
467 def test(self):
468 pass
469 m.testcase_1 = MyTestCase
470
471 loader = unittest.TestLoader()
472 suite = loader.loadTestsFromName('testcase_1', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000473 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000474 self.assertEqual(list(suite), [MyTestCase('test')])
475
476 # "The specifier name is a ``dotted name'' that may resolve either to
477 # a module, a test case class, a TestSuite instance, a test method
478 # within a test case class, or a callable object which returns a
479 # TestCase or TestSuite instance."
480 def test_loadTestsFromName__relative_TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000481 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000482 class MyTestCase(unittest.TestCase):
483 def test(self):
484 pass
485 m.testsuite = unittest.TestSuite([MyTestCase('test')])
486
487 loader = unittest.TestLoader()
488 suite = loader.loadTestsFromName('testsuite', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000489 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000490
491 self.assertEqual(list(suite), [MyTestCase('test')])
492
493 # "The specifier name is a ``dotted name'' that may resolve ... to
494 # ... a test method within a test case class"
495 def test_loadTestsFromName__relative_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000496 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000497 class MyTestCase(unittest.TestCase):
498 def test(self):
499 pass
500 m.testcase_1 = MyTestCase
501
502 loader = unittest.TestLoader()
503 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000504 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000505
506 self.assertEqual(list(suite), [MyTestCase('test')])
507
508 # "The specifier name is a ``dotted name'' that may resolve either to
509 # a module, a test case class, a TestSuite instance, a test method
510 # within a test case class, or a callable object which returns a
511 # TestCase or TestSuite instance."
512 #
513 # Does loadTestsFromName() raise the proper exception when trying to
514 # resolve "a test method within a test case class" that doesn't exist
515 # for the given name (relative to a provided module)?
516 def test_loadTestsFromName__relative_invalid_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000517 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000518 class MyTestCase(unittest.TestCase):
519 def test(self):
520 pass
521 m.testcase_1 = MyTestCase
522
523 loader = unittest.TestLoader()
524 try:
525 loader.loadTestsFromName('testcase_1.testfoo', m)
526 except AttributeError as e:
527 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
528 else:
529 self.fail("Failed to raise AttributeError")
530
531 # "The specifier name is a ``dotted name'' that may resolve ... to
532 # ... a callable object which returns a ... TestSuite instance"
533 def test_loadTestsFromName__callable__TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000534 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000535 testcase_1 = unittest.FunctionTestCase(lambda: None)
536 testcase_2 = unittest.FunctionTestCase(lambda: None)
537 def return_TestSuite():
538 return unittest.TestSuite([testcase_1, testcase_2])
539 m.return_TestSuite = return_TestSuite
540
541 loader = unittest.TestLoader()
542 suite = loader.loadTestsFromName('return_TestSuite', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000543 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000544 self.assertEqual(list(suite), [testcase_1, testcase_2])
545
546 # "The specifier name is a ``dotted name'' that may resolve ... to
547 # ... a callable object which returns a TestCase ... instance"
548 def test_loadTestsFromName__callable__TestCase_instance(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000549 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000550 testcase_1 = unittest.FunctionTestCase(lambda: None)
551 def return_TestCase():
552 return testcase_1
553 m.return_TestCase = return_TestCase
554
555 loader = unittest.TestLoader()
556 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000557 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000558 self.assertEqual(list(suite), [testcase_1])
559
560 # "The specifier name is a ``dotted name'' that may resolve ... to
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000561 # ... a callable object which returns a TestCase ... instance"
562 #*****************************************************************
563 #Override the suiteClass attribute to ensure that the suiteClass
564 #attribute is used
565 def test_loadTestsFromName__callable__TestCase_instance_ProperSuiteClass(self):
566 class SubTestSuite(unittest.TestSuite):
567 pass
568 m = types.ModuleType('m')
569 testcase_1 = unittest.FunctionTestCase(lambda: None)
570 def return_TestCase():
571 return testcase_1
572 m.return_TestCase = return_TestCase
573
574 loader = unittest.TestLoader()
575 loader.suiteClass = SubTestSuite
576 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000577 self.assertIsInstance(suite, loader.suiteClass)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000578 self.assertEqual(list(suite), [testcase_1])
579
580 # "The specifier name is a ``dotted name'' that may resolve ... to
581 # ... a test method within a test case class"
582 #*****************************************************************
583 #Override the suiteClass attribute to ensure that the suiteClass
584 #attribute is used
585 def test_loadTestsFromName__relative_testmethod_ProperSuiteClass(self):
586 class SubTestSuite(unittest.TestSuite):
587 pass
588 m = types.ModuleType('m')
589 class MyTestCase(unittest.TestCase):
590 def test(self):
591 pass
592 m.testcase_1 = MyTestCase
593
594 loader = unittest.TestLoader()
595 loader.suiteClass=SubTestSuite
596 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000597 self.assertIsInstance(suite, loader.suiteClass)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000598
599 self.assertEqual(list(suite), [MyTestCase('test')])
600
601 # "The specifier name is a ``dotted name'' that may resolve ... to
Guido van Rossumd8faa362007-04-27 19:54:29 +0000602 # ... a callable object which returns a TestCase or TestSuite instance"
603 #
604 # What happens if the callable returns something else?
605 def test_loadTestsFromName__callable__wrong_type(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000606 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000607 def return_wrong():
608 return 6
609 m.return_wrong = return_wrong
610
611 loader = unittest.TestLoader()
612 try:
613 suite = loader.loadTestsFromName('return_wrong', m)
614 except TypeError:
615 pass
616 else:
617 self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
618
619 # "The specifier can refer to modules and packages which have not been
620 # imported; they will be imported as a side-effect"
621 def test_loadTestsFromName__module_not_loaded(self):
622 # We're going to try to load this module as a side-effect, so it
623 # better not be loaded before we try.
624 #
625 # Why pick audioop? Google shows it isn't used very often, so there's
626 # a good chance that it won't be imported when this test is run
627 module_name = 'audioop'
628
629 import sys
630 if module_name in sys.modules:
631 del sys.modules[module_name]
632
633 loader = unittest.TestLoader()
634 try:
635 suite = loader.loadTestsFromName(module_name)
636
Ezio Melottie9615932010-01-24 19:26:24 +0000637 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000638 self.assertEqual(list(suite), [])
639
640 # audioop should now be loaded, thanks to loadTestsFromName()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000641 self.assertIn(module_name, sys.modules)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000642 finally:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000643 if module_name in sys.modules:
644 del sys.modules[module_name]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000645
646 ################################################################
647 ### Tests for TestLoader.loadTestsFromName()
648
649 ### Tests for TestLoader.loadTestsFromNames()
650 ################################################################
651
652 # "Similar to loadTestsFromName(), but takes a sequence of names rather
653 # than a single name."
654 #
655 # What happens if that sequence of names is empty?
656 def test_loadTestsFromNames__empty_name_list(self):
657 loader = unittest.TestLoader()
658
659 suite = loader.loadTestsFromNames([])
Ezio Melottie9615932010-01-24 19:26:24 +0000660 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000661 self.assertEqual(list(suite), [])
662
663 # "Similar to loadTestsFromName(), but takes a sequence of names rather
664 # than a single name."
665 # ...
666 # "The method optionally resolves name relative to the given module"
667 #
668 # What happens if that sequence of names is empty?
669 #
670 # XXX Should this raise a ValueError or just return an empty TestSuite?
671 def test_loadTestsFromNames__relative_empty_name_list(self):
672 loader = unittest.TestLoader()
673
674 suite = loader.loadTestsFromNames([], unittest)
Ezio Melottie9615932010-01-24 19:26:24 +0000675 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000676 self.assertEqual(list(suite), [])
677
678 # "The specifier name is a ``dotted name'' that may resolve either to
679 # a module, a test case class, a TestSuite instance, a test method
680 # within a test case class, or a callable object which returns a
681 # TestCase or TestSuite instance."
682 #
683 # Is ValueError raised in response to an empty name?
684 def test_loadTestsFromNames__empty_name(self):
685 loader = unittest.TestLoader()
686
687 try:
688 loader.loadTestsFromNames([''])
689 except ValueError as e:
690 self.assertEqual(str(e), "Empty module name")
691 else:
692 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
693
694 # "The specifier name is a ``dotted name'' that may resolve either to
695 # a module, a test case class, a TestSuite instance, a test method
696 # within a test case class, or a callable object which returns a
697 # TestCase or TestSuite instance."
698 #
699 # What happens when presented with an impossible module name?
700 def test_loadTestsFromNames__malformed_name(self):
701 loader = unittest.TestLoader()
702
703 # XXX Should this raise ValueError or ImportError?
704 try:
705 loader.loadTestsFromNames(['abc () //'])
706 except ValueError:
707 pass
708 except ImportError:
709 pass
710 else:
711 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
712
713 # "The specifier name is a ``dotted name'' that may resolve either to
714 # a module, a test case class, a TestSuite instance, a test method
715 # within a test case class, or a callable object which returns a
716 # TestCase or TestSuite instance."
717 #
718 # What happens when no module can be found for the given name?
719 def test_loadTestsFromNames__unknown_module_name(self):
720 loader = unittest.TestLoader()
721
722 try:
723 loader.loadTestsFromNames(['sdasfasfasdf'])
724 except ImportError as e:
725 self.assertEqual(str(e), "No module named sdasfasfasdf")
726 else:
727 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
728
729 # "The specifier name is a ``dotted name'' that may resolve either to
730 # a module, a test case class, a TestSuite instance, a test method
731 # within a test case class, or a callable object which returns a
732 # TestCase or TestSuite instance."
733 #
734 # What happens when the module can be found, but not the attribute?
735 def test_loadTestsFromNames__unknown_attr_name(self):
736 loader = unittest.TestLoader()
737
738 try:
739 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
740 except AttributeError as e:
741 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
742 else:
743 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
744
745 # "The specifier name is a ``dotted name'' that may resolve either to
746 # a module, a test case class, a TestSuite instance, a test method
747 # within a test case class, or a callable object which returns a
748 # TestCase or TestSuite instance."
749 # ...
750 # "The method optionally resolves name relative to the given module"
751 #
752 # What happens when given an unknown attribute on a specified `module`
753 # argument?
754 def test_loadTestsFromNames__unknown_name_relative_1(self):
755 loader = unittest.TestLoader()
756
757 try:
758 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
759 except AttributeError as e:
760 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
761 else:
762 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
763
764 # "The specifier name is a ``dotted name'' that may resolve either to
765 # a module, a test case class, a TestSuite instance, a test method
766 # within a test case class, or a callable object which returns a
767 # TestCase or TestSuite instance."
768 # ...
769 # "The method optionally resolves name relative to the given module"
770 #
771 # Do unknown attributes (relative to a provided module) still raise an
772 # exception even in the presence of valid attribute names?
773 def test_loadTestsFromNames__unknown_name_relative_2(self):
774 loader = unittest.TestLoader()
775
776 try:
777 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
778 except AttributeError as e:
779 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
780 else:
781 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
782
783 # "The specifier name is a ``dotted name'' that may resolve either to
784 # a module, a test case class, a TestSuite instance, a test method
785 # within a test case class, or a callable object which returns a
786 # TestCase or TestSuite instance."
787 # ...
788 # "The method optionally resolves name relative to the given module"
789 #
790 # What happens when faced with the empty string?
791 #
792 # XXX This currently raises AttributeError, though ValueError is probably
793 # more appropriate
794 def test_loadTestsFromNames__relative_empty_name(self):
795 loader = unittest.TestLoader()
796
797 try:
798 loader.loadTestsFromNames([''], unittest)
799 except AttributeError:
800 pass
801 else:
802 self.fail("Failed to raise ValueError")
803
804 # "The specifier name is a ``dotted name'' that may resolve either to
805 # a module, a test case class, a TestSuite instance, a test method
806 # within a test case class, or a callable object which returns a
807 # TestCase or TestSuite instance."
808 # ...
809 # "The method optionally resolves name relative to the given module"
810 #
811 # What happens when presented with an impossible attribute name?
812 def test_loadTestsFromNames__relative_malformed_name(self):
813 loader = unittest.TestLoader()
814
815 # XXX Should this raise AttributeError or ValueError?
816 try:
817 loader.loadTestsFromNames(['abc () //'], unittest)
818 except AttributeError:
819 pass
820 except ValueError:
821 pass
822 else:
823 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
824
825 # "The method optionally resolves name relative to the given module"
826 #
827 # Does loadTestsFromNames() make sure the provided `module` is in fact
828 # a module?
829 #
830 # XXX This validation is currently not done. This flexibility should
831 # either be documented or a TypeError should be raised.
832 def test_loadTestsFromNames__relative_not_a_module(self):
833 class MyTestCase(unittest.TestCase):
834 def test(self):
835 pass
836
837 class NotAModule(object):
838 test_2 = MyTestCase
839
840 loader = unittest.TestLoader()
841 suite = loader.loadTestsFromNames(['test_2'], NotAModule)
842
843 reference = [unittest.TestSuite([MyTestCase('test')])]
844 self.assertEqual(list(suite), reference)
845
846 # "The specifier name is a ``dotted name'' that may resolve either to
847 # a module, a test case class, a TestSuite instance, a test method
848 # within a test case class, or a callable object which returns a
849 # TestCase or TestSuite instance."
850 #
851 # Does it raise an exception if the name resolves to an invalid
852 # object?
853 def test_loadTestsFromNames__relative_bad_object(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000854 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000855 m.testcase_1 = object()
856
857 loader = unittest.TestLoader()
858 try:
859 loader.loadTestsFromNames(['testcase_1'], m)
860 except TypeError:
861 pass
862 else:
863 self.fail("Should have raised TypeError")
864
865 # "The specifier name is a ``dotted name'' that may resolve ... to
866 # ... a test case class"
867 def test_loadTestsFromNames__relative_TestCase_subclass(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000868 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000869 class MyTestCase(unittest.TestCase):
870 def test(self):
871 pass
872 m.testcase_1 = MyTestCase
873
874 loader = unittest.TestLoader()
875 suite = loader.loadTestsFromNames(['testcase_1'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000876 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000877
878 expected = loader.suiteClass([MyTestCase('test')])
879 self.assertEqual(list(suite), [expected])
880
881 # "The specifier name is a ``dotted name'' that may resolve ... to
882 # ... a TestSuite instance"
883 def test_loadTestsFromNames__relative_TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000884 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000885 class MyTestCase(unittest.TestCase):
886 def test(self):
887 pass
888 m.testsuite = unittest.TestSuite([MyTestCase('test')])
889
890 loader = unittest.TestLoader()
891 suite = loader.loadTestsFromNames(['testsuite'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000892 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000893
894 self.assertEqual(list(suite), [m.testsuite])
895
896 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
897 # test method within a test case class"
898 def test_loadTestsFromNames__relative_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000899 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000900 class MyTestCase(unittest.TestCase):
901 def test(self):
902 pass
903 m.testcase_1 = MyTestCase
904
905 loader = unittest.TestLoader()
906 suite = loader.loadTestsFromNames(['testcase_1.test'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000907 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000908
909 ref_suite = unittest.TestSuite([MyTestCase('test')])
910 self.assertEqual(list(suite), [ref_suite])
911
912 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
913 # test method within a test case class"
914 #
915 # Does the method gracefully handle names that initially look like they
916 # resolve to "a test method within a test case class" but don't?
917 def test_loadTestsFromNames__relative_invalid_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000918 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000919 class MyTestCase(unittest.TestCase):
920 def test(self):
921 pass
922 m.testcase_1 = MyTestCase
923
924 loader = unittest.TestLoader()
925 try:
926 loader.loadTestsFromNames(['testcase_1.testfoo'], m)
927 except AttributeError as e:
928 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
929 else:
930 self.fail("Failed to raise AttributeError")
931
932 # "The specifier name is a ``dotted name'' that may resolve ... to
933 # ... a callable object which returns a ... TestSuite instance"
934 def test_loadTestsFromNames__callable__TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000935 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000936 testcase_1 = unittest.FunctionTestCase(lambda: None)
937 testcase_2 = unittest.FunctionTestCase(lambda: None)
938 def return_TestSuite():
939 return unittest.TestSuite([testcase_1, testcase_2])
940 m.return_TestSuite = return_TestSuite
941
942 loader = unittest.TestLoader()
943 suite = loader.loadTestsFromNames(['return_TestSuite'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000944 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000945
946 expected = unittest.TestSuite([testcase_1, testcase_2])
947 self.assertEqual(list(suite), [expected])
948
949 # "The specifier name is a ``dotted name'' that may resolve ... to
950 # ... a callable object which returns a TestCase ... instance"
951 def test_loadTestsFromNames__callable__TestCase_instance(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000952 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000953 testcase_1 = unittest.FunctionTestCase(lambda: None)
954 def return_TestCase():
955 return testcase_1
956 m.return_TestCase = return_TestCase
957
958 loader = unittest.TestLoader()
959 suite = loader.loadTestsFromNames(['return_TestCase'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000960 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000961
962 ref_suite = unittest.TestSuite([testcase_1])
963 self.assertEqual(list(suite), [ref_suite])
964
965 # "The specifier name is a ``dotted name'' that may resolve ... to
966 # ... a callable object which returns a TestCase or TestSuite instance"
967 #
968 # Are staticmethods handled correctly?
969 def test_loadTestsFromNames__callable__call_staticmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000970 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000971 class Test1(unittest.TestCase):
972 def test(self):
973 pass
974
975 testcase_1 = Test1('test')
976 class Foo(unittest.TestCase):
977 @staticmethod
978 def foo():
979 return testcase_1
980 m.Foo = Foo
981
982 loader = unittest.TestLoader()
983 suite = loader.loadTestsFromNames(['Foo.foo'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000984 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000985
986 ref_suite = unittest.TestSuite([testcase_1])
987 self.assertEqual(list(suite), [ref_suite])
988
989 # "The specifier name is a ``dotted name'' that may resolve ... to
990 # ... a callable object which returns a TestCase or TestSuite instance"
991 #
992 # What happens when the callable returns something else?
993 def test_loadTestsFromNames__callable__wrong_type(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000994 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000995 def return_wrong():
996 return 6
997 m.return_wrong = return_wrong
998
999 loader = unittest.TestLoader()
1000 try:
1001 suite = loader.loadTestsFromNames(['return_wrong'], m)
1002 except TypeError:
1003 pass
1004 else:
1005 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
1006
1007 # "The specifier can refer to modules and packages which have not been
1008 # imported; they will be imported as a side-effect"
1009 def test_loadTestsFromNames__module_not_loaded(self):
1010 # We're going to try to load this module as a side-effect, so it
1011 # better not be loaded before we try.
1012 #
1013 # Why pick audioop? Google shows it isn't used very often, so there's
1014 # a good chance that it won't be imported when this test is run
1015 module_name = 'audioop'
1016
1017 import sys
1018 if module_name in sys.modules:
1019 del sys.modules[module_name]
1020
1021 loader = unittest.TestLoader()
1022 try:
1023 suite = loader.loadTestsFromNames([module_name])
1024
Ezio Melottie9615932010-01-24 19:26:24 +00001025 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001026 self.assertEqual(list(suite), [unittest.TestSuite()])
1027
1028 # audioop should now be loaded, thanks to loadTestsFromName()
Benjamin Peterson577473f2010-01-19 00:09:57 +00001029 self.assertIn(module_name, sys.modules)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001030 finally:
Guido van Rossum360e4b82007-05-14 22:51:27 +00001031 if module_name in sys.modules:
1032 del sys.modules[module_name]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001033
1034 ################################################################
1035 ### /Tests for TestLoader.loadTestsFromNames()
1036
1037 ### Tests for TestLoader.getTestCaseNames()
1038 ################################################################
1039
1040 # "Return a sorted sequence of method names found within testCaseClass"
1041 #
1042 # Test.foobar is defined to make sure getTestCaseNames() respects
1043 # loader.testMethodPrefix
1044 def test_getTestCaseNames(self):
1045 class Test(unittest.TestCase):
1046 def test_1(self): pass
1047 def test_2(self): pass
1048 def foobar(self): pass
1049
1050 loader = unittest.TestLoader()
1051
1052 self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])
1053
1054 # "Return a sorted sequence of method names found within testCaseClass"
1055 #
1056 # Does getTestCaseNames() behave appropriately if no tests are found?
1057 def test_getTestCaseNames__no_tests(self):
1058 class Test(unittest.TestCase):
1059 def foobar(self): pass
1060
1061 loader = unittest.TestLoader()
1062
1063 self.assertEqual(loader.getTestCaseNames(Test), [])
1064
1065 # "Return a sorted sequence of method names found within testCaseClass"
1066 #
1067 # Are not-TestCases handled gracefully?
1068 #
1069 # XXX This should raise a TypeError, not return a list
1070 #
1071 # XXX It's too late in the 2.5 release cycle to fix this, but it should
1072 # probably be revisited for 2.6
1073 def test_getTestCaseNames__not_a_TestCase(self):
1074 class BadCase(int):
1075 def test_foo(self):
1076 pass
1077
1078 loader = unittest.TestLoader()
1079 names = loader.getTestCaseNames(BadCase)
1080
1081 self.assertEqual(names, ['test_foo'])
1082
1083 # "Return a sorted sequence of method names found within testCaseClass"
1084 #
1085 # Make sure inherited names are handled.
1086 #
1087 # TestP.foobar is defined to make sure getTestCaseNames() respects
1088 # loader.testMethodPrefix
1089 def test_getTestCaseNames__inheritance(self):
1090 class TestP(unittest.TestCase):
1091 def test_1(self): pass
1092 def test_2(self): pass
1093 def foobar(self): pass
1094
1095 class TestC(TestP):
1096 def test_1(self): pass
1097 def test_3(self): pass
1098
1099 loader = unittest.TestLoader()
1100
1101 names = ['test_1', 'test_2', 'test_3']
1102 self.assertEqual(loader.getTestCaseNames(TestC), names)
1103
1104 ################################################################
1105 ### /Tests for TestLoader.getTestCaseNames()
1106
1107 ### Tests for TestLoader.testMethodPrefix
1108 ################################################################
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__loadTestsFromTestCase(self):
1116 class Foo(unittest.TestCase):
1117 def test_1(self): pass
1118 def test_2(self): pass
1119 def foo_bar(self): pass
1120
1121 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1122 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1123
1124 loader = unittest.TestLoader()
1125 loader.testMethodPrefix = 'foo'
1126 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
1127
1128 loader.testMethodPrefix = 'test'
1129 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
1130
1131 # "String giving the prefix of method names which will be interpreted as
1132 # test methods"
1133 #
1134 # Implicit in the documentation is that testMethodPrefix is respected by
1135 # all loadTestsFrom* methods.
1136 def test_testMethodPrefix__loadTestsFromModule(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001137 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001138 class Foo(unittest.TestCase):
1139 def test_1(self): pass
1140 def test_2(self): pass
1141 def foo_bar(self): pass
1142 m.Foo = Foo
1143
1144 tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
1145 tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]
1146
1147 loader = unittest.TestLoader()
1148 loader.testMethodPrefix = 'foo'
1149 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
1150
1151 loader.testMethodPrefix = 'test'
1152 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
1153
1154 # "String giving the prefix of method names which will be interpreted as
1155 # test methods"
1156 #
1157 # Implicit in the documentation is that testMethodPrefix is respected by
1158 # all loadTestsFrom* methods.
1159 def test_testMethodPrefix__loadTestsFromName(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001160 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001161 class Foo(unittest.TestCase):
1162 def test_1(self): pass
1163 def test_2(self): pass
1164 def foo_bar(self): pass
1165 m.Foo = Foo
1166
1167 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1168 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1169
1170 loader = unittest.TestLoader()
1171 loader.testMethodPrefix = 'foo'
1172 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
1173
1174 loader.testMethodPrefix = 'test'
1175 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
1176
1177 # "String giving the prefix of method names which will be interpreted as
1178 # test methods"
1179 #
1180 # Implicit in the documentation is that testMethodPrefix is respected by
1181 # all loadTestsFrom* methods.
1182 def test_testMethodPrefix__loadTestsFromNames(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001183 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001184 class Foo(unittest.TestCase):
1185 def test_1(self): pass
1186 def test_2(self): pass
1187 def foo_bar(self): pass
1188 m.Foo = Foo
1189
1190 tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
1191 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1192 tests_2 = unittest.TestSuite([tests_2])
1193
1194 loader = unittest.TestLoader()
1195 loader.testMethodPrefix = 'foo'
1196 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)
1197
1198 loader.testMethodPrefix = 'test'
1199 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)
1200
1201 # "The default value is 'test'"
1202 def test_testMethodPrefix__default_value(self):
1203 loader = unittest.TestLoader()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001204 self.assertEqual(loader.testMethodPrefix, 'test')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001205
1206 ################################################################
1207 ### /Tests for TestLoader.testMethodPrefix
1208
1209 ### Tests for TestLoader.sortTestMethodsUsing
1210 ################################################################
1211
1212 # "Function to be used to compare method names when sorting them in
1213 # getTestCaseNames() and all the loadTestsFromX() methods"
1214 def test_sortTestMethodsUsing__loadTestsFromTestCase(self):
1215 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001216 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001217
1218 class Foo(unittest.TestCase):
1219 def test_1(self): pass
1220 def test_2(self): pass
1221
1222 loader = unittest.TestLoader()
1223 loader.sortTestMethodsUsing = reversed_cmp
1224
1225 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1226 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
1227
1228 # "Function to be used to compare method names when sorting them in
1229 # getTestCaseNames() and all the loadTestsFromX() methods"
1230 def test_sortTestMethodsUsing__loadTestsFromModule(self):
1231 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001232 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001233
Christian Heimes45f9af32007-11-27 21:50:00 +00001234 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001235 class Foo(unittest.TestCase):
1236 def test_1(self): pass
1237 def test_2(self): pass
1238 m.Foo = Foo
1239
1240 loader = unittest.TestLoader()
1241 loader.sortTestMethodsUsing = reversed_cmp
1242
1243 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1244 self.assertEqual(list(loader.loadTestsFromModule(m)), tests)
1245
1246 # "Function to be used to compare method names when sorting them in
1247 # getTestCaseNames() and all the loadTestsFromX() methods"
1248 def test_sortTestMethodsUsing__loadTestsFromName(self):
1249 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001250 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001251
Christian Heimes45f9af32007-11-27 21:50:00 +00001252 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001253 class Foo(unittest.TestCase):
1254 def test_1(self): pass
1255 def test_2(self): pass
1256 m.Foo = Foo
1257
1258 loader = unittest.TestLoader()
1259 loader.sortTestMethodsUsing = reversed_cmp
1260
1261 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1262 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
1263
1264 # "Function to be used to compare method names when sorting them in
1265 # getTestCaseNames() and all the loadTestsFromX() methods"
1266 def test_sortTestMethodsUsing__loadTestsFromNames(self):
1267 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001268 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001269
Christian Heimes45f9af32007-11-27 21:50:00 +00001270 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001271 class Foo(unittest.TestCase):
1272 def test_1(self): pass
1273 def test_2(self): pass
1274 m.Foo = Foo
1275
1276 loader = unittest.TestLoader()
1277 loader.sortTestMethodsUsing = reversed_cmp
1278
1279 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1280 self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)
1281
1282 # "Function to be used to compare method names when sorting them in
1283 # getTestCaseNames()"
1284 #
1285 # Does it actually affect getTestCaseNames()?
1286 def test_sortTestMethodsUsing__getTestCaseNames(self):
1287 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001288 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001289
1290 class Foo(unittest.TestCase):
1291 def test_1(self): pass
1292 def test_2(self): pass
1293
1294 loader = unittest.TestLoader()
1295 loader.sortTestMethodsUsing = reversed_cmp
1296
1297 test_names = ['test_2', 'test_1']
1298 self.assertEqual(loader.getTestCaseNames(Foo), test_names)
1299
1300 # "The default value is the built-in cmp() function"
Mark Dickinsona56c4672009-01-27 18:17:45 +00001301 # Since cmp is now defunct, we simply verify that the results
1302 # occur in the same order as they would with the default sort.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001303 def test_sortTestMethodsUsing__default_value(self):
1304 loader = unittest.TestLoader()
Mark Dickinsona56c4672009-01-27 18:17:45 +00001305
1306 class Foo(unittest.TestCase):
1307 def test_2(self): pass
1308 def test_3(self): pass
1309 def test_1(self): pass
1310
1311 test_names = ['test_2', 'test_3', 'test_1']
1312 self.assertEqual(loader.getTestCaseNames(Foo), sorted(test_names))
1313
Guido van Rossumd8faa362007-04-27 19:54:29 +00001314
1315 # "it can be set to None to disable the sort."
1316 #
1317 # XXX How is this different from reassigning cmp? Are the tests returned
1318 # in a random order or something? This behaviour should die
1319 def test_sortTestMethodsUsing__None(self):
1320 class Foo(unittest.TestCase):
1321 def test_1(self): pass
1322 def test_2(self): pass
1323
1324 loader = unittest.TestLoader()
1325 loader.sortTestMethodsUsing = None
1326
1327 test_names = ['test_2', 'test_1']
1328 self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))
1329
1330 ################################################################
1331 ### /Tests for TestLoader.sortTestMethodsUsing
1332
1333 ### Tests for TestLoader.suiteClass
1334 ################################################################
1335
1336 # "Callable object that constructs a test suite from a list of tests."
1337 def test_suiteClass__loadTestsFromTestCase(self):
1338 class Foo(unittest.TestCase):
1339 def test_1(self): pass
1340 def test_2(self): pass
1341 def foo_bar(self): pass
1342
1343 tests = [Foo('test_1'), Foo('test_2')]
1344
1345 loader = unittest.TestLoader()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001346 loader.suiteClass = list
Guido van Rossumd8faa362007-04-27 19:54:29 +00001347 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
1348
1349 # It is implicit in the documentation for TestLoader.suiteClass that
1350 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
1351 def test_suiteClass__loadTestsFromModule(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001352 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001353 class Foo(unittest.TestCase):
1354 def test_1(self): pass
1355 def test_2(self): pass
1356 def foo_bar(self): pass
1357 m.Foo = Foo
1358
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001359 tests = [[Foo('test_1'), Foo('test_2')]]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001360
1361 loader = unittest.TestLoader()
1362 loader.suiteClass = list
1363 self.assertEqual(loader.loadTestsFromModule(m), tests)
1364
1365 # It is implicit in the documentation for TestLoader.suiteClass that
1366 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
1367 def test_suiteClass__loadTestsFromName(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001368 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001369 class Foo(unittest.TestCase):
1370 def test_1(self): pass
1371 def test_2(self): pass
1372 def foo_bar(self): pass
1373 m.Foo = Foo
1374
1375 tests = [Foo('test_1'), Foo('test_2')]
1376
1377 loader = unittest.TestLoader()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001378 loader.suiteClass = list
Guido van Rossumd8faa362007-04-27 19:54:29 +00001379 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
1380
1381 # It is implicit in the documentation for TestLoader.suiteClass that
1382 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
1383 def test_suiteClass__loadTestsFromNames(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001384 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001385 class Foo(unittest.TestCase):
1386 def test_1(self): pass
1387 def test_2(self): pass
1388 def foo_bar(self): pass
1389 m.Foo = Foo
1390
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001391 tests = [[Foo('test_1'), Foo('test_2')]]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001392
1393 loader = unittest.TestLoader()
1394 loader.suiteClass = list
1395 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)
1396
1397 # "The default value is the TestSuite class"
1398 def test_suiteClass__default_value(self):
1399 loader = unittest.TestLoader()
Benjamin Petersone1759f82009-06-30 23:35:19 +00001400 self.assertTrue(loader.suiteClass is unittest.TestSuite)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001401
1402 ################################################################
1403 ### /Tests for TestLoader.suiteClass
1404
1405### Support code for Test_TestSuite
1406################################################################
1407
1408class Foo(unittest.TestCase):
1409 def test_1(self): pass
1410 def test_2(self): pass
1411 def test_3(self): pass
1412 def runTest(self): pass
1413
1414def _mk_TestSuite(*names):
1415 return unittest.TestSuite(Foo(n) for n in names)
1416
1417################################################################
1418### /Support code for Test_TestSuite
1419
1420class Test_TestSuite(TestCase, TestEquality):
1421
1422 ### Set up attributes needed by inherited tests
1423 ################################################################
1424
1425 # Used by TestEquality.test_eq
1426 eq_pairs = [(unittest.TestSuite(), unittest.TestSuite())
1427 ,(unittest.TestSuite(), unittest.TestSuite([]))
1428 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]
1429
1430 # Used by TestEquality.test_ne
1431 ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1'))
1432 ,(unittest.TestSuite([]), _mk_TestSuite('test_1'))
1433 ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3'))
1434 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]
1435
1436 ################################################################
1437 ### /Set up attributes needed by inherited tests
1438
1439 ### Tests for TestSuite.__init__
1440 ################################################################
1441
1442 # "class TestSuite([tests])"
1443 #
1444 # The tests iterable should be optional
1445 def test_init__tests_optional(self):
1446 suite = unittest.TestSuite()
1447
1448 self.assertEqual(suite.countTestCases(), 0)
1449
1450 # "class TestSuite([tests])"
1451 # ...
1452 # "If tests is given, it must be an iterable of individual test cases
1453 # or other test suites that will be used to build the suite initially"
1454 #
1455 # TestSuite should deal with empty tests iterables by allowing the
1456 # creation of an empty suite
1457 def test_init__empty_tests(self):
1458 suite = unittest.TestSuite([])
1459
1460 self.assertEqual(suite.countTestCases(), 0)
1461
1462 # "class TestSuite([tests])"
1463 # ...
1464 # "If tests is given, it must be an iterable of individual test cases
1465 # or other test suites that will be used to build the suite initially"
1466 #
1467 # TestSuite should allow any iterable to provide tests
1468 def test_init__tests_from_any_iterable(self):
1469 def tests():
1470 yield unittest.FunctionTestCase(lambda: None)
1471 yield unittest.FunctionTestCase(lambda: None)
1472
1473 suite_1 = unittest.TestSuite(tests())
1474 self.assertEqual(suite_1.countTestCases(), 2)
1475
1476 suite_2 = unittest.TestSuite(suite_1)
1477 self.assertEqual(suite_2.countTestCases(), 2)
1478
1479 suite_3 = unittest.TestSuite(set(suite_1))
1480 self.assertEqual(suite_3.countTestCases(), 2)
1481
1482 # "class TestSuite([tests])"
1483 # ...
1484 # "If tests is given, it must be an iterable of individual test cases
1485 # or other test suites that will be used to build the suite initially"
1486 #
1487 # Does TestSuite() also allow other TestSuite() instances to be present
1488 # in the tests iterable?
1489 def test_init__TestSuite_instances_in_tests(self):
1490 def tests():
1491 ftc = unittest.FunctionTestCase(lambda: None)
1492 yield unittest.TestSuite([ftc])
1493 yield unittest.FunctionTestCase(lambda: None)
1494
1495 suite = unittest.TestSuite(tests())
1496 self.assertEqual(suite.countTestCases(), 2)
1497
1498 ################################################################
1499 ### /Tests for TestSuite.__init__
1500
1501 # Container types should support the iter protocol
1502 def test_iter(self):
1503 test1 = unittest.FunctionTestCase(lambda: None)
1504 test2 = unittest.FunctionTestCase(lambda: None)
1505 suite = unittest.TestSuite((test1, test2))
1506
1507 self.assertEqual(list(suite), [test1, test2])
1508
1509 # "Return the number of tests represented by the this test object.
1510 # ...this method is also implemented by the TestSuite class, which can
1511 # return larger [greater than 1] values"
1512 #
1513 # Presumably an empty TestSuite returns 0?
1514 def test_countTestCases_zero_simple(self):
1515 suite = unittest.TestSuite()
1516
1517 self.assertEqual(suite.countTestCases(), 0)
1518
1519 # "Return the number of tests represented by the this test object.
1520 # ...this method is also implemented by the TestSuite class, which can
1521 # return larger [greater than 1] values"
1522 #
1523 # Presumably an empty TestSuite (even if it contains other empty
1524 # TestSuite instances) returns 0?
1525 def test_countTestCases_zero_nested(self):
1526 class Test1(unittest.TestCase):
1527 def test(self):
1528 pass
1529
1530 suite = unittest.TestSuite([unittest.TestSuite()])
1531
1532 self.assertEqual(suite.countTestCases(), 0)
1533
1534 # "Return the number of tests represented by the this test object.
1535 # ...this method is also implemented by the TestSuite class, which can
1536 # return larger [greater than 1] values"
1537 def test_countTestCases_simple(self):
1538 test1 = unittest.FunctionTestCase(lambda: None)
1539 test2 = unittest.FunctionTestCase(lambda: None)
1540 suite = unittest.TestSuite((test1, test2))
1541
1542 self.assertEqual(suite.countTestCases(), 2)
1543
1544 # "Return the number of tests represented by the this test object.
1545 # ...this method is also implemented by the TestSuite class, which can
1546 # return larger [greater than 1] values"
1547 #
1548 # Make sure this holds for nested TestSuite instances, too
1549 def test_countTestCases_nested(self):
1550 class Test1(unittest.TestCase):
1551 def test1(self): pass
1552 def test2(self): pass
1553
1554 test2 = unittest.FunctionTestCase(lambda: None)
1555 test3 = unittest.FunctionTestCase(lambda: None)
1556 child = unittest.TestSuite((Test1('test2'), test2))
1557 parent = unittest.TestSuite((test3, child, Test1('test1')))
1558
1559 self.assertEqual(parent.countTestCases(), 4)
1560
1561 # "Run the tests associated with this suite, collecting the result into
1562 # the test result object passed as result."
1563 #
1564 # And if there are no tests? What then?
1565 def test_run__empty_suite(self):
1566 events = []
1567 result = LoggingResult(events)
1568
1569 suite = unittest.TestSuite()
1570
1571 suite.run(result)
1572
1573 self.assertEqual(events, [])
1574
1575 # "Note that unlike TestCase.run(), TestSuite.run() requires the
1576 # "result object to be passed in."
1577 def test_run__requires_result(self):
1578 suite = unittest.TestSuite()
1579
1580 try:
1581 suite.run()
1582 except TypeError:
1583 pass
1584 else:
1585 self.fail("Failed to raise TypeError")
1586
1587 # "Run the tests associated with this suite, collecting the result into
1588 # the test result object passed as result."
1589 def test_run(self):
1590 events = []
1591 result = LoggingResult(events)
1592
1593 class LoggingCase(unittest.TestCase):
1594 def run(self, result):
1595 events.append('run %s' % self._testMethodName)
1596
1597 def test1(self): pass
1598 def test2(self): pass
1599
1600 tests = [LoggingCase('test1'), LoggingCase('test2')]
1601
1602 unittest.TestSuite(tests).run(result)
1603
1604 self.assertEqual(events, ['run test1', 'run test2'])
1605
1606 # "Add a TestCase ... to the suite"
1607 def test_addTest__TestCase(self):
1608 class Foo(unittest.TestCase):
1609 def test(self): pass
1610
1611 test = Foo('test')
1612 suite = unittest.TestSuite()
1613
1614 suite.addTest(test)
1615
1616 self.assertEqual(suite.countTestCases(), 1)
1617 self.assertEqual(list(suite), [test])
1618
1619 # "Add a ... TestSuite to the suite"
1620 def test_addTest__TestSuite(self):
1621 class Foo(unittest.TestCase):
1622 def test(self): pass
1623
1624 suite_2 = unittest.TestSuite([Foo('test')])
1625
1626 suite = unittest.TestSuite()
1627 suite.addTest(suite_2)
1628
1629 self.assertEqual(suite.countTestCases(), 1)
1630 self.assertEqual(list(suite), [suite_2])
1631
1632 # "Add all the tests from an iterable of TestCase and TestSuite
1633 # instances to this test suite."
1634 #
1635 # "This is equivalent to iterating over tests, calling addTest() for
1636 # each element"
1637 def test_addTests(self):
1638 class Foo(unittest.TestCase):
1639 def test_1(self): pass
1640 def test_2(self): pass
1641
1642 test_1 = Foo('test_1')
1643 test_2 = Foo('test_2')
1644 inner_suite = unittest.TestSuite([test_2])
1645
1646 def gen():
1647 yield test_1
1648 yield test_2
1649 yield inner_suite
1650
1651 suite_1 = unittest.TestSuite()
1652 suite_1.addTests(gen())
1653
1654 self.assertEqual(list(suite_1), list(gen()))
1655
1656 # "This is equivalent to iterating over tests, calling addTest() for
1657 # each element"
1658 suite_2 = unittest.TestSuite()
1659 for t in gen():
1660 suite_2.addTest(t)
1661
1662 self.assertEqual(suite_1, suite_2)
1663
1664 # "Add all the tests from an iterable of TestCase and TestSuite
1665 # instances to this test suite."
1666 #
1667 # What happens if it doesn't get an iterable?
1668 def test_addTest__noniterable(self):
1669 suite = unittest.TestSuite()
1670
1671 try:
1672 suite.addTests(5)
1673 except TypeError:
1674 pass
1675 else:
1676 self.fail("Failed to raise TypeError")
1677
1678 def test_addTest__noncallable(self):
1679 suite = unittest.TestSuite()
1680 self.assertRaises(TypeError, suite.addTest, 5)
1681
1682 def test_addTest__casesuiteclass(self):
1683 suite = unittest.TestSuite()
1684 self.assertRaises(TypeError, suite.addTest, Test_TestSuite)
1685 self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)
1686
1687 def test_addTests__string(self):
1688 suite = unittest.TestSuite()
1689 self.assertRaises(TypeError, suite.addTests, "foo")
1690
1691
1692class Test_FunctionTestCase(TestCase):
1693
1694 # "Return the number of tests represented by the this test object. For
1695 # TestCase instances, this will always be 1"
1696 def test_countTestCases(self):
1697 test = unittest.FunctionTestCase(lambda: None)
1698
1699 self.assertEqual(test.countTestCases(), 1)
1700
1701 # "When a setUp() method is defined, the test runner will run that method
1702 # prior to each test. Likewise, if a tearDown() method is defined, the
1703 # test runner will invoke that method after each test. In the example,
1704 # setUp() was used to create a fresh sequence for each test."
1705 #
1706 # Make sure the proper call order is maintained, even if setUp() raises
1707 # an exception.
1708 def test_run_call_order__error_in_setUp(self):
1709 events = []
1710 result = LoggingResult(events)
1711
1712 def setUp():
1713 events.append('setUp')
1714 raise RuntimeError('raised by setUp')
1715
1716 def test():
1717 events.append('test')
1718
1719 def tearDown():
1720 events.append('tearDown')
1721
1722 expected = ['startTest', 'setUp', 'addError', 'stopTest']
1723 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1724 self.assertEqual(events, expected)
1725
1726 # "When a setUp() method is defined, the test runner will run that method
1727 # prior to each test. Likewise, if a tearDown() method is defined, the
1728 # test runner will invoke that method after each test. In the example,
1729 # setUp() was used to create a fresh sequence for each test."
1730 #
1731 # Make sure the proper call order is maintained, even if the test raises
1732 # an error (as opposed to a failure).
1733 def test_run_call_order__error_in_test(self):
1734 events = []
1735 result = LoggingResult(events)
1736
1737 def setUp():
1738 events.append('setUp')
1739
1740 def test():
1741 events.append('test')
1742 raise RuntimeError('raised by test')
1743
1744 def tearDown():
1745 events.append('tearDown')
1746
1747 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
1748 'stopTest']
1749 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1750 self.assertEqual(events, expected)
1751
1752 # "When a setUp() method is defined, the test runner will run that method
1753 # prior to each test. Likewise, if a tearDown() method is defined, the
1754 # test runner will invoke that method after each test. In the example,
1755 # setUp() was used to create a fresh sequence for each test."
1756 #
1757 # Make sure the proper call order is maintained, even if the test signals
1758 # a failure (as opposed to an error).
1759 def test_run_call_order__failure_in_test(self):
1760 events = []
1761 result = LoggingResult(events)
1762
1763 def setUp():
1764 events.append('setUp')
1765
1766 def test():
1767 events.append('test')
1768 self.fail('raised by test')
1769
1770 def tearDown():
1771 events.append('tearDown')
1772
1773 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
1774 'stopTest']
1775 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1776 self.assertEqual(events, expected)
1777
1778 # "When a setUp() method is defined, the test runner will run that method
1779 # prior to each test. Likewise, if a tearDown() method is defined, the
1780 # test runner will invoke that method after each test. In the example,
1781 # setUp() was used to create a fresh sequence for each test."
1782 #
1783 # Make sure the proper call order is maintained, even if tearDown() raises
1784 # an exception.
1785 def test_run_call_order__error_in_tearDown(self):
1786 events = []
1787 result = LoggingResult(events)
1788
1789 def setUp():
1790 events.append('setUp')
1791
1792 def test():
1793 events.append('test')
1794
1795 def tearDown():
1796 events.append('tearDown')
1797 raise RuntimeError('raised by tearDown')
1798
1799 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
1800 'stopTest']
1801 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1802 self.assertEqual(events, expected)
1803
1804 # "Return a string identifying the specific test case."
1805 #
1806 # Because of the vague nature of the docs, I'm not going to lock this
1807 # test down too much. Really all that can be asserted is that the id()
1808 # will be a string (either 8-byte or unicode -- again, because the docs
1809 # just say "string")
1810 def test_id(self):
1811 test = unittest.FunctionTestCase(lambda: None)
1812
Ezio Melottie9615932010-01-24 19:26:24 +00001813 self.assertIsInstance(test.id(), str)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001814
1815 # "Returns a one-line description of the test, or None if no description
1816 # has been provided. The default implementation of this method returns
1817 # the first line of the test method's docstring, if available, or None."
1818 def test_shortDescription__no_docstring(self):
1819 test = unittest.FunctionTestCase(lambda: None)
1820
1821 self.assertEqual(test.shortDescription(), None)
1822
1823 # "Returns a one-line description of the test, or None if no description
1824 # has been provided. The default implementation of this method returns
1825 # the first line of the test method's docstring, if available, or None."
1826 def test_shortDescription__singleline_docstring(self):
1827 desc = "this tests foo"
1828 test = unittest.FunctionTestCase(lambda: None, description=desc)
1829
1830 self.assertEqual(test.shortDescription(), "this tests foo")
1831
1832class Test_TestResult(TestCase):
1833 # Note: there are not separate tests for TestResult.wasSuccessful(),
1834 # TestResult.errors, TestResult.failures, TestResult.testsRun or
1835 # TestResult.shouldStop because these only have meaning in terms of
1836 # other TestResult methods.
1837 #
1838 # Accordingly, tests for the aforenamed attributes are incorporated
1839 # in with the tests for the defining methods.
1840 ################################################################
1841
1842 def test_init(self):
1843 result = unittest.TestResult()
1844
Benjamin Petersone1759f82009-06-30 23:35:19 +00001845 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001846 self.assertEqual(len(result.errors), 0)
1847 self.assertEqual(len(result.failures), 0)
1848 self.assertEqual(result.testsRun, 0)
1849 self.assertEqual(result.shouldStop, False)
1850
1851 # "This method can be called to signal that the set of tests being
1852 # run should be aborted by setting the TestResult's shouldStop
1853 # attribute to True."
1854 def test_stop(self):
1855 result = unittest.TestResult()
1856
1857 result.stop()
1858
1859 self.assertEqual(result.shouldStop, True)
1860
1861 # "Called when the test case test is about to be run. The default
1862 # implementation simply increments the instance's testsRun counter."
1863 def test_startTest(self):
1864 class Foo(unittest.TestCase):
1865 def test_1(self):
1866 pass
1867
1868 test = Foo('test_1')
1869
1870 result = unittest.TestResult()
1871
1872 result.startTest(test)
1873
Benjamin Petersone1759f82009-06-30 23:35:19 +00001874 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001875 self.assertEqual(len(result.errors), 0)
1876 self.assertEqual(len(result.failures), 0)
1877 self.assertEqual(result.testsRun, 1)
1878 self.assertEqual(result.shouldStop, False)
1879
1880 result.stopTest(test)
1881
1882 # "Called after the test case test has been executed, regardless of
1883 # the outcome. The default implementation does nothing."
1884 def test_stopTest(self):
1885 class Foo(unittest.TestCase):
1886 def test_1(self):
1887 pass
1888
1889 test = Foo('test_1')
1890
1891 result = unittest.TestResult()
1892
1893 result.startTest(test)
1894
Benjamin Petersone1759f82009-06-30 23:35:19 +00001895 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001896 self.assertEqual(len(result.errors), 0)
1897 self.assertEqual(len(result.failures), 0)
1898 self.assertEqual(result.testsRun, 1)
1899 self.assertEqual(result.shouldStop, False)
1900
1901 result.stopTest(test)
1902
1903 # Same tests as above; make sure nothing has changed
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
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001910 # "Called before and after tests are run. The default implementation does nothing."
1911 def test_startTestRun_stopTestRun(self):
1912 result = unittest.TestResult()
1913 result.startTestRun()
1914 result.stopTestRun()
1915
Guido van Rossumd8faa362007-04-27 19:54:29 +00001916 # "addSuccess(test)"
1917 # ...
1918 # "Called when the test case test succeeds"
1919 # ...
1920 # "wasSuccessful() - Returns True if all tests run so far have passed,
1921 # otherwise returns False"
1922 # ...
1923 # "testsRun - The total number of tests run so far."
1924 # ...
1925 # "errors - A list containing 2-tuples of TestCase instances and
1926 # formatted tracebacks. Each tuple represents a test which raised an
1927 # unexpected exception. Contains formatted
1928 # tracebacks instead of sys.exc_info() results."
1929 # ...
1930 # "failures - A list containing 2-tuples of TestCase instances and
1931 # formatted tracebacks. Each tuple represents a test where a failure was
1932 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1933 # methods. Contains formatted tracebacks instead
1934 # of sys.exc_info() results."
1935 def test_addSuccess(self):
1936 class Foo(unittest.TestCase):
1937 def test_1(self):
1938 pass
1939
1940 test = Foo('test_1')
1941
1942 result = unittest.TestResult()
1943
1944 result.startTest(test)
1945 result.addSuccess(test)
1946 result.stopTest(test)
1947
Benjamin Petersone1759f82009-06-30 23:35:19 +00001948 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001949 self.assertEqual(len(result.errors), 0)
1950 self.assertEqual(len(result.failures), 0)
1951 self.assertEqual(result.testsRun, 1)
1952 self.assertEqual(result.shouldStop, False)
1953
1954 # "addFailure(test, err)"
1955 # ...
1956 # "Called when the test case test signals a failure. err is a tuple of
1957 # the form returned by sys.exc_info(): (type, value, traceback)"
1958 # ...
1959 # "wasSuccessful() - Returns True if all tests run so far have passed,
1960 # otherwise returns False"
1961 # ...
1962 # "testsRun - The total number of tests run so far."
1963 # ...
1964 # "errors - A list containing 2-tuples of TestCase instances and
1965 # formatted tracebacks. Each tuple represents a test which raised an
1966 # unexpected exception. Contains formatted
1967 # tracebacks instead of sys.exc_info() results."
1968 # ...
1969 # "failures - A list containing 2-tuples of TestCase instances and
1970 # formatted tracebacks. Each tuple represents a test where a failure was
1971 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1972 # methods. Contains formatted tracebacks instead
1973 # of sys.exc_info() results."
1974 def test_addFailure(self):
1975 import sys
1976
1977 class Foo(unittest.TestCase):
1978 def test_1(self):
1979 pass
1980
1981 test = Foo('test_1')
1982 try:
1983 test.fail("foo")
1984 except:
1985 exc_info_tuple = sys.exc_info()
1986
1987 result = unittest.TestResult()
1988
1989 result.startTest(test)
1990 result.addFailure(test, exc_info_tuple)
1991 result.stopTest(test)
1992
Benjamin Petersone1759f82009-06-30 23:35:19 +00001993 self.assertFalse(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001994 self.assertEqual(len(result.errors), 0)
1995 self.assertEqual(len(result.failures), 1)
1996 self.assertEqual(result.testsRun, 1)
1997 self.assertEqual(result.shouldStop, False)
1998
1999 test_case, formatted_exc = result.failures[0]
Benjamin Petersone1759f82009-06-30 23:35:19 +00002000 self.assertTrue(test_case is test)
Ezio Melottie9615932010-01-24 19:26:24 +00002001 self.assertIsInstance(formatted_exc, str)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002002
2003 # "addError(test, err)"
2004 # ...
2005 # "Called when the test case test raises an unexpected exception err
2006 # is a tuple of the form returned by sys.exc_info():
2007 # (type, value, traceback)"
2008 # ...
2009 # "wasSuccessful() - Returns True if all tests run so far have passed,
2010 # otherwise returns False"
2011 # ...
2012 # "testsRun - The total number of tests run so far."
2013 # ...
2014 # "errors - A list containing 2-tuples of TestCase instances and
2015 # formatted tracebacks. Each tuple represents a test which raised an
2016 # unexpected exception. Contains formatted
2017 # tracebacks instead of sys.exc_info() results."
2018 # ...
2019 # "failures - A list containing 2-tuples of TestCase instances and
2020 # formatted tracebacks. Each tuple represents a test where a failure was
2021 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
2022 # methods. Contains formatted tracebacks instead
2023 # of sys.exc_info() results."
2024 def test_addError(self):
2025 import sys
2026
2027 class Foo(unittest.TestCase):
2028 def test_1(self):
2029 pass
2030
2031 test = Foo('test_1')
2032 try:
2033 raise TypeError()
2034 except:
2035 exc_info_tuple = sys.exc_info()
2036
2037 result = unittest.TestResult()
2038
2039 result.startTest(test)
2040 result.addError(test, exc_info_tuple)
2041 result.stopTest(test)
2042
Benjamin Petersone1759f82009-06-30 23:35:19 +00002043 self.assertFalse(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00002044 self.assertEqual(len(result.errors), 1)
2045 self.assertEqual(len(result.failures), 0)
2046 self.assertEqual(result.testsRun, 1)
2047 self.assertEqual(result.shouldStop, False)
2048
2049 test_case, formatted_exc = result.errors[0]
Benjamin Petersone1759f82009-06-30 23:35:19 +00002050 self.assertTrue(test_case is test)
Ezio Melottie9615932010-01-24 19:26:24 +00002051 self.assertIsInstance(formatted_exc, str)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002052
2053### Support code for Test_TestCase
2054################################################################
2055
2056class Foo(unittest.TestCase):
2057 def runTest(self): pass
2058 def test1(self): pass
2059
2060class Bar(Foo):
2061 def test2(self): pass
2062
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002063class LoggingTestCase(unittest.TestCase):
2064 """A test case which logs its calls."""
2065
2066 def __init__(self, events):
2067 super(LoggingTestCase, self).__init__('test')
2068 self.events = events
2069
2070 def setUp(self):
2071 self.events.append('setUp')
2072
2073 def test(self):
2074 self.events.append('test')
2075
2076 def tearDown(self):
2077 self.events.append('tearDown')
2078
2079class ResultWithNoStartTestRunStopTestRun(object):
2080 """An object honouring TestResult before startTestRun/stopTestRun."""
2081
2082 def __init__(self):
2083 self.failures = []
2084 self.errors = []
2085 self.testsRun = 0
2086 self.skipped = []
2087 self.expectedFailures = []
2088 self.unexpectedSuccesses = []
2089 self.shouldStop = False
2090
2091 def startTest(self, test):
2092 pass
2093
2094 def stopTest(self, test):
2095 pass
2096
2097 def addError(self, test):
2098 pass
2099
2100 def addFailure(self, test):
2101 pass
2102
2103 def addSuccess(self, test):
2104 pass
2105
2106 def wasSuccessful(self):
2107 return True
2108
2109
Guido van Rossumd8faa362007-04-27 19:54:29 +00002110################################################################
2111### /Support code for Test_TestCase
2112
2113class Test_TestCase(TestCase, TestEquality, TestHashing):
2114
2115 ### Set up attributes used by inherited tests
2116 ################################################################
2117
2118 # Used by TestHashing.test_hash and TestEquality.test_eq
2119 eq_pairs = [(Foo('test1'), Foo('test1'))]
2120
2121 # Used by TestEquality.test_ne
2122 ne_pairs = [(Foo('test1'), Foo('runTest'))
2123 ,(Foo('test1'), Bar('test1'))
2124 ,(Foo('test1'), Bar('test2'))]
2125
2126 ################################################################
2127 ### /Set up attributes used by inherited tests
2128
2129
2130 # "class TestCase([methodName])"
2131 # ...
2132 # "Each instance of TestCase will run a single test method: the
2133 # method named methodName."
2134 # ...
2135 # "methodName defaults to "runTest"."
2136 #
2137 # Make sure it really is optional, and that it defaults to the proper
2138 # thing.
2139 def test_init__no_test_name(self):
2140 class Test(unittest.TestCase):
2141 def runTest(self): raise MyException()
2142 def test(self): pass
2143
2144 self.assertEqual(Test().id()[-13:], '.Test.runTest')
2145
2146 # "class TestCase([methodName])"
2147 # ...
2148 # "Each instance of TestCase will run a single test method: the
2149 # method named methodName."
2150 def test_init__test_name__valid(self):
2151 class Test(unittest.TestCase):
2152 def runTest(self): raise MyException()
2153 def test(self): pass
2154
2155 self.assertEqual(Test('test').id()[-10:], '.Test.test')
2156
2157 # "class TestCase([methodName])"
2158 # ...
2159 # "Each instance of TestCase will run a single test method: the
2160 # method named methodName."
2161 def test_init__test_name__invalid(self):
2162 class Test(unittest.TestCase):
2163 def runTest(self): raise MyException()
2164 def test(self): pass
2165
2166 try:
2167 Test('testfoo')
2168 except ValueError:
2169 pass
2170 else:
2171 self.fail("Failed to raise ValueError")
2172
2173 # "Return the number of tests represented by the this test object. For
2174 # TestCase instances, this will always be 1"
2175 def test_countTestCases(self):
2176 class Foo(unittest.TestCase):
2177 def test(self): pass
2178
2179 self.assertEqual(Foo('test').countTestCases(), 1)
2180
2181 # "Return the default type of test result object to be used to run this
2182 # test. For TestCase instances, this will always be
2183 # unittest.TestResult; subclasses of TestCase should
2184 # override this as necessary."
2185 def test_defaultTestResult(self):
2186 class Foo(unittest.TestCase):
2187 def runTest(self):
2188 pass
2189
2190 result = Foo().defaultTestResult()
2191 self.assertEqual(type(result), unittest.TestResult)
2192
2193 # "When a setUp() method is defined, the test runner will run that method
2194 # prior to each test. Likewise, if a tearDown() method is defined, the
2195 # test runner will invoke that method after each test. In the example,
2196 # setUp() was used to create a fresh sequence for each test."
2197 #
2198 # Make sure the proper call order is maintained, even if setUp() raises
2199 # an exception.
2200 def test_run_call_order__error_in_setUp(self):
2201 events = []
2202 result = LoggingResult(events)
2203
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002204 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002205 def setUp(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002206 super(Foo, self).setUp()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002207 raise RuntimeError('raised by Foo.setUp')
2208
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002209 Foo(events).run(result)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002210 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2211 self.assertEqual(events, expected)
2212
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002213 # "With a temporary result stopTestRun is called when setUp errors.
2214 def test_run_call_order__error_in_setUp_default_result(self):
2215 events = []
2216
2217 class Foo(LoggingTestCase):
2218 def defaultTestResult(self):
2219 return LoggingResult(self.events)
2220
2221 def setUp(self):
2222 super(Foo, self).setUp()
2223 raise RuntimeError('raised by Foo.setUp')
2224
2225 Foo(events).run()
2226 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2227 'stopTest', 'stopTestRun']
2228 self.assertEqual(events, expected)
2229
Guido van Rossumd8faa362007-04-27 19:54:29 +00002230 # "When a setUp() method is defined, the test runner will run that method
2231 # prior to each test. Likewise, if a tearDown() method is defined, the
2232 # test runner will invoke that method after each test. In the example,
2233 # setUp() was used to create a fresh sequence for each test."
2234 #
2235 # Make sure the proper call order is maintained, even if the test raises
2236 # an error (as opposed to a failure).
2237 def test_run_call_order__error_in_test(self):
2238 events = []
2239 result = LoggingResult(events)
2240
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002241 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002242 def test(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002243 super(Foo, self).test()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002244 raise RuntimeError('raised by Foo.test')
2245
Guido van Rossumd8faa362007-04-27 19:54:29 +00002246 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2247 'stopTest']
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002248 Foo(events).run(result)
2249 self.assertEqual(events, expected)
2250
2251 # "With a default result, an error in the test still results in stopTestRun
2252 # being called."
2253 def test_run_call_order__error_in_test_default_result(self):
2254 events = []
2255
2256 class Foo(LoggingTestCase):
2257 def defaultTestResult(self):
2258 return LoggingResult(self.events)
2259
2260 def test(self):
2261 super(Foo, self).test()
2262 raise RuntimeError('raised by Foo.test')
2263
2264 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2265 'tearDown', 'stopTest', 'stopTestRun']
2266 Foo(events).run()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002267 self.assertEqual(events, expected)
2268
2269 # "When a setUp() method is defined, the test runner will run that method
2270 # prior to each test. Likewise, if a tearDown() method is defined, the
2271 # test runner will invoke that method after each test. In the example,
2272 # setUp() was used to create a fresh sequence for each test."
2273 #
2274 # Make sure the proper call order is maintained, even if the test signals
2275 # a failure (as opposed to an error).
2276 def test_run_call_order__failure_in_test(self):
2277 events = []
2278 result = LoggingResult(events)
2279
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002280 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002281 def test(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002282 super(Foo, self).test()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002283 self.fail('raised by Foo.test')
2284
Guido van Rossumd8faa362007-04-27 19:54:29 +00002285 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2286 'stopTest']
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002287 Foo(events).run(result)
2288 self.assertEqual(events, expected)
2289
2290 # "When a test fails with a default result stopTestRun is still called."
2291 def test_run_call_order__failure_in_test_default_result(self):
2292
2293 class Foo(LoggingTestCase):
2294 def defaultTestResult(self):
2295 return LoggingResult(self.events)
2296 def test(self):
2297 super(Foo, self).test()
2298 self.fail('raised by Foo.test')
2299
2300 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2301 'tearDown', 'stopTest', 'stopTestRun']
2302 events = []
2303 Foo(events).run()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002304 self.assertEqual(events, expected)
2305
2306 # "When a setUp() method is defined, the test runner will run that method
2307 # prior to each test. Likewise, if a tearDown() method is defined, the
2308 # test runner will invoke that method after each test. In the example,
2309 # setUp() was used to create a fresh sequence for each test."
2310 #
2311 # Make sure the proper call order is maintained, even if tearDown() raises
2312 # an exception.
2313 def test_run_call_order__error_in_tearDown(self):
2314 events = []
2315 result = LoggingResult(events)
2316
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002317 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002318 def tearDown(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002319 super(Foo, self).tearDown()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002320 raise RuntimeError('raised by Foo.tearDown')
2321
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002322 Foo(events).run(result)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002323 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2324 'stopTest']
2325 self.assertEqual(events, expected)
2326
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002327 # "When tearDown errors with a default result stopTestRun is still called."
2328 def test_run_call_order__error_in_tearDown_default_result(self):
2329
2330 class Foo(LoggingTestCase):
2331 def defaultTestResult(self):
2332 return LoggingResult(self.events)
2333 def tearDown(self):
2334 super(Foo, self).tearDown()
2335 raise RuntimeError('raised by Foo.tearDown')
2336
2337 events = []
2338 Foo(events).run()
2339 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2340 'addError', 'stopTest', 'stopTestRun']
2341 self.assertEqual(events, expected)
2342
2343 # "TestCase.run() still works when the defaultTestResult is a TestResult
2344 # that does not support startTestRun and stopTestRun.
2345 def test_run_call_order_default_result(self):
2346
2347 class Foo(unittest.TestCase):
2348 def defaultTestResult(self):
2349 return ResultWithNoStartTestRunStopTestRun()
2350 def test(self):
2351 pass
2352
2353 Foo('test').run()
2354
Guido van Rossumd8faa362007-04-27 19:54:29 +00002355 # "This class attribute gives the exception raised by the test() method.
2356 # If a test framework needs to use a specialized exception, possibly to
2357 # carry additional information, it must subclass this exception in
2358 # order to ``play fair'' with the framework. The initial value of this
2359 # attribute is AssertionError"
2360 def test_failureException__default(self):
2361 class Foo(unittest.TestCase):
2362 def test(self):
2363 pass
2364
Benjamin Petersone1759f82009-06-30 23:35:19 +00002365 self.assertTrue(Foo('test').failureException is AssertionError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002366
2367 # "This class attribute gives the exception raised by the test() method.
2368 # If a test framework needs to use a specialized exception, possibly to
2369 # carry additional information, it must subclass this exception in
2370 # order to ``play fair'' with the framework."
2371 #
2372 # Make sure TestCase.run() respects the designated failureException
2373 def test_failureException__subclassing__explicit_raise(self):
2374 events = []
2375 result = LoggingResult(events)
2376
2377 class Foo(unittest.TestCase):
2378 def test(self):
2379 raise RuntimeError()
2380
2381 failureException = RuntimeError
2382
Benjamin Petersone1759f82009-06-30 23:35:19 +00002383 self.assertTrue(Foo('test').failureException is RuntimeError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002384
2385
2386 Foo('test').run(result)
2387 expected = ['startTest', 'addFailure', 'stopTest']
2388 self.assertEqual(events, expected)
2389
2390 # "This class attribute gives the exception raised by the test() method.
2391 # If a test framework needs to use a specialized exception, possibly to
2392 # carry additional information, it must subclass this exception in
2393 # order to ``play fair'' with the framework."
2394 #
2395 # Make sure TestCase.run() respects the designated failureException
2396 def test_failureException__subclassing__implicit_raise(self):
2397 events = []
2398 result = LoggingResult(events)
2399
2400 class Foo(unittest.TestCase):
2401 def test(self):
2402 self.fail("foo")
2403
2404 failureException = RuntimeError
2405
Benjamin Petersone1759f82009-06-30 23:35:19 +00002406 self.assertTrue(Foo('test').failureException is RuntimeError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002407
2408
2409 Foo('test').run(result)
2410 expected = ['startTest', 'addFailure', 'stopTest']
2411 self.assertEqual(events, expected)
2412
2413 # "The default implementation does nothing."
2414 def test_setUp(self):
2415 class Foo(unittest.TestCase):
2416 def runTest(self):
2417 pass
2418
2419 # ... and nothing should happen
2420 Foo().setUp()
2421
2422 # "The default implementation does nothing."
2423 def test_tearDown(self):
2424 class Foo(unittest.TestCase):
2425 def runTest(self):
2426 pass
2427
2428 # ... and nothing should happen
2429 Foo().tearDown()
2430
2431 # "Return a string identifying the specific test case."
2432 #
2433 # Because of the vague nature of the docs, I'm not going to lock this
2434 # test down too much. Really all that can be asserted is that the id()
2435 # will be a string (either 8-byte or unicode -- again, because the docs
2436 # just say "string")
2437 def test_id(self):
2438 class Foo(unittest.TestCase):
2439 def runTest(self):
2440 pass
2441
Ezio Melottie9615932010-01-24 19:26:24 +00002442 self.assertIsInstance(Foo().id(), str)
2443
Guido van Rossumd8faa362007-04-27 19:54:29 +00002444
Guido van Rossumd8faa362007-04-27 19:54:29 +00002445 # "If result is omitted or None, a temporary result object is created
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002446 # and used, but is not made available to the caller. As TestCase owns the
2447 # temporary result startTestRun and stopTestRun are called.
2448
Guido van Rossumd8faa362007-04-27 19:54:29 +00002449 def test_run__uses_defaultTestResult(self):
2450 events = []
2451
2452 class Foo(unittest.TestCase):
2453 def test(self):
2454 events.append('test')
2455
2456 def defaultTestResult(self):
2457 return LoggingResult(events)
2458
2459 # Make run() find a result object on its own
2460 Foo('test').run()
2461
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002462 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2463 'stopTest', 'stopTestRun']
Guido van Rossumd8faa362007-04-27 19:54:29 +00002464 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002465
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002466 def testShortDescriptionWithoutDocstring(self):
2467 self.assertEqual(
2468 self.shortDescription(),
2469 'testShortDescriptionWithoutDocstring (' + __name__ +
2470 '.Test_TestCase)')
2471
2472 def testShortDescriptionWithOneLineDocstring(self):
2473 """Tests shortDescription() for a method with a docstring."""
2474 self.assertEqual(
2475 self.shortDescription(),
2476 ('testShortDescriptionWithOneLineDocstring '
2477 '(' + __name__ + '.Test_TestCase)\n'
2478 'Tests shortDescription() for a method with a docstring.'))
2479
2480 def testShortDescriptionWithMultiLineDocstring(self):
2481 """Tests shortDescription() for a method with a longer docstring.
2482
2483 This method ensures that only the first line of a docstring is
2484 returned used in the short description, no matter how long the
2485 whole thing is.
2486 """
2487 self.assertEqual(
2488 self.shortDescription(),
2489 ('testShortDescriptionWithMultiLineDocstring '
2490 '(' + __name__ + '.Test_TestCase)\n'
2491 'Tests shortDescription() for a method with a longer '
2492 'docstring.'))
2493
2494 def testAddTypeEqualityFunc(self):
2495 class SadSnake(object):
2496 """Dummy class for test_addTypeEqualityFunc."""
2497 s1, s2 = SadSnake(), SadSnake()
2498 self.assertFalse(s1 == s2)
2499 def AllSnakesCreatedEqual(a, b, msg=None):
2500 return type(a) == type(b) == SadSnake
2501 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2502 self.assertEqual(s1, s2)
2503 # No this doesn't clean up and remove the SadSnake equality func
2504 # from this TestCase instance but since its a local nothing else
2505 # will ever notice that.
2506
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00002507 def testAssertIs(self):
2508 thing = object()
2509 self.assertIs(thing, thing)
2510 self.assertRaises(self.failureException, self.assertIs, thing, object())
2511
2512 def testAssertIsNot(self):
2513 thing = object()
2514 self.assertIsNot(thing, object())
2515 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2516
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00002517 def testAssertIsInstance(self):
2518 thing = []
2519 self.assertIsInstance(thing, list)
2520 self.assertRaises(self.failureException, self.assertIsInstance,
2521 thing, dict)
2522
2523 def testAssertNotIsInstance(self):
2524 thing = []
2525 self.assertNotIsInstance(thing, dict)
2526 self.assertRaises(self.failureException, self.assertNotIsInstance,
2527 thing, list)
2528
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002529 def testAssertIn(self):
2530 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2531
2532 self.assertIn('a', 'abc')
2533 self.assertIn(2, [1, 2, 3])
2534 self.assertIn('monkey', animals)
2535
2536 self.assertNotIn('d', 'abc')
2537 self.assertNotIn(0, [1, 2, 3])
2538 self.assertNotIn('otter', animals)
2539
2540 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2541 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2542 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2543 animals)
2544
2545 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2546 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2547 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2548 animals)
2549
2550 def testAssertDictContainsSubset(self):
2551 self.assertDictContainsSubset({}, {})
2552 self.assertDictContainsSubset({}, {'a': 1})
2553 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2554 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2555 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2556
2557 self.assertRaises(unittest.TestCase.failureException,
2558 self.assertDictContainsSubset, {'a': 2}, {'a': 1},
2559 '.*Mismatched values:.*')
2560
2561 self.assertRaises(unittest.TestCase.failureException,
2562 self.assertDictContainsSubset, {'c': 1}, {'a': 1},
2563 '.*Missing:.*')
2564
2565 self.assertRaises(unittest.TestCase.failureException,
2566 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2567 {'a': 1}, '.*Missing:.*')
2568
2569 self.assertRaises(unittest.TestCase.failureException,
2570 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2571 {'a': 1}, '.*Missing:.*Mismatched values:.*')
2572
2573 def testAssertEqual(self):
2574 equal_pairs = [
2575 ((), ()),
2576 ({}, {}),
2577 ([], []),
2578 (set(), set()),
2579 (frozenset(), frozenset())]
2580 for a, b in equal_pairs:
2581 # This mess of try excepts is to test the assertEqual behavior
2582 # itself.
2583 try:
2584 self.assertEqual(a, b)
2585 except self.failureException:
2586 self.fail('assertEqual(%r, %r) failed' % (a, b))
2587 try:
2588 self.assertEqual(a, b, msg='foo')
2589 except self.failureException:
2590 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2591 try:
2592 self.assertEqual(a, b, 'foo')
2593 except self.failureException:
2594 self.fail('assertEqual(%r, %r) with third parameter failed' %
2595 (a, b))
2596
2597 unequal_pairs = [
2598 ((), []),
2599 ({}, set()),
2600 (set([4,1]), frozenset([4,2])),
2601 (frozenset([4,5]), set([2,3])),
2602 (set([3,4]), set([5,4]))]
2603 for a, b in unequal_pairs:
2604 self.assertRaises(self.failureException, self.assertEqual, a, b)
2605 self.assertRaises(self.failureException, self.assertEqual, a, b,
2606 'foo')
2607 self.assertRaises(self.failureException, self.assertEqual, a, b,
2608 msg='foo')
2609
2610 def testEquality(self):
2611 self.assertListEqual([], [])
2612 self.assertTupleEqual((), ())
2613 self.assertSequenceEqual([], ())
2614
2615 a = [0, 'a', []]
2616 b = []
2617 self.assertRaises(unittest.TestCase.failureException,
2618 self.assertListEqual, a, b)
2619 self.assertRaises(unittest.TestCase.failureException,
2620 self.assertListEqual, tuple(a), tuple(b))
2621 self.assertRaises(unittest.TestCase.failureException,
2622 self.assertSequenceEqual, a, tuple(b))
2623
2624 b.extend(a)
2625 self.assertListEqual(a, b)
2626 self.assertTupleEqual(tuple(a), tuple(b))
2627 self.assertSequenceEqual(a, tuple(b))
2628 self.assertSequenceEqual(tuple(a), b)
2629
2630 self.assertRaises(self.failureException, self.assertListEqual,
2631 a, tuple(b))
2632 self.assertRaises(self.failureException, self.assertTupleEqual,
2633 tuple(a), b)
2634 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2635 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2636 tuple(b))
2637 self.assertRaises(self.failureException, self.assertSequenceEqual,
2638 None, tuple(b))
2639 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2640 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2641 self.assertRaises(self.failureException, self.assertSequenceEqual,
2642 1, 1)
2643
2644 self.assertDictEqual({}, {})
2645
2646 c = { 'x': 1 }
2647 d = {}
2648 self.assertRaises(unittest.TestCase.failureException,
2649 self.assertDictEqual, c, d)
2650
2651 d.update(c)
2652 self.assertDictEqual(c, d)
2653
2654 d['x'] = 0
2655 self.assertRaises(unittest.TestCase.failureException,
2656 self.assertDictEqual, c, d, 'These are unequal')
2657
2658 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2659 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2660 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2661
2662 self.assertSameElements([1, 2, 3], [3, 2, 1])
2663 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2664 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2665 self.assertRaises(self.failureException, self.assertSameElements,
2666 [10], [10, 11])
2667 self.assertRaises(self.failureException, self.assertSameElements,
2668 [10, 11], [10])
2669
2670 # Test that sequences of unhashable objects can be tested for sameness:
2671 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00002672
Benjamin Peterson3bb6b7a2009-04-04 16:46:24 +00002673 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002674 self.assertRaises(self.failureException, self.assertSameElements,
2675 [[1]], [[2]])
Michael Foorda5809c82009-04-04 18:55:09 +00002676 self.assertRaises(self.failureException, self.assertSameElements,
2677 [{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 2}])
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002678
2679 def testAssertSetEqual(self):
2680 set1 = set()
2681 set2 = set()
2682 self.assertSetEqual(set1, set2)
2683
2684 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2685 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2686 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2687 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2688
2689 set1 = set(['a'])
2690 set2 = set()
2691 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2692
2693 set1 = set(['a'])
2694 set2 = set(['a'])
2695 self.assertSetEqual(set1, set2)
2696
2697 set1 = set(['a'])
2698 set2 = set(['a', 'b'])
2699 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2700
2701 set1 = set(['a'])
2702 set2 = frozenset(['a', 'b'])
2703 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2704
2705 set1 = set(['a', 'b'])
2706 set2 = frozenset(['a', 'b'])
2707 self.assertSetEqual(set1, set2)
2708
2709 set1 = set()
2710 set2 = "foo"
2711 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2712 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2713
2714 # make sure any string formatting is tuple-safe
2715 set1 = set([(0, 1), (2, 3)])
2716 set2 = set([(4, 5)])
2717 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2718
2719 def testInequality(self):
2720 # Try ints
2721 self.assertGreater(2, 1)
2722 self.assertGreaterEqual(2, 1)
2723 self.assertGreaterEqual(1, 1)
2724 self.assertLess(1, 2)
2725 self.assertLessEqual(1, 2)
2726 self.assertLessEqual(1, 1)
2727 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2728 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2729 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2730 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2731 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2732 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2733
2734 # Try Floats
2735 self.assertGreater(1.1, 1.0)
2736 self.assertGreaterEqual(1.1, 1.0)
2737 self.assertGreaterEqual(1.0, 1.0)
2738 self.assertLess(1.0, 1.1)
2739 self.assertLessEqual(1.0, 1.1)
2740 self.assertLessEqual(1.0, 1.0)
2741 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2742 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2743 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2744 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2745 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2746 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2747
2748 # Try Strings
2749 self.assertGreater('bug', 'ant')
2750 self.assertGreaterEqual('bug', 'ant')
2751 self.assertGreaterEqual('ant', 'ant')
2752 self.assertLess('ant', 'bug')
2753 self.assertLessEqual('ant', 'bug')
2754 self.assertLessEqual('ant', 'ant')
2755 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2756 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2757 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2758 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2759 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2760 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2761
2762 # Try bytes
2763 self.assertGreater(b'bug', b'ant')
2764 self.assertGreaterEqual(b'bug', b'ant')
2765 self.assertGreaterEqual(b'ant', b'ant')
2766 self.assertLess(b'ant', b'bug')
2767 self.assertLessEqual(b'ant', b'bug')
2768 self.assertLessEqual(b'ant', b'ant')
2769 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'bug')
2770 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'ant')
2771 self.assertRaises(self.failureException, self.assertGreaterEqual, b'ant',
2772 b'bug')
2773 self.assertRaises(self.failureException, self.assertLess, b'bug', b'ant')
2774 self.assertRaises(self.failureException, self.assertLess, b'ant', b'ant')
2775 self.assertRaises(self.failureException, self.assertLessEqual, b'bug', b'ant')
2776
2777 def testAssertMultiLineEqual(self):
2778 sample_text = """\
2779http://www.python.org/doc/2.3/lib/module-unittest.html
2780test case
2781 A test case is the smallest unit of testing. [...]
2782"""
2783 revised_sample_text = """\
2784http://www.python.org/doc/2.4.1/lib/module-unittest.html
2785test case
2786 A test case is the smallest unit of testing. [...] You may provide your
2787 own implementation that does not subclass from TestCase, of course.
2788"""
2789 sample_text_error = """
2790- http://www.python.org/doc/2.3/lib/module-unittest.html
2791? ^
2792+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2793? ^^^
2794 test case
2795- A test case is the smallest unit of testing. [...]
2796+ A test case is the smallest unit of testing. [...] You may provide your
2797? +++++++++++++++++++++
2798+ own implementation that does not subclass from TestCase, of course.
2799"""
2800
2801 try:
2802 self.assertMultiLineEqual(sample_text, revised_sample_text)
2803 except self.failureException as e:
2804 # no fair testing ourself with ourself, use assertEqual..
2805 self.assertEqual(sample_text_error, str(e))
2806
2807 def testAssertIsNone(self):
2808 self.assertIsNone(None)
2809 self.assertRaises(self.failureException, self.assertIsNone, False)
2810 self.assertIsNotNone('DjZoPloGears on Rails')
2811 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2812
2813 def testAssertRegexpMatches(self):
2814 self.assertRegexpMatches('asdfabasdf', r'ab+')
2815 self.assertRaises(self.failureException, self.assertRegexpMatches,
2816 'saaas', r'aaaa')
2817
2818 def testAssertRaisesRegexp(self):
2819 class ExceptionMock(Exception):
2820 pass
2821
2822 def Stub():
2823 raise ExceptionMock('We expect')
2824
2825 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2826 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2827
2828 def testAssertNotRaisesRegexp(self):
2829 self.assertRaisesRegexp(
Benjamin Peterson4f75b642009-04-04 16:39:09 +00002830 self.failureException, '^Exception not raised by <lambda>$',
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002831 self.assertRaisesRegexp, Exception, re.compile('x'),
2832 lambda: None)
2833 self.assertRaisesRegexp(
Benjamin Peterson4f75b642009-04-04 16:39:09 +00002834 self.failureException, '^Exception not raised by <lambda>$',
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002835 self.assertRaisesRegexp, Exception, 'x',
2836 lambda: None)
2837
2838 def testAssertRaisesRegexpMismatch(self):
2839 def Stub():
2840 raise Exception('Unexpected')
2841
2842 self.assertRaisesRegexp(
2843 self.failureException,
2844 r'"\^Expected\$" does not match "Unexpected"',
2845 self.assertRaisesRegexp, Exception, '^Expected$',
2846 Stub)
2847 self.assertRaisesRegexp(
2848 self.failureException,
2849 r'"\^Expected\$" does not match "Unexpected"',
2850 self.assertRaisesRegexp, Exception,
2851 re.compile('^Expected$'), Stub)
2852
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +00002853 def testAssertRaisesExcValue(self):
2854 class ExceptionMock(Exception):
2855 pass
2856
2857 def Stub(foo):
2858 raise ExceptionMock(foo)
2859 v = "particular value"
2860
2861 ctx = self.assertRaises(ExceptionMock)
2862 with ctx:
2863 Stub(v)
2864 e = ctx.exc_value
Ezio Melottie9615932010-01-24 19:26:24 +00002865 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +00002866 self.assertEqual(e.args[0], v)
2867
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002868 def testSynonymAssertMethodNames(self):
2869 """Test undocumented method name synonyms.
2870
2871 Please do not use these methods names in your own code.
2872
2873 This test confirms their continued existence and functionality
2874 in order to avoid breaking existing code.
2875 """
2876 self.assertNotEquals(3, 5)
2877 self.assertEquals(3, 3)
2878 self.assertAlmostEquals(2.0, 2.0)
2879 self.assertNotAlmostEquals(3.0, 5.0)
2880 self.assert_(True)
2881
2882 def testPendingDeprecationMethodNames(self):
2883 """Test fail* methods pending deprecation, they will warn in 3.2.
2884
2885 Do not use these methods. They will go away in 3.3.
2886 """
Benjamin Peterson6bcbad52009-06-30 23:45:41 +00002887 old = (
2888 (self.failIfEqual, (3, 5)),
2889 (self.failUnlessEqual, (3, 3)),
2890 (self.failUnlessAlmostEqual, (2.0, 2.0)),
2891 (self.failIfAlmostEqual, (3.0, 5.0)),
2892 (self.failUnless, (True,)),
2893 (self.failUnlessRaises, (TypeError, lambda _: 3.14 + 'spam')),
2894 (self.failIf, (False,))
2895 )
2896 for meth, args in old:
2897 with warnings.catch_warnings(record=True) as w:
2898 meth(*args)
2899 self.assertEqual(len(w), 1)
2900 self.assertIs(w[0].category, DeprecationWarning)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002901
2902 def testDeepcopy(self):
2903 # Issue: 5660
2904 class TestableTest(TestCase):
2905 def testNothing(self):
2906 pass
2907
2908 test = TestableTest('testNothing')
2909
2910 # This shouldn't blow up
2911 deepcopy(test)
2912
Benjamin Peterson5254c042009-03-23 22:25:03 +00002913
2914class Test_TestSkipping(TestCase):
2915
2916 def test_skipping(self):
2917 class Foo(unittest.TestCase):
2918 def test_skip_me(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00002919 self.skipTest("skip")
Benjamin Peterson5254c042009-03-23 22:25:03 +00002920 events = []
2921 result = LoggingResult(events)
2922 test = Foo("test_skip_me")
2923 test.run(result)
2924 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2925 self.assertEqual(result.skipped, [(test, "skip")])
2926
2927 # Try letting setUp skip the test now.
2928 class Foo(unittest.TestCase):
2929 def setUp(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00002930 self.skipTest("testing")
Benjamin Peterson5254c042009-03-23 22:25:03 +00002931 def test_nothing(self): pass
2932 events = []
2933 result = LoggingResult(events)
2934 test = Foo("test_nothing")
2935 test.run(result)
2936 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2937 self.assertEqual(result.skipped, [(test, "testing")])
2938 self.assertEqual(result.testsRun, 1)
2939
2940 def test_skipping_decorators(self):
2941 op_table = ((unittest.skipUnless, False, True),
2942 (unittest.skipIf, True, False))
2943 for deco, do_skip, dont_skip in op_table:
2944 class Foo(unittest.TestCase):
2945 @deco(do_skip, "testing")
2946 def test_skip(self): pass
2947
2948 @deco(dont_skip, "testing")
2949 def test_dont_skip(self): pass
2950 test_do_skip = Foo("test_skip")
2951 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002952 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002953 events = []
2954 result = LoggingResult(events)
2955 suite.run(result)
2956 self.assertEqual(len(result.skipped), 1)
2957 expected = ['startTest', 'addSkip', 'stopTest',
2958 'startTest', 'addSuccess', 'stopTest']
2959 self.assertEqual(events, expected)
2960 self.assertEqual(result.testsRun, 2)
2961 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
2962 self.assertTrue(result.wasSuccessful())
2963
2964 def test_skip_class(self):
2965 @unittest.skip("testing")
2966 class Foo(unittest.TestCase):
2967 def test_1(self):
2968 record.append(1)
2969 record = []
2970 result = unittest.TestResult()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002971 test = Foo("test_1")
2972 suite = unittest.TestSuite([test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002973 suite.run(result)
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002974 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002975 self.assertEqual(record, [])
2976
2977 def test_expected_failure(self):
2978 class Foo(unittest.TestCase):
2979 @unittest.expectedFailure
2980 def test_die(self):
2981 self.fail("help me!")
2982 events = []
2983 result = LoggingResult(events)
2984 test = Foo("test_die")
2985 test.run(result)
2986 self.assertEqual(events,
2987 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Peterson52baa292009-03-24 00:56:30 +00002988 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson5254c042009-03-23 22:25:03 +00002989 self.assertTrue(result.wasSuccessful())
2990
2991 def test_unexpected_success(self):
2992 class Foo(unittest.TestCase):
2993 @unittest.expectedFailure
2994 def test_die(self):
2995 pass
2996 events = []
2997 result = LoggingResult(events)
2998 test = Foo("test_die")
2999 test.run(result)
3000 self.assertEqual(events,
3001 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3002 self.assertFalse(result.failures)
Benjamin Peterson52baa292009-03-24 00:56:30 +00003003 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003004 self.assertTrue(result.wasSuccessful())
3005
3006
3007
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003008class Test_Assertions(TestCase):
3009 def test_AlmostEqual(self):
Benjamin Petersone1759f82009-06-30 23:35:19 +00003010 self.assertAlmostEqual(1.00000001, 1.0)
3011 self.assertNotAlmostEqual(1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003012 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003013 self.assertAlmostEqual, 1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003014 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003015 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003016
Benjamin Petersone1759f82009-06-30 23:35:19 +00003017 self.assertAlmostEqual(1.1, 1.0, places=0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003018 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003019 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003020
Benjamin Petersone1759f82009-06-30 23:35:19 +00003021 self.assertAlmostEqual(0, .1+.1j, places=0)
3022 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003023 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003024 self.assertAlmostEqual, 0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003025 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003026 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003027
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003028 self.assertAlmostEqual(float('inf'), float('inf'))
3029 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3030 float('inf'), float('inf'))
3031
3032
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003033 def test_assertRaises(self):
3034 def _raise(e):
3035 raise e
3036 self.assertRaises(KeyError, _raise, KeyError)
3037 self.assertRaises(KeyError, _raise, KeyError("key"))
3038 try:
3039 self.assertRaises(KeyError, lambda: None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003040 except self.failureException as e:
Ezio Melottib58e0bd2010-01-23 15:40:09 +00003041 self.assertIn("KeyError not raised", str(e))
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003042 else:
3043 self.fail("assertRaises() didn't fail")
3044 try:
3045 self.assertRaises(KeyError, _raise, ValueError)
3046 except ValueError:
3047 pass
3048 else:
3049 self.fail("assertRaises() didn't let exception pass through")
3050 with self.assertRaises(KeyError):
3051 raise KeyError
3052 with self.assertRaises(KeyError):
3053 raise KeyError("key")
3054 try:
3055 with self.assertRaises(KeyError):
3056 pass
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003057 except self.failureException as e:
Ezio Melottib58e0bd2010-01-23 15:40:09 +00003058 self.assertIn("KeyError not raised", str(e))
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003059 else:
3060 self.fail("assertRaises() didn't fail")
3061 try:
3062 with self.assertRaises(KeyError):
3063 raise ValueError
3064 except ValueError:
3065 pass
3066 else:
3067 self.fail("assertRaises() didn't let exception pass through")
3068
3069
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003070class TestLongMessage(TestCase):
3071 """Test that the individual asserts honour longMessage.
3072 This actually tests all the message behaviour for
3073 asserts that use longMessage."""
3074
3075 def setUp(self):
3076 class TestableTestFalse(TestCase):
3077 longMessage = False
3078 failureException = self.failureException
3079
3080 def testTest(self):
3081 pass
3082
3083 class TestableTestTrue(TestCase):
3084 longMessage = True
3085 failureException = self.failureException
3086
3087 def testTest(self):
3088 pass
3089
3090 self.testableTrue = TestableTestTrue('testTest')
3091 self.testableFalse = TestableTestFalse('testTest')
3092
3093 def testDefault(self):
3094 self.assertFalse(TestCase.longMessage)
3095
3096 def test_formatMsg(self):
3097 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3098 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3099
3100 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3101 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3102
3103 def assertMessages(self, methodName, args, errors):
3104 def getMethod(i):
3105 useTestableFalse = i < 2
3106 if useTestableFalse:
3107 test = self.testableFalse
3108 else:
3109 test = self.testableTrue
3110 return getattr(test, methodName)
3111
3112 for i, expected_regexp in enumerate(errors):
3113 testMethod = getMethod(i)
3114 kwargs = {}
3115 withMsg = i % 2
3116 if withMsg:
3117 kwargs = {"msg": "oops"}
3118
3119 with self.assertRaisesRegexp(self.failureException,
3120 expected_regexp=expected_regexp):
3121 testMethod(*args, **kwargs)
3122
3123 def testAssertTrue(self):
3124 self.assertMessages('assertTrue', (False,),
3125 ["^False is not True$", "^oops$", "^False is not True$",
3126 "^False is not True : oops$"])
3127
3128 def testAssertFalse(self):
3129 self.assertMessages('assertFalse', (True,),
3130 ["^True is not False$", "^oops$", "^True is not False$",
3131 "^True is not False : oops$"])
3132
3133 def testNotEqual(self):
3134 self.assertMessages('assertNotEqual', (1, 1),
3135 ["^1 == 1$", "^oops$", "^1 == 1$",
3136 "^1 == 1 : oops$"])
3137
3138 def testAlmostEqual(self):
3139 self.assertMessages('assertAlmostEqual', (1, 2),
3140 ["^1 != 2 within 7 places$", "^oops$",
3141 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3142
3143 def testNotAlmostEqual(self):
3144 self.assertMessages('assertNotAlmostEqual', (1, 1),
3145 ["^1 == 1 within 7 places$", "^oops$",
3146 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3147
3148 def test_baseAssertEqual(self):
3149 self.assertMessages('_baseAssertEqual', (1, 2),
3150 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3151
3152 def testAssertSequenceEqual(self):
3153 # Error messages are multiline so not testing on full message
3154 # assertTupleEqual and assertListEqual delegate to this method
3155 self.assertMessages('assertSequenceEqual', ([], [None]),
3156 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3157 r"\+ \[None\] : oops$"])
3158
3159 def testAssertSetEqual(self):
3160 self.assertMessages('assertSetEqual', (set(), set([None])),
3161 ["None$", "^oops$", "None$",
3162 "None : oops$"])
3163
3164 def testAssertIn(self):
3165 self.assertMessages('assertIn', (None, []),
3166 ['^None not found in \[\]$', "^oops$",
3167 '^None not found in \[\]$',
3168 '^None not found in \[\] : oops$'])
3169
3170 def testAssertNotIn(self):
3171 self.assertMessages('assertNotIn', (None, [None]),
3172 ['^None unexpectedly found in \[None\]$', "^oops$",
3173 '^None unexpectedly found in \[None\]$',
3174 '^None unexpectedly found in \[None\] : oops$'])
3175
3176 def testAssertDictEqual(self):
3177 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3178 [r"\+ \{'key': 'value'\}$", "^oops$",
3179 "\+ \{'key': 'value'\}$",
3180 "\+ \{'key': 'value'\} : oops$"])
3181
3182 def testAssertDictContainsSubset(self):
3183 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3184 ["^Missing: 'key'$", "^oops$",
3185 "^Missing: 'key'$",
3186 "^Missing: 'key' : oops$"])
3187
3188 def testAssertSameElements(self):
3189 self.assertMessages('assertSameElements', ([], [None]),
3190 [r"\[None\]$", "^oops$",
3191 r"\[None\]$",
3192 r"\[None\] : oops$"])
3193
3194 def testAssertMultiLineEqual(self):
3195 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3196 [r"\+ foo$", "^oops$",
3197 r"\+ foo$",
3198 r"\+ foo : oops$"])
3199
3200 def testAssertLess(self):
3201 self.assertMessages('assertLess', (2, 1),
3202 ["^2 not less than 1$", "^oops$",
3203 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3204
3205 def testAssertLessEqual(self):
3206 self.assertMessages('assertLessEqual', (2, 1),
3207 ["^2 not less than or equal to 1$", "^oops$",
3208 "^2 not less than or equal to 1$",
3209 "^2 not less than or equal to 1 : oops$"])
3210
3211 def testAssertGreater(self):
3212 self.assertMessages('assertGreater', (1, 2),
3213 ["^1 not greater than 2$", "^oops$",
3214 "^1 not greater than 2$",
3215 "^1 not greater than 2 : oops$"])
3216
3217 def testAssertGreaterEqual(self):
3218 self.assertMessages('assertGreaterEqual', (1, 2),
3219 ["^1 not greater than or equal to 2$", "^oops$",
3220 "^1 not greater than or equal to 2$",
3221 "^1 not greater than or equal to 2 : oops$"])
3222
3223 def testAssertIsNone(self):
3224 self.assertMessages('assertIsNone', ('not None',),
3225 ["^'not None' is not None$", "^oops$",
3226 "^'not None' is not None$",
3227 "^'not None' is not None : oops$"])
3228
3229 def testAssertIsNotNone(self):
3230 self.assertMessages('assertIsNotNone', (None,),
3231 ["^unexpectedly None$", "^oops$",
3232 "^unexpectedly None$",
3233 "^unexpectedly None : oops$"])
3234
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00003235 def testAssertIs(self):
3236 self.assertMessages('assertIs', (None, 'foo'),
3237 ["^None is not 'foo'$", "^oops$",
3238 "^None is not 'foo'$",
3239 "^None is not 'foo' : oops$"])
3240
3241 def testAssertIsNot(self):
3242 self.assertMessages('assertIsNot', (None, None),
3243 ["^unexpectedly identical: None$", "^oops$",
3244 "^unexpectedly identical: None$",
3245 "^unexpectedly identical: None : oops$"])
3246
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003247
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003248class TestCleanUp(TestCase):
3249
3250 def testCleanUp(self):
3251 class TestableTest(TestCase):
3252 def testNothing(self):
3253 pass
3254
3255 test = TestableTest('testNothing')
3256 self.assertEqual(test._cleanups, [])
3257
3258 cleanups = []
3259
3260 def cleanup1(*args, **kwargs):
3261 cleanups.append((1, args, kwargs))
3262
3263 def cleanup2(*args, **kwargs):
3264 cleanups.append((2, args, kwargs))
3265
3266 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3267 test.addCleanup(cleanup2)
3268
3269 self.assertEqual(test._cleanups,
3270 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3271 (cleanup2, (), {})])
3272
3273 result = test.doCleanups()
3274 self.assertTrue(result)
3275
3276 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3277
3278 def testCleanUpWithErrors(self):
3279 class TestableTest(TestCase):
3280 def testNothing(self):
3281 pass
3282
3283 class MockResult(object):
3284 errors = []
3285 def addError(self, test, exc_info):
3286 self.errors.append((test, exc_info))
3287
3288 result = MockResult()
3289 test = TestableTest('testNothing')
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00003290 test._resultForDoCleanups = result
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003291
3292 exc1 = Exception('foo')
3293 exc2 = Exception('bar')
3294 def cleanup1():
3295 raise exc1
3296
3297 def cleanup2():
3298 raise exc2
3299
3300 test.addCleanup(cleanup1)
3301 test.addCleanup(cleanup2)
3302
3303 self.assertFalse(test.doCleanups())
3304
3305 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3306 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3307 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3308
3309 def testCleanupInRun(self):
3310 blowUp = False
3311 ordering = []
3312
3313 class TestableTest(TestCase):
3314 def setUp(self):
3315 ordering.append('setUp')
3316 if blowUp:
3317 raise Exception('foo')
3318
3319 def testNothing(self):
3320 ordering.append('test')
3321
3322 def tearDown(self):
3323 ordering.append('tearDown')
3324
3325 test = TestableTest('testNothing')
3326
3327 def cleanup1():
3328 ordering.append('cleanup1')
3329 def cleanup2():
3330 ordering.append('cleanup2')
3331 test.addCleanup(cleanup1)
3332 test.addCleanup(cleanup2)
3333
3334 def success(some_test):
3335 self.assertEqual(some_test, test)
3336 ordering.append('success')
3337
3338 result = unittest.TestResult()
3339 result.addSuccess = success
3340
3341 test.run(result)
3342 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3343 'cleanup2', 'cleanup1', 'success'])
3344
3345 blowUp = True
3346 ordering = []
3347 test = TestableTest('testNothing')
3348 test.addCleanup(cleanup1)
3349 test.run(result)
3350 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3351
3352
3353class Test_TestProgram(TestCase):
3354
3355 # Horrible white box test
3356 def testNoExit(self):
3357 result = object()
3358 test = object()
3359
3360 class FakeRunner(object):
3361 def run(self, test):
3362 self.test = test
3363 return result
3364
3365 runner = FakeRunner()
3366
Benjamin Petersond2397752009-06-27 23:45:02 +00003367 oldParseArgs = TestProgram.parseArgs
3368 def restoreParseArgs():
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003369 TestProgram.parseArgs = oldParseArgs
Benjamin Petersond2397752009-06-27 23:45:02 +00003370 TestProgram.parseArgs = lambda *args: None
3371 self.addCleanup(restoreParseArgs)
3372
3373 def removeTest():
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003374 del TestProgram.test
Benjamin Petersond2397752009-06-27 23:45:02 +00003375 TestProgram.test = test
3376 self.addCleanup(removeTest)
3377
3378 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3379
3380 self.assertEqual(program.result, result)
3381 self.assertEqual(runner.test, test)
3382 self.assertEqual(program.verbosity, 2)
3383
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003384 class FooBar(unittest.TestCase):
3385 def testPass(self):
3386 assert True
3387 def testFail(self):
3388 assert False
3389
3390 class FooBarLoader(unittest.TestLoader):
3391 """Test loader that returns a suite containing FooBar."""
3392 def loadTestsFromModule(self, module):
3393 return self.suiteClass(
3394 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3395
3396
3397 def test_NonExit(self):
3398 program = unittest.main(exit=False,
3399 argv=["foobar"],
3400 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3401 testLoader=self.FooBarLoader())
3402 self.assertTrue(hasattr(program, 'result'))
3403
3404
3405 def test_Exit(self):
3406 self.assertRaises(
3407 SystemExit,
3408 unittest.main,
3409 argv=["foobar"],
3410 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3411 exit=True,
3412 testLoader=self.FooBarLoader())
3413
3414
3415 def test_ExitAsDefault(self):
3416 self.assertRaises(
3417 SystemExit,
3418 unittest.main,
3419 argv=["foobar"],
3420 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3421 testLoader=self.FooBarLoader())
3422
3423
3424class Test_TextTestRunner(TestCase):
3425 """Tests for TextTestRunner."""
3426
3427 def test_works_with_result_without_startTestRun_stopTestRun(self):
3428 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3429 separator2 = ''
3430 def printErrors(self):
3431 pass
3432
3433 class Runner(unittest.TextTestRunner):
3434 def __init__(self):
3435 super(Runner, self).__init__(io.StringIO())
3436
3437 def _makeResult(self):
3438 return OldTextResult()
3439
3440 runner = Runner()
3441 runner.run(unittest.TestSuite())
3442
3443 def test_startTestRun_stopTestRun_called(self):
3444 class LoggingTextResult(LoggingResult):
3445 separator2 = ''
3446 def printErrors(self):
3447 pass
3448
3449 class LoggingRunner(unittest.TextTestRunner):
3450 def __init__(self, events):
3451 super(LoggingRunner, self).__init__(io.StringIO())
3452 self._events = events
3453
3454 def _makeResult(self):
3455 return LoggingTextResult(self._events)
3456
3457 events = []
3458 runner = LoggingRunner(events)
3459 runner.run(unittest.TestSuite())
3460 expected = ['startTestRun', 'stopTestRun']
3461 self.assertEqual(events, expected)
3462
Antoine Pitrouc63ecee2009-11-10 21:34:48 +00003463 def test_pickle_unpickle(self):
3464 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3465 # required by test_multiprocessing under Windows (in verbose mode).
3466 stream = io.StringIO("foo")
3467 runner = unittest.TextTestRunner(stream)
3468 for protocol in range(2, pickle.HIGHEST_PROTOCOL + 1):
3469 s = pickle.dumps(runner, protocol)
3470 obj = pickle.loads(s)
3471 # StringIO objects never compare equal, a cheap test instead.
3472 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3473
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003474
Benjamin Petersond2397752009-06-27 23:45:02 +00003475class TestDiscovery(TestCase):
3476
3477 # Heavily mocked tests so I can avoid hitting the filesystem
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003478 def test_get_name_from_path(self):
Benjamin Petersond2397752009-06-27 23:45:02 +00003479 loader = unittest.TestLoader()
Benjamin Petersond2397752009-06-27 23:45:02 +00003480 loader._top_level_dir = '/foo'
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003481 name = loader._get_name_from_path('/foo/bar/baz.py')
3482 self.assertEqual(name, 'bar.baz')
Benjamin Petersond2397752009-06-27 23:45:02 +00003483
3484 if not __debug__:
3485 # asserts are off
3486 return
3487
3488 with self.assertRaises(AssertionError):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003489 loader._get_name_from_path('/bar/baz.py')
Benjamin Petersond2397752009-06-27 23:45:02 +00003490
3491 def test_find_tests(self):
3492 loader = unittest.TestLoader()
3493
3494 original_listdir = os.listdir
3495 def restore_listdir():
3496 os.listdir = original_listdir
3497 original_isfile = os.path.isfile
3498 def restore_isfile():
3499 os.path.isfile = original_isfile
3500 original_isdir = os.path.isdir
3501 def restore_isdir():
3502 os.path.isdir = original_isdir
3503
3504 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003505 'test.foo', 'test-not-a-module.py', 'another_dir'],
Benjamin Petersond2397752009-06-27 23:45:02 +00003506 ['test3.py', 'test4.py', ]]
3507 os.listdir = lambda path: path_lists.pop(0)
3508 self.addCleanup(restore_listdir)
3509
3510 def isdir(path):
3511 return path.endswith('dir')
3512 os.path.isdir = isdir
3513 self.addCleanup(restore_isdir)
3514
3515 def isfile(path):
3516 # another_dir is not a package and so shouldn't be recursed into
3517 return not path.endswith('dir') and not 'another_dir' in path
3518 os.path.isfile = isfile
3519 self.addCleanup(restore_isfile)
3520
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003521 loader._get_module_from_name = lambda path: path + ' module'
Benjamin Petersond2397752009-06-27 23:45:02 +00003522 loader.loadTestsFromModule = lambda module: module + ' tests'
3523
3524 loader._top_level_dir = '/foo'
3525 suite = list(loader._find_tests('/foo', 'test*.py'))
3526
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003527 expected = [name + ' module tests' for name in
3528 ('test1', 'test2')]
3529 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3530 ('test3', 'test4')])
Benjamin Petersond2397752009-06-27 23:45:02 +00003531 self.assertEqual(suite, expected)
3532
3533 def test_find_tests_with_package(self):
3534 loader = unittest.TestLoader()
3535
3536 original_listdir = os.listdir
3537 def restore_listdir():
3538 os.listdir = original_listdir
3539 original_isfile = os.path.isfile
3540 def restore_isfile():
3541 os.path.isfile = original_isfile
3542 original_isdir = os.path.isdir
3543 def restore_isdir():
3544 os.path.isdir = original_isdir
3545
3546 directories = ['a_directory', 'test_directory', 'test_directory2']
3547 path_lists = [directories, [], [], []]
3548 os.listdir = lambda path: path_lists.pop(0)
3549 self.addCleanup(restore_listdir)
3550
3551 os.path.isdir = lambda path: True
3552 self.addCleanup(restore_isdir)
3553
3554 os.path.isfile = lambda path: os.path.basename(path) not in directories
3555 self.addCleanup(restore_isfile)
3556
3557 class Module(object):
3558 paths = []
3559 load_tests_args = []
3560
3561 def __init__(self, path):
3562 self.path = path
3563 self.paths.append(path)
3564 if os.path.basename(path) == 'test_directory':
3565 def load_tests(loader, tests, pattern):
3566 self.load_tests_args.append((loader, tests, pattern))
3567 return 'load_tests'
3568 self.load_tests = load_tests
3569
3570 def __eq__(self, other):
3571 return self.path == other.path
3572
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003573 loader._get_module_from_name = lambda name: Module(name)
Benjamin Petersond2397752009-06-27 23:45:02 +00003574 def loadTestsFromModule(module, use_load_tests):
3575 if use_load_tests:
3576 raise self.failureException('use_load_tests should be False for packages')
3577 return module.path + ' module tests'
3578 loader.loadTestsFromModule = loadTestsFromModule
3579
3580 loader._top_level_dir = '/foo'
3581 # this time no '.py' on the pattern so that it can match
3582 # a test package
3583 suite = list(loader._find_tests('/foo', 'test*'))
3584
3585 # We should have loaded tests from the test_directory package by calling load_tests
3586 # and directly from the test_directory2 package
3587 self.assertEqual(suite,
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003588 ['load_tests', 'test_directory2' + ' module tests'])
3589 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Benjamin Petersond2397752009-06-27 23:45:02 +00003590
3591 # load_tests should have been called once with loader, tests and pattern
3592 self.assertEqual(Module.load_tests_args,
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003593 [(loader, 'test_directory' + ' module tests', 'test*')])
Benjamin Petersond2397752009-06-27 23:45:02 +00003594
3595 def test_discover(self):
3596 loader = unittest.TestLoader()
3597
3598 original_isfile = os.path.isfile
3599 def restore_isfile():
3600 os.path.isfile = original_isfile
3601
3602 os.path.isfile = lambda path: False
3603 self.addCleanup(restore_isfile)
3604
Nick Coghlan6ead5522009-10-18 13:19:33 +00003605 orig_sys_path = sys.path[:]
3606 def restore_path():
3607 sys.path[:] = orig_sys_path
3608 self.addCleanup(restore_path)
Benjamin Petersond2397752009-06-27 23:45:02 +00003609
Nick Coghlan6ead5522009-10-18 13:19:33 +00003610 full_path = os.path.abspath(os.path.normpath('/foo'))
Benjamin Petersond2397752009-06-27 23:45:02 +00003611 with self.assertRaises(ImportError):
3612 loader.discover('/foo/bar', top_level_dir='/foo')
3613
3614 self.assertEqual(loader._top_level_dir, full_path)
3615 self.assertIn(full_path, sys.path)
3616
3617 os.path.isfile = lambda path: True
3618 _find_tests_args = []
3619 def _find_tests(start_dir, pattern):
3620 _find_tests_args.append((start_dir, pattern))
3621 return ['tests']
3622 loader._find_tests = _find_tests
3623 loader.suiteClass = str
3624
3625 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3626
3627 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3628 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3629 self.assertEqual(suite, "['tests']")
3630 self.assertEqual(loader._top_level_dir, top_level_dir)
3631 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlan6ead5522009-10-18 13:19:33 +00003632 self.assertIn(top_level_dir, sys.path)
Benjamin Petersond2397752009-06-27 23:45:02 +00003633
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003634 def test_discover_with_modules_that_fail_to_import(self):
3635 loader = unittest.TestLoader()
3636
3637 listdir = os.listdir
3638 os.listdir = lambda _: ['test_this_does_not_exist.py']
3639 isfile = os.path.isfile
3640 os.path.isfile = lambda _: True
Nick Coghlan6ead5522009-10-18 13:19:33 +00003641 orig_sys_path = sys.path[:]
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003642 def restore():
3643 os.path.isfile = isfile
3644 os.listdir = listdir
Nick Coghlan6ead5522009-10-18 13:19:33 +00003645 sys.path[:] = orig_sys_path
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003646 self.addCleanup(restore)
3647
3648 suite = loader.discover('.')
Nick Coghlan6ead5522009-10-18 13:19:33 +00003649 self.assertIn(os.getcwd(), sys.path)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003650 self.assertEqual(suite.countTestCases(), 1)
3651 test = list(list(suite)[0])[0] # extract test from suite
3652
3653 with self.assertRaises(ImportError):
3654 test.test_this_does_not_exist()
3655
Benjamin Petersond2397752009-06-27 23:45:02 +00003656 def test_command_line_handling_parseArgs(self):
3657 # Haha - take that uninstantiable class
3658 program = object.__new__(TestProgram)
3659
3660 args = []
3661 def do_discovery(argv):
3662 args.extend(argv)
3663 program._do_discovery = do_discovery
3664 program.parseArgs(['something', 'discover'])
3665 self.assertEqual(args, [])
3666
3667 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3668 self.assertEqual(args, ['foo', 'bar'])
3669
3670 def test_command_line_handling_do_discovery_too_many_arguments(self):
3671 class Stop(Exception):
3672 pass
3673 def usageExit():
3674 raise Stop
3675
3676 program = object.__new__(TestProgram)
3677 program.usageExit = usageExit
3678
3679 with self.assertRaises(Stop):
3680 # too many args
3681 program._do_discovery(['one', 'two', 'three', 'four'])
3682
3683
3684 def test_command_line_handling_do_discovery_calls_loader(self):
3685 program = object.__new__(TestProgram)
3686
3687 class Loader(object):
3688 args = []
3689 def discover(self, start_dir, pattern, top_level_dir):
3690 self.args.append((start_dir, pattern, top_level_dir))
3691 return 'tests'
3692
3693 program._do_discovery(['-v'], Loader=Loader)
3694 self.assertEqual(program.verbosity, 2)
3695 self.assertEqual(program.test, 'tests')
3696 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3697
3698 Loader.args = []
3699 program = object.__new__(TestProgram)
3700 program._do_discovery(['--verbose'], Loader=Loader)
3701 self.assertEqual(program.test, 'tests')
3702 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3703
3704 Loader.args = []
3705 program = object.__new__(TestProgram)
3706 program._do_discovery([], Loader=Loader)
3707 self.assertEqual(program.test, 'tests')
3708 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3709
3710 Loader.args = []
3711 program = object.__new__(TestProgram)
3712 program._do_discovery(['fish'], Loader=Loader)
3713 self.assertEqual(program.test, 'tests')
3714 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3715
3716 Loader.args = []
3717 program = object.__new__(TestProgram)
3718 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3719 self.assertEqual(program.test, 'tests')
3720 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3721
3722 Loader.args = []
3723 program = object.__new__(TestProgram)
3724 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3725 self.assertEqual(program.test, 'tests')
3726 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3727
3728 Loader.args = []
3729 program = object.__new__(TestProgram)
3730 program._do_discovery(['-s', 'fish'], Loader=Loader)
3731 self.assertEqual(program.test, 'tests')
3732 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3733
3734 Loader.args = []
3735 program = object.__new__(TestProgram)
3736 program._do_discovery(['-t', 'fish'], Loader=Loader)
3737 self.assertEqual(program.test, 'tests')
3738 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3739
3740 Loader.args = []
3741 program = object.__new__(TestProgram)
3742 program._do_discovery(['-p', 'fish'], Loader=Loader)
3743 self.assertEqual(program.test, 'tests')
3744 self.assertEqual(Loader.args, [('.', 'fish', None)])
3745
3746 Loader.args = []
3747 program = object.__new__(TestProgram)
3748 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3749 self.assertEqual(program.test, 'tests')
3750 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3751 self.assertEqual(program.verbosity, 2)
3752
3753
Jim Fultonfafd8742004-08-28 15:22:12 +00003754######################################################################
3755## Main
3756######################################################################
3757
3758def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003759 support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003760 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003761 Test_TestSkipping, Test_Assertions, TestLongMessage,
Antoine Pitrouc63ecee2009-11-10 21:34:48 +00003762 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner)
Jim Fultonfafd8742004-08-28 15:22:12 +00003763
Guido van Rossumd8faa362007-04-27 19:54:29 +00003764if __name__ == "__main__":
Jim Fultonfafd8742004-08-28 15:22:12 +00003765 test_main()