blob: 0727931fdea3dceef29d01f29e2d50cc664c007f [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
Guido van Rossumd8faa362007-04-27 19:54:29 +0000629 if module_name in sys.modules:
630 del sys.modules[module_name]
631
632 loader = unittest.TestLoader()
633 try:
634 suite = loader.loadTestsFromName(module_name)
635
Ezio Melottie9615932010-01-24 19:26:24 +0000636 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000637 self.assertEqual(list(suite), [])
638
639 # audioop should now be loaded, thanks to loadTestsFromName()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000640 self.assertIn(module_name, sys.modules)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000641 finally:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000642 if module_name in sys.modules:
643 del sys.modules[module_name]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000644
645 ################################################################
646 ### Tests for TestLoader.loadTestsFromName()
647
648 ### Tests for TestLoader.loadTestsFromNames()
649 ################################################################
650
651 # "Similar to loadTestsFromName(), but takes a sequence of names rather
652 # than a single name."
653 #
654 # What happens if that sequence of names is empty?
655 def test_loadTestsFromNames__empty_name_list(self):
656 loader = unittest.TestLoader()
657
658 suite = loader.loadTestsFromNames([])
Ezio Melottie9615932010-01-24 19:26:24 +0000659 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000660 self.assertEqual(list(suite), [])
661
662 # "Similar to loadTestsFromName(), but takes a sequence of names rather
663 # than a single name."
664 # ...
665 # "The method optionally resolves name relative to the given module"
666 #
667 # What happens if that sequence of names is empty?
668 #
669 # XXX Should this raise a ValueError or just return an empty TestSuite?
670 def test_loadTestsFromNames__relative_empty_name_list(self):
671 loader = unittest.TestLoader()
672
673 suite = loader.loadTestsFromNames([], unittest)
Ezio Melottie9615932010-01-24 19:26:24 +0000674 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000675 self.assertEqual(list(suite), [])
676
677 # "The specifier name is a ``dotted name'' that may resolve either to
678 # a module, a test case class, a TestSuite instance, a test method
679 # within a test case class, or a callable object which returns a
680 # TestCase or TestSuite instance."
681 #
682 # Is ValueError raised in response to an empty name?
683 def test_loadTestsFromNames__empty_name(self):
684 loader = unittest.TestLoader()
685
686 try:
687 loader.loadTestsFromNames([''])
688 except ValueError as e:
689 self.assertEqual(str(e), "Empty module name")
690 else:
691 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
692
693 # "The specifier name is a ``dotted name'' that may resolve either to
694 # a module, a test case class, a TestSuite instance, a test method
695 # within a test case class, or a callable object which returns a
696 # TestCase or TestSuite instance."
697 #
698 # What happens when presented with an impossible module name?
699 def test_loadTestsFromNames__malformed_name(self):
700 loader = unittest.TestLoader()
701
702 # XXX Should this raise ValueError or ImportError?
703 try:
704 loader.loadTestsFromNames(['abc () //'])
705 except ValueError:
706 pass
707 except ImportError:
708 pass
709 else:
710 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
711
712 # "The specifier name is a ``dotted name'' that may resolve either to
713 # a module, a test case class, a TestSuite instance, a test method
714 # within a test case class, or a callable object which returns a
715 # TestCase or TestSuite instance."
716 #
717 # What happens when no module can be found for the given name?
718 def test_loadTestsFromNames__unknown_module_name(self):
719 loader = unittest.TestLoader()
720
721 try:
722 loader.loadTestsFromNames(['sdasfasfasdf'])
723 except ImportError as e:
724 self.assertEqual(str(e), "No module named sdasfasfasdf")
725 else:
726 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
727
728 # "The specifier name is a ``dotted name'' that may resolve either to
729 # a module, a test case class, a TestSuite instance, a test method
730 # within a test case class, or a callable object which returns a
731 # TestCase or TestSuite instance."
732 #
733 # What happens when the module can be found, but not the attribute?
734 def test_loadTestsFromNames__unknown_attr_name(self):
735 loader = unittest.TestLoader()
736
737 try:
738 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
739 except AttributeError as e:
740 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
741 else:
742 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
743
744 # "The specifier name is a ``dotted name'' that may resolve either to
745 # a module, a test case class, a TestSuite instance, a test method
746 # within a test case class, or a callable object which returns a
747 # TestCase or TestSuite instance."
748 # ...
749 # "The method optionally resolves name relative to the given module"
750 #
751 # What happens when given an unknown attribute on a specified `module`
752 # argument?
753 def test_loadTestsFromNames__unknown_name_relative_1(self):
754 loader = unittest.TestLoader()
755
756 try:
757 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
758 except AttributeError as e:
759 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
760 else:
761 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
762
763 # "The specifier name is a ``dotted name'' that may resolve either to
764 # a module, a test case class, a TestSuite instance, a test method
765 # within a test case class, or a callable object which returns a
766 # TestCase or TestSuite instance."
767 # ...
768 # "The method optionally resolves name relative to the given module"
769 #
770 # Do unknown attributes (relative to a provided module) still raise an
771 # exception even in the presence of valid attribute names?
772 def test_loadTestsFromNames__unknown_name_relative_2(self):
773 loader = unittest.TestLoader()
774
775 try:
776 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
777 except AttributeError as e:
778 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
779 else:
780 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
781
782 # "The specifier name is a ``dotted name'' that may resolve either to
783 # a module, a test case class, a TestSuite instance, a test method
784 # within a test case class, or a callable object which returns a
785 # TestCase or TestSuite instance."
786 # ...
787 # "The method optionally resolves name relative to the given module"
788 #
789 # What happens when faced with the empty string?
790 #
791 # XXX This currently raises AttributeError, though ValueError is probably
792 # more appropriate
793 def test_loadTestsFromNames__relative_empty_name(self):
794 loader = unittest.TestLoader()
795
796 try:
797 loader.loadTestsFromNames([''], unittest)
798 except AttributeError:
799 pass
800 else:
801 self.fail("Failed to raise ValueError")
802
803 # "The specifier name is a ``dotted name'' that may resolve either to
804 # a module, a test case class, a TestSuite instance, a test method
805 # within a test case class, or a callable object which returns a
806 # TestCase or TestSuite instance."
807 # ...
808 # "The method optionally resolves name relative to the given module"
809 #
810 # What happens when presented with an impossible attribute name?
811 def test_loadTestsFromNames__relative_malformed_name(self):
812 loader = unittest.TestLoader()
813
814 # XXX Should this raise AttributeError or ValueError?
815 try:
816 loader.loadTestsFromNames(['abc () //'], unittest)
817 except AttributeError:
818 pass
819 except ValueError:
820 pass
821 else:
822 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
823
824 # "The method optionally resolves name relative to the given module"
825 #
826 # Does loadTestsFromNames() make sure the provided `module` is in fact
827 # a module?
828 #
829 # XXX This validation is currently not done. This flexibility should
830 # either be documented or a TypeError should be raised.
831 def test_loadTestsFromNames__relative_not_a_module(self):
832 class MyTestCase(unittest.TestCase):
833 def test(self):
834 pass
835
836 class NotAModule(object):
837 test_2 = MyTestCase
838
839 loader = unittest.TestLoader()
840 suite = loader.loadTestsFromNames(['test_2'], NotAModule)
841
842 reference = [unittest.TestSuite([MyTestCase('test')])]
843 self.assertEqual(list(suite), reference)
844
845 # "The specifier name is a ``dotted name'' that may resolve either to
846 # a module, a test case class, a TestSuite instance, a test method
847 # within a test case class, or a callable object which returns a
848 # TestCase or TestSuite instance."
849 #
850 # Does it raise an exception if the name resolves to an invalid
851 # object?
852 def test_loadTestsFromNames__relative_bad_object(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000853 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000854 m.testcase_1 = object()
855
856 loader = unittest.TestLoader()
857 try:
858 loader.loadTestsFromNames(['testcase_1'], m)
859 except TypeError:
860 pass
861 else:
862 self.fail("Should have raised TypeError")
863
864 # "The specifier name is a ``dotted name'' that may resolve ... to
865 # ... a test case class"
866 def test_loadTestsFromNames__relative_TestCase_subclass(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000867 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000868 class MyTestCase(unittest.TestCase):
869 def test(self):
870 pass
871 m.testcase_1 = MyTestCase
872
873 loader = unittest.TestLoader()
874 suite = loader.loadTestsFromNames(['testcase_1'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000875 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000876
877 expected = loader.suiteClass([MyTestCase('test')])
878 self.assertEqual(list(suite), [expected])
879
880 # "The specifier name is a ``dotted name'' that may resolve ... to
881 # ... a TestSuite instance"
882 def test_loadTestsFromNames__relative_TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000883 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000884 class MyTestCase(unittest.TestCase):
885 def test(self):
886 pass
887 m.testsuite = unittest.TestSuite([MyTestCase('test')])
888
889 loader = unittest.TestLoader()
890 suite = loader.loadTestsFromNames(['testsuite'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000891 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000892
893 self.assertEqual(list(suite), [m.testsuite])
894
895 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
896 # test method within a test case class"
897 def test_loadTestsFromNames__relative_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000898 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000899 class MyTestCase(unittest.TestCase):
900 def test(self):
901 pass
902 m.testcase_1 = MyTestCase
903
904 loader = unittest.TestLoader()
905 suite = loader.loadTestsFromNames(['testcase_1.test'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000906 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000907
908 ref_suite = unittest.TestSuite([MyTestCase('test')])
909 self.assertEqual(list(suite), [ref_suite])
910
911 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
912 # test method within a test case class"
913 #
914 # Does the method gracefully handle names that initially look like they
915 # resolve to "a test method within a test case class" but don't?
916 def test_loadTestsFromNames__relative_invalid_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000917 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000918 class MyTestCase(unittest.TestCase):
919 def test(self):
920 pass
921 m.testcase_1 = MyTestCase
922
923 loader = unittest.TestLoader()
924 try:
925 loader.loadTestsFromNames(['testcase_1.testfoo'], m)
926 except AttributeError as e:
927 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
928 else:
929 self.fail("Failed to raise AttributeError")
930
931 # "The specifier name is a ``dotted name'' that may resolve ... to
932 # ... a callable object which returns a ... TestSuite instance"
933 def test_loadTestsFromNames__callable__TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000934 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000935 testcase_1 = unittest.FunctionTestCase(lambda: None)
936 testcase_2 = unittest.FunctionTestCase(lambda: None)
937 def return_TestSuite():
938 return unittest.TestSuite([testcase_1, testcase_2])
939 m.return_TestSuite = return_TestSuite
940
941 loader = unittest.TestLoader()
942 suite = loader.loadTestsFromNames(['return_TestSuite'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000943 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000944
945 expected = unittest.TestSuite([testcase_1, testcase_2])
946 self.assertEqual(list(suite), [expected])
947
948 # "The specifier name is a ``dotted name'' that may resolve ... to
949 # ... a callable object which returns a TestCase ... instance"
950 def test_loadTestsFromNames__callable__TestCase_instance(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000951 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000952 testcase_1 = unittest.FunctionTestCase(lambda: None)
953 def return_TestCase():
954 return testcase_1
955 m.return_TestCase = return_TestCase
956
957 loader = unittest.TestLoader()
958 suite = loader.loadTestsFromNames(['return_TestCase'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000959 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000960
961 ref_suite = unittest.TestSuite([testcase_1])
962 self.assertEqual(list(suite), [ref_suite])
963
964 # "The specifier name is a ``dotted name'' that may resolve ... to
965 # ... a callable object which returns a TestCase or TestSuite instance"
966 #
967 # Are staticmethods handled correctly?
968 def test_loadTestsFromNames__callable__call_staticmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000969 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000970 class Test1(unittest.TestCase):
971 def test(self):
972 pass
973
974 testcase_1 = Test1('test')
975 class Foo(unittest.TestCase):
976 @staticmethod
977 def foo():
978 return testcase_1
979 m.Foo = Foo
980
981 loader = unittest.TestLoader()
982 suite = loader.loadTestsFromNames(['Foo.foo'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000983 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000984
985 ref_suite = unittest.TestSuite([testcase_1])
986 self.assertEqual(list(suite), [ref_suite])
987
988 # "The specifier name is a ``dotted name'' that may resolve ... to
989 # ... a callable object which returns a TestCase or TestSuite instance"
990 #
991 # What happens when the callable returns something else?
992 def test_loadTestsFromNames__callable__wrong_type(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000993 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000994 def return_wrong():
995 return 6
996 m.return_wrong = return_wrong
997
998 loader = unittest.TestLoader()
999 try:
1000 suite = loader.loadTestsFromNames(['return_wrong'], m)
1001 except TypeError:
1002 pass
1003 else:
1004 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
1005
1006 # "The specifier can refer to modules and packages which have not been
1007 # imported; they will be imported as a side-effect"
1008 def test_loadTestsFromNames__module_not_loaded(self):
1009 # We're going to try to load this module as a side-effect, so it
1010 # better not be loaded before we try.
1011 #
1012 # Why pick audioop? Google shows it isn't used very often, so there's
1013 # a good chance that it won't be imported when this test is run
1014 module_name = 'audioop'
1015
Guido van Rossumd8faa362007-04-27 19:54:29 +00001016 if module_name in sys.modules:
1017 del sys.modules[module_name]
1018
1019 loader = unittest.TestLoader()
1020 try:
1021 suite = loader.loadTestsFromNames([module_name])
1022
Ezio Melottie9615932010-01-24 19:26:24 +00001023 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001024 self.assertEqual(list(suite), [unittest.TestSuite()])
1025
1026 # audioop should now be loaded, thanks to loadTestsFromName()
Benjamin Peterson577473f2010-01-19 00:09:57 +00001027 self.assertIn(module_name, sys.modules)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001028 finally:
Guido van Rossum360e4b82007-05-14 22:51:27 +00001029 if module_name in sys.modules:
1030 del sys.modules[module_name]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001031
1032 ################################################################
1033 ### /Tests for TestLoader.loadTestsFromNames()
1034
1035 ### Tests for TestLoader.getTestCaseNames()
1036 ################################################################
1037
1038 # "Return a sorted sequence of method names found within testCaseClass"
1039 #
1040 # Test.foobar is defined to make sure getTestCaseNames() respects
1041 # loader.testMethodPrefix
1042 def test_getTestCaseNames(self):
1043 class Test(unittest.TestCase):
1044 def test_1(self): pass
1045 def test_2(self): pass
1046 def foobar(self): pass
1047
1048 loader = unittest.TestLoader()
1049
1050 self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])
1051
1052 # "Return a sorted sequence of method names found within testCaseClass"
1053 #
1054 # Does getTestCaseNames() behave appropriately if no tests are found?
1055 def test_getTestCaseNames__no_tests(self):
1056 class Test(unittest.TestCase):
1057 def foobar(self): pass
1058
1059 loader = unittest.TestLoader()
1060
1061 self.assertEqual(loader.getTestCaseNames(Test), [])
1062
1063 # "Return a sorted sequence of method names found within testCaseClass"
1064 #
1065 # Are not-TestCases handled gracefully?
1066 #
1067 # XXX This should raise a TypeError, not return a list
1068 #
1069 # XXX It's too late in the 2.5 release cycle to fix this, but it should
1070 # probably be revisited for 2.6
1071 def test_getTestCaseNames__not_a_TestCase(self):
1072 class BadCase(int):
1073 def test_foo(self):
1074 pass
1075
1076 loader = unittest.TestLoader()
1077 names = loader.getTestCaseNames(BadCase)
1078
1079 self.assertEqual(names, ['test_foo'])
1080
1081 # "Return a sorted sequence of method names found within testCaseClass"
1082 #
1083 # Make sure inherited names are handled.
1084 #
1085 # TestP.foobar is defined to make sure getTestCaseNames() respects
1086 # loader.testMethodPrefix
1087 def test_getTestCaseNames__inheritance(self):
1088 class TestP(unittest.TestCase):
1089 def test_1(self): pass
1090 def test_2(self): pass
1091 def foobar(self): pass
1092
1093 class TestC(TestP):
1094 def test_1(self): pass
1095 def test_3(self): pass
1096
1097 loader = unittest.TestLoader()
1098
1099 names = ['test_1', 'test_2', 'test_3']
1100 self.assertEqual(loader.getTestCaseNames(TestC), names)
1101
1102 ################################################################
1103 ### /Tests for TestLoader.getTestCaseNames()
1104
1105 ### Tests for TestLoader.testMethodPrefix
1106 ################################################################
1107
1108 # "String giving the prefix of method names which will be interpreted as
1109 # test methods"
1110 #
1111 # Implicit in the documentation is that testMethodPrefix is respected by
1112 # all loadTestsFrom* methods.
1113 def test_testMethodPrefix__loadTestsFromTestCase(self):
1114 class Foo(unittest.TestCase):
1115 def test_1(self): pass
1116 def test_2(self): pass
1117 def foo_bar(self): pass
1118
1119 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1120 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1121
1122 loader = unittest.TestLoader()
1123 loader.testMethodPrefix = 'foo'
1124 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
1125
1126 loader.testMethodPrefix = 'test'
1127 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
1128
1129 # "String giving the prefix of method names which will be interpreted as
1130 # test methods"
1131 #
1132 # Implicit in the documentation is that testMethodPrefix is respected by
1133 # all loadTestsFrom* methods.
1134 def test_testMethodPrefix__loadTestsFromModule(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001135 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001136 class Foo(unittest.TestCase):
1137 def test_1(self): pass
1138 def test_2(self): pass
1139 def foo_bar(self): pass
1140 m.Foo = Foo
1141
1142 tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
1143 tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]
1144
1145 loader = unittest.TestLoader()
1146 loader.testMethodPrefix = 'foo'
1147 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
1148
1149 loader.testMethodPrefix = 'test'
1150 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
1151
1152 # "String giving the prefix of method names which will be interpreted as
1153 # test methods"
1154 #
1155 # Implicit in the documentation is that testMethodPrefix is respected by
1156 # all loadTestsFrom* methods.
1157 def test_testMethodPrefix__loadTestsFromName(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001158 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001159 class Foo(unittest.TestCase):
1160 def test_1(self): pass
1161 def test_2(self): pass
1162 def foo_bar(self): pass
1163 m.Foo = Foo
1164
1165 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1166 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1167
1168 loader = unittest.TestLoader()
1169 loader.testMethodPrefix = 'foo'
1170 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
1171
1172 loader.testMethodPrefix = 'test'
1173 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
1174
1175 # "String giving the prefix of method names which will be interpreted as
1176 # test methods"
1177 #
1178 # Implicit in the documentation is that testMethodPrefix is respected by
1179 # all loadTestsFrom* methods.
1180 def test_testMethodPrefix__loadTestsFromNames(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001181 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001182 class Foo(unittest.TestCase):
1183 def test_1(self): pass
1184 def test_2(self): pass
1185 def foo_bar(self): pass
1186 m.Foo = Foo
1187
1188 tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
1189 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1190 tests_2 = unittest.TestSuite([tests_2])
1191
1192 loader = unittest.TestLoader()
1193 loader.testMethodPrefix = 'foo'
1194 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)
1195
1196 loader.testMethodPrefix = 'test'
1197 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)
1198
1199 # "The default value is 'test'"
1200 def test_testMethodPrefix__default_value(self):
1201 loader = unittest.TestLoader()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001202 self.assertEqual(loader.testMethodPrefix, 'test')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001203
1204 ################################################################
1205 ### /Tests for TestLoader.testMethodPrefix
1206
1207 ### Tests for TestLoader.sortTestMethodsUsing
1208 ################################################################
1209
1210 # "Function to be used to compare method names when sorting them in
1211 # getTestCaseNames() and all the loadTestsFromX() methods"
1212 def test_sortTestMethodsUsing__loadTestsFromTestCase(self):
1213 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001214 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001215
1216 class Foo(unittest.TestCase):
1217 def test_1(self): pass
1218 def test_2(self): pass
1219
1220 loader = unittest.TestLoader()
1221 loader.sortTestMethodsUsing = reversed_cmp
1222
1223 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1224 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
1225
1226 # "Function to be used to compare method names when sorting them in
1227 # getTestCaseNames() and all the loadTestsFromX() methods"
1228 def test_sortTestMethodsUsing__loadTestsFromModule(self):
1229 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001230 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001231
Christian Heimes45f9af32007-11-27 21:50:00 +00001232 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001233 class Foo(unittest.TestCase):
1234 def test_1(self): pass
1235 def test_2(self): pass
1236 m.Foo = Foo
1237
1238 loader = unittest.TestLoader()
1239 loader.sortTestMethodsUsing = reversed_cmp
1240
1241 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1242 self.assertEqual(list(loader.loadTestsFromModule(m)), tests)
1243
1244 # "Function to be used to compare method names when sorting them in
1245 # getTestCaseNames() and all the loadTestsFromX() methods"
1246 def test_sortTestMethodsUsing__loadTestsFromName(self):
1247 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001248 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001249
Christian Heimes45f9af32007-11-27 21:50:00 +00001250 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001251 class Foo(unittest.TestCase):
1252 def test_1(self): pass
1253 def test_2(self): pass
1254 m.Foo = Foo
1255
1256 loader = unittest.TestLoader()
1257 loader.sortTestMethodsUsing = reversed_cmp
1258
1259 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1260 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
1261
1262 # "Function to be used to compare method names when sorting them in
1263 # getTestCaseNames() and all the loadTestsFromX() methods"
1264 def test_sortTestMethodsUsing__loadTestsFromNames(self):
1265 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001266 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001267
Christian Heimes45f9af32007-11-27 21:50:00 +00001268 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001269 class Foo(unittest.TestCase):
1270 def test_1(self): pass
1271 def test_2(self): pass
1272 m.Foo = Foo
1273
1274 loader = unittest.TestLoader()
1275 loader.sortTestMethodsUsing = reversed_cmp
1276
1277 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1278 self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)
1279
1280 # "Function to be used to compare method names when sorting them in
1281 # getTestCaseNames()"
1282 #
1283 # Does it actually affect getTestCaseNames()?
1284 def test_sortTestMethodsUsing__getTestCaseNames(self):
1285 def reversed_cmp(x, y):
Mark Dickinsona56c4672009-01-27 18:17:45 +00001286 return -((x > y) - (x < y))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001287
1288 class Foo(unittest.TestCase):
1289 def test_1(self): pass
1290 def test_2(self): pass
1291
1292 loader = unittest.TestLoader()
1293 loader.sortTestMethodsUsing = reversed_cmp
1294
1295 test_names = ['test_2', 'test_1']
1296 self.assertEqual(loader.getTestCaseNames(Foo), test_names)
1297
1298 # "The default value is the built-in cmp() function"
Mark Dickinsona56c4672009-01-27 18:17:45 +00001299 # Since cmp is now defunct, we simply verify that the results
1300 # occur in the same order as they would with the default sort.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001301 def test_sortTestMethodsUsing__default_value(self):
1302 loader = unittest.TestLoader()
Mark Dickinsona56c4672009-01-27 18:17:45 +00001303
1304 class Foo(unittest.TestCase):
1305 def test_2(self): pass
1306 def test_3(self): pass
1307 def test_1(self): pass
1308
1309 test_names = ['test_2', 'test_3', 'test_1']
1310 self.assertEqual(loader.getTestCaseNames(Foo), sorted(test_names))
1311
Guido van Rossumd8faa362007-04-27 19:54:29 +00001312
1313 # "it can be set to None to disable the sort."
1314 #
1315 # XXX How is this different from reassigning cmp? Are the tests returned
1316 # in a random order or something? This behaviour should die
1317 def test_sortTestMethodsUsing__None(self):
1318 class Foo(unittest.TestCase):
1319 def test_1(self): pass
1320 def test_2(self): pass
1321
1322 loader = unittest.TestLoader()
1323 loader.sortTestMethodsUsing = None
1324
1325 test_names = ['test_2', 'test_1']
1326 self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))
1327
1328 ################################################################
1329 ### /Tests for TestLoader.sortTestMethodsUsing
1330
1331 ### Tests for TestLoader.suiteClass
1332 ################################################################
1333
1334 # "Callable object that constructs a test suite from a list of tests."
1335 def test_suiteClass__loadTestsFromTestCase(self):
1336 class Foo(unittest.TestCase):
1337 def test_1(self): pass
1338 def test_2(self): pass
1339 def foo_bar(self): pass
1340
1341 tests = [Foo('test_1'), Foo('test_2')]
1342
1343 loader = unittest.TestLoader()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001344 loader.suiteClass = list
Guido van Rossumd8faa362007-04-27 19:54:29 +00001345 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
1346
1347 # It is implicit in the documentation for TestLoader.suiteClass that
1348 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
1349 def test_suiteClass__loadTestsFromModule(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001350 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001351 class Foo(unittest.TestCase):
1352 def test_1(self): pass
1353 def test_2(self): pass
1354 def foo_bar(self): pass
1355 m.Foo = Foo
1356
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001357 tests = [[Foo('test_1'), Foo('test_2')]]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001358
1359 loader = unittest.TestLoader()
1360 loader.suiteClass = list
1361 self.assertEqual(loader.loadTestsFromModule(m), tests)
1362
1363 # It is implicit in the documentation for TestLoader.suiteClass that
1364 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
1365 def test_suiteClass__loadTestsFromName(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001366 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001367 class Foo(unittest.TestCase):
1368 def test_1(self): pass
1369 def test_2(self): pass
1370 def foo_bar(self): pass
1371 m.Foo = Foo
1372
1373 tests = [Foo('test_1'), Foo('test_2')]
1374
1375 loader = unittest.TestLoader()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001376 loader.suiteClass = list
Guido van Rossumd8faa362007-04-27 19:54:29 +00001377 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
1378
1379 # It is implicit in the documentation for TestLoader.suiteClass that
1380 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
1381 def test_suiteClass__loadTestsFromNames(self):
Christian Heimes45f9af32007-11-27 21:50:00 +00001382 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001383 class Foo(unittest.TestCase):
1384 def test_1(self): pass
1385 def test_2(self): pass
1386 def foo_bar(self): pass
1387 m.Foo = Foo
1388
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001389 tests = [[Foo('test_1'), Foo('test_2')]]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001390
1391 loader = unittest.TestLoader()
1392 loader.suiteClass = list
1393 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)
1394
1395 # "The default value is the TestSuite class"
1396 def test_suiteClass__default_value(self):
1397 loader = unittest.TestLoader()
Benjamin Petersone1759f82009-06-30 23:35:19 +00001398 self.assertTrue(loader.suiteClass is unittest.TestSuite)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001399
1400 ################################################################
1401 ### /Tests for TestLoader.suiteClass
1402
1403### Support code for Test_TestSuite
1404################################################################
1405
1406class Foo(unittest.TestCase):
1407 def test_1(self): pass
1408 def test_2(self): pass
1409 def test_3(self): pass
1410 def runTest(self): pass
1411
1412def _mk_TestSuite(*names):
1413 return unittest.TestSuite(Foo(n) for n in names)
1414
1415################################################################
1416### /Support code for Test_TestSuite
1417
1418class Test_TestSuite(TestCase, TestEquality):
1419
1420 ### Set up attributes needed by inherited tests
1421 ################################################################
1422
1423 # Used by TestEquality.test_eq
1424 eq_pairs = [(unittest.TestSuite(), unittest.TestSuite())
1425 ,(unittest.TestSuite(), unittest.TestSuite([]))
1426 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]
1427
1428 # Used by TestEquality.test_ne
1429 ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1'))
1430 ,(unittest.TestSuite([]), _mk_TestSuite('test_1'))
1431 ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3'))
1432 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]
1433
1434 ################################################################
1435 ### /Set up attributes needed by inherited tests
1436
1437 ### Tests for TestSuite.__init__
1438 ################################################################
1439
1440 # "class TestSuite([tests])"
1441 #
1442 # The tests iterable should be optional
1443 def test_init__tests_optional(self):
1444 suite = unittest.TestSuite()
1445
1446 self.assertEqual(suite.countTestCases(), 0)
1447
1448 # "class TestSuite([tests])"
1449 # ...
1450 # "If tests is given, it must be an iterable of individual test cases
1451 # or other test suites that will be used to build the suite initially"
1452 #
1453 # TestSuite should deal with empty tests iterables by allowing the
1454 # creation of an empty suite
1455 def test_init__empty_tests(self):
1456 suite = unittest.TestSuite([])
1457
1458 self.assertEqual(suite.countTestCases(), 0)
1459
1460 # "class TestSuite([tests])"
1461 # ...
1462 # "If tests is given, it must be an iterable of individual test cases
1463 # or other test suites that will be used to build the suite initially"
1464 #
1465 # TestSuite should allow any iterable to provide tests
1466 def test_init__tests_from_any_iterable(self):
1467 def tests():
1468 yield unittest.FunctionTestCase(lambda: None)
1469 yield unittest.FunctionTestCase(lambda: None)
1470
1471 suite_1 = unittest.TestSuite(tests())
1472 self.assertEqual(suite_1.countTestCases(), 2)
1473
1474 suite_2 = unittest.TestSuite(suite_1)
1475 self.assertEqual(suite_2.countTestCases(), 2)
1476
1477 suite_3 = unittest.TestSuite(set(suite_1))
1478 self.assertEqual(suite_3.countTestCases(), 2)
1479
1480 # "class TestSuite([tests])"
1481 # ...
1482 # "If tests is given, it must be an iterable of individual test cases
1483 # or other test suites that will be used to build the suite initially"
1484 #
1485 # Does TestSuite() also allow other TestSuite() instances to be present
1486 # in the tests iterable?
1487 def test_init__TestSuite_instances_in_tests(self):
1488 def tests():
1489 ftc = unittest.FunctionTestCase(lambda: None)
1490 yield unittest.TestSuite([ftc])
1491 yield unittest.FunctionTestCase(lambda: None)
1492
1493 suite = unittest.TestSuite(tests())
1494 self.assertEqual(suite.countTestCases(), 2)
1495
1496 ################################################################
1497 ### /Tests for TestSuite.__init__
1498
1499 # Container types should support the iter protocol
1500 def test_iter(self):
1501 test1 = unittest.FunctionTestCase(lambda: None)
1502 test2 = unittest.FunctionTestCase(lambda: None)
1503 suite = unittest.TestSuite((test1, test2))
1504
1505 self.assertEqual(list(suite), [test1, test2])
1506
1507 # "Return the number of tests represented by the this test object.
1508 # ...this method is also implemented by the TestSuite class, which can
1509 # return larger [greater than 1] values"
1510 #
1511 # Presumably an empty TestSuite returns 0?
1512 def test_countTestCases_zero_simple(self):
1513 suite = unittest.TestSuite()
1514
1515 self.assertEqual(suite.countTestCases(), 0)
1516
1517 # "Return the number of tests represented by the this test object.
1518 # ...this method is also implemented by the TestSuite class, which can
1519 # return larger [greater than 1] values"
1520 #
1521 # Presumably an empty TestSuite (even if it contains other empty
1522 # TestSuite instances) returns 0?
1523 def test_countTestCases_zero_nested(self):
1524 class Test1(unittest.TestCase):
1525 def test(self):
1526 pass
1527
1528 suite = unittest.TestSuite([unittest.TestSuite()])
1529
1530 self.assertEqual(suite.countTestCases(), 0)
1531
1532 # "Return the number of tests represented by the this test object.
1533 # ...this method is also implemented by the TestSuite class, which can
1534 # return larger [greater than 1] values"
1535 def test_countTestCases_simple(self):
1536 test1 = unittest.FunctionTestCase(lambda: None)
1537 test2 = unittest.FunctionTestCase(lambda: None)
1538 suite = unittest.TestSuite((test1, test2))
1539
1540 self.assertEqual(suite.countTestCases(), 2)
1541
1542 # "Return the number of tests represented by the this test object.
1543 # ...this method is also implemented by the TestSuite class, which can
1544 # return larger [greater than 1] values"
1545 #
1546 # Make sure this holds for nested TestSuite instances, too
1547 def test_countTestCases_nested(self):
1548 class Test1(unittest.TestCase):
1549 def test1(self): pass
1550 def test2(self): pass
1551
1552 test2 = unittest.FunctionTestCase(lambda: None)
1553 test3 = unittest.FunctionTestCase(lambda: None)
1554 child = unittest.TestSuite((Test1('test2'), test2))
1555 parent = unittest.TestSuite((test3, child, Test1('test1')))
1556
1557 self.assertEqual(parent.countTestCases(), 4)
1558
1559 # "Run the tests associated with this suite, collecting the result into
1560 # the test result object passed as result."
1561 #
1562 # And if there are no tests? What then?
1563 def test_run__empty_suite(self):
1564 events = []
1565 result = LoggingResult(events)
1566
1567 suite = unittest.TestSuite()
1568
1569 suite.run(result)
1570
1571 self.assertEqual(events, [])
1572
1573 # "Note that unlike TestCase.run(), TestSuite.run() requires the
1574 # "result object to be passed in."
1575 def test_run__requires_result(self):
1576 suite = unittest.TestSuite()
1577
1578 try:
1579 suite.run()
1580 except TypeError:
1581 pass
1582 else:
1583 self.fail("Failed to raise TypeError")
1584
1585 # "Run the tests associated with this suite, collecting the result into
1586 # the test result object passed as result."
1587 def test_run(self):
1588 events = []
1589 result = LoggingResult(events)
1590
1591 class LoggingCase(unittest.TestCase):
1592 def run(self, result):
1593 events.append('run %s' % self._testMethodName)
1594
1595 def test1(self): pass
1596 def test2(self): pass
1597
1598 tests = [LoggingCase('test1'), LoggingCase('test2')]
1599
1600 unittest.TestSuite(tests).run(result)
1601
1602 self.assertEqual(events, ['run test1', 'run test2'])
1603
1604 # "Add a TestCase ... to the suite"
1605 def test_addTest__TestCase(self):
1606 class Foo(unittest.TestCase):
1607 def test(self): pass
1608
1609 test = Foo('test')
1610 suite = unittest.TestSuite()
1611
1612 suite.addTest(test)
1613
1614 self.assertEqual(suite.countTestCases(), 1)
1615 self.assertEqual(list(suite), [test])
1616
1617 # "Add a ... TestSuite to the suite"
1618 def test_addTest__TestSuite(self):
1619 class Foo(unittest.TestCase):
1620 def test(self): pass
1621
1622 suite_2 = unittest.TestSuite([Foo('test')])
1623
1624 suite = unittest.TestSuite()
1625 suite.addTest(suite_2)
1626
1627 self.assertEqual(suite.countTestCases(), 1)
1628 self.assertEqual(list(suite), [suite_2])
1629
1630 # "Add all the tests from an iterable of TestCase and TestSuite
1631 # instances to this test suite."
1632 #
1633 # "This is equivalent to iterating over tests, calling addTest() for
1634 # each element"
1635 def test_addTests(self):
1636 class Foo(unittest.TestCase):
1637 def test_1(self): pass
1638 def test_2(self): pass
1639
1640 test_1 = Foo('test_1')
1641 test_2 = Foo('test_2')
1642 inner_suite = unittest.TestSuite([test_2])
1643
1644 def gen():
1645 yield test_1
1646 yield test_2
1647 yield inner_suite
1648
1649 suite_1 = unittest.TestSuite()
1650 suite_1.addTests(gen())
1651
1652 self.assertEqual(list(suite_1), list(gen()))
1653
1654 # "This is equivalent to iterating over tests, calling addTest() for
1655 # each element"
1656 suite_2 = unittest.TestSuite()
1657 for t in gen():
1658 suite_2.addTest(t)
1659
1660 self.assertEqual(suite_1, suite_2)
1661
1662 # "Add all the tests from an iterable of TestCase and TestSuite
1663 # instances to this test suite."
1664 #
1665 # What happens if it doesn't get an iterable?
1666 def test_addTest__noniterable(self):
1667 suite = unittest.TestSuite()
1668
1669 try:
1670 suite.addTests(5)
1671 except TypeError:
1672 pass
1673 else:
1674 self.fail("Failed to raise TypeError")
1675
1676 def test_addTest__noncallable(self):
1677 suite = unittest.TestSuite()
1678 self.assertRaises(TypeError, suite.addTest, 5)
1679
1680 def test_addTest__casesuiteclass(self):
1681 suite = unittest.TestSuite()
1682 self.assertRaises(TypeError, suite.addTest, Test_TestSuite)
1683 self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)
1684
1685 def test_addTests__string(self):
1686 suite = unittest.TestSuite()
1687 self.assertRaises(TypeError, suite.addTests, "foo")
1688
1689
1690class Test_FunctionTestCase(TestCase):
1691
1692 # "Return the number of tests represented by the this test object. For
1693 # TestCase instances, this will always be 1"
1694 def test_countTestCases(self):
1695 test = unittest.FunctionTestCase(lambda: None)
1696
1697 self.assertEqual(test.countTestCases(), 1)
1698
1699 # "When a setUp() method is defined, the test runner will run that method
1700 # prior to each test. Likewise, if a tearDown() method is defined, the
1701 # test runner will invoke that method after each test. In the example,
1702 # setUp() was used to create a fresh sequence for each test."
1703 #
1704 # Make sure the proper call order is maintained, even if setUp() raises
1705 # an exception.
1706 def test_run_call_order__error_in_setUp(self):
1707 events = []
1708 result = LoggingResult(events)
1709
1710 def setUp():
1711 events.append('setUp')
1712 raise RuntimeError('raised by setUp')
1713
1714 def test():
1715 events.append('test')
1716
1717 def tearDown():
1718 events.append('tearDown')
1719
1720 expected = ['startTest', 'setUp', 'addError', 'stopTest']
1721 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1722 self.assertEqual(events, expected)
1723
1724 # "When a setUp() method is defined, the test runner will run that method
1725 # prior to each test. Likewise, if a tearDown() method is defined, the
1726 # test runner will invoke that method after each test. In the example,
1727 # setUp() was used to create a fresh sequence for each test."
1728 #
1729 # Make sure the proper call order is maintained, even if the test raises
1730 # an error (as opposed to a failure).
1731 def test_run_call_order__error_in_test(self):
1732 events = []
1733 result = LoggingResult(events)
1734
1735 def setUp():
1736 events.append('setUp')
1737
1738 def test():
1739 events.append('test')
1740 raise RuntimeError('raised by test')
1741
1742 def tearDown():
1743 events.append('tearDown')
1744
1745 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
1746 'stopTest']
1747 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1748 self.assertEqual(events, expected)
1749
1750 # "When a setUp() method is defined, the test runner will run that method
1751 # prior to each test. Likewise, if a tearDown() method is defined, the
1752 # test runner will invoke that method after each test. In the example,
1753 # setUp() was used to create a fresh sequence for each test."
1754 #
1755 # Make sure the proper call order is maintained, even if the test signals
1756 # a failure (as opposed to an error).
1757 def test_run_call_order__failure_in_test(self):
1758 events = []
1759 result = LoggingResult(events)
1760
1761 def setUp():
1762 events.append('setUp')
1763
1764 def test():
1765 events.append('test')
1766 self.fail('raised by test')
1767
1768 def tearDown():
1769 events.append('tearDown')
1770
1771 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
1772 'stopTest']
1773 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1774 self.assertEqual(events, expected)
1775
1776 # "When a setUp() method is defined, the test runner will run that method
1777 # prior to each test. Likewise, if a tearDown() method is defined, the
1778 # test runner will invoke that method after each test. In the example,
1779 # setUp() was used to create a fresh sequence for each test."
1780 #
1781 # Make sure the proper call order is maintained, even if tearDown() raises
1782 # an exception.
1783 def test_run_call_order__error_in_tearDown(self):
1784 events = []
1785 result = LoggingResult(events)
1786
1787 def setUp():
1788 events.append('setUp')
1789
1790 def test():
1791 events.append('test')
1792
1793 def tearDown():
1794 events.append('tearDown')
1795 raise RuntimeError('raised by tearDown')
1796
1797 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
1798 'stopTest']
1799 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1800 self.assertEqual(events, expected)
1801
1802 # "Return a string identifying the specific test case."
1803 #
1804 # Because of the vague nature of the docs, I'm not going to lock this
1805 # test down too much. Really all that can be asserted is that the id()
1806 # will be a string (either 8-byte or unicode -- again, because the docs
1807 # just say "string")
1808 def test_id(self):
1809 test = unittest.FunctionTestCase(lambda: None)
1810
Ezio Melottie9615932010-01-24 19:26:24 +00001811 self.assertIsInstance(test.id(), str)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001812
1813 # "Returns a one-line description of the test, or None if no description
1814 # has been provided. The default implementation of this method returns
1815 # the first line of the test method's docstring, if available, or None."
1816 def test_shortDescription__no_docstring(self):
1817 test = unittest.FunctionTestCase(lambda: None)
1818
1819 self.assertEqual(test.shortDescription(), None)
1820
1821 # "Returns a one-line description of the test, or None if no description
1822 # has been provided. The default implementation of this method returns
1823 # the first line of the test method's docstring, if available, or None."
1824 def test_shortDescription__singleline_docstring(self):
1825 desc = "this tests foo"
1826 test = unittest.FunctionTestCase(lambda: None, description=desc)
1827
1828 self.assertEqual(test.shortDescription(), "this tests foo")
1829
1830class Test_TestResult(TestCase):
1831 # Note: there are not separate tests for TestResult.wasSuccessful(),
1832 # TestResult.errors, TestResult.failures, TestResult.testsRun or
1833 # TestResult.shouldStop because these only have meaning in terms of
1834 # other TestResult methods.
1835 #
1836 # Accordingly, tests for the aforenamed attributes are incorporated
1837 # in with the tests for the defining methods.
1838 ################################################################
1839
1840 def test_init(self):
1841 result = unittest.TestResult()
1842
Benjamin Petersone1759f82009-06-30 23:35:19 +00001843 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001844 self.assertEqual(len(result.errors), 0)
1845 self.assertEqual(len(result.failures), 0)
1846 self.assertEqual(result.testsRun, 0)
1847 self.assertEqual(result.shouldStop, False)
1848
1849 # "This method can be called to signal that the set of tests being
1850 # run should be aborted by setting the TestResult's shouldStop
1851 # attribute to True."
1852 def test_stop(self):
1853 result = unittest.TestResult()
1854
1855 result.stop()
1856
1857 self.assertEqual(result.shouldStop, True)
1858
1859 # "Called when the test case test is about to be run. The default
1860 # implementation simply increments the instance's testsRun counter."
1861 def test_startTest(self):
1862 class Foo(unittest.TestCase):
1863 def test_1(self):
1864 pass
1865
1866 test = Foo('test_1')
1867
1868 result = unittest.TestResult()
1869
1870 result.startTest(test)
1871
Benjamin Petersone1759f82009-06-30 23:35:19 +00001872 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001873 self.assertEqual(len(result.errors), 0)
1874 self.assertEqual(len(result.failures), 0)
1875 self.assertEqual(result.testsRun, 1)
1876 self.assertEqual(result.shouldStop, False)
1877
1878 result.stopTest(test)
1879
1880 # "Called after the test case test has been executed, regardless of
1881 # the outcome. The default implementation does nothing."
1882 def test_stopTest(self):
1883 class Foo(unittest.TestCase):
1884 def test_1(self):
1885 pass
1886
1887 test = Foo('test_1')
1888
1889 result = unittest.TestResult()
1890
1891 result.startTest(test)
1892
Benjamin Petersone1759f82009-06-30 23:35:19 +00001893 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001894 self.assertEqual(len(result.errors), 0)
1895 self.assertEqual(len(result.failures), 0)
1896 self.assertEqual(result.testsRun, 1)
1897 self.assertEqual(result.shouldStop, False)
1898
1899 result.stopTest(test)
1900
1901 # Same tests as above; make sure nothing has changed
Benjamin Petersone1759f82009-06-30 23:35:19 +00001902 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001903 self.assertEqual(len(result.errors), 0)
1904 self.assertEqual(len(result.failures), 0)
1905 self.assertEqual(result.testsRun, 1)
1906 self.assertEqual(result.shouldStop, False)
1907
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001908 # "Called before and after tests are run. The default implementation does nothing."
1909 def test_startTestRun_stopTestRun(self):
1910 result = unittest.TestResult()
1911 result.startTestRun()
1912 result.stopTestRun()
1913
Guido van Rossumd8faa362007-04-27 19:54:29 +00001914 # "addSuccess(test)"
1915 # ...
1916 # "Called when the test case test succeeds"
1917 # ...
1918 # "wasSuccessful() - Returns True if all tests run so far have passed,
1919 # otherwise returns False"
1920 # ...
1921 # "testsRun - The total number of tests run so far."
1922 # ...
1923 # "errors - A list containing 2-tuples of TestCase instances and
1924 # formatted tracebacks. Each tuple represents a test which raised an
1925 # unexpected exception. Contains formatted
1926 # tracebacks instead of sys.exc_info() results."
1927 # ...
1928 # "failures - A list containing 2-tuples of TestCase instances and
1929 # formatted tracebacks. Each tuple represents a test where a failure was
1930 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1931 # methods. Contains formatted tracebacks instead
1932 # of sys.exc_info() results."
1933 def test_addSuccess(self):
1934 class Foo(unittest.TestCase):
1935 def test_1(self):
1936 pass
1937
1938 test = Foo('test_1')
1939
1940 result = unittest.TestResult()
1941
1942 result.startTest(test)
1943 result.addSuccess(test)
1944 result.stopTest(test)
1945
Benjamin Petersone1759f82009-06-30 23:35:19 +00001946 self.assertTrue(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001947 self.assertEqual(len(result.errors), 0)
1948 self.assertEqual(len(result.failures), 0)
1949 self.assertEqual(result.testsRun, 1)
1950 self.assertEqual(result.shouldStop, False)
1951
1952 # "addFailure(test, err)"
1953 # ...
1954 # "Called when the test case test signals a failure. err is a tuple of
1955 # the form returned by sys.exc_info(): (type, value, traceback)"
1956 # ...
1957 # "wasSuccessful() - Returns True if all tests run so far have passed,
1958 # otherwise returns False"
1959 # ...
1960 # "testsRun - The total number of tests run so far."
1961 # ...
1962 # "errors - A list containing 2-tuples of TestCase instances and
1963 # formatted tracebacks. Each tuple represents a test which raised an
1964 # unexpected exception. Contains formatted
1965 # tracebacks instead of sys.exc_info() results."
1966 # ...
1967 # "failures - A list containing 2-tuples of TestCase instances and
1968 # formatted tracebacks. Each tuple represents a test where a failure was
1969 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1970 # methods. Contains formatted tracebacks instead
1971 # of sys.exc_info() results."
1972 def test_addFailure(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001973 class Foo(unittest.TestCase):
1974 def test_1(self):
1975 pass
1976
1977 test = Foo('test_1')
1978 try:
1979 test.fail("foo")
1980 except:
1981 exc_info_tuple = sys.exc_info()
1982
1983 result = unittest.TestResult()
1984
1985 result.startTest(test)
1986 result.addFailure(test, exc_info_tuple)
1987 result.stopTest(test)
1988
Benjamin Petersone1759f82009-06-30 23:35:19 +00001989 self.assertFalse(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001990 self.assertEqual(len(result.errors), 0)
1991 self.assertEqual(len(result.failures), 1)
1992 self.assertEqual(result.testsRun, 1)
1993 self.assertEqual(result.shouldStop, False)
1994
1995 test_case, formatted_exc = result.failures[0]
Benjamin Petersone1759f82009-06-30 23:35:19 +00001996 self.assertTrue(test_case is test)
Ezio Melottie9615932010-01-24 19:26:24 +00001997 self.assertIsInstance(formatted_exc, str)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001998
1999 # "addError(test, err)"
2000 # ...
2001 # "Called when the test case test raises an unexpected exception err
2002 # is a tuple of the form returned by sys.exc_info():
2003 # (type, value, traceback)"
2004 # ...
2005 # "wasSuccessful() - Returns True if all tests run so far have passed,
2006 # otherwise returns False"
2007 # ...
2008 # "testsRun - The total number of tests run so far."
2009 # ...
2010 # "errors - A list containing 2-tuples of TestCase instances and
2011 # formatted tracebacks. Each tuple represents a test which raised an
2012 # unexpected exception. Contains formatted
2013 # tracebacks instead of sys.exc_info() results."
2014 # ...
2015 # "failures - A list containing 2-tuples of TestCase instances and
2016 # formatted tracebacks. Each tuple represents a test where a failure was
2017 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
2018 # methods. Contains formatted tracebacks instead
2019 # of sys.exc_info() results."
2020 def test_addError(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002021 class Foo(unittest.TestCase):
2022 def test_1(self):
2023 pass
2024
2025 test = Foo('test_1')
2026 try:
2027 raise TypeError()
2028 except:
2029 exc_info_tuple = sys.exc_info()
2030
2031 result = unittest.TestResult()
2032
2033 result.startTest(test)
2034 result.addError(test, exc_info_tuple)
2035 result.stopTest(test)
2036
Benjamin Petersone1759f82009-06-30 23:35:19 +00002037 self.assertFalse(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00002038 self.assertEqual(len(result.errors), 1)
2039 self.assertEqual(len(result.failures), 0)
2040 self.assertEqual(result.testsRun, 1)
2041 self.assertEqual(result.shouldStop, False)
2042
2043 test_case, formatted_exc = result.errors[0]
Benjamin Petersone1759f82009-06-30 23:35:19 +00002044 self.assertTrue(test_case is test)
Ezio Melottie9615932010-01-24 19:26:24 +00002045 self.assertIsInstance(formatted_exc, str)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002046
Michael Foord34c94622010-02-10 15:51:42 +00002047 def testGetDescriptionWithoutDocstring(self):
2048 result = unittest.TextTestResult(None, True, None)
2049 self.assertEqual(
2050 result.getDescription(self),
2051 'testGetDescriptionWithoutDocstring (' + __name__ +
2052 '.Test_TestResult)')
2053
2054 def testGetDescriptionWithOneLineDocstring(self):
2055 """Tests getDescription() for a method with a docstring."""
2056 result = unittest.TextTestResult(None, True, None)
2057 self.assertEqual(
2058 result.getDescription(self),
2059 ('testGetDescriptionWithOneLineDocstring '
2060 '(' + __name__ + '.Test_TestResult)\n'
2061 'Tests getDescription() for a method with a docstring.'))
2062
2063 def testGetDescriptionWithMultiLineDocstring(self):
2064 """Tests getDescription() for a method with a longer docstring.
2065 The second line of the docstring.
2066 """
2067 result = unittest.TextTestResult(None, True, None)
2068 self.assertEqual(
2069 result.getDescription(self),
2070 ('testGetDescriptionWithMultiLineDocstring '
2071 '(' + __name__ + '.Test_TestResult)\n'
2072 'Tests getDescription() for a method with a longer '
2073 'docstring.'))
2074
2075
Guido van Rossumd8faa362007-04-27 19:54:29 +00002076### Support code for Test_TestCase
2077################################################################
2078
2079class Foo(unittest.TestCase):
2080 def runTest(self): pass
2081 def test1(self): pass
2082
2083class Bar(Foo):
2084 def test2(self): pass
2085
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002086class LoggingTestCase(unittest.TestCase):
2087 """A test case which logs its calls."""
2088
2089 def __init__(self, events):
2090 super(LoggingTestCase, self).__init__('test')
2091 self.events = events
2092
2093 def setUp(self):
2094 self.events.append('setUp')
2095
2096 def test(self):
2097 self.events.append('test')
2098
2099 def tearDown(self):
2100 self.events.append('tearDown')
2101
2102class ResultWithNoStartTestRunStopTestRun(object):
2103 """An object honouring TestResult before startTestRun/stopTestRun."""
2104
2105 def __init__(self):
2106 self.failures = []
2107 self.errors = []
2108 self.testsRun = 0
2109 self.skipped = []
2110 self.expectedFailures = []
2111 self.unexpectedSuccesses = []
2112 self.shouldStop = False
2113
2114 def startTest(self, test):
2115 pass
2116
2117 def stopTest(self, test):
2118 pass
2119
2120 def addError(self, test):
2121 pass
2122
2123 def addFailure(self, test):
2124 pass
2125
2126 def addSuccess(self, test):
2127 pass
2128
2129 def wasSuccessful(self):
2130 return True
2131
2132
Guido van Rossumd8faa362007-04-27 19:54:29 +00002133################################################################
2134### /Support code for Test_TestCase
2135
2136class Test_TestCase(TestCase, TestEquality, TestHashing):
2137
2138 ### Set up attributes used by inherited tests
2139 ################################################################
2140
2141 # Used by TestHashing.test_hash and TestEquality.test_eq
2142 eq_pairs = [(Foo('test1'), Foo('test1'))]
2143
2144 # Used by TestEquality.test_ne
2145 ne_pairs = [(Foo('test1'), Foo('runTest'))
2146 ,(Foo('test1'), Bar('test1'))
2147 ,(Foo('test1'), Bar('test2'))]
2148
2149 ################################################################
2150 ### /Set up attributes used by inherited tests
2151
2152
2153 # "class TestCase([methodName])"
2154 # ...
2155 # "Each instance of TestCase will run a single test method: the
2156 # method named methodName."
2157 # ...
2158 # "methodName defaults to "runTest"."
2159 #
2160 # Make sure it really is optional, and that it defaults to the proper
2161 # thing.
2162 def test_init__no_test_name(self):
2163 class Test(unittest.TestCase):
2164 def runTest(self): raise MyException()
2165 def test(self): pass
2166
2167 self.assertEqual(Test().id()[-13:], '.Test.runTest')
2168
2169 # "class TestCase([methodName])"
2170 # ...
2171 # "Each instance of TestCase will run a single test method: the
2172 # method named methodName."
2173 def test_init__test_name__valid(self):
2174 class Test(unittest.TestCase):
2175 def runTest(self): raise MyException()
2176 def test(self): pass
2177
2178 self.assertEqual(Test('test').id()[-10:], '.Test.test')
2179
2180 # "class TestCase([methodName])"
2181 # ...
2182 # "Each instance of TestCase will run a single test method: the
2183 # method named methodName."
2184 def test_init__test_name__invalid(self):
2185 class Test(unittest.TestCase):
2186 def runTest(self): raise MyException()
2187 def test(self): pass
2188
2189 try:
2190 Test('testfoo')
2191 except ValueError:
2192 pass
2193 else:
2194 self.fail("Failed to raise ValueError")
2195
2196 # "Return the number of tests represented by the this test object. For
2197 # TestCase instances, this will always be 1"
2198 def test_countTestCases(self):
2199 class Foo(unittest.TestCase):
2200 def test(self): pass
2201
2202 self.assertEqual(Foo('test').countTestCases(), 1)
2203
2204 # "Return the default type of test result object to be used to run this
2205 # test. For TestCase instances, this will always be
2206 # unittest.TestResult; subclasses of TestCase should
2207 # override this as necessary."
2208 def test_defaultTestResult(self):
2209 class Foo(unittest.TestCase):
2210 def runTest(self):
2211 pass
2212
2213 result = Foo().defaultTestResult()
2214 self.assertEqual(type(result), unittest.TestResult)
2215
2216 # "When a setUp() method is defined, the test runner will run that method
2217 # prior to each test. Likewise, if a tearDown() method is defined, the
2218 # test runner will invoke that method after each test. In the example,
2219 # setUp() was used to create a fresh sequence for each test."
2220 #
2221 # Make sure the proper call order is maintained, even if setUp() raises
2222 # an exception.
2223 def test_run_call_order__error_in_setUp(self):
2224 events = []
2225 result = LoggingResult(events)
2226
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002227 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002228 def setUp(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002229 super(Foo, self).setUp()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002230 raise RuntimeError('raised by Foo.setUp')
2231
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002232 Foo(events).run(result)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002233 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2234 self.assertEqual(events, expected)
2235
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002236 # "With a temporary result stopTestRun is called when setUp errors.
2237 def test_run_call_order__error_in_setUp_default_result(self):
2238 events = []
2239
2240 class Foo(LoggingTestCase):
2241 def defaultTestResult(self):
2242 return LoggingResult(self.events)
2243
2244 def setUp(self):
2245 super(Foo, self).setUp()
2246 raise RuntimeError('raised by Foo.setUp')
2247
2248 Foo(events).run()
2249 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2250 'stopTest', 'stopTestRun']
2251 self.assertEqual(events, expected)
2252
Guido van Rossumd8faa362007-04-27 19:54:29 +00002253 # "When a setUp() method is defined, the test runner will run that method
2254 # prior to each test. Likewise, if a tearDown() method is defined, the
2255 # test runner will invoke that method after each test. In the example,
2256 # setUp() was used to create a fresh sequence for each test."
2257 #
2258 # Make sure the proper call order is maintained, even if the test raises
2259 # an error (as opposed to a failure).
2260 def test_run_call_order__error_in_test(self):
2261 events = []
2262 result = LoggingResult(events)
2263
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002264 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002265 def test(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002266 super(Foo, self).test()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002267 raise RuntimeError('raised by Foo.test')
2268
Guido van Rossumd8faa362007-04-27 19:54:29 +00002269 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2270 'stopTest']
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002271 Foo(events).run(result)
2272 self.assertEqual(events, expected)
2273
2274 # "With a default result, an error in the test still results in stopTestRun
2275 # being called."
2276 def test_run_call_order__error_in_test_default_result(self):
2277 events = []
2278
2279 class Foo(LoggingTestCase):
2280 def defaultTestResult(self):
2281 return LoggingResult(self.events)
2282
2283 def test(self):
2284 super(Foo, self).test()
2285 raise RuntimeError('raised by Foo.test')
2286
2287 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2288 'tearDown', 'stopTest', 'stopTestRun']
2289 Foo(events).run()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002290 self.assertEqual(events, expected)
2291
2292 # "When a setUp() method is defined, the test runner will run that method
2293 # prior to each test. Likewise, if a tearDown() method is defined, the
2294 # test runner will invoke that method after each test. In the example,
2295 # setUp() was used to create a fresh sequence for each test."
2296 #
2297 # Make sure the proper call order is maintained, even if the test signals
2298 # a failure (as opposed to an error).
2299 def test_run_call_order__failure_in_test(self):
2300 events = []
2301 result = LoggingResult(events)
2302
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002303 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002304 def test(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002305 super(Foo, self).test()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002306 self.fail('raised by Foo.test')
2307
Guido van Rossumd8faa362007-04-27 19:54:29 +00002308 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2309 'stopTest']
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002310 Foo(events).run(result)
2311 self.assertEqual(events, expected)
2312
2313 # "When a test fails with a default result stopTestRun is still called."
2314 def test_run_call_order__failure_in_test_default_result(self):
2315
2316 class Foo(LoggingTestCase):
2317 def defaultTestResult(self):
2318 return LoggingResult(self.events)
2319 def test(self):
2320 super(Foo, self).test()
2321 self.fail('raised by Foo.test')
2322
2323 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2324 'tearDown', 'stopTest', 'stopTestRun']
2325 events = []
2326 Foo(events).run()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002327 self.assertEqual(events, expected)
2328
2329 # "When a setUp() method is defined, the test runner will run that method
2330 # prior to each test. Likewise, if a tearDown() method is defined, the
2331 # test runner will invoke that method after each test. In the example,
2332 # setUp() was used to create a fresh sequence for each test."
2333 #
2334 # Make sure the proper call order is maintained, even if tearDown() raises
2335 # an exception.
2336 def test_run_call_order__error_in_tearDown(self):
2337 events = []
2338 result = LoggingResult(events)
2339
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002340 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002341 def tearDown(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002342 super(Foo, self).tearDown()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002343 raise RuntimeError('raised by Foo.tearDown')
2344
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002345 Foo(events).run(result)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002346 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2347 'stopTest']
2348 self.assertEqual(events, expected)
2349
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002350 # "When tearDown errors with a default result stopTestRun is still called."
2351 def test_run_call_order__error_in_tearDown_default_result(self):
2352
2353 class Foo(LoggingTestCase):
2354 def defaultTestResult(self):
2355 return LoggingResult(self.events)
2356 def tearDown(self):
2357 super(Foo, self).tearDown()
2358 raise RuntimeError('raised by Foo.tearDown')
2359
2360 events = []
2361 Foo(events).run()
2362 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2363 'addError', 'stopTest', 'stopTestRun']
2364 self.assertEqual(events, expected)
2365
2366 # "TestCase.run() still works when the defaultTestResult is a TestResult
2367 # that does not support startTestRun and stopTestRun.
2368 def test_run_call_order_default_result(self):
2369
2370 class Foo(unittest.TestCase):
2371 def defaultTestResult(self):
2372 return ResultWithNoStartTestRunStopTestRun()
2373 def test(self):
2374 pass
2375
2376 Foo('test').run()
2377
Guido van Rossumd8faa362007-04-27 19:54:29 +00002378 # "This class attribute gives the exception raised by the test() method.
2379 # If a test framework needs to use a specialized exception, possibly to
2380 # carry additional information, it must subclass this exception in
2381 # order to ``play fair'' with the framework. The initial value of this
2382 # attribute is AssertionError"
2383 def test_failureException__default(self):
2384 class Foo(unittest.TestCase):
2385 def test(self):
2386 pass
2387
Benjamin Petersone1759f82009-06-30 23:35:19 +00002388 self.assertTrue(Foo('test').failureException is AssertionError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002389
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__explicit_raise(self):
2397 events = []
2398 result = LoggingResult(events)
2399
2400 class Foo(unittest.TestCase):
2401 def test(self):
2402 raise RuntimeError()
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 # "This class attribute gives the exception raised by the test() method.
2414 # If a test framework needs to use a specialized exception, possibly to
2415 # carry additional information, it must subclass this exception in
2416 # order to ``play fair'' with the framework."
2417 #
2418 # Make sure TestCase.run() respects the designated failureException
2419 def test_failureException__subclassing__implicit_raise(self):
2420 events = []
2421 result = LoggingResult(events)
2422
2423 class Foo(unittest.TestCase):
2424 def test(self):
2425 self.fail("foo")
2426
2427 failureException = RuntimeError
2428
Benjamin Petersone1759f82009-06-30 23:35:19 +00002429 self.assertTrue(Foo('test').failureException is RuntimeError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002430
2431
2432 Foo('test').run(result)
2433 expected = ['startTest', 'addFailure', 'stopTest']
2434 self.assertEqual(events, expected)
2435
2436 # "The default implementation does nothing."
2437 def test_setUp(self):
2438 class Foo(unittest.TestCase):
2439 def runTest(self):
2440 pass
2441
2442 # ... and nothing should happen
2443 Foo().setUp()
2444
2445 # "The default implementation does nothing."
2446 def test_tearDown(self):
2447 class Foo(unittest.TestCase):
2448 def runTest(self):
2449 pass
2450
2451 # ... and nothing should happen
2452 Foo().tearDown()
2453
2454 # "Return a string identifying the specific test case."
2455 #
2456 # Because of the vague nature of the docs, I'm not going to lock this
2457 # test down too much. Really all that can be asserted is that the id()
2458 # will be a string (either 8-byte or unicode -- again, because the docs
2459 # just say "string")
2460 def test_id(self):
2461 class Foo(unittest.TestCase):
2462 def runTest(self):
2463 pass
2464
Ezio Melottie9615932010-01-24 19:26:24 +00002465 self.assertIsInstance(Foo().id(), str)
2466
Guido van Rossumd8faa362007-04-27 19:54:29 +00002467
Guido van Rossumd8faa362007-04-27 19:54:29 +00002468 # "If result is omitted or None, a temporary result object is created
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002469 # and used, but is not made available to the caller. As TestCase owns the
2470 # temporary result startTestRun and stopTestRun are called.
2471
Guido van Rossumd8faa362007-04-27 19:54:29 +00002472 def test_run__uses_defaultTestResult(self):
2473 events = []
2474
2475 class Foo(unittest.TestCase):
2476 def test(self):
2477 events.append('test')
2478
2479 def defaultTestResult(self):
2480 return LoggingResult(events)
2481
2482 # Make run() find a result object on its own
2483 Foo('test').run()
2484
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002485 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2486 'stopTest', 'stopTestRun']
Guido van Rossumd8faa362007-04-27 19:54:29 +00002487 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002488
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002489 def testShortDescriptionWithoutDocstring(self):
Michael Foord34c94622010-02-10 15:51:42 +00002490 self.assertIsNone(self.shortDescription())
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002491
2492 def testShortDescriptionWithOneLineDocstring(self):
2493 """Tests shortDescription() for a method with a docstring."""
2494 self.assertEqual(
2495 self.shortDescription(),
Michael Foord34c94622010-02-10 15:51:42 +00002496 'Tests shortDescription() for a method with a docstring.')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002497
2498 def testShortDescriptionWithMultiLineDocstring(self):
2499 """Tests shortDescription() for a method with a longer docstring.
2500
2501 This method ensures that only the first line of a docstring is
2502 returned used in the short description, no matter how long the
2503 whole thing is.
2504 """
2505 self.assertEqual(
2506 self.shortDescription(),
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002507 'Tests shortDescription() for a method with a longer '
Michael Foord34c94622010-02-10 15:51:42 +00002508 'docstring.')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002509
2510 def testAddTypeEqualityFunc(self):
2511 class SadSnake(object):
2512 """Dummy class for test_addTypeEqualityFunc."""
2513 s1, s2 = SadSnake(), SadSnake()
2514 self.assertFalse(s1 == s2)
2515 def AllSnakesCreatedEqual(a, b, msg=None):
2516 return type(a) == type(b) == SadSnake
2517 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2518 self.assertEqual(s1, s2)
2519 # No this doesn't clean up and remove the SadSnake equality func
2520 # from this TestCase instance but since its a local nothing else
2521 # will ever notice that.
2522
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00002523 def testAssertIs(self):
2524 thing = object()
2525 self.assertIs(thing, thing)
2526 self.assertRaises(self.failureException, self.assertIs, thing, object())
2527
2528 def testAssertIsNot(self):
2529 thing = object()
2530 self.assertIsNot(thing, object())
2531 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2532
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00002533 def testAssertIsInstance(self):
2534 thing = []
2535 self.assertIsInstance(thing, list)
2536 self.assertRaises(self.failureException, self.assertIsInstance,
2537 thing, dict)
2538
2539 def testAssertNotIsInstance(self):
2540 thing = []
2541 self.assertNotIsInstance(thing, dict)
2542 self.assertRaises(self.failureException, self.assertNotIsInstance,
2543 thing, list)
2544
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002545 def testAssertIn(self):
2546 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2547
2548 self.assertIn('a', 'abc')
2549 self.assertIn(2, [1, 2, 3])
2550 self.assertIn('monkey', animals)
2551
2552 self.assertNotIn('d', 'abc')
2553 self.assertNotIn(0, [1, 2, 3])
2554 self.assertNotIn('otter', animals)
2555
2556 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2557 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2558 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2559 animals)
2560
2561 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2562 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2563 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2564 animals)
2565
2566 def testAssertDictContainsSubset(self):
2567 self.assertDictContainsSubset({}, {})
2568 self.assertDictContainsSubset({}, {'a': 1})
2569 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2570 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2571 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2572
2573 self.assertRaises(unittest.TestCase.failureException,
2574 self.assertDictContainsSubset, {'a': 2}, {'a': 1},
2575 '.*Mismatched values:.*')
2576
2577 self.assertRaises(unittest.TestCase.failureException,
2578 self.assertDictContainsSubset, {'c': 1}, {'a': 1},
2579 '.*Missing:.*')
2580
2581 self.assertRaises(unittest.TestCase.failureException,
2582 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2583 {'a': 1}, '.*Missing:.*')
2584
2585 self.assertRaises(unittest.TestCase.failureException,
2586 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2587 {'a': 1}, '.*Missing:.*Mismatched values:.*')
2588
2589 def testAssertEqual(self):
2590 equal_pairs = [
2591 ((), ()),
2592 ({}, {}),
2593 ([], []),
2594 (set(), set()),
2595 (frozenset(), frozenset())]
2596 for a, b in equal_pairs:
2597 # This mess of try excepts is to test the assertEqual behavior
2598 # itself.
2599 try:
2600 self.assertEqual(a, b)
2601 except self.failureException:
2602 self.fail('assertEqual(%r, %r) failed' % (a, b))
2603 try:
2604 self.assertEqual(a, b, msg='foo')
2605 except self.failureException:
2606 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2607 try:
2608 self.assertEqual(a, b, 'foo')
2609 except self.failureException:
2610 self.fail('assertEqual(%r, %r) with third parameter failed' %
2611 (a, b))
2612
2613 unequal_pairs = [
2614 ((), []),
2615 ({}, set()),
2616 (set([4,1]), frozenset([4,2])),
2617 (frozenset([4,5]), set([2,3])),
2618 (set([3,4]), set([5,4]))]
2619 for a, b in unequal_pairs:
2620 self.assertRaises(self.failureException, self.assertEqual, a, b)
2621 self.assertRaises(self.failureException, self.assertEqual, a, b,
2622 'foo')
2623 self.assertRaises(self.failureException, self.assertEqual, a, b,
2624 msg='foo')
2625
2626 def testEquality(self):
2627 self.assertListEqual([], [])
2628 self.assertTupleEqual((), ())
2629 self.assertSequenceEqual([], ())
2630
2631 a = [0, 'a', []]
2632 b = []
2633 self.assertRaises(unittest.TestCase.failureException,
2634 self.assertListEqual, a, b)
2635 self.assertRaises(unittest.TestCase.failureException,
2636 self.assertListEqual, tuple(a), tuple(b))
2637 self.assertRaises(unittest.TestCase.failureException,
2638 self.assertSequenceEqual, a, tuple(b))
2639
2640 b.extend(a)
2641 self.assertListEqual(a, b)
2642 self.assertTupleEqual(tuple(a), tuple(b))
2643 self.assertSequenceEqual(a, tuple(b))
2644 self.assertSequenceEqual(tuple(a), b)
2645
2646 self.assertRaises(self.failureException, self.assertListEqual,
2647 a, tuple(b))
2648 self.assertRaises(self.failureException, self.assertTupleEqual,
2649 tuple(a), b)
2650 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2651 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2652 tuple(b))
2653 self.assertRaises(self.failureException, self.assertSequenceEqual,
2654 None, tuple(b))
2655 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2656 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2657 self.assertRaises(self.failureException, self.assertSequenceEqual,
2658 1, 1)
2659
2660 self.assertDictEqual({}, {})
2661
2662 c = { 'x': 1 }
2663 d = {}
2664 self.assertRaises(unittest.TestCase.failureException,
2665 self.assertDictEqual, c, d)
2666
2667 d.update(c)
2668 self.assertDictEqual(c, d)
2669
2670 d['x'] = 0
2671 self.assertRaises(unittest.TestCase.failureException,
2672 self.assertDictEqual, c, d, 'These are unequal')
2673
2674 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2675 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2676 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2677
2678 self.assertSameElements([1, 2, 3], [3, 2, 1])
2679 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2680 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2681 self.assertRaises(self.failureException, self.assertSameElements,
2682 [10], [10, 11])
2683 self.assertRaises(self.failureException, self.assertSameElements,
2684 [10, 11], [10])
2685
2686 # Test that sequences of unhashable objects can be tested for sameness:
2687 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00002688
Benjamin Peterson3bb6b7a2009-04-04 16:46:24 +00002689 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002690 self.assertRaises(self.failureException, self.assertSameElements,
2691 [[1]], [[2]])
Michael Foorda5809c82009-04-04 18:55:09 +00002692 self.assertRaises(self.failureException, self.assertSameElements,
2693 [{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 2}])
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002694
2695 def testAssertSetEqual(self):
2696 set1 = set()
2697 set2 = set()
2698 self.assertSetEqual(set1, set2)
2699
2700 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2701 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2702 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2703 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2704
2705 set1 = set(['a'])
2706 set2 = set()
2707 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2708
2709 set1 = set(['a'])
2710 set2 = set(['a'])
2711 self.assertSetEqual(set1, set2)
2712
2713 set1 = set(['a'])
2714 set2 = set(['a', 'b'])
2715 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2716
2717 set1 = set(['a'])
2718 set2 = frozenset(['a', 'b'])
2719 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2720
2721 set1 = set(['a', 'b'])
2722 set2 = frozenset(['a', 'b'])
2723 self.assertSetEqual(set1, set2)
2724
2725 set1 = set()
2726 set2 = "foo"
2727 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2728 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2729
2730 # make sure any string formatting is tuple-safe
2731 set1 = set([(0, 1), (2, 3)])
2732 set2 = set([(4, 5)])
2733 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2734
2735 def testInequality(self):
2736 # Try ints
2737 self.assertGreater(2, 1)
2738 self.assertGreaterEqual(2, 1)
2739 self.assertGreaterEqual(1, 1)
2740 self.assertLess(1, 2)
2741 self.assertLessEqual(1, 2)
2742 self.assertLessEqual(1, 1)
2743 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2744 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2745 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2746 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2747 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2748 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2749
2750 # Try Floats
2751 self.assertGreater(1.1, 1.0)
2752 self.assertGreaterEqual(1.1, 1.0)
2753 self.assertGreaterEqual(1.0, 1.0)
2754 self.assertLess(1.0, 1.1)
2755 self.assertLessEqual(1.0, 1.1)
2756 self.assertLessEqual(1.0, 1.0)
2757 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2758 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2759 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2760 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2761 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2762 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2763
2764 # Try Strings
2765 self.assertGreater('bug', 'ant')
2766 self.assertGreaterEqual('bug', 'ant')
2767 self.assertGreaterEqual('ant', 'ant')
2768 self.assertLess('ant', 'bug')
2769 self.assertLessEqual('ant', 'bug')
2770 self.assertLessEqual('ant', 'ant')
2771 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2772 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2773 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2774 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2775 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2776 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2777
2778 # Try bytes
2779 self.assertGreater(b'bug', b'ant')
2780 self.assertGreaterEqual(b'bug', b'ant')
2781 self.assertGreaterEqual(b'ant', b'ant')
2782 self.assertLess(b'ant', b'bug')
2783 self.assertLessEqual(b'ant', b'bug')
2784 self.assertLessEqual(b'ant', b'ant')
2785 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'bug')
2786 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'ant')
2787 self.assertRaises(self.failureException, self.assertGreaterEqual, b'ant',
2788 b'bug')
2789 self.assertRaises(self.failureException, self.assertLess, b'bug', b'ant')
2790 self.assertRaises(self.failureException, self.assertLess, b'ant', b'ant')
2791 self.assertRaises(self.failureException, self.assertLessEqual, b'bug', b'ant')
2792
2793 def testAssertMultiLineEqual(self):
2794 sample_text = """\
2795http://www.python.org/doc/2.3/lib/module-unittest.html
2796test case
2797 A test case is the smallest unit of testing. [...]
2798"""
2799 revised_sample_text = """\
2800http://www.python.org/doc/2.4.1/lib/module-unittest.html
2801test case
2802 A test case is the smallest unit of testing. [...] You may provide your
2803 own implementation that does not subclass from TestCase, of course.
2804"""
2805 sample_text_error = """
2806- http://www.python.org/doc/2.3/lib/module-unittest.html
2807? ^
2808+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2809? ^^^
2810 test case
2811- A test case is the smallest unit of testing. [...]
2812+ A test case is the smallest unit of testing. [...] You may provide your
2813? +++++++++++++++++++++
2814+ own implementation that does not subclass from TestCase, of course.
2815"""
2816
2817 try:
2818 self.assertMultiLineEqual(sample_text, revised_sample_text)
2819 except self.failureException as e:
Michael Foord02834952010-02-08 23:10:39 +00002820 # no fair testing ourself with ourself, and assertEqual is used for strings
2821 # so can't use assertEqual either. Just use assertTrue.
2822 self.assertTrue(sample_text_error == str(e))
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002823
2824 def testAssertIsNone(self):
2825 self.assertIsNone(None)
2826 self.assertRaises(self.failureException, self.assertIsNone, False)
2827 self.assertIsNotNone('DjZoPloGears on Rails')
2828 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2829
2830 def testAssertRegexpMatches(self):
2831 self.assertRegexpMatches('asdfabasdf', r'ab+')
2832 self.assertRaises(self.failureException, self.assertRegexpMatches,
2833 'saaas', r'aaaa')
2834
2835 def testAssertRaisesRegexp(self):
2836 class ExceptionMock(Exception):
2837 pass
2838
2839 def Stub():
2840 raise ExceptionMock('We expect')
2841
2842 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2843 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2844
2845 def testAssertNotRaisesRegexp(self):
2846 self.assertRaisesRegexp(
Benjamin Peterson4f75b642009-04-04 16:39:09 +00002847 self.failureException, '^Exception not raised by <lambda>$',
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002848 self.assertRaisesRegexp, Exception, re.compile('x'),
2849 lambda: None)
2850 self.assertRaisesRegexp(
Benjamin Peterson4f75b642009-04-04 16:39:09 +00002851 self.failureException, '^Exception not raised by <lambda>$',
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002852 self.assertRaisesRegexp, Exception, 'x',
2853 lambda: None)
2854
2855 def testAssertRaisesRegexpMismatch(self):
2856 def Stub():
2857 raise Exception('Unexpected')
2858
2859 self.assertRaisesRegexp(
2860 self.failureException,
2861 r'"\^Expected\$" does not match "Unexpected"',
2862 self.assertRaisesRegexp, Exception, '^Expected$',
2863 Stub)
2864 self.assertRaisesRegexp(
2865 self.failureException,
2866 r'"\^Expected\$" does not match "Unexpected"',
2867 self.assertRaisesRegexp, Exception,
2868 re.compile('^Expected$'), Stub)
2869
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +00002870 def testAssertRaisesExcValue(self):
2871 class ExceptionMock(Exception):
2872 pass
2873
2874 def Stub(foo):
2875 raise ExceptionMock(foo)
2876 v = "particular value"
2877
2878 ctx = self.assertRaises(ExceptionMock)
2879 with ctx:
2880 Stub(v)
Ezio Melotti49008232010-02-08 21:57:48 +00002881 e = ctx.exception
Ezio Melottie9615932010-01-24 19:26:24 +00002882 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +00002883 self.assertEqual(e.args[0], v)
2884
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002885 def testSynonymAssertMethodNames(self):
2886 """Test undocumented method name synonyms.
2887
2888 Please do not use these methods names in your own code.
2889
2890 This test confirms their continued existence and functionality
2891 in order to avoid breaking existing code.
2892 """
2893 self.assertNotEquals(3, 5)
2894 self.assertEquals(3, 3)
2895 self.assertAlmostEquals(2.0, 2.0)
2896 self.assertNotAlmostEquals(3.0, 5.0)
2897 self.assert_(True)
2898
2899 def testPendingDeprecationMethodNames(self):
2900 """Test fail* methods pending deprecation, they will warn in 3.2.
2901
2902 Do not use these methods. They will go away in 3.3.
2903 """
Benjamin Peterson6bcbad52009-06-30 23:45:41 +00002904 old = (
2905 (self.failIfEqual, (3, 5)),
2906 (self.failUnlessEqual, (3, 3)),
2907 (self.failUnlessAlmostEqual, (2.0, 2.0)),
2908 (self.failIfAlmostEqual, (3.0, 5.0)),
2909 (self.failUnless, (True,)),
2910 (self.failUnlessRaises, (TypeError, lambda _: 3.14 + 'spam')),
2911 (self.failIf, (False,))
2912 )
2913 for meth, args in old:
2914 with warnings.catch_warnings(record=True) as w:
2915 meth(*args)
2916 self.assertEqual(len(w), 1)
2917 self.assertIs(w[0].category, DeprecationWarning)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002918
2919 def testDeepcopy(self):
2920 # Issue: 5660
2921 class TestableTest(TestCase):
2922 def testNothing(self):
2923 pass
2924
2925 test = TestableTest('testNothing')
2926
2927 # This shouldn't blow up
2928 deepcopy(test)
2929
Benjamin Peterson5254c042009-03-23 22:25:03 +00002930
2931class Test_TestSkipping(TestCase):
2932
2933 def test_skipping(self):
2934 class Foo(unittest.TestCase):
2935 def test_skip_me(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00002936 self.skipTest("skip")
Benjamin Peterson5254c042009-03-23 22:25:03 +00002937 events = []
2938 result = LoggingResult(events)
2939 test = Foo("test_skip_me")
2940 test.run(result)
2941 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2942 self.assertEqual(result.skipped, [(test, "skip")])
2943
2944 # Try letting setUp skip the test now.
2945 class Foo(unittest.TestCase):
2946 def setUp(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00002947 self.skipTest("testing")
Benjamin Peterson5254c042009-03-23 22:25:03 +00002948 def test_nothing(self): pass
2949 events = []
2950 result = LoggingResult(events)
2951 test = Foo("test_nothing")
2952 test.run(result)
2953 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2954 self.assertEqual(result.skipped, [(test, "testing")])
2955 self.assertEqual(result.testsRun, 1)
2956
2957 def test_skipping_decorators(self):
2958 op_table = ((unittest.skipUnless, False, True),
2959 (unittest.skipIf, True, False))
2960 for deco, do_skip, dont_skip in op_table:
2961 class Foo(unittest.TestCase):
2962 @deco(do_skip, "testing")
2963 def test_skip(self): pass
2964
2965 @deco(dont_skip, "testing")
2966 def test_dont_skip(self): pass
2967 test_do_skip = Foo("test_skip")
2968 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002969 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002970 events = []
2971 result = LoggingResult(events)
2972 suite.run(result)
2973 self.assertEqual(len(result.skipped), 1)
2974 expected = ['startTest', 'addSkip', 'stopTest',
2975 'startTest', 'addSuccess', 'stopTest']
2976 self.assertEqual(events, expected)
2977 self.assertEqual(result.testsRun, 2)
2978 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
2979 self.assertTrue(result.wasSuccessful())
2980
2981 def test_skip_class(self):
2982 @unittest.skip("testing")
2983 class Foo(unittest.TestCase):
2984 def test_1(self):
2985 record.append(1)
2986 record = []
2987 result = unittest.TestResult()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002988 test = Foo("test_1")
2989 suite = unittest.TestSuite([test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002990 suite.run(result)
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002991 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002992 self.assertEqual(record, [])
2993
2994 def test_expected_failure(self):
2995 class Foo(unittest.TestCase):
2996 @unittest.expectedFailure
2997 def test_die(self):
2998 self.fail("help me!")
2999 events = []
3000 result = LoggingResult(events)
3001 test = Foo("test_die")
3002 test.run(result)
3003 self.assertEqual(events,
3004 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Peterson52baa292009-03-24 00:56:30 +00003005 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson5254c042009-03-23 22:25:03 +00003006 self.assertTrue(result.wasSuccessful())
3007
3008 def test_unexpected_success(self):
3009 class Foo(unittest.TestCase):
3010 @unittest.expectedFailure
3011 def test_die(self):
3012 pass
3013 events = []
3014 result = LoggingResult(events)
3015 test = Foo("test_die")
3016 test.run(result)
3017 self.assertEqual(events,
3018 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3019 self.assertFalse(result.failures)
Benjamin Peterson52baa292009-03-24 00:56:30 +00003020 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003021 self.assertTrue(result.wasSuccessful())
3022
3023
3024
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003025class Test_Assertions(TestCase):
3026 def test_AlmostEqual(self):
Benjamin Petersone1759f82009-06-30 23:35:19 +00003027 self.assertAlmostEqual(1.00000001, 1.0)
3028 self.assertNotAlmostEqual(1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003029 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003030 self.assertAlmostEqual, 1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003031 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003032 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003033
Benjamin Petersone1759f82009-06-30 23:35:19 +00003034 self.assertAlmostEqual(1.1, 1.0, places=0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003035 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003036 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003037
Benjamin Petersone1759f82009-06-30 23:35:19 +00003038 self.assertAlmostEqual(0, .1+.1j, places=0)
3039 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003040 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003041 self.assertAlmostEqual, 0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003042 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003043 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003044
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003045 self.assertAlmostEqual(float('inf'), float('inf'))
3046 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3047 float('inf'), float('inf'))
3048
3049
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003050 def test_assertRaises(self):
3051 def _raise(e):
3052 raise e
3053 self.assertRaises(KeyError, _raise, KeyError)
3054 self.assertRaises(KeyError, _raise, KeyError("key"))
3055 try:
3056 self.assertRaises(KeyError, lambda: None)
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 self.assertRaises(KeyError, _raise, ValueError)
3063 except ValueError:
3064 pass
3065 else:
3066 self.fail("assertRaises() didn't let exception pass through")
Ezio Melotti49008232010-02-08 21:57:48 +00003067 with self.assertRaises(KeyError) as cm:
3068 try:
3069 raise KeyError
3070 except Exception as e:
3071 exc = e
3072 raise
3073 self.assertIs(cm.exception, exc)
3074
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003075 with self.assertRaises(KeyError):
3076 raise KeyError("key")
3077 try:
3078 with self.assertRaises(KeyError):
3079 pass
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003080 except self.failureException as e:
Ezio Melottib58e0bd2010-01-23 15:40:09 +00003081 self.assertIn("KeyError not raised", str(e))
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003082 else:
3083 self.fail("assertRaises() didn't fail")
3084 try:
3085 with self.assertRaises(KeyError):
3086 raise ValueError
3087 except ValueError:
3088 pass
3089 else:
3090 self.fail("assertRaises() didn't let exception pass through")
3091
3092
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003093class TestLongMessage(TestCase):
3094 """Test that the individual asserts honour longMessage.
3095 This actually tests all the message behaviour for
3096 asserts that use longMessage."""
3097
3098 def setUp(self):
3099 class TestableTestFalse(TestCase):
3100 longMessage = False
3101 failureException = self.failureException
3102
3103 def testTest(self):
3104 pass
3105
3106 class TestableTestTrue(TestCase):
3107 longMessage = True
3108 failureException = self.failureException
3109
3110 def testTest(self):
3111 pass
3112
3113 self.testableTrue = TestableTestTrue('testTest')
3114 self.testableFalse = TestableTestFalse('testTest')
3115
3116 def testDefault(self):
3117 self.assertFalse(TestCase.longMessage)
3118
3119 def test_formatMsg(self):
3120 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3121 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3122
3123 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3124 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3125
3126 def assertMessages(self, methodName, args, errors):
3127 def getMethod(i):
3128 useTestableFalse = i < 2
3129 if useTestableFalse:
3130 test = self.testableFalse
3131 else:
3132 test = self.testableTrue
3133 return getattr(test, methodName)
3134
3135 for i, expected_regexp in enumerate(errors):
3136 testMethod = getMethod(i)
3137 kwargs = {}
3138 withMsg = i % 2
3139 if withMsg:
3140 kwargs = {"msg": "oops"}
3141
3142 with self.assertRaisesRegexp(self.failureException,
3143 expected_regexp=expected_regexp):
3144 testMethod(*args, **kwargs)
3145
3146 def testAssertTrue(self):
3147 self.assertMessages('assertTrue', (False,),
3148 ["^False is not True$", "^oops$", "^False is not True$",
3149 "^False is not True : oops$"])
3150
3151 def testAssertFalse(self):
3152 self.assertMessages('assertFalse', (True,),
3153 ["^True is not False$", "^oops$", "^True is not False$",
3154 "^True is not False : oops$"])
3155
3156 def testNotEqual(self):
3157 self.assertMessages('assertNotEqual', (1, 1),
3158 ["^1 == 1$", "^oops$", "^1 == 1$",
3159 "^1 == 1 : oops$"])
3160
3161 def testAlmostEqual(self):
3162 self.assertMessages('assertAlmostEqual', (1, 2),
3163 ["^1 != 2 within 7 places$", "^oops$",
3164 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3165
3166 def testNotAlmostEqual(self):
3167 self.assertMessages('assertNotAlmostEqual', (1, 1),
3168 ["^1 == 1 within 7 places$", "^oops$",
3169 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3170
3171 def test_baseAssertEqual(self):
3172 self.assertMessages('_baseAssertEqual', (1, 2),
3173 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3174
3175 def testAssertSequenceEqual(self):
3176 # Error messages are multiline so not testing on full message
3177 # assertTupleEqual and assertListEqual delegate to this method
3178 self.assertMessages('assertSequenceEqual', ([], [None]),
3179 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3180 r"\+ \[None\] : oops$"])
3181
3182 def testAssertSetEqual(self):
3183 self.assertMessages('assertSetEqual', (set(), set([None])),
3184 ["None$", "^oops$", "None$",
3185 "None : oops$"])
3186
3187 def testAssertIn(self):
3188 self.assertMessages('assertIn', (None, []),
3189 ['^None not found in \[\]$', "^oops$",
3190 '^None not found in \[\]$',
3191 '^None not found in \[\] : oops$'])
3192
3193 def testAssertNotIn(self):
3194 self.assertMessages('assertNotIn', (None, [None]),
3195 ['^None unexpectedly found in \[None\]$', "^oops$",
3196 '^None unexpectedly found in \[None\]$',
3197 '^None unexpectedly found in \[None\] : oops$'])
3198
3199 def testAssertDictEqual(self):
3200 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3201 [r"\+ \{'key': 'value'\}$", "^oops$",
3202 "\+ \{'key': 'value'\}$",
3203 "\+ \{'key': 'value'\} : oops$"])
3204
3205 def testAssertDictContainsSubset(self):
3206 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3207 ["^Missing: 'key'$", "^oops$",
3208 "^Missing: 'key'$",
3209 "^Missing: 'key' : oops$"])
3210
3211 def testAssertSameElements(self):
3212 self.assertMessages('assertSameElements', ([], [None]),
3213 [r"\[None\]$", "^oops$",
3214 r"\[None\]$",
3215 r"\[None\] : oops$"])
3216
3217 def testAssertMultiLineEqual(self):
3218 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3219 [r"\+ foo$", "^oops$",
3220 r"\+ foo$",
3221 r"\+ foo : oops$"])
3222
3223 def testAssertLess(self):
3224 self.assertMessages('assertLess', (2, 1),
3225 ["^2 not less than 1$", "^oops$",
3226 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3227
3228 def testAssertLessEqual(self):
3229 self.assertMessages('assertLessEqual', (2, 1),
3230 ["^2 not less than or equal to 1$", "^oops$",
3231 "^2 not less than or equal to 1$",
3232 "^2 not less than or equal to 1 : oops$"])
3233
3234 def testAssertGreater(self):
3235 self.assertMessages('assertGreater', (1, 2),
3236 ["^1 not greater than 2$", "^oops$",
3237 "^1 not greater than 2$",
3238 "^1 not greater than 2 : oops$"])
3239
3240 def testAssertGreaterEqual(self):
3241 self.assertMessages('assertGreaterEqual', (1, 2),
3242 ["^1 not greater than or equal to 2$", "^oops$",
3243 "^1 not greater than or equal to 2$",
3244 "^1 not greater than or equal to 2 : oops$"])
3245
3246 def testAssertIsNone(self):
3247 self.assertMessages('assertIsNone', ('not None',),
3248 ["^'not None' is not None$", "^oops$",
3249 "^'not None' is not None$",
3250 "^'not None' is not None : oops$"])
3251
3252 def testAssertIsNotNone(self):
3253 self.assertMessages('assertIsNotNone', (None,),
3254 ["^unexpectedly None$", "^oops$",
3255 "^unexpectedly None$",
3256 "^unexpectedly None : oops$"])
3257
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00003258 def testAssertIs(self):
3259 self.assertMessages('assertIs', (None, 'foo'),
3260 ["^None is not 'foo'$", "^oops$",
3261 "^None is not 'foo'$",
3262 "^None is not 'foo' : oops$"])
3263
3264 def testAssertIsNot(self):
3265 self.assertMessages('assertIsNot', (None, None),
3266 ["^unexpectedly identical: None$", "^oops$",
3267 "^unexpectedly identical: None$",
3268 "^unexpectedly identical: None : oops$"])
3269
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003270
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003271class TestCleanUp(TestCase):
3272
3273 def testCleanUp(self):
3274 class TestableTest(TestCase):
3275 def testNothing(self):
3276 pass
3277
3278 test = TestableTest('testNothing')
3279 self.assertEqual(test._cleanups, [])
3280
3281 cleanups = []
3282
3283 def cleanup1(*args, **kwargs):
3284 cleanups.append((1, args, kwargs))
3285
3286 def cleanup2(*args, **kwargs):
3287 cleanups.append((2, args, kwargs))
3288
3289 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3290 test.addCleanup(cleanup2)
3291
3292 self.assertEqual(test._cleanups,
3293 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3294 (cleanup2, (), {})])
3295
3296 result = test.doCleanups()
3297 self.assertTrue(result)
3298
3299 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3300
3301 def testCleanUpWithErrors(self):
3302 class TestableTest(TestCase):
3303 def testNothing(self):
3304 pass
3305
3306 class MockResult(object):
3307 errors = []
3308 def addError(self, test, exc_info):
3309 self.errors.append((test, exc_info))
3310
3311 result = MockResult()
3312 test = TestableTest('testNothing')
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00003313 test._resultForDoCleanups = result
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003314
3315 exc1 = Exception('foo')
3316 exc2 = Exception('bar')
3317 def cleanup1():
3318 raise exc1
3319
3320 def cleanup2():
3321 raise exc2
3322
3323 test.addCleanup(cleanup1)
3324 test.addCleanup(cleanup2)
3325
3326 self.assertFalse(test.doCleanups())
3327
3328 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3329 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3330 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3331
3332 def testCleanupInRun(self):
3333 blowUp = False
3334 ordering = []
3335
3336 class TestableTest(TestCase):
3337 def setUp(self):
3338 ordering.append('setUp')
3339 if blowUp:
3340 raise Exception('foo')
3341
3342 def testNothing(self):
3343 ordering.append('test')
3344
3345 def tearDown(self):
3346 ordering.append('tearDown')
3347
3348 test = TestableTest('testNothing')
3349
3350 def cleanup1():
3351 ordering.append('cleanup1')
3352 def cleanup2():
3353 ordering.append('cleanup2')
3354 test.addCleanup(cleanup1)
3355 test.addCleanup(cleanup2)
3356
3357 def success(some_test):
3358 self.assertEqual(some_test, test)
3359 ordering.append('success')
3360
3361 result = unittest.TestResult()
3362 result.addSuccess = success
3363
3364 test.run(result)
3365 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3366 'cleanup2', 'cleanup1', 'success'])
3367
3368 blowUp = True
3369 ordering = []
3370 test = TestableTest('testNothing')
3371 test.addCleanup(cleanup1)
3372 test.run(result)
3373 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3374
3375
3376class Test_TestProgram(TestCase):
3377
3378 # Horrible white box test
3379 def testNoExit(self):
3380 result = object()
3381 test = object()
3382
3383 class FakeRunner(object):
3384 def run(self, test):
3385 self.test = test
3386 return result
3387
3388 runner = FakeRunner()
3389
Benjamin Petersond2397752009-06-27 23:45:02 +00003390 oldParseArgs = TestProgram.parseArgs
3391 def restoreParseArgs():
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003392 TestProgram.parseArgs = oldParseArgs
Benjamin Petersond2397752009-06-27 23:45:02 +00003393 TestProgram.parseArgs = lambda *args: None
3394 self.addCleanup(restoreParseArgs)
3395
3396 def removeTest():
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003397 del TestProgram.test
Benjamin Petersond2397752009-06-27 23:45:02 +00003398 TestProgram.test = test
3399 self.addCleanup(removeTest)
3400
3401 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3402
3403 self.assertEqual(program.result, result)
3404 self.assertEqual(runner.test, test)
3405 self.assertEqual(program.verbosity, 2)
3406
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003407 class FooBar(unittest.TestCase):
3408 def testPass(self):
3409 assert True
3410 def testFail(self):
3411 assert False
3412
3413 class FooBarLoader(unittest.TestLoader):
3414 """Test loader that returns a suite containing FooBar."""
3415 def loadTestsFromModule(self, module):
3416 return self.suiteClass(
3417 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3418
3419
3420 def test_NonExit(self):
3421 program = unittest.main(exit=False,
3422 argv=["foobar"],
3423 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3424 testLoader=self.FooBarLoader())
3425 self.assertTrue(hasattr(program, 'result'))
3426
3427
3428 def test_Exit(self):
3429 self.assertRaises(
3430 SystemExit,
3431 unittest.main,
3432 argv=["foobar"],
3433 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3434 exit=True,
3435 testLoader=self.FooBarLoader())
3436
3437
3438 def test_ExitAsDefault(self):
3439 self.assertRaises(
3440 SystemExit,
3441 unittest.main,
3442 argv=["foobar"],
3443 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3444 testLoader=self.FooBarLoader())
3445
3446
3447class Test_TextTestRunner(TestCase):
3448 """Tests for TextTestRunner."""
3449
3450 def test_works_with_result_without_startTestRun_stopTestRun(self):
3451 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3452 separator2 = ''
3453 def printErrors(self):
3454 pass
3455
3456 class Runner(unittest.TextTestRunner):
3457 def __init__(self):
3458 super(Runner, self).__init__(io.StringIO())
3459
3460 def _makeResult(self):
3461 return OldTextResult()
3462
3463 runner = Runner()
3464 runner.run(unittest.TestSuite())
3465
3466 def test_startTestRun_stopTestRun_called(self):
3467 class LoggingTextResult(LoggingResult):
3468 separator2 = ''
3469 def printErrors(self):
3470 pass
3471
3472 class LoggingRunner(unittest.TextTestRunner):
3473 def __init__(self, events):
3474 super(LoggingRunner, self).__init__(io.StringIO())
3475 self._events = events
3476
3477 def _makeResult(self):
3478 return LoggingTextResult(self._events)
3479
3480 events = []
3481 runner = LoggingRunner(events)
3482 runner.run(unittest.TestSuite())
3483 expected = ['startTestRun', 'stopTestRun']
3484 self.assertEqual(events, expected)
3485
Antoine Pitrouc63ecee2009-11-10 21:34:48 +00003486 def test_pickle_unpickle(self):
3487 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3488 # required by test_multiprocessing under Windows (in verbose mode).
3489 stream = io.StringIO("foo")
3490 runner = unittest.TextTestRunner(stream)
3491 for protocol in range(2, pickle.HIGHEST_PROTOCOL + 1):
3492 s = pickle.dumps(runner, protocol)
3493 obj = pickle.loads(s)
3494 # StringIO objects never compare equal, a cheap test instead.
3495 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3496
Michael Foord34c94622010-02-10 15:51:42 +00003497 def test_resultclass(self):
3498 def MockResultClass(*args):
3499 return args
3500 STREAM = object()
3501 DESCRIPTIONS = object()
3502 VERBOSITY = object()
3503 runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY,
3504 resultclass=MockResultClass)
3505 self.assertEqual(runner.resultclass, MockResultClass)
3506
3507 expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY)
3508 self.assertEqual(runner._makeResult(), expectedresult)
3509
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003510
Benjamin Petersond2397752009-06-27 23:45:02 +00003511class TestDiscovery(TestCase):
3512
3513 # Heavily mocked tests so I can avoid hitting the filesystem
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003514 def test_get_name_from_path(self):
Benjamin Petersond2397752009-06-27 23:45:02 +00003515 loader = unittest.TestLoader()
Benjamin Petersond2397752009-06-27 23:45:02 +00003516 loader._top_level_dir = '/foo'
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003517 name = loader._get_name_from_path('/foo/bar/baz.py')
3518 self.assertEqual(name, 'bar.baz')
Benjamin Petersond2397752009-06-27 23:45:02 +00003519
3520 if not __debug__:
3521 # asserts are off
3522 return
3523
3524 with self.assertRaises(AssertionError):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003525 loader._get_name_from_path('/bar/baz.py')
Benjamin Petersond2397752009-06-27 23:45:02 +00003526
3527 def test_find_tests(self):
3528 loader = unittest.TestLoader()
3529
3530 original_listdir = os.listdir
3531 def restore_listdir():
3532 os.listdir = original_listdir
3533 original_isfile = os.path.isfile
3534 def restore_isfile():
3535 os.path.isfile = original_isfile
3536 original_isdir = os.path.isdir
3537 def restore_isdir():
3538 os.path.isdir = original_isdir
3539
3540 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003541 'test.foo', 'test-not-a-module.py', 'another_dir'],
Benjamin Petersond2397752009-06-27 23:45:02 +00003542 ['test3.py', 'test4.py', ]]
3543 os.listdir = lambda path: path_lists.pop(0)
3544 self.addCleanup(restore_listdir)
3545
3546 def isdir(path):
3547 return path.endswith('dir')
3548 os.path.isdir = isdir
3549 self.addCleanup(restore_isdir)
3550
3551 def isfile(path):
3552 # another_dir is not a package and so shouldn't be recursed into
3553 return not path.endswith('dir') and not 'another_dir' in path
3554 os.path.isfile = isfile
3555 self.addCleanup(restore_isfile)
3556
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003557 loader._get_module_from_name = lambda path: path + ' module'
Benjamin Petersond2397752009-06-27 23:45:02 +00003558 loader.loadTestsFromModule = lambda module: module + ' tests'
3559
3560 loader._top_level_dir = '/foo'
3561 suite = list(loader._find_tests('/foo', 'test*.py'))
3562
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003563 expected = [name + ' module tests' for name in
3564 ('test1', 'test2')]
3565 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3566 ('test3', 'test4')])
Benjamin Petersond2397752009-06-27 23:45:02 +00003567 self.assertEqual(suite, expected)
3568
3569 def test_find_tests_with_package(self):
3570 loader = unittest.TestLoader()
3571
3572 original_listdir = os.listdir
3573 def restore_listdir():
3574 os.listdir = original_listdir
3575 original_isfile = os.path.isfile
3576 def restore_isfile():
3577 os.path.isfile = original_isfile
3578 original_isdir = os.path.isdir
3579 def restore_isdir():
3580 os.path.isdir = original_isdir
3581
3582 directories = ['a_directory', 'test_directory', 'test_directory2']
3583 path_lists = [directories, [], [], []]
3584 os.listdir = lambda path: path_lists.pop(0)
3585 self.addCleanup(restore_listdir)
3586
3587 os.path.isdir = lambda path: True
3588 self.addCleanup(restore_isdir)
3589
3590 os.path.isfile = lambda path: os.path.basename(path) not in directories
3591 self.addCleanup(restore_isfile)
3592
3593 class Module(object):
3594 paths = []
3595 load_tests_args = []
3596
3597 def __init__(self, path):
3598 self.path = path
3599 self.paths.append(path)
3600 if os.path.basename(path) == 'test_directory':
3601 def load_tests(loader, tests, pattern):
3602 self.load_tests_args.append((loader, tests, pattern))
3603 return 'load_tests'
3604 self.load_tests = load_tests
3605
3606 def __eq__(self, other):
3607 return self.path == other.path
3608
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003609 loader._get_module_from_name = lambda name: Module(name)
Benjamin Petersond2397752009-06-27 23:45:02 +00003610 def loadTestsFromModule(module, use_load_tests):
3611 if use_load_tests:
3612 raise self.failureException('use_load_tests should be False for packages')
3613 return module.path + ' module tests'
3614 loader.loadTestsFromModule = loadTestsFromModule
3615
3616 loader._top_level_dir = '/foo'
3617 # this time no '.py' on the pattern so that it can match
3618 # a test package
3619 suite = list(loader._find_tests('/foo', 'test*'))
3620
3621 # We should have loaded tests from the test_directory package by calling load_tests
3622 # and directly from the test_directory2 package
3623 self.assertEqual(suite,
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003624 ['load_tests', 'test_directory2' + ' module tests'])
3625 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Benjamin Petersond2397752009-06-27 23:45:02 +00003626
3627 # load_tests should have been called once with loader, tests and pattern
3628 self.assertEqual(Module.load_tests_args,
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003629 [(loader, 'test_directory' + ' module tests', 'test*')])
Benjamin Petersond2397752009-06-27 23:45:02 +00003630
3631 def test_discover(self):
3632 loader = unittest.TestLoader()
3633
3634 original_isfile = os.path.isfile
3635 def restore_isfile():
3636 os.path.isfile = original_isfile
3637
3638 os.path.isfile = lambda path: False
3639 self.addCleanup(restore_isfile)
3640
Nick Coghlan6ead5522009-10-18 13:19:33 +00003641 orig_sys_path = sys.path[:]
3642 def restore_path():
3643 sys.path[:] = orig_sys_path
3644 self.addCleanup(restore_path)
Benjamin Petersond2397752009-06-27 23:45:02 +00003645
Nick Coghlan6ead5522009-10-18 13:19:33 +00003646 full_path = os.path.abspath(os.path.normpath('/foo'))
Benjamin Petersond2397752009-06-27 23:45:02 +00003647 with self.assertRaises(ImportError):
3648 loader.discover('/foo/bar', top_level_dir='/foo')
3649
3650 self.assertEqual(loader._top_level_dir, full_path)
3651 self.assertIn(full_path, sys.path)
3652
3653 os.path.isfile = lambda path: True
3654 _find_tests_args = []
3655 def _find_tests(start_dir, pattern):
3656 _find_tests_args.append((start_dir, pattern))
3657 return ['tests']
3658 loader._find_tests = _find_tests
3659 loader.suiteClass = str
3660
3661 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3662
3663 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3664 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3665 self.assertEqual(suite, "['tests']")
3666 self.assertEqual(loader._top_level_dir, top_level_dir)
3667 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlan6ead5522009-10-18 13:19:33 +00003668 self.assertIn(top_level_dir, sys.path)
Benjamin Petersond2397752009-06-27 23:45:02 +00003669
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003670 def test_discover_with_modules_that_fail_to_import(self):
3671 loader = unittest.TestLoader()
3672
3673 listdir = os.listdir
3674 os.listdir = lambda _: ['test_this_does_not_exist.py']
3675 isfile = os.path.isfile
3676 os.path.isfile = lambda _: True
Nick Coghlan6ead5522009-10-18 13:19:33 +00003677 orig_sys_path = sys.path[:]
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003678 def restore():
3679 os.path.isfile = isfile
3680 os.listdir = listdir
Nick Coghlan6ead5522009-10-18 13:19:33 +00003681 sys.path[:] = orig_sys_path
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003682 self.addCleanup(restore)
3683
3684 suite = loader.discover('.')
Nick Coghlan6ead5522009-10-18 13:19:33 +00003685 self.assertIn(os.getcwd(), sys.path)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003686 self.assertEqual(suite.countTestCases(), 1)
3687 test = list(list(suite)[0])[0] # extract test from suite
3688
3689 with self.assertRaises(ImportError):
3690 test.test_this_does_not_exist()
3691
Benjamin Petersond2397752009-06-27 23:45:02 +00003692 def test_command_line_handling_parseArgs(self):
3693 # Haha - take that uninstantiable class
3694 program = object.__new__(TestProgram)
3695
3696 args = []
3697 def do_discovery(argv):
3698 args.extend(argv)
3699 program._do_discovery = do_discovery
3700 program.parseArgs(['something', 'discover'])
3701 self.assertEqual(args, [])
3702
3703 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3704 self.assertEqual(args, ['foo', 'bar'])
3705
3706 def test_command_line_handling_do_discovery_too_many_arguments(self):
3707 class Stop(Exception):
3708 pass
3709 def usageExit():
3710 raise Stop
3711
3712 program = object.__new__(TestProgram)
3713 program.usageExit = usageExit
3714
3715 with self.assertRaises(Stop):
3716 # too many args
3717 program._do_discovery(['one', 'two', 'three', 'four'])
3718
3719
3720 def test_command_line_handling_do_discovery_calls_loader(self):
3721 program = object.__new__(TestProgram)
3722
3723 class Loader(object):
3724 args = []
3725 def discover(self, start_dir, pattern, top_level_dir):
3726 self.args.append((start_dir, pattern, top_level_dir))
3727 return 'tests'
3728
3729 program._do_discovery(['-v'], Loader=Loader)
3730 self.assertEqual(program.verbosity, 2)
3731 self.assertEqual(program.test, 'tests')
3732 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3733
3734 Loader.args = []
3735 program = object.__new__(TestProgram)
3736 program._do_discovery(['--verbose'], Loader=Loader)
3737 self.assertEqual(program.test, 'tests')
3738 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3739
3740 Loader.args = []
3741 program = object.__new__(TestProgram)
3742 program._do_discovery([], Loader=Loader)
3743 self.assertEqual(program.test, 'tests')
3744 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3745
3746 Loader.args = []
3747 program = object.__new__(TestProgram)
3748 program._do_discovery(['fish'], Loader=Loader)
3749 self.assertEqual(program.test, 'tests')
3750 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3751
3752 Loader.args = []
3753 program = object.__new__(TestProgram)
3754 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3755 self.assertEqual(program.test, 'tests')
3756 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3757
3758 Loader.args = []
3759 program = object.__new__(TestProgram)
3760 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3761 self.assertEqual(program.test, 'tests')
3762 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3763
3764 Loader.args = []
3765 program = object.__new__(TestProgram)
3766 program._do_discovery(['-s', 'fish'], Loader=Loader)
3767 self.assertEqual(program.test, 'tests')
3768 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3769
3770 Loader.args = []
3771 program = object.__new__(TestProgram)
3772 program._do_discovery(['-t', 'fish'], Loader=Loader)
3773 self.assertEqual(program.test, 'tests')
3774 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3775
3776 Loader.args = []
3777 program = object.__new__(TestProgram)
3778 program._do_discovery(['-p', 'fish'], Loader=Loader)
3779 self.assertEqual(program.test, 'tests')
3780 self.assertEqual(Loader.args, [('.', 'fish', None)])
3781
3782 Loader.args = []
3783 program = object.__new__(TestProgram)
3784 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3785 self.assertEqual(program.test, 'tests')
3786 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3787 self.assertEqual(program.verbosity, 2)
3788
3789
Jim Fultonfafd8742004-08-28 15:22:12 +00003790######################################################################
3791## Main
3792######################################################################
3793
3794def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003795 support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003796 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003797 Test_TestSkipping, Test_Assertions, TestLongMessage,
Antoine Pitrouc63ecee2009-11-10 21:34:48 +00003798 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner)
Jim Fultonfafd8742004-08-28 15:22:12 +00003799
Guido van Rossumd8faa362007-04-27 19:54:29 +00003800if __name__ == "__main__":
Jim Fultonfafd8742004-08-28 15:22:12 +00003801 test_main()