blob: 73b32754f000e3b98e73844745e38ab6a90ff456 [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):
275 load_tests_args.extend((loader, tests, pattern))
276 return tests
277 m.load_tests = load_tests
278
279 loader = unittest.TestLoader()
280 suite = loader.loadTestsFromModule(m)
281 self.assertEquals(load_tests_args, [loader, suite, None])
282
283 load_tests_args = []
284 suite = loader.loadTestsFromModule(m, use_load_tests=False)
285 self.assertEquals(load_tests_args, [])
286
Guido van Rossumd8faa362007-04-27 19:54:29 +0000287 ################################################################
288 ### /Tests for TestLoader.loadTestsFromModule()
289
290 ### Tests for TestLoader.loadTestsFromName()
291 ################################################################
292
293 # "The specifier name is a ``dotted name'' that may resolve either to
294 # a module, a test case class, a TestSuite instance, a test method
295 # within a test case class, or a callable object which returns a
296 # TestCase or TestSuite instance."
297 #
298 # Is ValueError raised in response to an empty name?
299 def test_loadTestsFromName__empty_name(self):
300 loader = unittest.TestLoader()
301
302 try:
303 loader.loadTestsFromName('')
304 except ValueError as e:
305 self.assertEqual(str(e), "Empty module name")
306 else:
307 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
308
309 # "The specifier name is a ``dotted name'' that may resolve either to
310 # a module, a test case class, a TestSuite instance, a test method
311 # within a test case class, or a callable object which returns a
312 # TestCase or TestSuite instance."
313 #
314 # What happens when the name contains invalid characters?
315 def test_loadTestsFromName__malformed_name(self):
316 loader = unittest.TestLoader()
317
318 # XXX Should this raise ValueError or ImportError?
319 try:
320 loader.loadTestsFromName('abc () //')
321 except ValueError:
322 pass
323 except ImportError:
324 pass
325 else:
326 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
327
328 # "The specifier name is a ``dotted name'' that may resolve ... to a
329 # module"
330 #
331 # What happens when a module by that name can't be found?
332 def test_loadTestsFromName__unknown_module_name(self):
333 loader = unittest.TestLoader()
334
335 try:
336 loader.loadTestsFromName('sdasfasfasdf')
337 except ImportError as e:
338 self.assertEqual(str(e), "No module named sdasfasfasdf")
339 else:
340 self.fail("TestLoader.loadTestsFromName failed to raise ImportError")
341
342 # "The specifier name is a ``dotted name'' that may resolve either to
343 # a module, a test case class, a TestSuite instance, a test method
344 # within a test case class, or a callable object which returns a
345 # TestCase or TestSuite instance."
346 #
347 # What happens when the module is found, but the attribute can't?
348 def test_loadTestsFromName__unknown_attr_name(self):
349 loader = unittest.TestLoader()
350
351 try:
352 loader.loadTestsFromName('unittest.sdasfasfasdf')
353 except AttributeError as e:
354 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
355 else:
356 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
357
358 # "The specifier name is a ``dotted name'' that may resolve either to
359 # a module, a test case class, a TestSuite instance, a test method
360 # within a test case class, or a callable object which returns a
361 # TestCase or TestSuite instance."
362 #
363 # What happens when we provide the module, but the attribute can't be
364 # found?
365 def test_loadTestsFromName__relative_unknown_name(self):
366 loader = unittest.TestLoader()
367
368 try:
369 loader.loadTestsFromName('sdasfasfasdf', unittest)
370 except AttributeError as e:
371 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
372 else:
373 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
374
375 # "The specifier name is a ``dotted name'' that may resolve either to
376 # a module, a test case class, a TestSuite instance, a test method
377 # within a test case class, or a callable object which returns a
378 # TestCase or TestSuite instance."
379 # ...
380 # "The method optionally resolves name relative to the given module"
381 #
382 # Does loadTestsFromName raise ValueError when passed an empty
383 # name relative to a provided module?
384 #
385 # XXX Should probably raise a ValueError instead of an AttributeError
386 def test_loadTestsFromName__relative_empty_name(self):
387 loader = unittest.TestLoader()
388
389 try:
390 loader.loadTestsFromName('', unittest)
391 except AttributeError as e:
392 pass
393 else:
394 self.fail("Failed to raise AttributeError")
395
396 # "The specifier name is a ``dotted name'' that may resolve either to
397 # a module, a test case class, a TestSuite instance, a test method
398 # within a test case class, or a callable object which returns a
399 # TestCase or TestSuite instance."
400 # ...
401 # "The method optionally resolves name relative to the given module"
402 #
403 # What happens when an impossible name is given, relative to the provided
404 # `module`?
405 def test_loadTestsFromName__relative_malformed_name(self):
406 loader = unittest.TestLoader()
407
408 # XXX Should this raise AttributeError or ValueError?
409 try:
410 loader.loadTestsFromName('abc () //', unittest)
411 except ValueError:
412 pass
413 except AttributeError:
414 pass
415 else:
416 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
417
418 # "The method optionally resolves name relative to the given module"
419 #
420 # Does loadTestsFromName raise TypeError when the `module` argument
421 # isn't a module object?
422 #
423 # XXX Accepts the not-a-module object, ignorning the object's type
424 # This should raise an exception or the method name should be changed
425 #
426 # XXX Some people are relying on this, so keep it for now
427 def test_loadTestsFromName__relative_not_a_module(self):
428 class MyTestCase(unittest.TestCase):
429 def test(self):
430 pass
431
432 class NotAModule(object):
433 test_2 = MyTestCase
434
435 loader = unittest.TestLoader()
436 suite = loader.loadTestsFromName('test_2', NotAModule)
437
438 reference = [MyTestCase('test')]
439 self.assertEqual(list(suite), reference)
440
441 # "The specifier name is a ``dotted name'' that may resolve either to
442 # a module, a test case class, a TestSuite instance, a test method
443 # within a test case class, or a callable object which returns a
444 # TestCase or TestSuite instance."
445 #
446 # Does it raise an exception if the name resolves to an invalid
447 # object?
448 def test_loadTestsFromName__relative_bad_object(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000449 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000450 m.testcase_1 = object()
451
452 loader = unittest.TestLoader()
453 try:
454 loader.loadTestsFromName('testcase_1', m)
455 except TypeError:
456 pass
457 else:
458 self.fail("Should have raised TypeError")
459
460 # "The specifier name is a ``dotted name'' that may
461 # resolve either to ... a test case class"
462 def test_loadTestsFromName__relative_TestCase_subclass(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000463 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000464 class MyTestCase(unittest.TestCase):
465 def test(self):
466 pass
467 m.testcase_1 = MyTestCase
468
469 loader = unittest.TestLoader()
470 suite = loader.loadTestsFromName('testcase_1', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000471 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000472 self.assertEqual(list(suite), [MyTestCase('test')])
473
474 # "The specifier name is a ``dotted name'' that may resolve either to
475 # a module, a test case class, a TestSuite instance, a test method
476 # within a test case class, or a callable object which returns a
477 # TestCase or TestSuite instance."
478 def test_loadTestsFromName__relative_TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000479 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000480 class MyTestCase(unittest.TestCase):
481 def test(self):
482 pass
483 m.testsuite = unittest.TestSuite([MyTestCase('test')])
484
485 loader = unittest.TestLoader()
486 suite = loader.loadTestsFromName('testsuite', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000487 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000488
489 self.assertEqual(list(suite), [MyTestCase('test')])
490
491 # "The specifier name is a ``dotted name'' that may resolve ... to
492 # ... a test method within a test case class"
493 def test_loadTestsFromName__relative_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000494 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000495 class MyTestCase(unittest.TestCase):
496 def test(self):
497 pass
498 m.testcase_1 = MyTestCase
499
500 loader = unittest.TestLoader()
501 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000502 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000503
504 self.assertEqual(list(suite), [MyTestCase('test')])
505
506 # "The specifier name is a ``dotted name'' that may resolve either to
507 # a module, a test case class, a TestSuite instance, a test method
508 # within a test case class, or a callable object which returns a
509 # TestCase or TestSuite instance."
510 #
511 # Does loadTestsFromName() raise the proper exception when trying to
512 # resolve "a test method within a test case class" that doesn't exist
513 # for the given name (relative to a provided module)?
514 def test_loadTestsFromName__relative_invalid_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000515 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000516 class MyTestCase(unittest.TestCase):
517 def test(self):
518 pass
519 m.testcase_1 = MyTestCase
520
521 loader = unittest.TestLoader()
522 try:
523 loader.loadTestsFromName('testcase_1.testfoo', m)
524 except AttributeError as e:
525 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
526 else:
527 self.fail("Failed to raise AttributeError")
528
529 # "The specifier name is a ``dotted name'' that may resolve ... to
530 # ... a callable object which returns a ... TestSuite instance"
531 def test_loadTestsFromName__callable__TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000532 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000533 testcase_1 = unittest.FunctionTestCase(lambda: None)
534 testcase_2 = unittest.FunctionTestCase(lambda: None)
535 def return_TestSuite():
536 return unittest.TestSuite([testcase_1, testcase_2])
537 m.return_TestSuite = return_TestSuite
538
539 loader = unittest.TestLoader()
540 suite = loader.loadTestsFromName('return_TestSuite', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000541 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000542 self.assertEqual(list(suite), [testcase_1, testcase_2])
543
544 # "The specifier name is a ``dotted name'' that may resolve ... to
545 # ... a callable object which returns a TestCase ... instance"
546 def test_loadTestsFromName__callable__TestCase_instance(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000547 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000548 testcase_1 = unittest.FunctionTestCase(lambda: None)
549 def return_TestCase():
550 return testcase_1
551 m.return_TestCase = return_TestCase
552
553 loader = unittest.TestLoader()
554 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000555 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000556 self.assertEqual(list(suite), [testcase_1])
557
558 # "The specifier name is a ``dotted name'' that may resolve ... to
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000559 # ... a callable object which returns a TestCase ... instance"
560 #*****************************************************************
561 #Override the suiteClass attribute to ensure that the suiteClass
562 #attribute is used
563 def test_loadTestsFromName__callable__TestCase_instance_ProperSuiteClass(self):
564 class SubTestSuite(unittest.TestSuite):
565 pass
566 m = types.ModuleType('m')
567 testcase_1 = unittest.FunctionTestCase(lambda: None)
568 def return_TestCase():
569 return testcase_1
570 m.return_TestCase = return_TestCase
571
572 loader = unittest.TestLoader()
573 loader.suiteClass = SubTestSuite
574 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000575 self.assertIsInstance(suite, loader.suiteClass)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000576 self.assertEqual(list(suite), [testcase_1])
577
578 # "The specifier name is a ``dotted name'' that may resolve ... to
579 # ... a test method within a test case class"
580 #*****************************************************************
581 #Override the suiteClass attribute to ensure that the suiteClass
582 #attribute is used
583 def test_loadTestsFromName__relative_testmethod_ProperSuiteClass(self):
584 class SubTestSuite(unittest.TestSuite):
585 pass
586 m = types.ModuleType('m')
587 class MyTestCase(unittest.TestCase):
588 def test(self):
589 pass
590 m.testcase_1 = MyTestCase
591
592 loader = unittest.TestLoader()
593 loader.suiteClass=SubTestSuite
594 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottie9615932010-01-24 19:26:24 +0000595 self.assertIsInstance(suite, loader.suiteClass)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000596
597 self.assertEqual(list(suite), [MyTestCase('test')])
598
599 # "The specifier name is a ``dotted name'' that may resolve ... to
Guido van Rossumd8faa362007-04-27 19:54:29 +0000600 # ... a callable object which returns a TestCase or TestSuite instance"
601 #
602 # What happens if the callable returns something else?
603 def test_loadTestsFromName__callable__wrong_type(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000604 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000605 def return_wrong():
606 return 6
607 m.return_wrong = return_wrong
608
609 loader = unittest.TestLoader()
610 try:
611 suite = loader.loadTestsFromName('return_wrong', m)
612 except TypeError:
613 pass
614 else:
615 self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
616
617 # "The specifier can refer to modules and packages which have not been
618 # imported; they will be imported as a side-effect"
619 def test_loadTestsFromName__module_not_loaded(self):
620 # We're going to try to load this module as a side-effect, so it
621 # better not be loaded before we try.
622 #
623 # Why pick audioop? Google shows it isn't used very often, so there's
624 # a good chance that it won't be imported when this test is run
625 module_name = 'audioop'
626
627 import sys
628 if module_name in sys.modules:
629 del sys.modules[module_name]
630
631 loader = unittest.TestLoader()
632 try:
633 suite = loader.loadTestsFromName(module_name)
634
Ezio Melottie9615932010-01-24 19:26:24 +0000635 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000636 self.assertEqual(list(suite), [])
637
638 # audioop should now be loaded, thanks to loadTestsFromName()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000639 self.assertIn(module_name, sys.modules)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000640 finally:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000641 if module_name in sys.modules:
642 del sys.modules[module_name]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000643
644 ################################################################
645 ### Tests for TestLoader.loadTestsFromName()
646
647 ### Tests for TestLoader.loadTestsFromNames()
648 ################################################################
649
650 # "Similar to loadTestsFromName(), but takes a sequence of names rather
651 # than a single name."
652 #
653 # What happens if that sequence of names is empty?
654 def test_loadTestsFromNames__empty_name_list(self):
655 loader = unittest.TestLoader()
656
657 suite = loader.loadTestsFromNames([])
Ezio Melottie9615932010-01-24 19:26:24 +0000658 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000659 self.assertEqual(list(suite), [])
660
661 # "Similar to loadTestsFromName(), but takes a sequence of names rather
662 # than a single name."
663 # ...
664 # "The method optionally resolves name relative to the given module"
665 #
666 # What happens if that sequence of names is empty?
667 #
668 # XXX Should this raise a ValueError or just return an empty TestSuite?
669 def test_loadTestsFromNames__relative_empty_name_list(self):
670 loader = unittest.TestLoader()
671
672 suite = loader.loadTestsFromNames([], unittest)
Ezio Melottie9615932010-01-24 19:26:24 +0000673 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000674 self.assertEqual(list(suite), [])
675
676 # "The specifier name is a ``dotted name'' that may resolve either to
677 # a module, a test case class, a TestSuite instance, a test method
678 # within a test case class, or a callable object which returns a
679 # TestCase or TestSuite instance."
680 #
681 # Is ValueError raised in response to an empty name?
682 def test_loadTestsFromNames__empty_name(self):
683 loader = unittest.TestLoader()
684
685 try:
686 loader.loadTestsFromNames([''])
687 except ValueError as e:
688 self.assertEqual(str(e), "Empty module name")
689 else:
690 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
691
692 # "The specifier name is a ``dotted name'' that may resolve either to
693 # a module, a test case class, a TestSuite instance, a test method
694 # within a test case class, or a callable object which returns a
695 # TestCase or TestSuite instance."
696 #
697 # What happens when presented with an impossible module name?
698 def test_loadTestsFromNames__malformed_name(self):
699 loader = unittest.TestLoader()
700
701 # XXX Should this raise ValueError or ImportError?
702 try:
703 loader.loadTestsFromNames(['abc () //'])
704 except ValueError:
705 pass
706 except ImportError:
707 pass
708 else:
709 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
710
711 # "The specifier name is a ``dotted name'' that may resolve either to
712 # a module, a test case class, a TestSuite instance, a test method
713 # within a test case class, or a callable object which returns a
714 # TestCase or TestSuite instance."
715 #
716 # What happens when no module can be found for the given name?
717 def test_loadTestsFromNames__unknown_module_name(self):
718 loader = unittest.TestLoader()
719
720 try:
721 loader.loadTestsFromNames(['sdasfasfasdf'])
722 except ImportError as e:
723 self.assertEqual(str(e), "No module named sdasfasfasdf")
724 else:
725 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
726
727 # "The specifier name is a ``dotted name'' that may resolve either to
728 # a module, a test case class, a TestSuite instance, a test method
729 # within a test case class, or a callable object which returns a
730 # TestCase or TestSuite instance."
731 #
732 # What happens when the module can be found, but not the attribute?
733 def test_loadTestsFromNames__unknown_attr_name(self):
734 loader = unittest.TestLoader()
735
736 try:
737 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
738 except AttributeError as e:
739 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
740 else:
741 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
742
743 # "The specifier name is a ``dotted name'' that may resolve either to
744 # a module, a test case class, a TestSuite instance, a test method
745 # within a test case class, or a callable object which returns a
746 # TestCase or TestSuite instance."
747 # ...
748 # "The method optionally resolves name relative to the given module"
749 #
750 # What happens when given an unknown attribute on a specified `module`
751 # argument?
752 def test_loadTestsFromNames__unknown_name_relative_1(self):
753 loader = unittest.TestLoader()
754
755 try:
756 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
757 except AttributeError as e:
758 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
759 else:
760 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
761
762 # "The specifier name is a ``dotted name'' that may resolve either to
763 # a module, a test case class, a TestSuite instance, a test method
764 # within a test case class, or a callable object which returns a
765 # TestCase or TestSuite instance."
766 # ...
767 # "The method optionally resolves name relative to the given module"
768 #
769 # Do unknown attributes (relative to a provided module) still raise an
770 # exception even in the presence of valid attribute names?
771 def test_loadTestsFromNames__unknown_name_relative_2(self):
772 loader = unittest.TestLoader()
773
774 try:
775 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
776 except AttributeError as e:
777 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
778 else:
779 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
780
781 # "The specifier name is a ``dotted name'' that may resolve either to
782 # a module, a test case class, a TestSuite instance, a test method
783 # within a test case class, or a callable object which returns a
784 # TestCase or TestSuite instance."
785 # ...
786 # "The method optionally resolves name relative to the given module"
787 #
788 # What happens when faced with the empty string?
789 #
790 # XXX This currently raises AttributeError, though ValueError is probably
791 # more appropriate
792 def test_loadTestsFromNames__relative_empty_name(self):
793 loader = unittest.TestLoader()
794
795 try:
796 loader.loadTestsFromNames([''], unittest)
797 except AttributeError:
798 pass
799 else:
800 self.fail("Failed to raise ValueError")
801
802 # "The specifier name is a ``dotted name'' that may resolve either to
803 # a module, a test case class, a TestSuite instance, a test method
804 # within a test case class, or a callable object which returns a
805 # TestCase or TestSuite instance."
806 # ...
807 # "The method optionally resolves name relative to the given module"
808 #
809 # What happens when presented with an impossible attribute name?
810 def test_loadTestsFromNames__relative_malformed_name(self):
811 loader = unittest.TestLoader()
812
813 # XXX Should this raise AttributeError or ValueError?
814 try:
815 loader.loadTestsFromNames(['abc () //'], unittest)
816 except AttributeError:
817 pass
818 except ValueError:
819 pass
820 else:
821 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
822
823 # "The method optionally resolves name relative to the given module"
824 #
825 # Does loadTestsFromNames() make sure the provided `module` is in fact
826 # a module?
827 #
828 # XXX This validation is currently not done. This flexibility should
829 # either be documented or a TypeError should be raised.
830 def test_loadTestsFromNames__relative_not_a_module(self):
831 class MyTestCase(unittest.TestCase):
832 def test(self):
833 pass
834
835 class NotAModule(object):
836 test_2 = MyTestCase
837
838 loader = unittest.TestLoader()
839 suite = loader.loadTestsFromNames(['test_2'], NotAModule)
840
841 reference = [unittest.TestSuite([MyTestCase('test')])]
842 self.assertEqual(list(suite), reference)
843
844 # "The specifier name is a ``dotted name'' that may resolve either to
845 # a module, a test case class, a TestSuite instance, a test method
846 # within a test case class, or a callable object which returns a
847 # TestCase or TestSuite instance."
848 #
849 # Does it raise an exception if the name resolves to an invalid
850 # object?
851 def test_loadTestsFromNames__relative_bad_object(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000852 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000853 m.testcase_1 = object()
854
855 loader = unittest.TestLoader()
856 try:
857 loader.loadTestsFromNames(['testcase_1'], m)
858 except TypeError:
859 pass
860 else:
861 self.fail("Should have raised TypeError")
862
863 # "The specifier name is a ``dotted name'' that may resolve ... to
864 # ... a test case class"
865 def test_loadTestsFromNames__relative_TestCase_subclass(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000866 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000867 class MyTestCase(unittest.TestCase):
868 def test(self):
869 pass
870 m.testcase_1 = MyTestCase
871
872 loader = unittest.TestLoader()
873 suite = loader.loadTestsFromNames(['testcase_1'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000874 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000875
876 expected = loader.suiteClass([MyTestCase('test')])
877 self.assertEqual(list(suite), [expected])
878
879 # "The specifier name is a ``dotted name'' that may resolve ... to
880 # ... a TestSuite instance"
881 def test_loadTestsFromNames__relative_TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000882 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000883 class MyTestCase(unittest.TestCase):
884 def test(self):
885 pass
886 m.testsuite = unittest.TestSuite([MyTestCase('test')])
887
888 loader = unittest.TestLoader()
889 suite = loader.loadTestsFromNames(['testsuite'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000890 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000891
892 self.assertEqual(list(suite), [m.testsuite])
893
894 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
895 # test method within a test case class"
896 def test_loadTestsFromNames__relative_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000897 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000898 class MyTestCase(unittest.TestCase):
899 def test(self):
900 pass
901 m.testcase_1 = MyTestCase
902
903 loader = unittest.TestLoader()
904 suite = loader.loadTestsFromNames(['testcase_1.test'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000905 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000906
907 ref_suite = unittest.TestSuite([MyTestCase('test')])
908 self.assertEqual(list(suite), [ref_suite])
909
910 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
911 # test method within a test case class"
912 #
913 # Does the method gracefully handle names that initially look like they
914 # resolve to "a test method within a test case class" but don't?
915 def test_loadTestsFromNames__relative_invalid_testmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000916 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000917 class MyTestCase(unittest.TestCase):
918 def test(self):
919 pass
920 m.testcase_1 = MyTestCase
921
922 loader = unittest.TestLoader()
923 try:
924 loader.loadTestsFromNames(['testcase_1.testfoo'], m)
925 except AttributeError as e:
926 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
927 else:
928 self.fail("Failed to raise AttributeError")
929
930 # "The specifier name is a ``dotted name'' that may resolve ... to
931 # ... a callable object which returns a ... TestSuite instance"
932 def test_loadTestsFromNames__callable__TestSuite(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000933 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000934 testcase_1 = unittest.FunctionTestCase(lambda: None)
935 testcase_2 = unittest.FunctionTestCase(lambda: None)
936 def return_TestSuite():
937 return unittest.TestSuite([testcase_1, testcase_2])
938 m.return_TestSuite = return_TestSuite
939
940 loader = unittest.TestLoader()
941 suite = loader.loadTestsFromNames(['return_TestSuite'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000942 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000943
944 expected = unittest.TestSuite([testcase_1, testcase_2])
945 self.assertEqual(list(suite), [expected])
946
947 # "The specifier name is a ``dotted name'' that may resolve ... to
948 # ... a callable object which returns a TestCase ... instance"
949 def test_loadTestsFromNames__callable__TestCase_instance(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000950 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000951 testcase_1 = unittest.FunctionTestCase(lambda: None)
952 def return_TestCase():
953 return testcase_1
954 m.return_TestCase = return_TestCase
955
956 loader = unittest.TestLoader()
957 suite = loader.loadTestsFromNames(['return_TestCase'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000958 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000959
960 ref_suite = unittest.TestSuite([testcase_1])
961 self.assertEqual(list(suite), [ref_suite])
962
963 # "The specifier name is a ``dotted name'' that may resolve ... to
964 # ... a callable object which returns a TestCase or TestSuite instance"
965 #
966 # Are staticmethods handled correctly?
967 def test_loadTestsFromNames__callable__call_staticmethod(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000968 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000969 class Test1(unittest.TestCase):
970 def test(self):
971 pass
972
973 testcase_1 = Test1('test')
974 class Foo(unittest.TestCase):
975 @staticmethod
976 def foo():
977 return testcase_1
978 m.Foo = Foo
979
980 loader = unittest.TestLoader()
981 suite = loader.loadTestsFromNames(['Foo.foo'], m)
Ezio Melottie9615932010-01-24 19:26:24 +0000982 self.assertIsInstance(suite, loader.suiteClass)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000983
984 ref_suite = unittest.TestSuite([testcase_1])
985 self.assertEqual(list(suite), [ref_suite])
986
987 # "The specifier name is a ``dotted name'' that may resolve ... to
988 # ... a callable object which returns a TestCase or TestSuite instance"
989 #
990 # What happens when the callable returns something else?
991 def test_loadTestsFromNames__callable__wrong_type(self):
Christian Heimes45f9af32007-11-27 21:50:00 +0000992 m = types.ModuleType('m')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000993 def return_wrong():
994 return 6
995 m.return_wrong = return_wrong
996
997 loader = unittest.TestLoader()
998 try:
999 suite = loader.loadTestsFromNames(['return_wrong'], m)
1000 except TypeError:
1001 pass
1002 else:
1003 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
1004
1005 # "The specifier can refer to modules and packages which have not been
1006 # imported; they will be imported as a side-effect"
1007 def test_loadTestsFromNames__module_not_loaded(self):
1008 # We're going to try to load this module as a side-effect, so it
1009 # better not be loaded before we try.
1010 #
1011 # Why pick audioop? Google shows it isn't used very often, so there's
1012 # a good chance that it won't be imported when this test is run
1013 module_name = 'audioop'
1014
1015 import sys
1016 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):
1973 import sys
1974
1975 class Foo(unittest.TestCase):
1976 def test_1(self):
1977 pass
1978
1979 test = Foo('test_1')
1980 try:
1981 test.fail("foo")
1982 except:
1983 exc_info_tuple = sys.exc_info()
1984
1985 result = unittest.TestResult()
1986
1987 result.startTest(test)
1988 result.addFailure(test, exc_info_tuple)
1989 result.stopTest(test)
1990
Benjamin Petersone1759f82009-06-30 23:35:19 +00001991 self.assertFalse(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001992 self.assertEqual(len(result.errors), 0)
1993 self.assertEqual(len(result.failures), 1)
1994 self.assertEqual(result.testsRun, 1)
1995 self.assertEqual(result.shouldStop, False)
1996
1997 test_case, formatted_exc = result.failures[0]
Benjamin Petersone1759f82009-06-30 23:35:19 +00001998 self.assertTrue(test_case is test)
Ezio Melottie9615932010-01-24 19:26:24 +00001999 self.assertIsInstance(formatted_exc, str)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002000
2001 # "addError(test, err)"
2002 # ...
2003 # "Called when the test case test raises an unexpected exception err
2004 # is a tuple of the form returned by sys.exc_info():
2005 # (type, value, traceback)"
2006 # ...
2007 # "wasSuccessful() - Returns True if all tests run so far have passed,
2008 # otherwise returns False"
2009 # ...
2010 # "testsRun - The total number of tests run so far."
2011 # ...
2012 # "errors - A list containing 2-tuples of TestCase instances and
2013 # formatted tracebacks. Each tuple represents a test which raised an
2014 # unexpected exception. Contains formatted
2015 # tracebacks instead of sys.exc_info() results."
2016 # ...
2017 # "failures - A list containing 2-tuples of TestCase instances and
2018 # formatted tracebacks. Each tuple represents a test where a failure was
2019 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
2020 # methods. Contains formatted tracebacks instead
2021 # of sys.exc_info() results."
2022 def test_addError(self):
2023 import sys
2024
2025 class Foo(unittest.TestCase):
2026 def test_1(self):
2027 pass
2028
2029 test = Foo('test_1')
2030 try:
2031 raise TypeError()
2032 except:
2033 exc_info_tuple = sys.exc_info()
2034
2035 result = unittest.TestResult()
2036
2037 result.startTest(test)
2038 result.addError(test, exc_info_tuple)
2039 result.stopTest(test)
2040
Benjamin Petersone1759f82009-06-30 23:35:19 +00002041 self.assertFalse(result.wasSuccessful())
Guido van Rossumd8faa362007-04-27 19:54:29 +00002042 self.assertEqual(len(result.errors), 1)
2043 self.assertEqual(len(result.failures), 0)
2044 self.assertEqual(result.testsRun, 1)
2045 self.assertEqual(result.shouldStop, False)
2046
2047 test_case, formatted_exc = result.errors[0]
Benjamin Petersone1759f82009-06-30 23:35:19 +00002048 self.assertTrue(test_case is test)
Ezio Melottie9615932010-01-24 19:26:24 +00002049 self.assertIsInstance(formatted_exc, str)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002050
2051### Support code for Test_TestCase
2052################################################################
2053
2054class Foo(unittest.TestCase):
2055 def runTest(self): pass
2056 def test1(self): pass
2057
2058class Bar(Foo):
2059 def test2(self): pass
2060
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002061class LoggingTestCase(unittest.TestCase):
2062 """A test case which logs its calls."""
2063
2064 def __init__(self, events):
2065 super(LoggingTestCase, self).__init__('test')
2066 self.events = events
2067
2068 def setUp(self):
2069 self.events.append('setUp')
2070
2071 def test(self):
2072 self.events.append('test')
2073
2074 def tearDown(self):
2075 self.events.append('tearDown')
2076
2077class ResultWithNoStartTestRunStopTestRun(object):
2078 """An object honouring TestResult before startTestRun/stopTestRun."""
2079
2080 def __init__(self):
2081 self.failures = []
2082 self.errors = []
2083 self.testsRun = 0
2084 self.skipped = []
2085 self.expectedFailures = []
2086 self.unexpectedSuccesses = []
2087 self.shouldStop = False
2088
2089 def startTest(self, test):
2090 pass
2091
2092 def stopTest(self, test):
2093 pass
2094
2095 def addError(self, test):
2096 pass
2097
2098 def addFailure(self, test):
2099 pass
2100
2101 def addSuccess(self, test):
2102 pass
2103
2104 def wasSuccessful(self):
2105 return True
2106
2107
Guido van Rossumd8faa362007-04-27 19:54:29 +00002108################################################################
2109### /Support code for Test_TestCase
2110
2111class Test_TestCase(TestCase, TestEquality, TestHashing):
2112
2113 ### Set up attributes used by inherited tests
2114 ################################################################
2115
2116 # Used by TestHashing.test_hash and TestEquality.test_eq
2117 eq_pairs = [(Foo('test1'), Foo('test1'))]
2118
2119 # Used by TestEquality.test_ne
2120 ne_pairs = [(Foo('test1'), Foo('runTest'))
2121 ,(Foo('test1'), Bar('test1'))
2122 ,(Foo('test1'), Bar('test2'))]
2123
2124 ################################################################
2125 ### /Set up attributes used by inherited tests
2126
2127
2128 # "class TestCase([methodName])"
2129 # ...
2130 # "Each instance of TestCase will run a single test method: the
2131 # method named methodName."
2132 # ...
2133 # "methodName defaults to "runTest"."
2134 #
2135 # Make sure it really is optional, and that it defaults to the proper
2136 # thing.
2137 def test_init__no_test_name(self):
2138 class Test(unittest.TestCase):
2139 def runTest(self): raise MyException()
2140 def test(self): pass
2141
2142 self.assertEqual(Test().id()[-13:], '.Test.runTest')
2143
2144 # "class TestCase([methodName])"
2145 # ...
2146 # "Each instance of TestCase will run a single test method: the
2147 # method named methodName."
2148 def test_init__test_name__valid(self):
2149 class Test(unittest.TestCase):
2150 def runTest(self): raise MyException()
2151 def test(self): pass
2152
2153 self.assertEqual(Test('test').id()[-10:], '.Test.test')
2154
2155 # "class TestCase([methodName])"
2156 # ...
2157 # "Each instance of TestCase will run a single test method: the
2158 # method named methodName."
2159 def test_init__test_name__invalid(self):
2160 class Test(unittest.TestCase):
2161 def runTest(self): raise MyException()
2162 def test(self): pass
2163
2164 try:
2165 Test('testfoo')
2166 except ValueError:
2167 pass
2168 else:
2169 self.fail("Failed to raise ValueError")
2170
2171 # "Return the number of tests represented by the this test object. For
2172 # TestCase instances, this will always be 1"
2173 def test_countTestCases(self):
2174 class Foo(unittest.TestCase):
2175 def test(self): pass
2176
2177 self.assertEqual(Foo('test').countTestCases(), 1)
2178
2179 # "Return the default type of test result object to be used to run this
2180 # test. For TestCase instances, this will always be
2181 # unittest.TestResult; subclasses of TestCase should
2182 # override this as necessary."
2183 def test_defaultTestResult(self):
2184 class Foo(unittest.TestCase):
2185 def runTest(self):
2186 pass
2187
2188 result = Foo().defaultTestResult()
2189 self.assertEqual(type(result), unittest.TestResult)
2190
2191 # "When a setUp() method is defined, the test runner will run that method
2192 # prior to each test. Likewise, if a tearDown() method is defined, the
2193 # test runner will invoke that method after each test. In the example,
2194 # setUp() was used to create a fresh sequence for each test."
2195 #
2196 # Make sure the proper call order is maintained, even if setUp() raises
2197 # an exception.
2198 def test_run_call_order__error_in_setUp(self):
2199 events = []
2200 result = LoggingResult(events)
2201
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002202 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002203 def setUp(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002204 super(Foo, self).setUp()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002205 raise RuntimeError('raised by Foo.setUp')
2206
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002207 Foo(events).run(result)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002208 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2209 self.assertEqual(events, expected)
2210
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002211 # "With a temporary result stopTestRun is called when setUp errors.
2212 def test_run_call_order__error_in_setUp_default_result(self):
2213 events = []
2214
2215 class Foo(LoggingTestCase):
2216 def defaultTestResult(self):
2217 return LoggingResult(self.events)
2218
2219 def setUp(self):
2220 super(Foo, self).setUp()
2221 raise RuntimeError('raised by Foo.setUp')
2222
2223 Foo(events).run()
2224 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2225 'stopTest', 'stopTestRun']
2226 self.assertEqual(events, expected)
2227
Guido van Rossumd8faa362007-04-27 19:54:29 +00002228 # "When a setUp() method is defined, the test runner will run that method
2229 # prior to each test. Likewise, if a tearDown() method is defined, the
2230 # test runner will invoke that method after each test. In the example,
2231 # setUp() was used to create a fresh sequence for each test."
2232 #
2233 # Make sure the proper call order is maintained, even if the test raises
2234 # an error (as opposed to a failure).
2235 def test_run_call_order__error_in_test(self):
2236 events = []
2237 result = LoggingResult(events)
2238
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002239 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002240 def test(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002241 super(Foo, self).test()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002242 raise RuntimeError('raised by Foo.test')
2243
Guido van Rossumd8faa362007-04-27 19:54:29 +00002244 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2245 'stopTest']
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002246 Foo(events).run(result)
2247 self.assertEqual(events, expected)
2248
2249 # "With a default result, an error in the test still results in stopTestRun
2250 # being called."
2251 def test_run_call_order__error_in_test_default_result(self):
2252 events = []
2253
2254 class Foo(LoggingTestCase):
2255 def defaultTestResult(self):
2256 return LoggingResult(self.events)
2257
2258 def test(self):
2259 super(Foo, self).test()
2260 raise RuntimeError('raised by Foo.test')
2261
2262 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2263 'tearDown', 'stopTest', 'stopTestRun']
2264 Foo(events).run()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002265 self.assertEqual(events, expected)
2266
2267 # "When a setUp() method is defined, the test runner will run that method
2268 # prior to each test. Likewise, if a tearDown() method is defined, the
2269 # test runner will invoke that method after each test. In the example,
2270 # setUp() was used to create a fresh sequence for each test."
2271 #
2272 # Make sure the proper call order is maintained, even if the test signals
2273 # a failure (as opposed to an error).
2274 def test_run_call_order__failure_in_test(self):
2275 events = []
2276 result = LoggingResult(events)
2277
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002278 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002279 def test(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002280 super(Foo, self).test()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002281 self.fail('raised by Foo.test')
2282
Guido van Rossumd8faa362007-04-27 19:54:29 +00002283 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2284 'stopTest']
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002285 Foo(events).run(result)
2286 self.assertEqual(events, expected)
2287
2288 # "When a test fails with a default result stopTestRun is still called."
2289 def test_run_call_order__failure_in_test_default_result(self):
2290
2291 class Foo(LoggingTestCase):
2292 def defaultTestResult(self):
2293 return LoggingResult(self.events)
2294 def test(self):
2295 super(Foo, self).test()
2296 self.fail('raised by Foo.test')
2297
2298 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2299 'tearDown', 'stopTest', 'stopTestRun']
2300 events = []
2301 Foo(events).run()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002302 self.assertEqual(events, expected)
2303
2304 # "When a setUp() method is defined, the test runner will run that method
2305 # prior to each test. Likewise, if a tearDown() method is defined, the
2306 # test runner will invoke that method after each test. In the example,
2307 # setUp() was used to create a fresh sequence for each test."
2308 #
2309 # Make sure the proper call order is maintained, even if tearDown() raises
2310 # an exception.
2311 def test_run_call_order__error_in_tearDown(self):
2312 events = []
2313 result = LoggingResult(events)
2314
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002315 class Foo(LoggingTestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002316 def tearDown(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002317 super(Foo, self).tearDown()
Guido van Rossumd8faa362007-04-27 19:54:29 +00002318 raise RuntimeError('raised by Foo.tearDown')
2319
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002320 Foo(events).run(result)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002321 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2322 'stopTest']
2323 self.assertEqual(events, expected)
2324
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002325 # "When tearDown errors with a default result stopTestRun is still called."
2326 def test_run_call_order__error_in_tearDown_default_result(self):
2327
2328 class Foo(LoggingTestCase):
2329 def defaultTestResult(self):
2330 return LoggingResult(self.events)
2331 def tearDown(self):
2332 super(Foo, self).tearDown()
2333 raise RuntimeError('raised by Foo.tearDown')
2334
2335 events = []
2336 Foo(events).run()
2337 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2338 'addError', 'stopTest', 'stopTestRun']
2339 self.assertEqual(events, expected)
2340
2341 # "TestCase.run() still works when the defaultTestResult is a TestResult
2342 # that does not support startTestRun and stopTestRun.
2343 def test_run_call_order_default_result(self):
2344
2345 class Foo(unittest.TestCase):
2346 def defaultTestResult(self):
2347 return ResultWithNoStartTestRunStopTestRun()
2348 def test(self):
2349 pass
2350
2351 Foo('test').run()
2352
Guido van Rossumd8faa362007-04-27 19:54:29 +00002353 # "This class attribute gives the exception raised by the test() method.
2354 # If a test framework needs to use a specialized exception, possibly to
2355 # carry additional information, it must subclass this exception in
2356 # order to ``play fair'' with the framework. The initial value of this
2357 # attribute is AssertionError"
2358 def test_failureException__default(self):
2359 class Foo(unittest.TestCase):
2360 def test(self):
2361 pass
2362
Benjamin Petersone1759f82009-06-30 23:35:19 +00002363 self.assertTrue(Foo('test').failureException is AssertionError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002364
2365 # "This class attribute gives the exception raised by the test() method.
2366 # If a test framework needs to use a specialized exception, possibly to
2367 # carry additional information, it must subclass this exception in
2368 # order to ``play fair'' with the framework."
2369 #
2370 # Make sure TestCase.run() respects the designated failureException
2371 def test_failureException__subclassing__explicit_raise(self):
2372 events = []
2373 result = LoggingResult(events)
2374
2375 class Foo(unittest.TestCase):
2376 def test(self):
2377 raise RuntimeError()
2378
2379 failureException = RuntimeError
2380
Benjamin Petersone1759f82009-06-30 23:35:19 +00002381 self.assertTrue(Foo('test').failureException is RuntimeError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002382
2383
2384 Foo('test').run(result)
2385 expected = ['startTest', 'addFailure', 'stopTest']
2386 self.assertEqual(events, expected)
2387
2388 # "This class attribute gives the exception raised by the test() method.
2389 # If a test framework needs to use a specialized exception, possibly to
2390 # carry additional information, it must subclass this exception in
2391 # order to ``play fair'' with the framework."
2392 #
2393 # Make sure TestCase.run() respects the designated failureException
2394 def test_failureException__subclassing__implicit_raise(self):
2395 events = []
2396 result = LoggingResult(events)
2397
2398 class Foo(unittest.TestCase):
2399 def test(self):
2400 self.fail("foo")
2401
2402 failureException = RuntimeError
2403
Benjamin Petersone1759f82009-06-30 23:35:19 +00002404 self.assertTrue(Foo('test').failureException is RuntimeError)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002405
2406
2407 Foo('test').run(result)
2408 expected = ['startTest', 'addFailure', 'stopTest']
2409 self.assertEqual(events, expected)
2410
2411 # "The default implementation does nothing."
2412 def test_setUp(self):
2413 class Foo(unittest.TestCase):
2414 def runTest(self):
2415 pass
2416
2417 # ... and nothing should happen
2418 Foo().setUp()
2419
2420 # "The default implementation does nothing."
2421 def test_tearDown(self):
2422 class Foo(unittest.TestCase):
2423 def runTest(self):
2424 pass
2425
2426 # ... and nothing should happen
2427 Foo().tearDown()
2428
2429 # "Return a string identifying the specific test case."
2430 #
2431 # Because of the vague nature of the docs, I'm not going to lock this
2432 # test down too much. Really all that can be asserted is that the id()
2433 # will be a string (either 8-byte or unicode -- again, because the docs
2434 # just say "string")
2435 def test_id(self):
2436 class Foo(unittest.TestCase):
2437 def runTest(self):
2438 pass
2439
Ezio Melottie9615932010-01-24 19:26:24 +00002440 self.assertIsInstance(Foo().id(), str)
2441
Guido van Rossumd8faa362007-04-27 19:54:29 +00002442
Guido van Rossumd8faa362007-04-27 19:54:29 +00002443 # "If result is omitted or None, a temporary result object is created
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002444 # and used, but is not made available to the caller. As TestCase owns the
2445 # temporary result startTestRun and stopTestRun are called.
2446
Guido van Rossumd8faa362007-04-27 19:54:29 +00002447 def test_run__uses_defaultTestResult(self):
2448 events = []
2449
2450 class Foo(unittest.TestCase):
2451 def test(self):
2452 events.append('test')
2453
2454 def defaultTestResult(self):
2455 return LoggingResult(events)
2456
2457 # Make run() find a result object on its own
2458 Foo('test').run()
2459
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002460 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2461 'stopTest', 'stopTestRun']
Guido van Rossumd8faa362007-04-27 19:54:29 +00002462 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002463
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002464 def testShortDescriptionWithoutDocstring(self):
2465 self.assertEqual(
2466 self.shortDescription(),
2467 'testShortDescriptionWithoutDocstring (' + __name__ +
2468 '.Test_TestCase)')
2469
2470 def testShortDescriptionWithOneLineDocstring(self):
2471 """Tests shortDescription() for a method with a docstring."""
2472 self.assertEqual(
2473 self.shortDescription(),
2474 ('testShortDescriptionWithOneLineDocstring '
2475 '(' + __name__ + '.Test_TestCase)\n'
2476 'Tests shortDescription() for a method with a docstring.'))
2477
2478 def testShortDescriptionWithMultiLineDocstring(self):
2479 """Tests shortDescription() for a method with a longer docstring.
2480
2481 This method ensures that only the first line of a docstring is
2482 returned used in the short description, no matter how long the
2483 whole thing is.
2484 """
2485 self.assertEqual(
2486 self.shortDescription(),
2487 ('testShortDescriptionWithMultiLineDocstring '
2488 '(' + __name__ + '.Test_TestCase)\n'
2489 'Tests shortDescription() for a method with a longer '
2490 'docstring.'))
2491
2492 def testAddTypeEqualityFunc(self):
2493 class SadSnake(object):
2494 """Dummy class for test_addTypeEqualityFunc."""
2495 s1, s2 = SadSnake(), SadSnake()
2496 self.assertFalse(s1 == s2)
2497 def AllSnakesCreatedEqual(a, b, msg=None):
2498 return type(a) == type(b) == SadSnake
2499 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2500 self.assertEqual(s1, s2)
2501 # No this doesn't clean up and remove the SadSnake equality func
2502 # from this TestCase instance but since its a local nothing else
2503 # will ever notice that.
2504
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00002505 def testAssertIs(self):
2506 thing = object()
2507 self.assertIs(thing, thing)
2508 self.assertRaises(self.failureException, self.assertIs, thing, object())
2509
2510 def testAssertIsNot(self):
2511 thing = object()
2512 self.assertIsNot(thing, object())
2513 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2514
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00002515 def testAssertIsInstance(self):
2516 thing = []
2517 self.assertIsInstance(thing, list)
2518 self.assertRaises(self.failureException, self.assertIsInstance,
2519 thing, dict)
2520
2521 def testAssertNotIsInstance(self):
2522 thing = []
2523 self.assertNotIsInstance(thing, dict)
2524 self.assertRaises(self.failureException, self.assertNotIsInstance,
2525 thing, list)
2526
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002527 def testAssertIn(self):
2528 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2529
2530 self.assertIn('a', 'abc')
2531 self.assertIn(2, [1, 2, 3])
2532 self.assertIn('monkey', animals)
2533
2534 self.assertNotIn('d', 'abc')
2535 self.assertNotIn(0, [1, 2, 3])
2536 self.assertNotIn('otter', animals)
2537
2538 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2539 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2540 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2541 animals)
2542
2543 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2544 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2545 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2546 animals)
2547
2548 def testAssertDictContainsSubset(self):
2549 self.assertDictContainsSubset({}, {})
2550 self.assertDictContainsSubset({}, {'a': 1})
2551 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2552 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2553 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2554
2555 self.assertRaises(unittest.TestCase.failureException,
2556 self.assertDictContainsSubset, {'a': 2}, {'a': 1},
2557 '.*Mismatched values:.*')
2558
2559 self.assertRaises(unittest.TestCase.failureException,
2560 self.assertDictContainsSubset, {'c': 1}, {'a': 1},
2561 '.*Missing:.*')
2562
2563 self.assertRaises(unittest.TestCase.failureException,
2564 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2565 {'a': 1}, '.*Missing:.*')
2566
2567 self.assertRaises(unittest.TestCase.failureException,
2568 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2569 {'a': 1}, '.*Missing:.*Mismatched values:.*')
2570
2571 def testAssertEqual(self):
2572 equal_pairs = [
2573 ((), ()),
2574 ({}, {}),
2575 ([], []),
2576 (set(), set()),
2577 (frozenset(), frozenset())]
2578 for a, b in equal_pairs:
2579 # This mess of try excepts is to test the assertEqual behavior
2580 # itself.
2581 try:
2582 self.assertEqual(a, b)
2583 except self.failureException:
2584 self.fail('assertEqual(%r, %r) failed' % (a, b))
2585 try:
2586 self.assertEqual(a, b, msg='foo')
2587 except self.failureException:
2588 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2589 try:
2590 self.assertEqual(a, b, 'foo')
2591 except self.failureException:
2592 self.fail('assertEqual(%r, %r) with third parameter failed' %
2593 (a, b))
2594
2595 unequal_pairs = [
2596 ((), []),
2597 ({}, set()),
2598 (set([4,1]), frozenset([4,2])),
2599 (frozenset([4,5]), set([2,3])),
2600 (set([3,4]), set([5,4]))]
2601 for a, b in unequal_pairs:
2602 self.assertRaises(self.failureException, self.assertEqual, a, b)
2603 self.assertRaises(self.failureException, self.assertEqual, a, b,
2604 'foo')
2605 self.assertRaises(self.failureException, self.assertEqual, a, b,
2606 msg='foo')
2607
2608 def testEquality(self):
2609 self.assertListEqual([], [])
2610 self.assertTupleEqual((), ())
2611 self.assertSequenceEqual([], ())
2612
2613 a = [0, 'a', []]
2614 b = []
2615 self.assertRaises(unittest.TestCase.failureException,
2616 self.assertListEqual, a, b)
2617 self.assertRaises(unittest.TestCase.failureException,
2618 self.assertListEqual, tuple(a), tuple(b))
2619 self.assertRaises(unittest.TestCase.failureException,
2620 self.assertSequenceEqual, a, tuple(b))
2621
2622 b.extend(a)
2623 self.assertListEqual(a, b)
2624 self.assertTupleEqual(tuple(a), tuple(b))
2625 self.assertSequenceEqual(a, tuple(b))
2626 self.assertSequenceEqual(tuple(a), b)
2627
2628 self.assertRaises(self.failureException, self.assertListEqual,
2629 a, tuple(b))
2630 self.assertRaises(self.failureException, self.assertTupleEqual,
2631 tuple(a), b)
2632 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2633 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2634 tuple(b))
2635 self.assertRaises(self.failureException, self.assertSequenceEqual,
2636 None, tuple(b))
2637 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2638 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2639 self.assertRaises(self.failureException, self.assertSequenceEqual,
2640 1, 1)
2641
2642 self.assertDictEqual({}, {})
2643
2644 c = { 'x': 1 }
2645 d = {}
2646 self.assertRaises(unittest.TestCase.failureException,
2647 self.assertDictEqual, c, d)
2648
2649 d.update(c)
2650 self.assertDictEqual(c, d)
2651
2652 d['x'] = 0
2653 self.assertRaises(unittest.TestCase.failureException,
2654 self.assertDictEqual, c, d, 'These are unequal')
2655
2656 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2657 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2658 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2659
2660 self.assertSameElements([1, 2, 3], [3, 2, 1])
2661 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2662 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2663 self.assertRaises(self.failureException, self.assertSameElements,
2664 [10], [10, 11])
2665 self.assertRaises(self.failureException, self.assertSameElements,
2666 [10, 11], [10])
2667
2668 # Test that sequences of unhashable objects can be tested for sameness:
2669 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00002670
Benjamin Peterson3bb6b7a2009-04-04 16:46:24 +00002671 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002672 self.assertRaises(self.failureException, self.assertSameElements,
2673 [[1]], [[2]])
Michael Foorda5809c82009-04-04 18:55:09 +00002674 self.assertRaises(self.failureException, self.assertSameElements,
2675 [{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 2}])
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002676
2677 def testAssertSetEqual(self):
2678 set1 = set()
2679 set2 = set()
2680 self.assertSetEqual(set1, set2)
2681
2682 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2683 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2684 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2685 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2686
2687 set1 = set(['a'])
2688 set2 = set()
2689 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2690
2691 set1 = set(['a'])
2692 set2 = set(['a'])
2693 self.assertSetEqual(set1, set2)
2694
2695 set1 = set(['a'])
2696 set2 = set(['a', 'b'])
2697 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2698
2699 set1 = set(['a'])
2700 set2 = frozenset(['a', 'b'])
2701 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2702
2703 set1 = set(['a', 'b'])
2704 set2 = frozenset(['a', 'b'])
2705 self.assertSetEqual(set1, set2)
2706
2707 set1 = set()
2708 set2 = "foo"
2709 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2710 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2711
2712 # make sure any string formatting is tuple-safe
2713 set1 = set([(0, 1), (2, 3)])
2714 set2 = set([(4, 5)])
2715 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2716
2717 def testInequality(self):
2718 # Try ints
2719 self.assertGreater(2, 1)
2720 self.assertGreaterEqual(2, 1)
2721 self.assertGreaterEqual(1, 1)
2722 self.assertLess(1, 2)
2723 self.assertLessEqual(1, 2)
2724 self.assertLessEqual(1, 1)
2725 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2726 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2727 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2728 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2729 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2730 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2731
2732 # Try Floats
2733 self.assertGreater(1.1, 1.0)
2734 self.assertGreaterEqual(1.1, 1.0)
2735 self.assertGreaterEqual(1.0, 1.0)
2736 self.assertLess(1.0, 1.1)
2737 self.assertLessEqual(1.0, 1.1)
2738 self.assertLessEqual(1.0, 1.0)
2739 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2740 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2741 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2742 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2743 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2744 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2745
2746 # Try Strings
2747 self.assertGreater('bug', 'ant')
2748 self.assertGreaterEqual('bug', 'ant')
2749 self.assertGreaterEqual('ant', 'ant')
2750 self.assertLess('ant', 'bug')
2751 self.assertLessEqual('ant', 'bug')
2752 self.assertLessEqual('ant', 'ant')
2753 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2754 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2755 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2756 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2757 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2758 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2759
2760 # Try bytes
2761 self.assertGreater(b'bug', b'ant')
2762 self.assertGreaterEqual(b'bug', b'ant')
2763 self.assertGreaterEqual(b'ant', b'ant')
2764 self.assertLess(b'ant', b'bug')
2765 self.assertLessEqual(b'ant', b'bug')
2766 self.assertLessEqual(b'ant', b'ant')
2767 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'bug')
2768 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'ant')
2769 self.assertRaises(self.failureException, self.assertGreaterEqual, b'ant',
2770 b'bug')
2771 self.assertRaises(self.failureException, self.assertLess, b'bug', b'ant')
2772 self.assertRaises(self.failureException, self.assertLess, b'ant', b'ant')
2773 self.assertRaises(self.failureException, self.assertLessEqual, b'bug', b'ant')
2774
2775 def testAssertMultiLineEqual(self):
2776 sample_text = """\
2777http://www.python.org/doc/2.3/lib/module-unittest.html
2778test case
2779 A test case is the smallest unit of testing. [...]
2780"""
2781 revised_sample_text = """\
2782http://www.python.org/doc/2.4.1/lib/module-unittest.html
2783test case
2784 A test case is the smallest unit of testing. [...] You may provide your
2785 own implementation that does not subclass from TestCase, of course.
2786"""
2787 sample_text_error = """
2788- http://www.python.org/doc/2.3/lib/module-unittest.html
2789? ^
2790+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2791? ^^^
2792 test case
2793- A test case is the smallest unit of testing. [...]
2794+ A test case is the smallest unit of testing. [...] You may provide your
2795? +++++++++++++++++++++
2796+ own implementation that does not subclass from TestCase, of course.
2797"""
2798
2799 try:
2800 self.assertMultiLineEqual(sample_text, revised_sample_text)
2801 except self.failureException as e:
2802 # no fair testing ourself with ourself, use assertEqual..
2803 self.assertEqual(sample_text_error, str(e))
2804
2805 def testAssertIsNone(self):
2806 self.assertIsNone(None)
2807 self.assertRaises(self.failureException, self.assertIsNone, False)
2808 self.assertIsNotNone('DjZoPloGears on Rails')
2809 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2810
2811 def testAssertRegexpMatches(self):
2812 self.assertRegexpMatches('asdfabasdf', r'ab+')
2813 self.assertRaises(self.failureException, self.assertRegexpMatches,
2814 'saaas', r'aaaa')
2815
2816 def testAssertRaisesRegexp(self):
2817 class ExceptionMock(Exception):
2818 pass
2819
2820 def Stub():
2821 raise ExceptionMock('We expect')
2822
2823 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2824 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2825
2826 def testAssertNotRaisesRegexp(self):
2827 self.assertRaisesRegexp(
Benjamin Peterson4f75b642009-04-04 16:39:09 +00002828 self.failureException, '^Exception not raised by <lambda>$',
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002829 self.assertRaisesRegexp, Exception, re.compile('x'),
2830 lambda: None)
2831 self.assertRaisesRegexp(
Benjamin Peterson4f75b642009-04-04 16:39:09 +00002832 self.failureException, '^Exception not raised by <lambda>$',
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002833 self.assertRaisesRegexp, Exception, 'x',
2834 lambda: None)
2835
2836 def testAssertRaisesRegexpMismatch(self):
2837 def Stub():
2838 raise Exception('Unexpected')
2839
2840 self.assertRaisesRegexp(
2841 self.failureException,
2842 r'"\^Expected\$" does not match "Unexpected"',
2843 self.assertRaisesRegexp, Exception, '^Expected$',
2844 Stub)
2845 self.assertRaisesRegexp(
2846 self.failureException,
2847 r'"\^Expected\$" does not match "Unexpected"',
2848 self.assertRaisesRegexp, Exception,
2849 re.compile('^Expected$'), Stub)
2850
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +00002851 def testAssertRaisesExcValue(self):
2852 class ExceptionMock(Exception):
2853 pass
2854
2855 def Stub(foo):
2856 raise ExceptionMock(foo)
2857 v = "particular value"
2858
2859 ctx = self.assertRaises(ExceptionMock)
2860 with ctx:
2861 Stub(v)
2862 e = ctx.exc_value
Ezio Melottie9615932010-01-24 19:26:24 +00002863 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónsson92a653a2009-11-13 16:10:13 +00002864 self.assertEqual(e.args[0], v)
2865
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002866 def testSynonymAssertMethodNames(self):
2867 """Test undocumented method name synonyms.
2868
2869 Please do not use these methods names in your own code.
2870
2871 This test confirms their continued existence and functionality
2872 in order to avoid breaking existing code.
2873 """
2874 self.assertNotEquals(3, 5)
2875 self.assertEquals(3, 3)
2876 self.assertAlmostEquals(2.0, 2.0)
2877 self.assertNotAlmostEquals(3.0, 5.0)
2878 self.assert_(True)
2879
2880 def testPendingDeprecationMethodNames(self):
2881 """Test fail* methods pending deprecation, they will warn in 3.2.
2882
2883 Do not use these methods. They will go away in 3.3.
2884 """
Benjamin Peterson6bcbad52009-06-30 23:45:41 +00002885 old = (
2886 (self.failIfEqual, (3, 5)),
2887 (self.failUnlessEqual, (3, 3)),
2888 (self.failUnlessAlmostEqual, (2.0, 2.0)),
2889 (self.failIfAlmostEqual, (3.0, 5.0)),
2890 (self.failUnless, (True,)),
2891 (self.failUnlessRaises, (TypeError, lambda _: 3.14 + 'spam')),
2892 (self.failIf, (False,))
2893 )
2894 for meth, args in old:
2895 with warnings.catch_warnings(record=True) as w:
2896 meth(*args)
2897 self.assertEqual(len(w), 1)
2898 self.assertIs(w[0].category, DeprecationWarning)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002899
2900 def testDeepcopy(self):
2901 # Issue: 5660
2902 class TestableTest(TestCase):
2903 def testNothing(self):
2904 pass
2905
2906 test = TestableTest('testNothing')
2907
2908 # This shouldn't blow up
2909 deepcopy(test)
2910
Benjamin Peterson5254c042009-03-23 22:25:03 +00002911
2912class Test_TestSkipping(TestCase):
2913
2914 def test_skipping(self):
2915 class Foo(unittest.TestCase):
2916 def test_skip_me(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00002917 self.skipTest("skip")
Benjamin Peterson5254c042009-03-23 22:25:03 +00002918 events = []
2919 result = LoggingResult(events)
2920 test = Foo("test_skip_me")
2921 test.run(result)
2922 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2923 self.assertEqual(result.skipped, [(test, "skip")])
2924
2925 # Try letting setUp skip the test now.
2926 class Foo(unittest.TestCase):
2927 def setUp(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00002928 self.skipTest("testing")
Benjamin Peterson5254c042009-03-23 22:25:03 +00002929 def test_nothing(self): pass
2930 events = []
2931 result = LoggingResult(events)
2932 test = Foo("test_nothing")
2933 test.run(result)
2934 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2935 self.assertEqual(result.skipped, [(test, "testing")])
2936 self.assertEqual(result.testsRun, 1)
2937
2938 def test_skipping_decorators(self):
2939 op_table = ((unittest.skipUnless, False, True),
2940 (unittest.skipIf, True, False))
2941 for deco, do_skip, dont_skip in op_table:
2942 class Foo(unittest.TestCase):
2943 @deco(do_skip, "testing")
2944 def test_skip(self): pass
2945
2946 @deco(dont_skip, "testing")
2947 def test_dont_skip(self): pass
2948 test_do_skip = Foo("test_skip")
2949 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002950 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002951 events = []
2952 result = LoggingResult(events)
2953 suite.run(result)
2954 self.assertEqual(len(result.skipped), 1)
2955 expected = ['startTest', 'addSkip', 'stopTest',
2956 'startTest', 'addSuccess', 'stopTest']
2957 self.assertEqual(events, expected)
2958 self.assertEqual(result.testsRun, 2)
2959 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
2960 self.assertTrue(result.wasSuccessful())
2961
2962 def test_skip_class(self):
2963 @unittest.skip("testing")
2964 class Foo(unittest.TestCase):
2965 def test_1(self):
2966 record.append(1)
2967 record = []
2968 result = unittest.TestResult()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002969 test = Foo("test_1")
2970 suite = unittest.TestSuite([test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002971 suite.run(result)
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002972 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002973 self.assertEqual(record, [])
2974
2975 def test_expected_failure(self):
2976 class Foo(unittest.TestCase):
2977 @unittest.expectedFailure
2978 def test_die(self):
2979 self.fail("help me!")
2980 events = []
2981 result = LoggingResult(events)
2982 test = Foo("test_die")
2983 test.run(result)
2984 self.assertEqual(events,
2985 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Peterson52baa292009-03-24 00:56:30 +00002986 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson5254c042009-03-23 22:25:03 +00002987 self.assertTrue(result.wasSuccessful())
2988
2989 def test_unexpected_success(self):
2990 class Foo(unittest.TestCase):
2991 @unittest.expectedFailure
2992 def test_die(self):
2993 pass
2994 events = []
2995 result = LoggingResult(events)
2996 test = Foo("test_die")
2997 test.run(result)
2998 self.assertEqual(events,
2999 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3000 self.assertFalse(result.failures)
Benjamin Peterson52baa292009-03-24 00:56:30 +00003001 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00003002 self.assertTrue(result.wasSuccessful())
3003
3004
3005
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003006class Test_Assertions(TestCase):
3007 def test_AlmostEqual(self):
Benjamin Petersone1759f82009-06-30 23:35:19 +00003008 self.assertAlmostEqual(1.00000001, 1.0)
3009 self.assertNotAlmostEqual(1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003010 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003011 self.assertAlmostEqual, 1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003012 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003013 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003014
Benjamin Petersone1759f82009-06-30 23:35:19 +00003015 self.assertAlmostEqual(1.1, 1.0, places=0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003016 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003017 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003018
Benjamin Petersone1759f82009-06-30 23:35:19 +00003019 self.assertAlmostEqual(0, .1+.1j, places=0)
3020 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003021 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003022 self.assertAlmostEqual, 0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003023 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003024 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003025
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003026 self.assertAlmostEqual(float('inf'), float('inf'))
3027 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3028 float('inf'), float('inf'))
3029
3030
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003031 def test_assertRaises(self):
3032 def _raise(e):
3033 raise e
3034 self.assertRaises(KeyError, _raise, KeyError)
3035 self.assertRaises(KeyError, _raise, KeyError("key"))
3036 try:
3037 self.assertRaises(KeyError, lambda: None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003038 except self.failureException as e:
Ezio Melottib58e0bd2010-01-23 15:40:09 +00003039 self.assertIn("KeyError not raised", str(e))
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003040 else:
3041 self.fail("assertRaises() didn't fail")
3042 try:
3043 self.assertRaises(KeyError, _raise, ValueError)
3044 except ValueError:
3045 pass
3046 else:
3047 self.fail("assertRaises() didn't let exception pass through")
3048 with self.assertRaises(KeyError):
3049 raise KeyError
3050 with self.assertRaises(KeyError):
3051 raise KeyError("key")
3052 try:
3053 with self.assertRaises(KeyError):
3054 pass
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003055 except self.failureException as e:
Ezio Melottib58e0bd2010-01-23 15:40:09 +00003056 self.assertIn("KeyError not raised", str(e))
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003057 else:
3058 self.fail("assertRaises() didn't fail")
3059 try:
3060 with self.assertRaises(KeyError):
3061 raise ValueError
3062 except ValueError:
3063 pass
3064 else:
3065 self.fail("assertRaises() didn't let exception pass through")
3066
3067
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003068class TestLongMessage(TestCase):
3069 """Test that the individual asserts honour longMessage.
3070 This actually tests all the message behaviour for
3071 asserts that use longMessage."""
3072
3073 def setUp(self):
3074 class TestableTestFalse(TestCase):
3075 longMessage = False
3076 failureException = self.failureException
3077
3078 def testTest(self):
3079 pass
3080
3081 class TestableTestTrue(TestCase):
3082 longMessage = True
3083 failureException = self.failureException
3084
3085 def testTest(self):
3086 pass
3087
3088 self.testableTrue = TestableTestTrue('testTest')
3089 self.testableFalse = TestableTestFalse('testTest')
3090
3091 def testDefault(self):
3092 self.assertFalse(TestCase.longMessage)
3093
3094 def test_formatMsg(self):
3095 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3096 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3097
3098 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3099 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3100
3101 def assertMessages(self, methodName, args, errors):
3102 def getMethod(i):
3103 useTestableFalse = i < 2
3104 if useTestableFalse:
3105 test = self.testableFalse
3106 else:
3107 test = self.testableTrue
3108 return getattr(test, methodName)
3109
3110 for i, expected_regexp in enumerate(errors):
3111 testMethod = getMethod(i)
3112 kwargs = {}
3113 withMsg = i % 2
3114 if withMsg:
3115 kwargs = {"msg": "oops"}
3116
3117 with self.assertRaisesRegexp(self.failureException,
3118 expected_regexp=expected_regexp):
3119 testMethod(*args, **kwargs)
3120
3121 def testAssertTrue(self):
3122 self.assertMessages('assertTrue', (False,),
3123 ["^False is not True$", "^oops$", "^False is not True$",
3124 "^False is not True : oops$"])
3125
3126 def testAssertFalse(self):
3127 self.assertMessages('assertFalse', (True,),
3128 ["^True is not False$", "^oops$", "^True is not False$",
3129 "^True is not False : oops$"])
3130
3131 def testNotEqual(self):
3132 self.assertMessages('assertNotEqual', (1, 1),
3133 ["^1 == 1$", "^oops$", "^1 == 1$",
3134 "^1 == 1 : oops$"])
3135
3136 def testAlmostEqual(self):
3137 self.assertMessages('assertAlmostEqual', (1, 2),
3138 ["^1 != 2 within 7 places$", "^oops$",
3139 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3140
3141 def testNotAlmostEqual(self):
3142 self.assertMessages('assertNotAlmostEqual', (1, 1),
3143 ["^1 == 1 within 7 places$", "^oops$",
3144 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3145
3146 def test_baseAssertEqual(self):
3147 self.assertMessages('_baseAssertEqual', (1, 2),
3148 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3149
3150 def testAssertSequenceEqual(self):
3151 # Error messages are multiline so not testing on full message
3152 # assertTupleEqual and assertListEqual delegate to this method
3153 self.assertMessages('assertSequenceEqual', ([], [None]),
3154 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3155 r"\+ \[None\] : oops$"])
3156
3157 def testAssertSetEqual(self):
3158 self.assertMessages('assertSetEqual', (set(), set([None])),
3159 ["None$", "^oops$", "None$",
3160 "None : oops$"])
3161
3162 def testAssertIn(self):
3163 self.assertMessages('assertIn', (None, []),
3164 ['^None not found in \[\]$', "^oops$",
3165 '^None not found in \[\]$',
3166 '^None not found in \[\] : oops$'])
3167
3168 def testAssertNotIn(self):
3169 self.assertMessages('assertNotIn', (None, [None]),
3170 ['^None unexpectedly found in \[None\]$', "^oops$",
3171 '^None unexpectedly found in \[None\]$',
3172 '^None unexpectedly found in \[None\] : oops$'])
3173
3174 def testAssertDictEqual(self):
3175 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3176 [r"\+ \{'key': 'value'\}$", "^oops$",
3177 "\+ \{'key': 'value'\}$",
3178 "\+ \{'key': 'value'\} : oops$"])
3179
3180 def testAssertDictContainsSubset(self):
3181 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3182 ["^Missing: 'key'$", "^oops$",
3183 "^Missing: 'key'$",
3184 "^Missing: 'key' : oops$"])
3185
3186 def testAssertSameElements(self):
3187 self.assertMessages('assertSameElements', ([], [None]),
3188 [r"\[None\]$", "^oops$",
3189 r"\[None\]$",
3190 r"\[None\] : oops$"])
3191
3192 def testAssertMultiLineEqual(self):
3193 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3194 [r"\+ foo$", "^oops$",
3195 r"\+ foo$",
3196 r"\+ foo : oops$"])
3197
3198 def testAssertLess(self):
3199 self.assertMessages('assertLess', (2, 1),
3200 ["^2 not less than 1$", "^oops$",
3201 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3202
3203 def testAssertLessEqual(self):
3204 self.assertMessages('assertLessEqual', (2, 1),
3205 ["^2 not less than or equal to 1$", "^oops$",
3206 "^2 not less than or equal to 1$",
3207 "^2 not less than or equal to 1 : oops$"])
3208
3209 def testAssertGreater(self):
3210 self.assertMessages('assertGreater', (1, 2),
3211 ["^1 not greater than 2$", "^oops$",
3212 "^1 not greater than 2$",
3213 "^1 not greater than 2 : oops$"])
3214
3215 def testAssertGreaterEqual(self):
3216 self.assertMessages('assertGreaterEqual', (1, 2),
3217 ["^1 not greater than or equal to 2$", "^oops$",
3218 "^1 not greater than or equal to 2$",
3219 "^1 not greater than or equal to 2 : oops$"])
3220
3221 def testAssertIsNone(self):
3222 self.assertMessages('assertIsNone', ('not None',),
3223 ["^'not None' is not None$", "^oops$",
3224 "^'not None' is not None$",
3225 "^'not None' is not None : oops$"])
3226
3227 def testAssertIsNotNone(self):
3228 self.assertMessages('assertIsNotNone', (None,),
3229 ["^unexpectedly None$", "^oops$",
3230 "^unexpectedly None$",
3231 "^unexpectedly None : oops$"])
3232
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00003233 def testAssertIs(self):
3234 self.assertMessages('assertIs', (None, 'foo'),
3235 ["^None is not 'foo'$", "^oops$",
3236 "^None is not 'foo'$",
3237 "^None is not 'foo' : oops$"])
3238
3239 def testAssertIsNot(self):
3240 self.assertMessages('assertIsNot', (None, None),
3241 ["^unexpectedly identical: None$", "^oops$",
3242 "^unexpectedly identical: None$",
3243 "^unexpectedly identical: None : oops$"])
3244
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003245
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003246class TestCleanUp(TestCase):
3247
3248 def testCleanUp(self):
3249 class TestableTest(TestCase):
3250 def testNothing(self):
3251 pass
3252
3253 test = TestableTest('testNothing')
3254 self.assertEqual(test._cleanups, [])
3255
3256 cleanups = []
3257
3258 def cleanup1(*args, **kwargs):
3259 cleanups.append((1, args, kwargs))
3260
3261 def cleanup2(*args, **kwargs):
3262 cleanups.append((2, args, kwargs))
3263
3264 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3265 test.addCleanup(cleanup2)
3266
3267 self.assertEqual(test._cleanups,
3268 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3269 (cleanup2, (), {})])
3270
3271 result = test.doCleanups()
3272 self.assertTrue(result)
3273
3274 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3275
3276 def testCleanUpWithErrors(self):
3277 class TestableTest(TestCase):
3278 def testNothing(self):
3279 pass
3280
3281 class MockResult(object):
3282 errors = []
3283 def addError(self, test, exc_info):
3284 self.errors.append((test, exc_info))
3285
3286 result = MockResult()
3287 test = TestableTest('testNothing')
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00003288 test._resultForDoCleanups = result
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003289
3290 exc1 = Exception('foo')
3291 exc2 = Exception('bar')
3292 def cleanup1():
3293 raise exc1
3294
3295 def cleanup2():
3296 raise exc2
3297
3298 test.addCleanup(cleanup1)
3299 test.addCleanup(cleanup2)
3300
3301 self.assertFalse(test.doCleanups())
3302
3303 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3304 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3305 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3306
3307 def testCleanupInRun(self):
3308 blowUp = False
3309 ordering = []
3310
3311 class TestableTest(TestCase):
3312 def setUp(self):
3313 ordering.append('setUp')
3314 if blowUp:
3315 raise Exception('foo')
3316
3317 def testNothing(self):
3318 ordering.append('test')
3319
3320 def tearDown(self):
3321 ordering.append('tearDown')
3322
3323 test = TestableTest('testNothing')
3324
3325 def cleanup1():
3326 ordering.append('cleanup1')
3327 def cleanup2():
3328 ordering.append('cleanup2')
3329 test.addCleanup(cleanup1)
3330 test.addCleanup(cleanup2)
3331
3332 def success(some_test):
3333 self.assertEqual(some_test, test)
3334 ordering.append('success')
3335
3336 result = unittest.TestResult()
3337 result.addSuccess = success
3338
3339 test.run(result)
3340 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3341 'cleanup2', 'cleanup1', 'success'])
3342
3343 blowUp = True
3344 ordering = []
3345 test = TestableTest('testNothing')
3346 test.addCleanup(cleanup1)
3347 test.run(result)
3348 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3349
3350
3351class Test_TestProgram(TestCase):
3352
3353 # Horrible white box test
3354 def testNoExit(self):
3355 result = object()
3356 test = object()
3357
3358 class FakeRunner(object):
3359 def run(self, test):
3360 self.test = test
3361 return result
3362
3363 runner = FakeRunner()
3364
Benjamin Petersond2397752009-06-27 23:45:02 +00003365 oldParseArgs = TestProgram.parseArgs
3366 def restoreParseArgs():
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003367 TestProgram.parseArgs = oldParseArgs
Benjamin Petersond2397752009-06-27 23:45:02 +00003368 TestProgram.parseArgs = lambda *args: None
3369 self.addCleanup(restoreParseArgs)
3370
3371 def removeTest():
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003372 del TestProgram.test
Benjamin Petersond2397752009-06-27 23:45:02 +00003373 TestProgram.test = test
3374 self.addCleanup(removeTest)
3375
3376 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3377
3378 self.assertEqual(program.result, result)
3379 self.assertEqual(runner.test, test)
3380 self.assertEqual(program.verbosity, 2)
3381
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003382 class FooBar(unittest.TestCase):
3383 def testPass(self):
3384 assert True
3385 def testFail(self):
3386 assert False
3387
3388 class FooBarLoader(unittest.TestLoader):
3389 """Test loader that returns a suite containing FooBar."""
3390 def loadTestsFromModule(self, module):
3391 return self.suiteClass(
3392 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3393
3394
3395 def test_NonExit(self):
3396 program = unittest.main(exit=False,
3397 argv=["foobar"],
3398 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3399 testLoader=self.FooBarLoader())
3400 self.assertTrue(hasattr(program, 'result'))
3401
3402
3403 def test_Exit(self):
3404 self.assertRaises(
3405 SystemExit,
3406 unittest.main,
3407 argv=["foobar"],
3408 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3409 exit=True,
3410 testLoader=self.FooBarLoader())
3411
3412
3413 def test_ExitAsDefault(self):
3414 self.assertRaises(
3415 SystemExit,
3416 unittest.main,
3417 argv=["foobar"],
3418 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3419 testLoader=self.FooBarLoader())
3420
3421
3422class Test_TextTestRunner(TestCase):
3423 """Tests for TextTestRunner."""
3424
3425 def test_works_with_result_without_startTestRun_stopTestRun(self):
3426 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3427 separator2 = ''
3428 def printErrors(self):
3429 pass
3430
3431 class Runner(unittest.TextTestRunner):
3432 def __init__(self):
3433 super(Runner, self).__init__(io.StringIO())
3434
3435 def _makeResult(self):
3436 return OldTextResult()
3437
3438 runner = Runner()
3439 runner.run(unittest.TestSuite())
3440
3441 def test_startTestRun_stopTestRun_called(self):
3442 class LoggingTextResult(LoggingResult):
3443 separator2 = ''
3444 def printErrors(self):
3445 pass
3446
3447 class LoggingRunner(unittest.TextTestRunner):
3448 def __init__(self, events):
3449 super(LoggingRunner, self).__init__(io.StringIO())
3450 self._events = events
3451
3452 def _makeResult(self):
3453 return LoggingTextResult(self._events)
3454
3455 events = []
3456 runner = LoggingRunner(events)
3457 runner.run(unittest.TestSuite())
3458 expected = ['startTestRun', 'stopTestRun']
3459 self.assertEqual(events, expected)
3460
Antoine Pitrouc63ecee2009-11-10 21:34:48 +00003461 def test_pickle_unpickle(self):
3462 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3463 # required by test_multiprocessing under Windows (in verbose mode).
3464 stream = io.StringIO("foo")
3465 runner = unittest.TextTestRunner(stream)
3466 for protocol in range(2, pickle.HIGHEST_PROTOCOL + 1):
3467 s = pickle.dumps(runner, protocol)
3468 obj = pickle.loads(s)
3469 # StringIO objects never compare equal, a cheap test instead.
3470 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3471
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003472
Benjamin Petersond2397752009-06-27 23:45:02 +00003473class TestDiscovery(TestCase):
3474
3475 # Heavily mocked tests so I can avoid hitting the filesystem
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003476 def test_get_name_from_path(self):
Benjamin Petersond2397752009-06-27 23:45:02 +00003477 loader = unittest.TestLoader()
Benjamin Petersond2397752009-06-27 23:45:02 +00003478 loader._top_level_dir = '/foo'
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003479 name = loader._get_name_from_path('/foo/bar/baz.py')
3480 self.assertEqual(name, 'bar.baz')
Benjamin Petersond2397752009-06-27 23:45:02 +00003481
3482 if not __debug__:
3483 # asserts are off
3484 return
3485
3486 with self.assertRaises(AssertionError):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003487 loader._get_name_from_path('/bar/baz.py')
Benjamin Petersond2397752009-06-27 23:45:02 +00003488
3489 def test_find_tests(self):
3490 loader = unittest.TestLoader()
3491
3492 original_listdir = os.listdir
3493 def restore_listdir():
3494 os.listdir = original_listdir
3495 original_isfile = os.path.isfile
3496 def restore_isfile():
3497 os.path.isfile = original_isfile
3498 original_isdir = os.path.isdir
3499 def restore_isdir():
3500 os.path.isdir = original_isdir
3501
3502 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003503 'test.foo', 'test-not-a-module.py', 'another_dir'],
Benjamin Petersond2397752009-06-27 23:45:02 +00003504 ['test3.py', 'test4.py', ]]
3505 os.listdir = lambda path: path_lists.pop(0)
3506 self.addCleanup(restore_listdir)
3507
3508 def isdir(path):
3509 return path.endswith('dir')
3510 os.path.isdir = isdir
3511 self.addCleanup(restore_isdir)
3512
3513 def isfile(path):
3514 # another_dir is not a package and so shouldn't be recursed into
3515 return not path.endswith('dir') and not 'another_dir' in path
3516 os.path.isfile = isfile
3517 self.addCleanup(restore_isfile)
3518
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003519 loader._get_module_from_name = lambda path: path + ' module'
Benjamin Petersond2397752009-06-27 23:45:02 +00003520 loader.loadTestsFromModule = lambda module: module + ' tests'
3521
3522 loader._top_level_dir = '/foo'
3523 suite = list(loader._find_tests('/foo', 'test*.py'))
3524
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003525 expected = [name + ' module tests' for name in
3526 ('test1', 'test2')]
3527 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3528 ('test3', 'test4')])
Benjamin Petersond2397752009-06-27 23:45:02 +00003529 self.assertEqual(suite, expected)
3530
3531 def test_find_tests_with_package(self):
3532 loader = unittest.TestLoader()
3533
3534 original_listdir = os.listdir
3535 def restore_listdir():
3536 os.listdir = original_listdir
3537 original_isfile = os.path.isfile
3538 def restore_isfile():
3539 os.path.isfile = original_isfile
3540 original_isdir = os.path.isdir
3541 def restore_isdir():
3542 os.path.isdir = original_isdir
3543
3544 directories = ['a_directory', 'test_directory', 'test_directory2']
3545 path_lists = [directories, [], [], []]
3546 os.listdir = lambda path: path_lists.pop(0)
3547 self.addCleanup(restore_listdir)
3548
3549 os.path.isdir = lambda path: True
3550 self.addCleanup(restore_isdir)
3551
3552 os.path.isfile = lambda path: os.path.basename(path) not in directories
3553 self.addCleanup(restore_isfile)
3554
3555 class Module(object):
3556 paths = []
3557 load_tests_args = []
3558
3559 def __init__(self, path):
3560 self.path = path
3561 self.paths.append(path)
3562 if os.path.basename(path) == 'test_directory':
3563 def load_tests(loader, tests, pattern):
3564 self.load_tests_args.append((loader, tests, pattern))
3565 return 'load_tests'
3566 self.load_tests = load_tests
3567
3568 def __eq__(self, other):
3569 return self.path == other.path
3570
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003571 loader._get_module_from_name = lambda name: Module(name)
Benjamin Petersond2397752009-06-27 23:45:02 +00003572 def loadTestsFromModule(module, use_load_tests):
3573 if use_load_tests:
3574 raise self.failureException('use_load_tests should be False for packages')
3575 return module.path + ' module tests'
3576 loader.loadTestsFromModule = loadTestsFromModule
3577
3578 loader._top_level_dir = '/foo'
3579 # this time no '.py' on the pattern so that it can match
3580 # a test package
3581 suite = list(loader._find_tests('/foo', 'test*'))
3582
3583 # We should have loaded tests from the test_directory package by calling load_tests
3584 # and directly from the test_directory2 package
3585 self.assertEqual(suite,
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003586 ['load_tests', 'test_directory2' + ' module tests'])
3587 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Benjamin Petersond2397752009-06-27 23:45:02 +00003588
3589 # load_tests should have been called once with loader, tests and pattern
3590 self.assertEqual(Module.load_tests_args,
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003591 [(loader, 'test_directory' + ' module tests', 'test*')])
Benjamin Petersond2397752009-06-27 23:45:02 +00003592
3593 def test_discover(self):
3594 loader = unittest.TestLoader()
3595
3596 original_isfile = os.path.isfile
3597 def restore_isfile():
3598 os.path.isfile = original_isfile
3599
3600 os.path.isfile = lambda path: False
3601 self.addCleanup(restore_isfile)
3602
Nick Coghlan6ead5522009-10-18 13:19:33 +00003603 orig_sys_path = sys.path[:]
3604 def restore_path():
3605 sys.path[:] = orig_sys_path
3606 self.addCleanup(restore_path)
Benjamin Petersond2397752009-06-27 23:45:02 +00003607
Nick Coghlan6ead5522009-10-18 13:19:33 +00003608 full_path = os.path.abspath(os.path.normpath('/foo'))
Benjamin Petersond2397752009-06-27 23:45:02 +00003609 with self.assertRaises(ImportError):
3610 loader.discover('/foo/bar', top_level_dir='/foo')
3611
3612 self.assertEqual(loader._top_level_dir, full_path)
3613 self.assertIn(full_path, sys.path)
3614
3615 os.path.isfile = lambda path: True
3616 _find_tests_args = []
3617 def _find_tests(start_dir, pattern):
3618 _find_tests_args.append((start_dir, pattern))
3619 return ['tests']
3620 loader._find_tests = _find_tests
3621 loader.suiteClass = str
3622
3623 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3624
3625 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3626 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3627 self.assertEqual(suite, "['tests']")
3628 self.assertEqual(loader._top_level_dir, top_level_dir)
3629 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlan6ead5522009-10-18 13:19:33 +00003630 self.assertIn(top_level_dir, sys.path)
Benjamin Petersond2397752009-06-27 23:45:02 +00003631
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003632 def test_discover_with_modules_that_fail_to_import(self):
3633 loader = unittest.TestLoader()
3634
3635 listdir = os.listdir
3636 os.listdir = lambda _: ['test_this_does_not_exist.py']
3637 isfile = os.path.isfile
3638 os.path.isfile = lambda _: True
Nick Coghlan6ead5522009-10-18 13:19:33 +00003639 orig_sys_path = sys.path[:]
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003640 def restore():
3641 os.path.isfile = isfile
3642 os.listdir = listdir
Nick Coghlan6ead5522009-10-18 13:19:33 +00003643 sys.path[:] = orig_sys_path
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003644 self.addCleanup(restore)
3645
3646 suite = loader.discover('.')
Nick Coghlan6ead5522009-10-18 13:19:33 +00003647 self.assertIn(os.getcwd(), sys.path)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003648 self.assertEqual(suite.countTestCases(), 1)
3649 test = list(list(suite)[0])[0] # extract test from suite
3650
3651 with self.assertRaises(ImportError):
3652 test.test_this_does_not_exist()
3653
Benjamin Petersond2397752009-06-27 23:45:02 +00003654 def test_command_line_handling_parseArgs(self):
3655 # Haha - take that uninstantiable class
3656 program = object.__new__(TestProgram)
3657
3658 args = []
3659 def do_discovery(argv):
3660 args.extend(argv)
3661 program._do_discovery = do_discovery
3662 program.parseArgs(['something', 'discover'])
3663 self.assertEqual(args, [])
3664
3665 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3666 self.assertEqual(args, ['foo', 'bar'])
3667
3668 def test_command_line_handling_do_discovery_too_many_arguments(self):
3669 class Stop(Exception):
3670 pass
3671 def usageExit():
3672 raise Stop
3673
3674 program = object.__new__(TestProgram)
3675 program.usageExit = usageExit
3676
3677 with self.assertRaises(Stop):
3678 # too many args
3679 program._do_discovery(['one', 'two', 'three', 'four'])
3680
3681
3682 def test_command_line_handling_do_discovery_calls_loader(self):
3683 program = object.__new__(TestProgram)
3684
3685 class Loader(object):
3686 args = []
3687 def discover(self, start_dir, pattern, top_level_dir):
3688 self.args.append((start_dir, pattern, top_level_dir))
3689 return 'tests'
3690
3691 program._do_discovery(['-v'], Loader=Loader)
3692 self.assertEqual(program.verbosity, 2)
3693 self.assertEqual(program.test, 'tests')
3694 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3695
3696 Loader.args = []
3697 program = object.__new__(TestProgram)
3698 program._do_discovery(['--verbose'], Loader=Loader)
3699 self.assertEqual(program.test, 'tests')
3700 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3701
3702 Loader.args = []
3703 program = object.__new__(TestProgram)
3704 program._do_discovery([], Loader=Loader)
3705 self.assertEqual(program.test, 'tests')
3706 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3707
3708 Loader.args = []
3709 program = object.__new__(TestProgram)
3710 program._do_discovery(['fish'], Loader=Loader)
3711 self.assertEqual(program.test, 'tests')
3712 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3713
3714 Loader.args = []
3715 program = object.__new__(TestProgram)
3716 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3717 self.assertEqual(program.test, 'tests')
3718 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3719
3720 Loader.args = []
3721 program = object.__new__(TestProgram)
3722 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3723 self.assertEqual(program.test, 'tests')
3724 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3725
3726 Loader.args = []
3727 program = object.__new__(TestProgram)
3728 program._do_discovery(['-s', 'fish'], Loader=Loader)
3729 self.assertEqual(program.test, 'tests')
3730 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3731
3732 Loader.args = []
3733 program = object.__new__(TestProgram)
3734 program._do_discovery(['-t', 'fish'], Loader=Loader)
3735 self.assertEqual(program.test, 'tests')
3736 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3737
3738 Loader.args = []
3739 program = object.__new__(TestProgram)
3740 program._do_discovery(['-p', 'fish'], Loader=Loader)
3741 self.assertEqual(program.test, 'tests')
3742 self.assertEqual(Loader.args, [('.', 'fish', None)])
3743
3744 Loader.args = []
3745 program = object.__new__(TestProgram)
3746 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3747 self.assertEqual(program.test, 'tests')
3748 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3749 self.assertEqual(program.verbosity, 2)
3750
3751
Jim Fultonfafd8742004-08-28 15:22:12 +00003752######################################################################
3753## Main
3754######################################################################
3755
3756def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003757 support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003758 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003759 Test_TestSkipping, Test_Assertions, TestLongMessage,
Antoine Pitrouc63ecee2009-11-10 21:34:48 +00003760 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner)
Jim Fultonfafd8742004-08-28 15:22:12 +00003761
Guido van Rossumd8faa362007-04-27 19:54:29 +00003762if __name__ == "__main__":
Jim Fultonfafd8742004-08-28 15:22:12 +00003763 test_main()