blob: 9cdca96f62fdc1c31a92fc7c58f7593b34532258 [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)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000189 self.assertTrue(isinstance(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)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000208 self.assertTrue(isinstance(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)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000221 self.assertTrue(isinstance(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)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000235 self.assertTrue(isinstance(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)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000471 self.assertTrue(isinstance(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)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000487 self.assertTrue(isinstance(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)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000502 self.assertTrue(isinstance(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)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000541 self.assertTrue(isinstance(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)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000555 self.assertTrue(isinstance(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)
575 self.assertTrue(isinstance(suite, loader.suiteClass))
576 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)
595 self.assertTrue(isinstance(suite, loader.suiteClass))
596
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
Benjamin Petersone1759f82009-06-30 23:35:19 +0000635 self.assertTrue(isinstance(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 Petersone1759f82009-06-30 23:35:19 +0000639 self.assertTrue(module_name in 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([])
Benjamin Petersone1759f82009-06-30 23:35:19 +0000658 self.assertTrue(isinstance(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)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000673 self.assertTrue(isinstance(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)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000874 self.assertTrue(isinstance(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)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000890 self.assertTrue(isinstance(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)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000905 self.assertTrue(isinstance(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)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000942 self.assertTrue(isinstance(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)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000958 self.assertTrue(isinstance(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)
Benjamin Petersone1759f82009-06-30 23:35:19 +0000982 self.assertTrue(isinstance(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
Benjamin Petersone1759f82009-06-30 23:35:19 +00001023 self.assertTrue(isinstance(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 Petersone1759f82009-06-30 23:35:19 +00001027 self.assertTrue(module_name in 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
Benjamin Petersone1759f82009-06-30 23:35:19 +00001811 self.assertTrue(isinstance(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)
1999 self.assertTrue(isinstance(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)
2049 self.assertTrue(isinstance(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
Benjamin Petersone1759f82009-06-30 23:35:19 +00002440 self.assertTrue(isinstance(Foo().id(), str))
Guido van Rossumd8faa362007-04-27 19:54:29 +00002441
Guido van Rossumd8faa362007-04-27 19:54:29 +00002442 # "If result is omitted or None, a temporary result object is created
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002443 # and used, but is not made available to the caller. As TestCase owns the
2444 # temporary result startTestRun and stopTestRun are called.
2445
Guido van Rossumd8faa362007-04-27 19:54:29 +00002446 def test_run__uses_defaultTestResult(self):
2447 events = []
2448
2449 class Foo(unittest.TestCase):
2450 def test(self):
2451 events.append('test')
2452
2453 def defaultTestResult(self):
2454 return LoggingResult(events)
2455
2456 # Make run() find a result object on its own
2457 Foo('test').run()
2458
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002459 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2460 'stopTest', 'stopTestRun']
Guido van Rossumd8faa362007-04-27 19:54:29 +00002461 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002462
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002463 def testShortDescriptionWithoutDocstring(self):
2464 self.assertEqual(
2465 self.shortDescription(),
2466 'testShortDescriptionWithoutDocstring (' + __name__ +
2467 '.Test_TestCase)')
2468
2469 def testShortDescriptionWithOneLineDocstring(self):
2470 """Tests shortDescription() for a method with a docstring."""
2471 self.assertEqual(
2472 self.shortDescription(),
2473 ('testShortDescriptionWithOneLineDocstring '
2474 '(' + __name__ + '.Test_TestCase)\n'
2475 'Tests shortDescription() for a method with a docstring.'))
2476
2477 def testShortDescriptionWithMultiLineDocstring(self):
2478 """Tests shortDescription() for a method with a longer docstring.
2479
2480 This method ensures that only the first line of a docstring is
2481 returned used in the short description, no matter how long the
2482 whole thing is.
2483 """
2484 self.assertEqual(
2485 self.shortDescription(),
2486 ('testShortDescriptionWithMultiLineDocstring '
2487 '(' + __name__ + '.Test_TestCase)\n'
2488 'Tests shortDescription() for a method with a longer '
2489 'docstring.'))
2490
2491 def testAddTypeEqualityFunc(self):
2492 class SadSnake(object):
2493 """Dummy class for test_addTypeEqualityFunc."""
2494 s1, s2 = SadSnake(), SadSnake()
2495 self.assertFalse(s1 == s2)
2496 def AllSnakesCreatedEqual(a, b, msg=None):
2497 return type(a) == type(b) == SadSnake
2498 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2499 self.assertEqual(s1, s2)
2500 # No this doesn't clean up and remove the SadSnake equality func
2501 # from this TestCase instance but since its a local nothing else
2502 # will ever notice that.
2503
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00002504 def testAssertIs(self):
2505 thing = object()
2506 self.assertIs(thing, thing)
2507 self.assertRaises(self.failureException, self.assertIs, thing, object())
2508
2509 def testAssertIsNot(self):
2510 thing = object()
2511 self.assertIsNot(thing, object())
2512 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2513
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00002514 def testAssertIsInstance(self):
2515 thing = []
2516 self.assertIsInstance(thing, list)
2517 self.assertRaises(self.failureException, self.assertIsInstance,
2518 thing, dict)
2519
2520 def testAssertNotIsInstance(self):
2521 thing = []
2522 self.assertNotIsInstance(thing, dict)
2523 self.assertRaises(self.failureException, self.assertNotIsInstance,
2524 thing, list)
2525
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002526 def testAssertIn(self):
2527 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2528
2529 self.assertIn('a', 'abc')
2530 self.assertIn(2, [1, 2, 3])
2531 self.assertIn('monkey', animals)
2532
2533 self.assertNotIn('d', 'abc')
2534 self.assertNotIn(0, [1, 2, 3])
2535 self.assertNotIn('otter', animals)
2536
2537 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2538 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2539 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2540 animals)
2541
2542 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2543 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2544 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2545 animals)
2546
2547 def testAssertDictContainsSubset(self):
2548 self.assertDictContainsSubset({}, {})
2549 self.assertDictContainsSubset({}, {'a': 1})
2550 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2551 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2552 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2553
2554 self.assertRaises(unittest.TestCase.failureException,
2555 self.assertDictContainsSubset, {'a': 2}, {'a': 1},
2556 '.*Mismatched values:.*')
2557
2558 self.assertRaises(unittest.TestCase.failureException,
2559 self.assertDictContainsSubset, {'c': 1}, {'a': 1},
2560 '.*Missing:.*')
2561
2562 self.assertRaises(unittest.TestCase.failureException,
2563 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2564 {'a': 1}, '.*Missing:.*')
2565
2566 self.assertRaises(unittest.TestCase.failureException,
2567 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2568 {'a': 1}, '.*Missing:.*Mismatched values:.*')
2569
2570 def testAssertEqual(self):
2571 equal_pairs = [
2572 ((), ()),
2573 ({}, {}),
2574 ([], []),
2575 (set(), set()),
2576 (frozenset(), frozenset())]
2577 for a, b in equal_pairs:
2578 # This mess of try excepts is to test the assertEqual behavior
2579 # itself.
2580 try:
2581 self.assertEqual(a, b)
2582 except self.failureException:
2583 self.fail('assertEqual(%r, %r) failed' % (a, b))
2584 try:
2585 self.assertEqual(a, b, msg='foo')
2586 except self.failureException:
2587 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2588 try:
2589 self.assertEqual(a, b, 'foo')
2590 except self.failureException:
2591 self.fail('assertEqual(%r, %r) with third parameter failed' %
2592 (a, b))
2593
2594 unequal_pairs = [
2595 ((), []),
2596 ({}, set()),
2597 (set([4,1]), frozenset([4,2])),
2598 (frozenset([4,5]), set([2,3])),
2599 (set([3,4]), set([5,4]))]
2600 for a, b in unequal_pairs:
2601 self.assertRaises(self.failureException, self.assertEqual, a, b)
2602 self.assertRaises(self.failureException, self.assertEqual, a, b,
2603 'foo')
2604 self.assertRaises(self.failureException, self.assertEqual, a, b,
2605 msg='foo')
2606
2607 def testEquality(self):
2608 self.assertListEqual([], [])
2609 self.assertTupleEqual((), ())
2610 self.assertSequenceEqual([], ())
2611
2612 a = [0, 'a', []]
2613 b = []
2614 self.assertRaises(unittest.TestCase.failureException,
2615 self.assertListEqual, a, b)
2616 self.assertRaises(unittest.TestCase.failureException,
2617 self.assertListEqual, tuple(a), tuple(b))
2618 self.assertRaises(unittest.TestCase.failureException,
2619 self.assertSequenceEqual, a, tuple(b))
2620
2621 b.extend(a)
2622 self.assertListEqual(a, b)
2623 self.assertTupleEqual(tuple(a), tuple(b))
2624 self.assertSequenceEqual(a, tuple(b))
2625 self.assertSequenceEqual(tuple(a), b)
2626
2627 self.assertRaises(self.failureException, self.assertListEqual,
2628 a, tuple(b))
2629 self.assertRaises(self.failureException, self.assertTupleEqual,
2630 tuple(a), b)
2631 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2632 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2633 tuple(b))
2634 self.assertRaises(self.failureException, self.assertSequenceEqual,
2635 None, tuple(b))
2636 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2637 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2638 self.assertRaises(self.failureException, self.assertSequenceEqual,
2639 1, 1)
2640
2641 self.assertDictEqual({}, {})
2642
2643 c = { 'x': 1 }
2644 d = {}
2645 self.assertRaises(unittest.TestCase.failureException,
2646 self.assertDictEqual, c, d)
2647
2648 d.update(c)
2649 self.assertDictEqual(c, d)
2650
2651 d['x'] = 0
2652 self.assertRaises(unittest.TestCase.failureException,
2653 self.assertDictEqual, c, d, 'These are unequal')
2654
2655 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2656 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2657 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2658
2659 self.assertSameElements([1, 2, 3], [3, 2, 1])
2660 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2661 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2662 self.assertRaises(self.failureException, self.assertSameElements,
2663 [10], [10, 11])
2664 self.assertRaises(self.failureException, self.assertSameElements,
2665 [10, 11], [10])
2666
2667 # Test that sequences of unhashable objects can be tested for sameness:
2668 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00002669
Benjamin Peterson3bb6b7a2009-04-04 16:46:24 +00002670 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002671 self.assertRaises(self.failureException, self.assertSameElements,
2672 [[1]], [[2]])
Michael Foorda5809c82009-04-04 18:55:09 +00002673 self.assertRaises(self.failureException, self.assertSameElements,
2674 [{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 2}])
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002675
2676 def testAssertSetEqual(self):
2677 set1 = set()
2678 set2 = set()
2679 self.assertSetEqual(set1, set2)
2680
2681 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2682 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2683 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2684 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2685
2686 set1 = set(['a'])
2687 set2 = set()
2688 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2689
2690 set1 = set(['a'])
2691 set2 = set(['a'])
2692 self.assertSetEqual(set1, set2)
2693
2694 set1 = set(['a'])
2695 set2 = set(['a', 'b'])
2696 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2697
2698 set1 = set(['a'])
2699 set2 = frozenset(['a', 'b'])
2700 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2701
2702 set1 = set(['a', 'b'])
2703 set2 = frozenset(['a', 'b'])
2704 self.assertSetEqual(set1, set2)
2705
2706 set1 = set()
2707 set2 = "foo"
2708 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2709 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2710
2711 # make sure any string formatting is tuple-safe
2712 set1 = set([(0, 1), (2, 3)])
2713 set2 = set([(4, 5)])
2714 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2715
2716 def testInequality(self):
2717 # Try ints
2718 self.assertGreater(2, 1)
2719 self.assertGreaterEqual(2, 1)
2720 self.assertGreaterEqual(1, 1)
2721 self.assertLess(1, 2)
2722 self.assertLessEqual(1, 2)
2723 self.assertLessEqual(1, 1)
2724 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2725 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2726 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2727 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2728 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2729 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2730
2731 # Try Floats
2732 self.assertGreater(1.1, 1.0)
2733 self.assertGreaterEqual(1.1, 1.0)
2734 self.assertGreaterEqual(1.0, 1.0)
2735 self.assertLess(1.0, 1.1)
2736 self.assertLessEqual(1.0, 1.1)
2737 self.assertLessEqual(1.0, 1.0)
2738 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2739 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2740 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2741 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2742 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2743 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2744
2745 # Try Strings
2746 self.assertGreater('bug', 'ant')
2747 self.assertGreaterEqual('bug', 'ant')
2748 self.assertGreaterEqual('ant', 'ant')
2749 self.assertLess('ant', 'bug')
2750 self.assertLessEqual('ant', 'bug')
2751 self.assertLessEqual('ant', 'ant')
2752 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2753 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2754 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2755 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2756 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2757 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2758
2759 # Try bytes
2760 self.assertGreater(b'bug', b'ant')
2761 self.assertGreaterEqual(b'bug', b'ant')
2762 self.assertGreaterEqual(b'ant', b'ant')
2763 self.assertLess(b'ant', b'bug')
2764 self.assertLessEqual(b'ant', b'bug')
2765 self.assertLessEqual(b'ant', b'ant')
2766 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'bug')
2767 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'ant')
2768 self.assertRaises(self.failureException, self.assertGreaterEqual, b'ant',
2769 b'bug')
2770 self.assertRaises(self.failureException, self.assertLess, b'bug', b'ant')
2771 self.assertRaises(self.failureException, self.assertLess, b'ant', b'ant')
2772 self.assertRaises(self.failureException, self.assertLessEqual, b'bug', b'ant')
2773
2774 def testAssertMultiLineEqual(self):
2775 sample_text = """\
2776http://www.python.org/doc/2.3/lib/module-unittest.html
2777test case
2778 A test case is the smallest unit of testing. [...]
2779"""
2780 revised_sample_text = """\
2781http://www.python.org/doc/2.4.1/lib/module-unittest.html
2782test case
2783 A test case is the smallest unit of testing. [...] You may provide your
2784 own implementation that does not subclass from TestCase, of course.
2785"""
2786 sample_text_error = """
2787- http://www.python.org/doc/2.3/lib/module-unittest.html
2788? ^
2789+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2790? ^^^
2791 test case
2792- A test case is the smallest unit of testing. [...]
2793+ A test case is the smallest unit of testing. [...] You may provide your
2794? +++++++++++++++++++++
2795+ own implementation that does not subclass from TestCase, of course.
2796"""
2797
2798 try:
2799 self.assertMultiLineEqual(sample_text, revised_sample_text)
2800 except self.failureException as e:
2801 # no fair testing ourself with ourself, use assertEqual..
2802 self.assertEqual(sample_text_error, str(e))
2803
2804 def testAssertIsNone(self):
2805 self.assertIsNone(None)
2806 self.assertRaises(self.failureException, self.assertIsNone, False)
2807 self.assertIsNotNone('DjZoPloGears on Rails')
2808 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2809
2810 def testAssertRegexpMatches(self):
2811 self.assertRegexpMatches('asdfabasdf', r'ab+')
2812 self.assertRaises(self.failureException, self.assertRegexpMatches,
2813 'saaas', r'aaaa')
2814
2815 def testAssertRaisesRegexp(self):
2816 class ExceptionMock(Exception):
2817 pass
2818
2819 def Stub():
2820 raise ExceptionMock('We expect')
2821
2822 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2823 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2824
2825 def testAssertNotRaisesRegexp(self):
2826 self.assertRaisesRegexp(
Benjamin Peterson4f75b642009-04-04 16:39:09 +00002827 self.failureException, '^Exception not raised by <lambda>$',
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002828 self.assertRaisesRegexp, Exception, re.compile('x'),
2829 lambda: None)
2830 self.assertRaisesRegexp(
Benjamin Peterson4f75b642009-04-04 16:39:09 +00002831 self.failureException, '^Exception not raised by <lambda>$',
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002832 self.assertRaisesRegexp, Exception, 'x',
2833 lambda: None)
2834
2835 def testAssertRaisesRegexpMismatch(self):
2836 def Stub():
2837 raise Exception('Unexpected')
2838
2839 self.assertRaisesRegexp(
2840 self.failureException,
2841 r'"\^Expected\$" does not match "Unexpected"',
2842 self.assertRaisesRegexp, Exception, '^Expected$',
2843 Stub)
2844 self.assertRaisesRegexp(
2845 self.failureException,
2846 r'"\^Expected\$" does not match "Unexpected"',
2847 self.assertRaisesRegexp, Exception,
2848 re.compile('^Expected$'), Stub)
2849
2850 def testSynonymAssertMethodNames(self):
2851 """Test undocumented method name synonyms.
2852
2853 Please do not use these methods names in your own code.
2854
2855 This test confirms their continued existence and functionality
2856 in order to avoid breaking existing code.
2857 """
2858 self.assertNotEquals(3, 5)
2859 self.assertEquals(3, 3)
2860 self.assertAlmostEquals(2.0, 2.0)
2861 self.assertNotAlmostEquals(3.0, 5.0)
2862 self.assert_(True)
2863
2864 def testPendingDeprecationMethodNames(self):
2865 """Test fail* methods pending deprecation, they will warn in 3.2.
2866
2867 Do not use these methods. They will go away in 3.3.
2868 """
Benjamin Peterson6bcbad52009-06-30 23:45:41 +00002869 old = (
2870 (self.failIfEqual, (3, 5)),
2871 (self.failUnlessEqual, (3, 3)),
2872 (self.failUnlessAlmostEqual, (2.0, 2.0)),
2873 (self.failIfAlmostEqual, (3.0, 5.0)),
2874 (self.failUnless, (True,)),
2875 (self.failUnlessRaises, (TypeError, lambda _: 3.14 + 'spam')),
2876 (self.failIf, (False,))
2877 )
2878 for meth, args in old:
2879 with warnings.catch_warnings(record=True) as w:
2880 meth(*args)
2881 self.assertEqual(len(w), 1)
2882 self.assertIs(w[0].category, DeprecationWarning)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002883
2884 def testDeepcopy(self):
2885 # Issue: 5660
2886 class TestableTest(TestCase):
2887 def testNothing(self):
2888 pass
2889
2890 test = TestableTest('testNothing')
2891
2892 # This shouldn't blow up
2893 deepcopy(test)
2894
Benjamin Peterson5254c042009-03-23 22:25:03 +00002895
2896class Test_TestSkipping(TestCase):
2897
2898 def test_skipping(self):
2899 class Foo(unittest.TestCase):
2900 def test_skip_me(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00002901 self.skipTest("skip")
Benjamin Peterson5254c042009-03-23 22:25:03 +00002902 events = []
2903 result = LoggingResult(events)
2904 test = Foo("test_skip_me")
2905 test.run(result)
2906 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2907 self.assertEqual(result.skipped, [(test, "skip")])
2908
2909 # Try letting setUp skip the test now.
2910 class Foo(unittest.TestCase):
2911 def setUp(self):
Benjamin Petersone549ead2009-03-28 21:42:05 +00002912 self.skipTest("testing")
Benjamin Peterson5254c042009-03-23 22:25:03 +00002913 def test_nothing(self): pass
2914 events = []
2915 result = LoggingResult(events)
2916 test = Foo("test_nothing")
2917 test.run(result)
2918 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2919 self.assertEqual(result.skipped, [(test, "testing")])
2920 self.assertEqual(result.testsRun, 1)
2921
2922 def test_skipping_decorators(self):
2923 op_table = ((unittest.skipUnless, False, True),
2924 (unittest.skipIf, True, False))
2925 for deco, do_skip, dont_skip in op_table:
2926 class Foo(unittest.TestCase):
2927 @deco(do_skip, "testing")
2928 def test_skip(self): pass
2929
2930 @deco(dont_skip, "testing")
2931 def test_dont_skip(self): pass
2932 test_do_skip = Foo("test_skip")
2933 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002934 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002935 events = []
2936 result = LoggingResult(events)
2937 suite.run(result)
2938 self.assertEqual(len(result.skipped), 1)
2939 expected = ['startTest', 'addSkip', 'stopTest',
2940 'startTest', 'addSuccess', 'stopTest']
2941 self.assertEqual(events, expected)
2942 self.assertEqual(result.testsRun, 2)
2943 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
2944 self.assertTrue(result.wasSuccessful())
2945
2946 def test_skip_class(self):
2947 @unittest.skip("testing")
2948 class Foo(unittest.TestCase):
2949 def test_1(self):
2950 record.append(1)
2951 record = []
2952 result = unittest.TestResult()
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002953 test = Foo("test_1")
2954 suite = unittest.TestSuite([test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002955 suite.run(result)
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00002956 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002957 self.assertEqual(record, [])
2958
2959 def test_expected_failure(self):
2960 class Foo(unittest.TestCase):
2961 @unittest.expectedFailure
2962 def test_die(self):
2963 self.fail("help me!")
2964 events = []
2965 result = LoggingResult(events)
2966 test = Foo("test_die")
2967 test.run(result)
2968 self.assertEqual(events,
2969 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Peterson52baa292009-03-24 00:56:30 +00002970 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson5254c042009-03-23 22:25:03 +00002971 self.assertTrue(result.wasSuccessful())
2972
2973 def test_unexpected_success(self):
2974 class Foo(unittest.TestCase):
2975 @unittest.expectedFailure
2976 def test_die(self):
2977 pass
2978 events = []
2979 result = LoggingResult(events)
2980 test = Foo("test_die")
2981 test.run(result)
2982 self.assertEqual(events,
2983 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
2984 self.assertFalse(result.failures)
Benjamin Peterson52baa292009-03-24 00:56:30 +00002985 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson5254c042009-03-23 22:25:03 +00002986 self.assertTrue(result.wasSuccessful())
2987
2988
2989
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00002990class Test_Assertions(TestCase):
2991 def test_AlmostEqual(self):
Benjamin Petersone1759f82009-06-30 23:35:19 +00002992 self.assertAlmostEqual(1.00000001, 1.0)
2993 self.assertNotAlmostEqual(1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002994 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00002995 self.assertAlmostEqual, 1.0000001, 1.0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00002996 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00002997 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00002998
Benjamin Petersone1759f82009-06-30 23:35:19 +00002999 self.assertAlmostEqual(1.1, 1.0, places=0)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003000 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003001 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003002
Benjamin Petersone1759f82009-06-30 23:35:19 +00003003 self.assertAlmostEqual(0, .1+.1j, places=0)
3004 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003005 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003006 self.assertAlmostEqual, 0, .1+.1j, places=1)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003007 self.assertRaises(self.failureException,
Benjamin Petersone1759f82009-06-30 23:35:19 +00003008 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003009
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003010 self.assertAlmostEqual(float('inf'), float('inf'))
3011 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3012 float('inf'), float('inf'))
3013
3014
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003015 def test_assertRaises(self):
3016 def _raise(e):
3017 raise e
3018 self.assertRaises(KeyError, _raise, KeyError)
3019 self.assertRaises(KeyError, _raise, KeyError("key"))
3020 try:
3021 self.assertRaises(KeyError, lambda: None)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003022 except self.failureException as e:
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003023 self.assert_("KeyError not raised" in str(e), str(e))
3024 else:
3025 self.fail("assertRaises() didn't fail")
3026 try:
3027 self.assertRaises(KeyError, _raise, ValueError)
3028 except ValueError:
3029 pass
3030 else:
3031 self.fail("assertRaises() didn't let exception pass through")
3032 with self.assertRaises(KeyError):
3033 raise KeyError
3034 with self.assertRaises(KeyError):
3035 raise KeyError("key")
3036 try:
3037 with self.assertRaises(KeyError):
3038 pass
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003039 except self.failureException as e:
Antoine Pitrou5acd41e2008-12-28 14:29:00 +00003040 self.assert_("KeyError not raised" in str(e), str(e))
3041 else:
3042 self.fail("assertRaises() didn't fail")
3043 try:
3044 with self.assertRaises(KeyError):
3045 raise ValueError
3046 except ValueError:
3047 pass
3048 else:
3049 self.fail("assertRaises() didn't let exception pass through")
3050
3051
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003052class TestLongMessage(TestCase):
3053 """Test that the individual asserts honour longMessage.
3054 This actually tests all the message behaviour for
3055 asserts that use longMessage."""
3056
3057 def setUp(self):
3058 class TestableTestFalse(TestCase):
3059 longMessage = False
3060 failureException = self.failureException
3061
3062 def testTest(self):
3063 pass
3064
3065 class TestableTestTrue(TestCase):
3066 longMessage = True
3067 failureException = self.failureException
3068
3069 def testTest(self):
3070 pass
3071
3072 self.testableTrue = TestableTestTrue('testTest')
3073 self.testableFalse = TestableTestFalse('testTest')
3074
3075 def testDefault(self):
3076 self.assertFalse(TestCase.longMessage)
3077
3078 def test_formatMsg(self):
3079 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3080 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3081
3082 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3083 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3084
3085 def assertMessages(self, methodName, args, errors):
3086 def getMethod(i):
3087 useTestableFalse = i < 2
3088 if useTestableFalse:
3089 test = self.testableFalse
3090 else:
3091 test = self.testableTrue
3092 return getattr(test, methodName)
3093
3094 for i, expected_regexp in enumerate(errors):
3095 testMethod = getMethod(i)
3096 kwargs = {}
3097 withMsg = i % 2
3098 if withMsg:
3099 kwargs = {"msg": "oops"}
3100
3101 with self.assertRaisesRegexp(self.failureException,
3102 expected_regexp=expected_regexp):
3103 testMethod(*args, **kwargs)
3104
3105 def testAssertTrue(self):
3106 self.assertMessages('assertTrue', (False,),
3107 ["^False is not True$", "^oops$", "^False is not True$",
3108 "^False is not True : oops$"])
3109
3110 def testAssertFalse(self):
3111 self.assertMessages('assertFalse', (True,),
3112 ["^True is not False$", "^oops$", "^True is not False$",
3113 "^True is not False : oops$"])
3114
3115 def testNotEqual(self):
3116 self.assertMessages('assertNotEqual', (1, 1),
3117 ["^1 == 1$", "^oops$", "^1 == 1$",
3118 "^1 == 1 : oops$"])
3119
3120 def testAlmostEqual(self):
3121 self.assertMessages('assertAlmostEqual', (1, 2),
3122 ["^1 != 2 within 7 places$", "^oops$",
3123 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3124
3125 def testNotAlmostEqual(self):
3126 self.assertMessages('assertNotAlmostEqual', (1, 1),
3127 ["^1 == 1 within 7 places$", "^oops$",
3128 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3129
3130 def test_baseAssertEqual(self):
3131 self.assertMessages('_baseAssertEqual', (1, 2),
3132 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3133
3134 def testAssertSequenceEqual(self):
3135 # Error messages are multiline so not testing on full message
3136 # assertTupleEqual and assertListEqual delegate to this method
3137 self.assertMessages('assertSequenceEqual', ([], [None]),
3138 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3139 r"\+ \[None\] : oops$"])
3140
3141 def testAssertSetEqual(self):
3142 self.assertMessages('assertSetEqual', (set(), set([None])),
3143 ["None$", "^oops$", "None$",
3144 "None : oops$"])
3145
3146 def testAssertIn(self):
3147 self.assertMessages('assertIn', (None, []),
3148 ['^None not found in \[\]$', "^oops$",
3149 '^None not found in \[\]$',
3150 '^None not found in \[\] : oops$'])
3151
3152 def testAssertNotIn(self):
3153 self.assertMessages('assertNotIn', (None, [None]),
3154 ['^None unexpectedly found in \[None\]$', "^oops$",
3155 '^None unexpectedly found in \[None\]$',
3156 '^None unexpectedly found in \[None\] : oops$'])
3157
3158 def testAssertDictEqual(self):
3159 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3160 [r"\+ \{'key': 'value'\}$", "^oops$",
3161 "\+ \{'key': 'value'\}$",
3162 "\+ \{'key': 'value'\} : oops$"])
3163
3164 def testAssertDictContainsSubset(self):
3165 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3166 ["^Missing: 'key'$", "^oops$",
3167 "^Missing: 'key'$",
3168 "^Missing: 'key' : oops$"])
3169
3170 def testAssertSameElements(self):
3171 self.assertMessages('assertSameElements', ([], [None]),
3172 [r"\[None\]$", "^oops$",
3173 r"\[None\]$",
3174 r"\[None\] : oops$"])
3175
3176 def testAssertMultiLineEqual(self):
3177 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3178 [r"\+ foo$", "^oops$",
3179 r"\+ foo$",
3180 r"\+ foo : oops$"])
3181
3182 def testAssertLess(self):
3183 self.assertMessages('assertLess', (2, 1),
3184 ["^2 not less than 1$", "^oops$",
3185 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3186
3187 def testAssertLessEqual(self):
3188 self.assertMessages('assertLessEqual', (2, 1),
3189 ["^2 not less than or equal to 1$", "^oops$",
3190 "^2 not less than or equal to 1$",
3191 "^2 not less than or equal to 1 : oops$"])
3192
3193 def testAssertGreater(self):
3194 self.assertMessages('assertGreater', (1, 2),
3195 ["^1 not greater than 2$", "^oops$",
3196 "^1 not greater than 2$",
3197 "^1 not greater than 2 : oops$"])
3198
3199 def testAssertGreaterEqual(self):
3200 self.assertMessages('assertGreaterEqual', (1, 2),
3201 ["^1 not greater than or equal to 2$", "^oops$",
3202 "^1 not greater than or equal to 2$",
3203 "^1 not greater than or equal to 2 : oops$"])
3204
3205 def testAssertIsNone(self):
3206 self.assertMessages('assertIsNone', ('not None',),
3207 ["^'not None' is not None$", "^oops$",
3208 "^'not None' is not None$",
3209 "^'not None' is not None : oops$"])
3210
3211 def testAssertIsNotNone(self):
3212 self.assertMessages('assertIsNotNone', (None,),
3213 ["^unexpectedly None$", "^oops$",
3214 "^unexpectedly None$",
3215 "^unexpectedly None : oops$"])
3216
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00003217 def testAssertIs(self):
3218 self.assertMessages('assertIs', (None, 'foo'),
3219 ["^None is not 'foo'$", "^oops$",
3220 "^None is not 'foo'$",
3221 "^None is not 'foo' : oops$"])
3222
3223 def testAssertIsNot(self):
3224 self.assertMessages('assertIsNot', (None, None),
3225 ["^unexpectedly identical: None$", "^oops$",
3226 "^unexpectedly identical: None$",
3227 "^unexpectedly identical: None : oops$"])
3228
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00003229
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003230class TestCleanUp(TestCase):
3231
3232 def testCleanUp(self):
3233 class TestableTest(TestCase):
3234 def testNothing(self):
3235 pass
3236
3237 test = TestableTest('testNothing')
3238 self.assertEqual(test._cleanups, [])
3239
3240 cleanups = []
3241
3242 def cleanup1(*args, **kwargs):
3243 cleanups.append((1, args, kwargs))
3244
3245 def cleanup2(*args, **kwargs):
3246 cleanups.append((2, args, kwargs))
3247
3248 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3249 test.addCleanup(cleanup2)
3250
3251 self.assertEqual(test._cleanups,
3252 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3253 (cleanup2, (), {})])
3254
3255 result = test.doCleanups()
3256 self.assertTrue(result)
3257
3258 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3259
3260 def testCleanUpWithErrors(self):
3261 class TestableTest(TestCase):
3262 def testNothing(self):
3263 pass
3264
3265 class MockResult(object):
3266 errors = []
3267 def addError(self, test, exc_info):
3268 self.errors.append((test, exc_info))
3269
3270 result = MockResult()
3271 test = TestableTest('testNothing')
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00003272 test._resultForDoCleanups = result
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003273
3274 exc1 = Exception('foo')
3275 exc2 = Exception('bar')
3276 def cleanup1():
3277 raise exc1
3278
3279 def cleanup2():
3280 raise exc2
3281
3282 test.addCleanup(cleanup1)
3283 test.addCleanup(cleanup2)
3284
3285 self.assertFalse(test.doCleanups())
3286
3287 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3288 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3289 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3290
3291 def testCleanupInRun(self):
3292 blowUp = False
3293 ordering = []
3294
3295 class TestableTest(TestCase):
3296 def setUp(self):
3297 ordering.append('setUp')
3298 if blowUp:
3299 raise Exception('foo')
3300
3301 def testNothing(self):
3302 ordering.append('test')
3303
3304 def tearDown(self):
3305 ordering.append('tearDown')
3306
3307 test = TestableTest('testNothing')
3308
3309 def cleanup1():
3310 ordering.append('cleanup1')
3311 def cleanup2():
3312 ordering.append('cleanup2')
3313 test.addCleanup(cleanup1)
3314 test.addCleanup(cleanup2)
3315
3316 def success(some_test):
3317 self.assertEqual(some_test, test)
3318 ordering.append('success')
3319
3320 result = unittest.TestResult()
3321 result.addSuccess = success
3322
3323 test.run(result)
3324 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3325 'cleanup2', 'cleanup1', 'success'])
3326
3327 blowUp = True
3328 ordering = []
3329 test = TestableTest('testNothing')
3330 test.addCleanup(cleanup1)
3331 test.run(result)
3332 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3333
3334
3335class Test_TestProgram(TestCase):
3336
3337 # Horrible white box test
3338 def testNoExit(self):
3339 result = object()
3340 test = object()
3341
3342 class FakeRunner(object):
3343 def run(self, test):
3344 self.test = test
3345 return result
3346
3347 runner = FakeRunner()
3348
Benjamin Petersond2397752009-06-27 23:45:02 +00003349 oldParseArgs = TestProgram.parseArgs
3350 def restoreParseArgs():
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003351 TestProgram.parseArgs = oldParseArgs
Benjamin Petersond2397752009-06-27 23:45:02 +00003352 TestProgram.parseArgs = lambda *args: None
3353 self.addCleanup(restoreParseArgs)
3354
3355 def removeTest():
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003356 del TestProgram.test
Benjamin Petersond2397752009-06-27 23:45:02 +00003357 TestProgram.test = test
3358 self.addCleanup(removeTest)
3359
3360 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3361
3362 self.assertEqual(program.result, result)
3363 self.assertEqual(runner.test, test)
3364 self.assertEqual(program.verbosity, 2)
3365
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003366 class FooBar(unittest.TestCase):
3367 def testPass(self):
3368 assert True
3369 def testFail(self):
3370 assert False
3371
3372 class FooBarLoader(unittest.TestLoader):
3373 """Test loader that returns a suite containing FooBar."""
3374 def loadTestsFromModule(self, module):
3375 return self.suiteClass(
3376 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3377
3378
3379 def test_NonExit(self):
3380 program = unittest.main(exit=False,
3381 argv=["foobar"],
3382 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3383 testLoader=self.FooBarLoader())
3384 self.assertTrue(hasattr(program, 'result'))
3385
3386
3387 def test_Exit(self):
3388 self.assertRaises(
3389 SystemExit,
3390 unittest.main,
3391 argv=["foobar"],
3392 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3393 exit=True,
3394 testLoader=self.FooBarLoader())
3395
3396
3397 def test_ExitAsDefault(self):
3398 self.assertRaises(
3399 SystemExit,
3400 unittest.main,
3401 argv=["foobar"],
3402 testRunner=unittest.TextTestRunner(stream=io.StringIO()),
3403 testLoader=self.FooBarLoader())
3404
3405
3406class Test_TextTestRunner(TestCase):
3407 """Tests for TextTestRunner."""
3408
3409 def test_works_with_result_without_startTestRun_stopTestRun(self):
3410 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3411 separator2 = ''
3412 def printErrors(self):
3413 pass
3414
3415 class Runner(unittest.TextTestRunner):
3416 def __init__(self):
3417 super(Runner, self).__init__(io.StringIO())
3418
3419 def _makeResult(self):
3420 return OldTextResult()
3421
3422 runner = Runner()
3423 runner.run(unittest.TestSuite())
3424
3425 def test_startTestRun_stopTestRun_called(self):
3426 class LoggingTextResult(LoggingResult):
3427 separator2 = ''
3428 def printErrors(self):
3429 pass
3430
3431 class LoggingRunner(unittest.TextTestRunner):
3432 def __init__(self, events):
3433 super(LoggingRunner, self).__init__(io.StringIO())
3434 self._events = events
3435
3436 def _makeResult(self):
3437 return LoggingTextResult(self._events)
3438
3439 events = []
3440 runner = LoggingRunner(events)
3441 runner.run(unittest.TestSuite())
3442 expected = ['startTestRun', 'stopTestRun']
3443 self.assertEqual(events, expected)
3444
Antoine Pitrouc63ecee2009-11-10 21:34:48 +00003445 def test_pickle_unpickle(self):
3446 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3447 # required by test_multiprocessing under Windows (in verbose mode).
3448 stream = io.StringIO("foo")
3449 runner = unittest.TextTestRunner(stream)
3450 for protocol in range(2, pickle.HIGHEST_PROTOCOL + 1):
3451 s = pickle.dumps(runner, protocol)
3452 obj = pickle.loads(s)
3453 # StringIO objects never compare equal, a cheap test instead.
3454 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3455
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003456
Benjamin Petersond2397752009-06-27 23:45:02 +00003457class TestDiscovery(TestCase):
3458
3459 # Heavily mocked tests so I can avoid hitting the filesystem
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003460 def test_get_name_from_path(self):
Benjamin Petersond2397752009-06-27 23:45:02 +00003461 loader = unittest.TestLoader()
Benjamin Petersond2397752009-06-27 23:45:02 +00003462 loader._top_level_dir = '/foo'
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003463 name = loader._get_name_from_path('/foo/bar/baz.py')
3464 self.assertEqual(name, 'bar.baz')
Benjamin Petersond2397752009-06-27 23:45:02 +00003465
3466 if not __debug__:
3467 # asserts are off
3468 return
3469
3470 with self.assertRaises(AssertionError):
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003471 loader._get_name_from_path('/bar/baz.py')
Benjamin Petersond2397752009-06-27 23:45:02 +00003472
3473 def test_find_tests(self):
3474 loader = unittest.TestLoader()
3475
3476 original_listdir = os.listdir
3477 def restore_listdir():
3478 os.listdir = original_listdir
3479 original_isfile = os.path.isfile
3480 def restore_isfile():
3481 os.path.isfile = original_isfile
3482 original_isdir = os.path.isdir
3483 def restore_isdir():
3484 os.path.isdir = original_isdir
3485
3486 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003487 'test.foo', 'test-not-a-module.py', 'another_dir'],
Benjamin Petersond2397752009-06-27 23:45:02 +00003488 ['test3.py', 'test4.py', ]]
3489 os.listdir = lambda path: path_lists.pop(0)
3490 self.addCleanup(restore_listdir)
3491
3492 def isdir(path):
3493 return path.endswith('dir')
3494 os.path.isdir = isdir
3495 self.addCleanup(restore_isdir)
3496
3497 def isfile(path):
3498 # another_dir is not a package and so shouldn't be recursed into
3499 return not path.endswith('dir') and not 'another_dir' in path
3500 os.path.isfile = isfile
3501 self.addCleanup(restore_isfile)
3502
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003503 loader._get_module_from_name = lambda path: path + ' module'
Benjamin Petersond2397752009-06-27 23:45:02 +00003504 loader.loadTestsFromModule = lambda module: module + ' tests'
3505
3506 loader._top_level_dir = '/foo'
3507 suite = list(loader._find_tests('/foo', 'test*.py'))
3508
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003509 expected = [name + ' module tests' for name in
3510 ('test1', 'test2')]
3511 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3512 ('test3', 'test4')])
Benjamin Petersond2397752009-06-27 23:45:02 +00003513 self.assertEqual(suite, expected)
3514
3515 def test_find_tests_with_package(self):
3516 loader = unittest.TestLoader()
3517
3518 original_listdir = os.listdir
3519 def restore_listdir():
3520 os.listdir = original_listdir
3521 original_isfile = os.path.isfile
3522 def restore_isfile():
3523 os.path.isfile = original_isfile
3524 original_isdir = os.path.isdir
3525 def restore_isdir():
3526 os.path.isdir = original_isdir
3527
3528 directories = ['a_directory', 'test_directory', 'test_directory2']
3529 path_lists = [directories, [], [], []]
3530 os.listdir = lambda path: path_lists.pop(0)
3531 self.addCleanup(restore_listdir)
3532
3533 os.path.isdir = lambda path: True
3534 self.addCleanup(restore_isdir)
3535
3536 os.path.isfile = lambda path: os.path.basename(path) not in directories
3537 self.addCleanup(restore_isfile)
3538
3539 class Module(object):
3540 paths = []
3541 load_tests_args = []
3542
3543 def __init__(self, path):
3544 self.path = path
3545 self.paths.append(path)
3546 if os.path.basename(path) == 'test_directory':
3547 def load_tests(loader, tests, pattern):
3548 self.load_tests_args.append((loader, tests, pattern))
3549 return 'load_tests'
3550 self.load_tests = load_tests
3551
3552 def __eq__(self, other):
3553 return self.path == other.path
3554
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003555 loader._get_module_from_name = lambda name: Module(name)
Benjamin Petersond2397752009-06-27 23:45:02 +00003556 def loadTestsFromModule(module, use_load_tests):
3557 if use_load_tests:
3558 raise self.failureException('use_load_tests should be False for packages')
3559 return module.path + ' module tests'
3560 loader.loadTestsFromModule = loadTestsFromModule
3561
3562 loader._top_level_dir = '/foo'
3563 # this time no '.py' on the pattern so that it can match
3564 # a test package
3565 suite = list(loader._find_tests('/foo', 'test*'))
3566
3567 # We should have loaded tests from the test_directory package by calling load_tests
3568 # and directly from the test_directory2 package
3569 self.assertEqual(suite,
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003570 ['load_tests', 'test_directory2' + ' module tests'])
3571 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Benjamin Petersond2397752009-06-27 23:45:02 +00003572
3573 # load_tests should have been called once with loader, tests and pattern
3574 self.assertEqual(Module.load_tests_args,
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003575 [(loader, 'test_directory' + ' module tests', 'test*')])
Benjamin Petersond2397752009-06-27 23:45:02 +00003576
3577 def test_discover(self):
3578 loader = unittest.TestLoader()
3579
3580 original_isfile = os.path.isfile
3581 def restore_isfile():
3582 os.path.isfile = original_isfile
3583
3584 os.path.isfile = lambda path: False
3585 self.addCleanup(restore_isfile)
3586
Nick Coghlan6ead5522009-10-18 13:19:33 +00003587 orig_sys_path = sys.path[:]
3588 def restore_path():
3589 sys.path[:] = orig_sys_path
3590 self.addCleanup(restore_path)
Benjamin Petersond2397752009-06-27 23:45:02 +00003591
Nick Coghlan6ead5522009-10-18 13:19:33 +00003592 full_path = os.path.abspath(os.path.normpath('/foo'))
Benjamin Petersond2397752009-06-27 23:45:02 +00003593 with self.assertRaises(ImportError):
3594 loader.discover('/foo/bar', top_level_dir='/foo')
3595
3596 self.assertEqual(loader._top_level_dir, full_path)
3597 self.assertIn(full_path, sys.path)
3598
3599 os.path.isfile = lambda path: True
3600 _find_tests_args = []
3601 def _find_tests(start_dir, pattern):
3602 _find_tests_args.append((start_dir, pattern))
3603 return ['tests']
3604 loader._find_tests = _find_tests
3605 loader.suiteClass = str
3606
3607 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3608
3609 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3610 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3611 self.assertEqual(suite, "['tests']")
3612 self.assertEqual(loader._top_level_dir, top_level_dir)
3613 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlan6ead5522009-10-18 13:19:33 +00003614 self.assertIn(top_level_dir, sys.path)
Benjamin Petersond2397752009-06-27 23:45:02 +00003615
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003616 def test_discover_with_modules_that_fail_to_import(self):
3617 loader = unittest.TestLoader()
3618
3619 listdir = os.listdir
3620 os.listdir = lambda _: ['test_this_does_not_exist.py']
3621 isfile = os.path.isfile
3622 os.path.isfile = lambda _: True
Nick Coghlan6ead5522009-10-18 13:19:33 +00003623 orig_sys_path = sys.path[:]
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003624 def restore():
3625 os.path.isfile = isfile
3626 os.listdir = listdir
Nick Coghlan6ead5522009-10-18 13:19:33 +00003627 sys.path[:] = orig_sys_path
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003628 self.addCleanup(restore)
3629
3630 suite = loader.discover('.')
Nick Coghlan6ead5522009-10-18 13:19:33 +00003631 self.assertIn(os.getcwd(), sys.path)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00003632 self.assertEqual(suite.countTestCases(), 1)
3633 test = list(list(suite)[0])[0] # extract test from suite
3634
3635 with self.assertRaises(ImportError):
3636 test.test_this_does_not_exist()
3637
Benjamin Petersond2397752009-06-27 23:45:02 +00003638 def test_command_line_handling_parseArgs(self):
3639 # Haha - take that uninstantiable class
3640 program = object.__new__(TestProgram)
3641
3642 args = []
3643 def do_discovery(argv):
3644 args.extend(argv)
3645 program._do_discovery = do_discovery
3646 program.parseArgs(['something', 'discover'])
3647 self.assertEqual(args, [])
3648
3649 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3650 self.assertEqual(args, ['foo', 'bar'])
3651
3652 def test_command_line_handling_do_discovery_too_many_arguments(self):
3653 class Stop(Exception):
3654 pass
3655 def usageExit():
3656 raise Stop
3657
3658 program = object.__new__(TestProgram)
3659 program.usageExit = usageExit
3660
3661 with self.assertRaises(Stop):
3662 # too many args
3663 program._do_discovery(['one', 'two', 'three', 'four'])
3664
3665
3666 def test_command_line_handling_do_discovery_calls_loader(self):
3667 program = object.__new__(TestProgram)
3668
3669 class Loader(object):
3670 args = []
3671 def discover(self, start_dir, pattern, top_level_dir):
3672 self.args.append((start_dir, pattern, top_level_dir))
3673 return 'tests'
3674
3675 program._do_discovery(['-v'], Loader=Loader)
3676 self.assertEqual(program.verbosity, 2)
3677 self.assertEqual(program.test, 'tests')
3678 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3679
3680 Loader.args = []
3681 program = object.__new__(TestProgram)
3682 program._do_discovery(['--verbose'], Loader=Loader)
3683 self.assertEqual(program.test, 'tests')
3684 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3685
3686 Loader.args = []
3687 program = object.__new__(TestProgram)
3688 program._do_discovery([], Loader=Loader)
3689 self.assertEqual(program.test, 'tests')
3690 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3691
3692 Loader.args = []
3693 program = object.__new__(TestProgram)
3694 program._do_discovery(['fish'], Loader=Loader)
3695 self.assertEqual(program.test, 'tests')
3696 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3697
3698 Loader.args = []
3699 program = object.__new__(TestProgram)
3700 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3701 self.assertEqual(program.test, 'tests')
3702 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3703
3704 Loader.args = []
3705 program = object.__new__(TestProgram)
3706 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3707 self.assertEqual(program.test, 'tests')
3708 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3709
3710 Loader.args = []
3711 program = object.__new__(TestProgram)
3712 program._do_discovery(['-s', 'fish'], Loader=Loader)
3713 self.assertEqual(program.test, 'tests')
3714 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3715
3716 Loader.args = []
3717 program = object.__new__(TestProgram)
3718 program._do_discovery(['-t', 'fish'], Loader=Loader)
3719 self.assertEqual(program.test, 'tests')
3720 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3721
3722 Loader.args = []
3723 program = object.__new__(TestProgram)
3724 program._do_discovery(['-p', 'fish'], Loader=Loader)
3725 self.assertEqual(program.test, 'tests')
3726 self.assertEqual(Loader.args, [('.', 'fish', None)])
3727
3728 Loader.args = []
3729 program = object.__new__(TestProgram)
3730 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3731 self.assertEqual(program.test, 'tests')
3732 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3733 self.assertEqual(program.verbosity, 2)
3734
3735
Jim Fultonfafd8742004-08-28 15:22:12 +00003736######################################################################
3737## Main
3738######################################################################
3739
3740def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003741 support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +00003742 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003743 Test_TestSkipping, Test_Assertions, TestLongMessage,
Antoine Pitrouc63ecee2009-11-10 21:34:48 +00003744 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner)
Jim Fultonfafd8742004-08-28 15:22:12 +00003745
Guido van Rossumd8faa362007-04-27 19:54:29 +00003746if __name__ == "__main__":
Jim Fultonfafd8742004-08-28 15:22:12 +00003747 test_main()