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