Changeset 391 for python/trunk/Lib/test/test_unittest.py
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Lib/test/test_unittest.py
r2 r391 1 """Test script for unittest. 1 import unittest.test 2 2 3 By Collin Winter <collinw at gmail.com>4 5 Still need testing:6 TestCase.{assert,fail}* methods (some are tested implicitly)7 """8 9 import sys10 3 from test import test_support 11 import unittest12 from unittest import TestCase13 import types14 15 ### Support code16 ################################################################17 18 class LoggingResult(unittest.TestResult):19 def __init__(self, log):20 self._events = log21 super(LoggingResult, self).__init__()22 23 def startTest(self, test):24 self._events.append('startTest')25 super(LoggingResult, self).startTest(test)26 27 def stopTest(self, test):28 self._events.append('stopTest')29 super(LoggingResult, self).stopTest(test)30 31 def addFailure(self, *args):32 self._events.append('addFailure')33 super(LoggingResult, self).addFailure(*args)34 35 def addError(self, *args):36 self._events.append('addError')37 super(LoggingResult, self).addError(*args)38 39 class TestEquality(object):40 # Check for a valid __eq__ implementation41 def test_eq(self):42 for obj_1, obj_2 in self.eq_pairs:43 self.assertEqual(obj_1, obj_2)44 self.assertEqual(obj_2, obj_1)45 46 # Check for a valid __ne__ implementation47 def test_ne(self):48 for obj_1, obj_2 in self.ne_pairs:49 self.failIfEqual(obj_1, obj_2)50 self.failIfEqual(obj_2, obj_1)51 52 class TestHashing(object):53 # Check for a valid __hash__ implementation54 def test_hash(self):55 for obj_1, obj_2 in self.eq_pairs:56 try:57 assert hash(obj_1) == hash(obj_2)58 except KeyboardInterrupt:59 raise60 except AssertionError:61 self.fail("%s and %s do not hash equal" % (obj_1, obj_2))62 except Exception, e:63 self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e))64 65 for obj_1, obj_2 in self.ne_pairs:66 try:67 assert hash(obj_1) != hash(obj_2)68 except KeyboardInterrupt:69 raise70 except AssertionError:71 self.fail("%s and %s hash equal, but shouldn't" % (obj_1, obj_2))72 except Exception, e:73 self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e))74 4 75 5 76 ################################################################ 77 ### /Support code 6 def test_main(): 7 test_support.run_unittest(unittest.test.suite()) 8 test_support.reap_children() 78 9 79 class Test_TestLoader(TestCase):80 81 ### Tests for TestLoader.loadTestsFromTestCase82 ################################################################83 84 # "Return a suite of all tests cases contained in the TestCase-derived85 # class testCaseClass"86 def test_loadTestsFromTestCase(self):87 class Foo(unittest.TestCase):88 def test_1(self): pass89 def test_2(self): pass90 def foo_bar(self): pass91 92 tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')])93 94 loader = unittest.TestLoader()95 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)96 97 # "Return a suite of all tests cases contained in the TestCase-derived98 # class testCaseClass"99 #100 # Make sure it does the right thing even if no tests were found101 def test_loadTestsFromTestCase__no_matches(self):102 class Foo(unittest.TestCase):103 def foo_bar(self): pass104 105 empty_suite = unittest.TestSuite()106 107 loader = unittest.TestLoader()108 self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite)109 110 # "Return a suite of all tests cases contained in the TestCase-derived111 # class testCaseClass"112 #113 # What happens if loadTestsFromTestCase() is given an object114 # that isn't a subclass of TestCase? Specifically, what happens115 # if testCaseClass is a subclass of TestSuite?116 #117 # This is checked for specifically in the code, so we better add a118 # test for it.119 def test_loadTestsFromTestCase__TestSuite_subclass(self):120 class NotATestCase(unittest.TestSuite):121 pass122 123 loader = unittest.TestLoader()124 try:125 loader.loadTestsFromTestCase(NotATestCase)126 except TypeError:127 pass128 else:129 self.fail('Should raise TypeError')130 131 # "Return a suite of all tests cases contained in the TestCase-derived132 # class testCaseClass"133 #134 # Make sure loadTestsFromTestCase() picks up the default test method135 # name (as specified by TestCase), even though the method name does136 # not match the default TestLoader.testMethodPrefix string137 def test_loadTestsFromTestCase__default_method_name(self):138 class Foo(unittest.TestCase):139 def runTest(self):140 pass141 142 loader = unittest.TestLoader()143 # This has to be false for the test to succeed144 self.failIf('runTest'.startswith(loader.testMethodPrefix))145 146 suite = loader.loadTestsFromTestCase(Foo)147 self.failUnless(isinstance(suite, loader.suiteClass))148 self.assertEqual(list(suite), [Foo('runTest')])149 150 ################################################################151 ### /Tests for TestLoader.loadTestsFromTestCase152 153 ### Tests for TestLoader.loadTestsFromModule154 ################################################################155 156 # "This method searches `module` for classes derived from TestCase"157 def test_loadTestsFromModule__TestCase_subclass(self):158 m = types.ModuleType('m')159 class MyTestCase(unittest.TestCase):160 def test(self):161 pass162 m.testcase_1 = MyTestCase163 164 loader = unittest.TestLoader()165 suite = loader.loadTestsFromModule(m)166 self.failUnless(isinstance(suite, loader.suiteClass))167 168 expected = [loader.suiteClass([MyTestCase('test')])]169 self.assertEqual(list(suite), expected)170 171 # "This method searches `module` for classes derived from TestCase"172 #173 # What happens if no tests are found (no TestCase instances)?174 def test_loadTestsFromModule__no_TestCase_instances(self):175 m = types.ModuleType('m')176 177 loader = unittest.TestLoader()178 suite = loader.loadTestsFromModule(m)179 self.failUnless(isinstance(suite, loader.suiteClass))180 self.assertEqual(list(suite), [])181 182 # "This method searches `module` for classes derived from TestCase"183 #184 # What happens if no tests are found (TestCases instances, but no tests)?185 def test_loadTestsFromModule__no_TestCase_tests(self):186 m = types.ModuleType('m')187 class MyTestCase(unittest.TestCase):188 pass189 m.testcase_1 = MyTestCase190 191 loader = unittest.TestLoader()192 suite = loader.loadTestsFromModule(m)193 self.failUnless(isinstance(suite, loader.suiteClass))194 195 self.assertEqual(list(suite), [loader.suiteClass()])196 197 # "This method searches `module` for classes derived from TestCase"s198 #199 # What happens if loadTestsFromModule() is given something other200 # than a module?201 #202 # XXX Currently, it succeeds anyway. This flexibility203 # should either be documented or loadTestsFromModule() should204 # raise a TypeError205 #206 # XXX Certain people are using this behaviour. We'll add a test for it207 def test_loadTestsFromModule__not_a_module(self):208 class MyTestCase(unittest.TestCase):209 def test(self):210 pass211 212 class NotAModule(object):213 test_2 = MyTestCase214 215 loader = unittest.TestLoader()216 suite = loader.loadTestsFromModule(NotAModule)217 218 reference = [unittest.TestSuite([MyTestCase('test')])]219 self.assertEqual(list(suite), reference)220 221 ################################################################222 ### /Tests for TestLoader.loadTestsFromModule()223 224 ### Tests for TestLoader.loadTestsFromName()225 ################################################################226 227 # "The specifier name is a ``dotted name'' that may resolve either to228 # a module, a test case class, a TestSuite instance, a test method229 # within a test case class, or a callable object which returns a230 # TestCase or TestSuite instance."231 #232 # Is ValueError raised in response to an empty name?233 def test_loadTestsFromName__empty_name(self):234 loader = unittest.TestLoader()235 236 try:237 loader.loadTestsFromName('')238 except ValueError, e:239 self.assertEqual(str(e), "Empty module name")240 else:241 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")242 243 # "The specifier name is a ``dotted name'' that may resolve either to244 # a module, a test case class, a TestSuite instance, a test method245 # within a test case class, or a callable object which returns a246 # TestCase or TestSuite instance."247 #248 # What happens when the name contains invalid characters?249 def test_loadTestsFromName__malformed_name(self):250 loader = unittest.TestLoader()251 252 # XXX Should this raise ValueError or ImportError?253 try:254 loader.loadTestsFromName('abc () //')255 except ValueError:256 pass257 except ImportError:258 pass259 else:260 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")261 262 # "The specifier name is a ``dotted name'' that may resolve ... to a263 # module"264 #265 # What happens when a module by that name can't be found?266 def test_loadTestsFromName__unknown_module_name(self):267 loader = unittest.TestLoader()268 269 try:270 loader.loadTestsFromName('sdasfasfasdf')271 except ImportError, e:272 self.assertEqual(str(e), "No module named sdasfasfasdf")273 else:274 self.fail("TestLoader.loadTestsFromName failed to raise ImportError")275 276 # "The specifier name is a ``dotted name'' that may resolve either to277 # a module, a test case class, a TestSuite instance, a test method278 # within a test case class, or a callable object which returns a279 # TestCase or TestSuite instance."280 #281 # What happens when the module is found, but the attribute can't?282 def test_loadTestsFromName__unknown_attr_name(self):283 loader = unittest.TestLoader()284 285 try:286 loader.loadTestsFromName('unittest.sdasfasfasdf')287 except AttributeError, e:288 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")289 else:290 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")291 292 # "The specifier name is a ``dotted name'' that may resolve either to293 # a module, a test case class, a TestSuite instance, a test method294 # within a test case class, or a callable object which returns a295 # TestCase or TestSuite instance."296 #297 # What happens when we provide the module, but the attribute can't be298 # found?299 def test_loadTestsFromName__relative_unknown_name(self):300 loader = unittest.TestLoader()301 302 try:303 loader.loadTestsFromName('sdasfasfasdf', unittest)304 except AttributeError, e:305 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")306 else:307 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")308 309 # "The specifier name is a ``dotted name'' that may resolve either to310 # a module, a test case class, a TestSuite instance, a test method311 # within a test case class, or a callable object which returns a312 # TestCase or TestSuite instance."313 # ...314 # "The method optionally resolves name relative to the given module"315 #316 # Does loadTestsFromName raise ValueError when passed an empty317 # name relative to a provided module?318 #319 # XXX Should probably raise a ValueError instead of an AttributeError320 def test_loadTestsFromName__relative_empty_name(self):321 loader = unittest.TestLoader()322 323 try:324 loader.loadTestsFromName('', unittest)325 except AttributeError, e:326 pass327 else:328 self.fail("Failed to raise AttributeError")329 330 # "The specifier name is a ``dotted name'' that may resolve either to331 # a module, a test case class, a TestSuite instance, a test method332 # within a test case class, or a callable object which returns a333 # TestCase or TestSuite instance."334 # ...335 # "The method optionally resolves name relative to the given module"336 #337 # What happens when an impossible name is given, relative to the provided338 # `module`?339 def test_loadTestsFromName__relative_malformed_name(self):340 loader = unittest.TestLoader()341 342 # XXX Should this raise AttributeError or ValueError?343 try:344 loader.loadTestsFromName('abc () //', unittest)345 except ValueError:346 pass347 except AttributeError:348 pass349 else:350 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")351 352 # "The method optionally resolves name relative to the given module"353 #354 # Does loadTestsFromName raise TypeError when the `module` argument355 # isn't a module object?356 #357 # XXX Accepts the not-a-module object, ignorning the object's type358 # This should raise an exception or the method name should be changed359 #360 # XXX Some people are relying on this, so keep it for now361 def test_loadTestsFromName__relative_not_a_module(self):362 class MyTestCase(unittest.TestCase):363 def test(self):364 pass365 366 class NotAModule(object):367 test_2 = MyTestCase368 369 loader = unittest.TestLoader()370 suite = loader.loadTestsFromName('test_2', NotAModule)371 372 reference = [MyTestCase('test')]373 self.assertEqual(list(suite), reference)374 375 # "The specifier name is a ``dotted name'' that may resolve either to376 # a module, a test case class, a TestSuite instance, a test method377 # within a test case class, or a callable object which returns a378 # TestCase or TestSuite instance."379 #380 # Does it raise an exception if the name resolves to an invalid381 # object?382 def test_loadTestsFromName__relative_bad_object(self):383 m = types.ModuleType('m')384 m.testcase_1 = object()385 386 loader = unittest.TestLoader()387 try:388 loader.loadTestsFromName('testcase_1', m)389 except TypeError:390 pass391 else:392 self.fail("Should have raised TypeError")393 394 # "The specifier name is a ``dotted name'' that may395 # resolve either to ... a test case class"396 def test_loadTestsFromName__relative_TestCase_subclass(self):397 m = types.ModuleType('m')398 class MyTestCase(unittest.TestCase):399 def test(self):400 pass401 m.testcase_1 = MyTestCase402 403 loader = unittest.TestLoader()404 suite = loader.loadTestsFromName('testcase_1', m)405 self.failUnless(isinstance(suite, loader.suiteClass))406 self.assertEqual(list(suite), [MyTestCase('test')])407 408 # "The specifier name is a ``dotted name'' that may resolve either to409 # a module, a test case class, a TestSuite instance, a test method410 # within a test case class, or a callable object which returns a411 # TestCase or TestSuite instance."412 def test_loadTestsFromName__relative_TestSuite(self):413 m = types.ModuleType('m')414 class MyTestCase(unittest.TestCase):415 def test(self):416 pass417 m.testsuite = unittest.TestSuite([MyTestCase('test')])418 419 loader = unittest.TestLoader()420 suite = loader.loadTestsFromName('testsuite', m)421 self.failUnless(isinstance(suite, loader.suiteClass))422 423 self.assertEqual(list(suite), [MyTestCase('test')])424 425 # "The specifier name is a ``dotted name'' that may resolve ... to426 # ... a test method within a test case class"427 def test_loadTestsFromName__relative_testmethod(self):428 m = types.ModuleType('m')429 class MyTestCase(unittest.TestCase):430 def test(self):431 pass432 m.testcase_1 = MyTestCase433 434 loader = unittest.TestLoader()435 suite = loader.loadTestsFromName('testcase_1.test', m)436 self.failUnless(isinstance(suite, loader.suiteClass))437 438 self.assertEqual(list(suite), [MyTestCase('test')])439 440 # "The specifier name is a ``dotted name'' that may resolve either to441 # a module, a test case class, a TestSuite instance, a test method442 # within a test case class, or a callable object which returns a443 # TestCase or TestSuite instance."444 #445 # Does loadTestsFromName() raise the proper exception when trying to446 # resolve "a test method within a test case class" that doesn't exist447 # for the given name (relative to a provided module)?448 def test_loadTestsFromName__relative_invalid_testmethod(self):449 m = types.ModuleType('m')450 class MyTestCase(unittest.TestCase):451 def test(self):452 pass453 m.testcase_1 = MyTestCase454 455 loader = unittest.TestLoader()456 try:457 loader.loadTestsFromName('testcase_1.testfoo', m)458 except AttributeError, e:459 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")460 else:461 self.fail("Failed to raise AttributeError")462 463 # "The specifier name is a ``dotted name'' that may resolve ... to464 # ... a callable object which returns a ... TestSuite instance"465 def test_loadTestsFromName__callable__TestSuite(self):466 m = types.ModuleType('m')467 testcase_1 = unittest.FunctionTestCase(lambda: None)468 testcase_2 = unittest.FunctionTestCase(lambda: None)469 def return_TestSuite():470 return unittest.TestSuite([testcase_1, testcase_2])471 m.return_TestSuite = return_TestSuite472 473 loader = unittest.TestLoader()474 suite = loader.loadTestsFromName('return_TestSuite', m)475 self.failUnless(isinstance(suite, loader.suiteClass))476 self.assertEqual(list(suite), [testcase_1, testcase_2])477 478 # "The specifier name is a ``dotted name'' that may resolve ... to479 # ... a callable object which returns a TestCase ... instance"480 def test_loadTestsFromName__callable__TestCase_instance(self):481 m = types.ModuleType('m')482 testcase_1 = unittest.FunctionTestCase(lambda: None)483 def return_TestCase():484 return testcase_1485 m.return_TestCase = return_TestCase486 487 loader = unittest.TestLoader()488 suite = loader.loadTestsFromName('return_TestCase', m)489 self.failUnless(isinstance(suite, loader.suiteClass))490 self.assertEqual(list(suite), [testcase_1])491 492 # "The specifier name is a ``dotted name'' that may resolve ... to493 # ... a callable object which returns a TestCase or TestSuite instance"494 #495 # What happens if the callable returns something else?496 def test_loadTestsFromName__callable__wrong_type(self):497 m = types.ModuleType('m')498 def return_wrong():499 return 6500 m.return_wrong = return_wrong501 502 loader = unittest.TestLoader()503 try:504 suite = loader.loadTestsFromName('return_wrong', m)505 except TypeError:506 pass507 else:508 self.fail("TestLoader.loadTestsFromName failed to raise TypeError")509 510 # "The specifier can refer to modules and packages which have not been511 # imported; they will be imported as a side-effect"512 def test_loadTestsFromName__module_not_loaded(self):513 # We're going to try to load this module as a side-effect, so it514 # better not be loaded before we try.515 #516 # Why pick audioop? Google shows it isn't used very often, so there's517 # a good chance that it won't be imported when this test is run518 module_name = 'audioop'519 520 import sys521 if module_name in sys.modules:522 del sys.modules[module_name]523 524 loader = unittest.TestLoader()525 try:526 suite = loader.loadTestsFromName(module_name)527 528 self.failUnless(isinstance(suite, loader.suiteClass))529 self.assertEqual(list(suite), [])530 531 # audioop should now be loaded, thanks to loadTestsFromName()532 self.failUnless(module_name in sys.modules)533 finally:534 if module_name in sys.modules:535 del sys.modules[module_name]536 537 ################################################################538 ### Tests for TestLoader.loadTestsFromName()539 540 ### Tests for TestLoader.loadTestsFromNames()541 ################################################################542 543 # "Similar to loadTestsFromName(), but takes a sequence of names rather544 # than a single name."545 #546 # What happens if that sequence of names is empty?547 def test_loadTestsFromNames__empty_name_list(self):548 loader = unittest.TestLoader()549 550 suite = loader.loadTestsFromNames([])551 self.failUnless(isinstance(suite, loader.suiteClass))552 self.assertEqual(list(suite), [])553 554 # "Similar to loadTestsFromName(), but takes a sequence of names rather555 # than a single name."556 # ...557 # "The method optionally resolves name relative to the given module"558 #559 # What happens if that sequence of names is empty?560 #561 # XXX Should this raise a ValueError or just return an empty TestSuite?562 def test_loadTestsFromNames__relative_empty_name_list(self):563 loader = unittest.TestLoader()564 565 suite = loader.loadTestsFromNames([], unittest)566 self.failUnless(isinstance(suite, loader.suiteClass))567 self.assertEqual(list(suite), [])568 569 # "The specifier name is a ``dotted name'' that may resolve either to570 # a module, a test case class, a TestSuite instance, a test method571 # within a test case class, or a callable object which returns a572 # TestCase or TestSuite instance."573 #574 # Is ValueError raised in response to an empty name?575 def test_loadTestsFromNames__empty_name(self):576 loader = unittest.TestLoader()577 578 try:579 loader.loadTestsFromNames([''])580 except ValueError, e:581 self.assertEqual(str(e), "Empty module name")582 else:583 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")584 585 # "The specifier name is a ``dotted name'' that may resolve either to586 # a module, a test case class, a TestSuite instance, a test method587 # within a test case class, or a callable object which returns a588 # TestCase or TestSuite instance."589 #590 # What happens when presented with an impossible module name?591 def test_loadTestsFromNames__malformed_name(self):592 loader = unittest.TestLoader()593 594 # XXX Should this raise ValueError or ImportError?595 try:596 loader.loadTestsFromNames(['abc () //'])597 except ValueError:598 pass599 except ImportError:600 pass601 else:602 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")603 604 # "The specifier name is a ``dotted name'' that may resolve either to605 # a module, a test case class, a TestSuite instance, a test method606 # within a test case class, or a callable object which returns a607 # TestCase or TestSuite instance."608 #609 # What happens when no module can be found for the given name?610 def test_loadTestsFromNames__unknown_module_name(self):611 loader = unittest.TestLoader()612 613 try:614 loader.loadTestsFromNames(['sdasfasfasdf'])615 except ImportError, e:616 self.assertEqual(str(e), "No module named sdasfasfasdf")617 else:618 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")619 620 # "The specifier name is a ``dotted name'' that may resolve either to621 # a module, a test case class, a TestSuite instance, a test method622 # within a test case class, or a callable object which returns a623 # TestCase or TestSuite instance."624 #625 # What happens when the module can be found, but not the attribute?626 def test_loadTestsFromNames__unknown_attr_name(self):627 loader = unittest.TestLoader()628 629 try:630 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])631 except AttributeError, e:632 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")633 else:634 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")635 636 # "The specifier name is a ``dotted name'' that may resolve either to637 # a module, a test case class, a TestSuite instance, a test method638 # within a test case class, or a callable object which returns a639 # TestCase or TestSuite instance."640 # ...641 # "The method optionally resolves name relative to the given module"642 #643 # What happens when given an unknown attribute on a specified `module`644 # argument?645 def test_loadTestsFromNames__unknown_name_relative_1(self):646 loader = unittest.TestLoader()647 648 try:649 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)650 except AttributeError, e:651 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")652 else:653 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")654 655 # "The specifier name is a ``dotted name'' that may resolve either to656 # a module, a test case class, a TestSuite instance, a test method657 # within a test case class, or a callable object which returns a658 # TestCase or TestSuite instance."659 # ...660 # "The method optionally resolves name relative to the given module"661 #662 # Do unknown attributes (relative to a provided module) still raise an663 # exception even in the presence of valid attribute names?664 def test_loadTestsFromNames__unknown_name_relative_2(self):665 loader = unittest.TestLoader()666 667 try:668 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)669 except AttributeError, e:670 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")671 else:672 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")673 674 # "The specifier name is a ``dotted name'' that may resolve either to675 # a module, a test case class, a TestSuite instance, a test method676 # within a test case class, or a callable object which returns a677 # TestCase or TestSuite instance."678 # ...679 # "The method optionally resolves name relative to the given module"680 #681 # What happens when faced with the empty string?682 #683 # XXX This currently raises AttributeError, though ValueError is probably684 # more appropriate685 def test_loadTestsFromNames__relative_empty_name(self):686 loader = unittest.TestLoader()687 688 try:689 loader.loadTestsFromNames([''], unittest)690 except AttributeError:691 pass692 else:693 self.fail("Failed to raise ValueError")694 695 # "The specifier name is a ``dotted name'' that may resolve either to696 # a module, a test case class, a TestSuite instance, a test method697 # within a test case class, or a callable object which returns a698 # TestCase or TestSuite instance."699 # ...700 # "The method optionally resolves name relative to the given module"701 #702 # What happens when presented with an impossible attribute name?703 def test_loadTestsFromNames__relative_malformed_name(self):704 loader = unittest.TestLoader()705 706 # XXX Should this raise AttributeError or ValueError?707 try:708 loader.loadTestsFromNames(['abc () //'], unittest)709 except AttributeError:710 pass711 except ValueError:712 pass713 else:714 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")715 716 # "The method optionally resolves name relative to the given module"717 #718 # Does loadTestsFromNames() make sure the provided `module` is in fact719 # a module?720 #721 # XXX This validation is currently not done. This flexibility should722 # either be documented or a TypeError should be raised.723 def test_loadTestsFromNames__relative_not_a_module(self):724 class MyTestCase(unittest.TestCase):725 def test(self):726 pass727 728 class NotAModule(object):729 test_2 = MyTestCase730 731 loader = unittest.TestLoader()732 suite = loader.loadTestsFromNames(['test_2'], NotAModule)733 734 reference = [unittest.TestSuite([MyTestCase('test')])]735 self.assertEqual(list(suite), reference)736 737 # "The specifier name is a ``dotted name'' that may resolve either to738 # a module, a test case class, a TestSuite instance, a test method739 # within a test case class, or a callable object which returns a740 # TestCase or TestSuite instance."741 #742 # Does it raise an exception if the name resolves to an invalid743 # object?744 def test_loadTestsFromNames__relative_bad_object(self):745 m = types.ModuleType('m')746 m.testcase_1 = object()747 748 loader = unittest.TestLoader()749 try:750 loader.loadTestsFromNames(['testcase_1'], m)751 except TypeError:752 pass753 else:754 self.fail("Should have raised TypeError")755 756 # "The specifier name is a ``dotted name'' that may resolve ... to757 # ... a test case class"758 def test_loadTestsFromNames__relative_TestCase_subclass(self):759 m = types.ModuleType('m')760 class MyTestCase(unittest.TestCase):761 def test(self):762 pass763 m.testcase_1 = MyTestCase764 765 loader = unittest.TestLoader()766 suite = loader.loadTestsFromNames(['testcase_1'], m)767 self.failUnless(isinstance(suite, loader.suiteClass))768 769 expected = loader.suiteClass([MyTestCase('test')])770 self.assertEqual(list(suite), [expected])771 772 # "The specifier name is a ``dotted name'' that may resolve ... to773 # ... a TestSuite instance"774 def test_loadTestsFromNames__relative_TestSuite(self):775 m = types.ModuleType('m')776 class MyTestCase(unittest.TestCase):777 def test(self):778 pass779 m.testsuite = unittest.TestSuite([MyTestCase('test')])780 781 loader = unittest.TestLoader()782 suite = loader.loadTestsFromNames(['testsuite'], m)783 self.failUnless(isinstance(suite, loader.suiteClass))784 785 self.assertEqual(list(suite), [m.testsuite])786 787 # "The specifier name is a ``dotted name'' that may resolve ... to ... a788 # test method within a test case class"789 def test_loadTestsFromNames__relative_testmethod(self):790 m = types.ModuleType('m')791 class MyTestCase(unittest.TestCase):792 def test(self):793 pass794 m.testcase_1 = MyTestCase795 796 loader = unittest.TestLoader()797 suite = loader.loadTestsFromNames(['testcase_1.test'], m)798 self.failUnless(isinstance(suite, loader.suiteClass))799 800 ref_suite = unittest.TestSuite([MyTestCase('test')])801 self.assertEqual(list(suite), [ref_suite])802 803 # "The specifier name is a ``dotted name'' that may resolve ... to ... a804 # test method within a test case class"805 #806 # Does the method gracefully handle names that initially look like they807 # resolve to "a test method within a test case class" but don't?808 def test_loadTestsFromNames__relative_invalid_testmethod(self):809 m = types.ModuleType('m')810 class MyTestCase(unittest.TestCase):811 def test(self):812 pass813 m.testcase_1 = MyTestCase814 815 loader = unittest.TestLoader()816 try:817 loader.loadTestsFromNames(['testcase_1.testfoo'], m)818 except AttributeError, e:819 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")820 else:821 self.fail("Failed to raise AttributeError")822 823 # "The specifier name is a ``dotted name'' that may resolve ... to824 # ... a callable object which returns a ... TestSuite instance"825 def test_loadTestsFromNames__callable__TestSuite(self):826 m = types.ModuleType('m')827 testcase_1 = unittest.FunctionTestCase(lambda: None)828 testcase_2 = unittest.FunctionTestCase(lambda: None)829 def return_TestSuite():830 return unittest.TestSuite([testcase_1, testcase_2])831 m.return_TestSuite = return_TestSuite832 833 loader = unittest.TestLoader()834 suite = loader.loadTestsFromNames(['return_TestSuite'], m)835 self.failUnless(isinstance(suite, loader.suiteClass))836 837 expected = unittest.TestSuite([testcase_1, testcase_2])838 self.assertEqual(list(suite), [expected])839 840 # "The specifier name is a ``dotted name'' that may resolve ... to841 # ... a callable object which returns a TestCase ... instance"842 def test_loadTestsFromNames__callable__TestCase_instance(self):843 m = types.ModuleType('m')844 testcase_1 = unittest.FunctionTestCase(lambda: None)845 def return_TestCase():846 return testcase_1847 m.return_TestCase = return_TestCase848 849 loader = unittest.TestLoader()850 suite = loader.loadTestsFromNames(['return_TestCase'], m)851 self.failUnless(isinstance(suite, loader.suiteClass))852 853 ref_suite = unittest.TestSuite([testcase_1])854 self.assertEqual(list(suite), [ref_suite])855 856 # "The specifier name is a ``dotted name'' that may resolve ... to857 # ... a callable object which returns a TestCase or TestSuite instance"858 #859 # Are staticmethods handled correctly?860 def test_loadTestsFromNames__callable__call_staticmethod(self):861 m = types.ModuleType('m')862 class Test1(unittest.TestCase):863 def test(self):864 pass865 866 testcase_1 = Test1('test')867 class Foo(unittest.TestCase):868 @staticmethod869 def foo():870 return testcase_1871 m.Foo = Foo872 873 loader = unittest.TestLoader()874 suite = loader.loadTestsFromNames(['Foo.foo'], m)875 self.failUnless(isinstance(suite, loader.suiteClass))876 877 ref_suite = unittest.TestSuite([testcase_1])878 self.assertEqual(list(suite), [ref_suite])879 880 # "The specifier name is a ``dotted name'' that may resolve ... to881 # ... a callable object which returns a TestCase or TestSuite instance"882 #883 # What happens when the callable returns something else?884 def test_loadTestsFromNames__callable__wrong_type(self):885 m = types.ModuleType('m')886 def return_wrong():887 return 6888 m.return_wrong = return_wrong889 890 loader = unittest.TestLoader()891 try:892 suite = loader.loadTestsFromNames(['return_wrong'], m)893 except TypeError:894 pass895 else:896 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")897 898 # "The specifier can refer to modules and packages which have not been899 # imported; they will be imported as a side-effect"900 def test_loadTestsFromNames__module_not_loaded(self):901 # We're going to try to load this module as a side-effect, so it902 # better not be loaded before we try.903 #904 # Why pick audioop? Google shows it isn't used very often, so there's905 # a good chance that it won't be imported when this test is run906 module_name = 'audioop'907 908 import sys909 if module_name in sys.modules:910 del sys.modules[module_name]911 912 loader = unittest.TestLoader()913 try:914 suite = loader.loadTestsFromNames([module_name])915 916 self.failUnless(isinstance(suite, loader.suiteClass))917 self.assertEqual(list(suite), [unittest.TestSuite()])918 919 # audioop should now be loaded, thanks to loadTestsFromName()920 self.failUnless(module_name in sys.modules)921 finally:922 if module_name in sys.modules:923 del sys.modules[module_name]924 925 ################################################################926 ### /Tests for TestLoader.loadTestsFromNames()927 928 ### Tests for TestLoader.getTestCaseNames()929 ################################################################930 931 # "Return a sorted sequence of method names found within testCaseClass"932 #933 # Test.foobar is defined to make sure getTestCaseNames() respects934 # loader.testMethodPrefix935 def test_getTestCaseNames(self):936 class Test(unittest.TestCase):937 def test_1(self): pass938 def test_2(self): pass939 def foobar(self): pass940 941 loader = unittest.TestLoader()942 943 self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])944 945 # "Return a sorted sequence of method names found within testCaseClass"946 #947 # Does getTestCaseNames() behave appropriately if no tests are found?948 def test_getTestCaseNames__no_tests(self):949 class Test(unittest.TestCase):950 def foobar(self): pass951 952 loader = unittest.TestLoader()953 954 self.assertEqual(loader.getTestCaseNames(Test), [])955 956 # "Return a sorted sequence of method names found within testCaseClass"957 #958 # Are not-TestCases handled gracefully?959 #960 # XXX This should raise a TypeError, not return a list961 #962 # XXX It's too late in the 2.5 release cycle to fix this, but it should963 # probably be revisited for 2.6964 def test_getTestCaseNames__not_a_TestCase(self):965 class BadCase(int):966 def test_foo(self):967 pass968 969 loader = unittest.TestLoader()970 names = loader.getTestCaseNames(BadCase)971 972 self.assertEqual(names, ['test_foo'])973 974 # "Return a sorted sequence of method names found within testCaseClass"975 #976 # Make sure inherited names are handled.977 #978 # TestP.foobar is defined to make sure getTestCaseNames() respects979 # loader.testMethodPrefix980 def test_getTestCaseNames__inheritance(self):981 class TestP(unittest.TestCase):982 def test_1(self): pass983 def test_2(self): pass984 def foobar(self): pass985 986 class TestC(TestP):987 def test_1(self): pass988 def test_3(self): pass989 990 loader = unittest.TestLoader()991 992 names = ['test_1', 'test_2', 'test_3']993 self.assertEqual(loader.getTestCaseNames(TestC), names)994 995 ################################################################996 ### /Tests for TestLoader.getTestCaseNames()997 998 ### Tests for TestLoader.testMethodPrefix999 ################################################################1000 1001 # "String giving the prefix of method names which will be interpreted as1002 # test methods"1003 #1004 # Implicit in the documentation is that testMethodPrefix is respected by1005 # all loadTestsFrom* methods.1006 def test_testMethodPrefix__loadTestsFromTestCase(self):1007 class Foo(unittest.TestCase):1008 def test_1(self): pass1009 def test_2(self): pass1010 def foo_bar(self): pass1011 1012 tests_1 = unittest.TestSuite([Foo('foo_bar')])1013 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])1014 1015 loader = unittest.TestLoader()1016 loader.testMethodPrefix = 'foo'1017 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)1018 1019 loader.testMethodPrefix = 'test'1020 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)1021 1022 # "String giving the prefix of method names which will be interpreted as1023 # test methods"1024 #1025 # Implicit in the documentation is that testMethodPrefix is respected by1026 # all loadTestsFrom* methods.1027 def test_testMethodPrefix__loadTestsFromModule(self):1028 m = types.ModuleType('m')1029 class Foo(unittest.TestCase):1030 def test_1(self): pass1031 def test_2(self): pass1032 def foo_bar(self): pass1033 m.Foo = Foo1034 1035 tests_1 = [unittest.TestSuite([Foo('foo_bar')])]1036 tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]1037 1038 loader = unittest.TestLoader()1039 loader.testMethodPrefix = 'foo'1040 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)1041 1042 loader.testMethodPrefix = 'test'1043 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)1044 1045 # "String giving the prefix of method names which will be interpreted as1046 # test methods"1047 #1048 # Implicit in the documentation is that testMethodPrefix is respected by1049 # all loadTestsFrom* methods.1050 def test_testMethodPrefix__loadTestsFromName(self):1051 m = types.ModuleType('m')1052 class Foo(unittest.TestCase):1053 def test_1(self): pass1054 def test_2(self): pass1055 def foo_bar(self): pass1056 m.Foo = Foo1057 1058 tests_1 = unittest.TestSuite([Foo('foo_bar')])1059 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])1060 1061 loader = unittest.TestLoader()1062 loader.testMethodPrefix = 'foo'1063 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)1064 1065 loader.testMethodPrefix = 'test'1066 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)1067 1068 # "String giving the prefix of method names which will be interpreted as1069 # test methods"1070 #1071 # Implicit in the documentation is that testMethodPrefix is respected by1072 # all loadTestsFrom* methods.1073 def test_testMethodPrefix__loadTestsFromNames(self):1074 m = types.ModuleType('m')1075 class Foo(unittest.TestCase):1076 def test_1(self): pass1077 def test_2(self): pass1078 def foo_bar(self): pass1079 m.Foo = Foo1080 1081 tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])1082 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])1083 tests_2 = unittest.TestSuite([tests_2])1084 1085 loader = unittest.TestLoader()1086 loader.testMethodPrefix = 'foo'1087 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)1088 1089 loader.testMethodPrefix = 'test'1090 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)1091 1092 # "The default value is 'test'"1093 def test_testMethodPrefix__default_value(self):1094 loader = unittest.TestLoader()1095 self.failUnless(loader.testMethodPrefix == 'test')1096 1097 ################################################################1098 ### /Tests for TestLoader.testMethodPrefix1099 1100 ### Tests for TestLoader.sortTestMethodsUsing1101 ################################################################1102 1103 # "Function to be used to compare method names when sorting them in1104 # getTestCaseNames() and all the loadTestsFromX() methods"1105 def test_sortTestMethodsUsing__loadTestsFromTestCase(self):1106 def reversed_cmp(x, y):1107 return -cmp(x, y)1108 1109 class Foo(unittest.TestCase):1110 def test_1(self): pass1111 def test_2(self): pass1112 1113 loader = unittest.TestLoader()1114 loader.sortTestMethodsUsing = reversed_cmp1115 1116 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])1117 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)1118 1119 # "Function to be used to compare method names when sorting them in1120 # getTestCaseNames() and all the loadTestsFromX() methods"1121 def test_sortTestMethodsUsing__loadTestsFromModule(self):1122 def reversed_cmp(x, y):1123 return -cmp(x, y)1124 1125 m = types.ModuleType('m')1126 class Foo(unittest.TestCase):1127 def test_1(self): pass1128 def test_2(self): pass1129 m.Foo = Foo1130 1131 loader = unittest.TestLoader()1132 loader.sortTestMethodsUsing = reversed_cmp1133 1134 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]1135 self.assertEqual(list(loader.loadTestsFromModule(m)), tests)1136 1137 # "Function to be used to compare method names when sorting them in1138 # getTestCaseNames() and all the loadTestsFromX() methods"1139 def test_sortTestMethodsUsing__loadTestsFromName(self):1140 def reversed_cmp(x, y):1141 return -cmp(x, y)1142 1143 m = types.ModuleType('m')1144 class Foo(unittest.TestCase):1145 def test_1(self): pass1146 def test_2(self): pass1147 m.Foo = Foo1148 1149 loader = unittest.TestLoader()1150 loader.sortTestMethodsUsing = reversed_cmp1151 1152 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])1153 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)1154 1155 # "Function to be used to compare method names when sorting them in1156 # getTestCaseNames() and all the loadTestsFromX() methods"1157 def test_sortTestMethodsUsing__loadTestsFromNames(self):1158 def reversed_cmp(x, y):1159 return -cmp(x, y)1160 1161 m = types.ModuleType('m')1162 class Foo(unittest.TestCase):1163 def test_1(self): pass1164 def test_2(self): pass1165 m.Foo = Foo1166 1167 loader = unittest.TestLoader()1168 loader.sortTestMethodsUsing = reversed_cmp1169 1170 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]1171 self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)1172 1173 # "Function to be used to compare method names when sorting them in1174 # getTestCaseNames()"1175 #1176 # Does it actually affect getTestCaseNames()?1177 def test_sortTestMethodsUsing__getTestCaseNames(self):1178 def reversed_cmp(x, y):1179 return -cmp(x, y)1180 1181 class Foo(unittest.TestCase):1182 def test_1(self): pass1183 def test_2(self): pass1184 1185 loader = unittest.TestLoader()1186 loader.sortTestMethodsUsing = reversed_cmp1187 1188 test_names = ['test_2', 'test_1']1189 self.assertEqual(loader.getTestCaseNames(Foo), test_names)1190 1191 # "The default value is the built-in cmp() function"1192 def test_sortTestMethodsUsing__default_value(self):1193 loader = unittest.TestLoader()1194 self.failUnless(loader.sortTestMethodsUsing is cmp)1195 1196 # "it can be set to None to disable the sort."1197 #1198 # XXX How is this different from reassigning cmp? Are the tests returned1199 # in a random order or something? This behaviour should die1200 def test_sortTestMethodsUsing__None(self):1201 class Foo(unittest.TestCase):1202 def test_1(self): pass1203 def test_2(self): pass1204 1205 loader = unittest.TestLoader()1206 loader.sortTestMethodsUsing = None1207 1208 test_names = ['test_2', 'test_1']1209 self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))1210 1211 ################################################################1212 ### /Tests for TestLoader.sortTestMethodsUsing1213 1214 ### Tests for TestLoader.suiteClass1215 ################################################################1216 1217 # "Callable object that constructs a test suite from a list of tests."1218 def test_suiteClass__loadTestsFromTestCase(self):1219 class Foo(unittest.TestCase):1220 def test_1(self): pass1221 def test_2(self): pass1222 def foo_bar(self): pass1223 1224 tests = [Foo('test_1'), Foo('test_2')]1225 1226 loader = unittest.TestLoader()1227 loader.suiteClass = list1228 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)1229 1230 # It is implicit in the documentation for TestLoader.suiteClass that1231 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure1232 def test_suiteClass__loadTestsFromModule(self):1233 m = types.ModuleType('m')1234 class Foo(unittest.TestCase):1235 def test_1(self): pass1236 def test_2(self): pass1237 def foo_bar(self): pass1238 m.Foo = Foo1239 1240 tests = [[Foo('test_1'), Foo('test_2')]]1241 1242 loader = unittest.TestLoader()1243 loader.suiteClass = list1244 self.assertEqual(loader.loadTestsFromModule(m), tests)1245 1246 # It is implicit in the documentation for TestLoader.suiteClass that1247 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure1248 def test_suiteClass__loadTestsFromName(self):1249 m = types.ModuleType('m')1250 class Foo(unittest.TestCase):1251 def test_1(self): pass1252 def test_2(self): pass1253 def foo_bar(self): pass1254 m.Foo = Foo1255 1256 tests = [Foo('test_1'), Foo('test_2')]1257 1258 loader = unittest.TestLoader()1259 loader.suiteClass = list1260 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)1261 1262 # It is implicit in the documentation for TestLoader.suiteClass that1263 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure1264 def test_suiteClass__loadTestsFromNames(self):1265 m = types.ModuleType('m')1266 class Foo(unittest.TestCase):1267 def test_1(self): pass1268 def test_2(self): pass1269 def foo_bar(self): pass1270 m.Foo = Foo1271 1272 tests = [[Foo('test_1'), Foo('test_2')]]1273 1274 loader = unittest.TestLoader()1275 loader.suiteClass = list1276 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)1277 1278 # "The default value is the TestSuite class"1279 def test_suiteClass__default_value(self):1280 loader = unittest.TestLoader()1281 self.failUnless(loader.suiteClass is unittest.TestSuite)1282 1283 ################################################################1284 ### /Tests for TestLoader.suiteClass1285 1286 ### Support code for Test_TestSuite1287 ################################################################1288 1289 class Foo(unittest.TestCase):1290 def test_1(self): pass1291 def test_2(self): pass1292 def test_3(self): pass1293 def runTest(self): pass1294 1295 def _mk_TestSuite(*names):1296 return unittest.TestSuite(Foo(n) for n in names)1297 1298 ################################################################1299 ### /Support code for Test_TestSuite1300 1301 class Test_TestSuite(TestCase, TestEquality):1302 1303 ### Set up attributes needed by inherited tests1304 ################################################################1305 1306 # Used by TestEquality.test_eq1307 eq_pairs = [(unittest.TestSuite(), unittest.TestSuite())1308 ,(unittest.TestSuite(), unittest.TestSuite([]))1309 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]1310 1311 # Used by TestEquality.test_ne1312 ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1'))1313 ,(unittest.TestSuite([]), _mk_TestSuite('test_1'))1314 ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3'))1315 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]1316 1317 ################################################################1318 ### /Set up attributes needed by inherited tests1319 1320 ### Tests for TestSuite.__init__1321 ################################################################1322 1323 # "class TestSuite([tests])"1324 #1325 # The tests iterable should be optional1326 def test_init__tests_optional(self):1327 suite = unittest.TestSuite()1328 1329 self.assertEqual(suite.countTestCases(), 0)1330 1331 # "class TestSuite([tests])"1332 # ...1333 # "If tests is given, it must be an iterable of individual test cases1334 # or other test suites that will be used to build the suite initially"1335 #1336 # TestSuite should deal with empty tests iterables by allowing the1337 # creation of an empty suite1338 def test_init__empty_tests(self):1339 suite = unittest.TestSuite([])1340 1341 self.assertEqual(suite.countTestCases(), 0)1342 1343 # "class TestSuite([tests])"1344 # ...1345 # "If tests is given, it must be an iterable of individual test cases1346 # or other test suites that will be used to build the suite initially"1347 #1348 # TestSuite should allow any iterable to provide tests1349 def test_init__tests_from_any_iterable(self):1350 def tests():1351 yield unittest.FunctionTestCase(lambda: None)1352 yield unittest.FunctionTestCase(lambda: None)1353 1354 suite_1 = unittest.TestSuite(tests())1355 self.assertEqual(suite_1.countTestCases(), 2)1356 1357 suite_2 = unittest.TestSuite(suite_1)1358 self.assertEqual(suite_2.countTestCases(), 2)1359 1360 suite_3 = unittest.TestSuite(set(suite_1))1361 self.assertEqual(suite_3.countTestCases(), 2)1362 1363 # "class TestSuite([tests])"1364 # ...1365 # "If tests is given, it must be an iterable of individual test cases1366 # or other test suites that will be used to build the suite initially"1367 #1368 # Does TestSuite() also allow other TestSuite() instances to be present1369 # in the tests iterable?1370 def test_init__TestSuite_instances_in_tests(self):1371 def tests():1372 ftc = unittest.FunctionTestCase(lambda: None)1373 yield unittest.TestSuite([ftc])1374 yield unittest.FunctionTestCase(lambda: None)1375 1376 suite = unittest.TestSuite(tests())1377 self.assertEqual(suite.countTestCases(), 2)1378 1379 ################################################################1380 ### /Tests for TestSuite.__init__1381 1382 # Container types should support the iter protocol1383 def test_iter(self):1384 test1 = unittest.FunctionTestCase(lambda: None)1385 test2 = unittest.FunctionTestCase(lambda: None)1386 suite = unittest.TestSuite((test1, test2))1387 1388 self.assertEqual(list(suite), [test1, test2])1389 1390 # "Return the number of tests represented by the this test object.1391 # ...this method is also implemented by the TestSuite class, which can1392 # return larger [greater than 1] values"1393 #1394 # Presumably an empty TestSuite returns 0?1395 def test_countTestCases_zero_simple(self):1396 suite = unittest.TestSuite()1397 1398 self.assertEqual(suite.countTestCases(), 0)1399 1400 # "Return the number of tests represented by the this test object.1401 # ...this method is also implemented by the TestSuite class, which can1402 # return larger [greater than 1] values"1403 #1404 # Presumably an empty TestSuite (even if it contains other empty1405 # TestSuite instances) returns 0?1406 def test_countTestCases_zero_nested(self):1407 class Test1(unittest.TestCase):1408 def test(self):1409 pass1410 1411 suite = unittest.TestSuite([unittest.TestSuite()])1412 1413 self.assertEqual(suite.countTestCases(), 0)1414 1415 # "Return the number of tests represented by the this test object.1416 # ...this method is also implemented by the TestSuite class, which can1417 # return larger [greater than 1] values"1418 def test_countTestCases_simple(self):1419 test1 = unittest.FunctionTestCase(lambda: None)1420 test2 = unittest.FunctionTestCase(lambda: None)1421 suite = unittest.TestSuite((test1, test2))1422 1423 self.assertEqual(suite.countTestCases(), 2)1424 1425 # "Return the number of tests represented by the this test object.1426 # ...this method is also implemented by the TestSuite class, which can1427 # return larger [greater than 1] values"1428 #1429 # Make sure this holds for nested TestSuite instances, too1430 def test_countTestCases_nested(self):1431 class Test1(unittest.TestCase):1432 def test1(self): pass1433 def test2(self): pass1434 1435 test2 = unittest.FunctionTestCase(lambda: None)1436 test3 = unittest.FunctionTestCase(lambda: None)1437 child = unittest.TestSuite((Test1('test2'), test2))1438 parent = unittest.TestSuite((test3, child, Test1('test1')))1439 1440 self.assertEqual(parent.countTestCases(), 4)1441 1442 # "Run the tests associated with this suite, collecting the result into1443 # the test result object passed as result."1444 #1445 # And if there are no tests? What then?1446 def test_run__empty_suite(self):1447 events = []1448 result = LoggingResult(events)1449 1450 suite = unittest.TestSuite()1451 1452 suite.run(result)1453 1454 self.assertEqual(events, [])1455 1456 # "Note that unlike TestCase.run(), TestSuite.run() requires the1457 # "result object to be passed in."1458 def test_run__requires_result(self):1459 suite = unittest.TestSuite()1460 1461 try:1462 suite.run()1463 except TypeError:1464 pass1465 else:1466 self.fail("Failed to raise TypeError")1467 1468 # "Run the tests associated with this suite, collecting the result into1469 # the test result object passed as result."1470 def test_run(self):1471 events = []1472 result = LoggingResult(events)1473 1474 class LoggingCase(unittest.TestCase):1475 def run(self, result):1476 events.append('run %s' % self._testMethodName)1477 1478 def test1(self): pass1479 def test2(self): pass1480 1481 tests = [LoggingCase('test1'), LoggingCase('test2')]1482 1483 unittest.TestSuite(tests).run(result)1484 1485 self.assertEqual(events, ['run test1', 'run test2'])1486 1487 # "Add a TestCase ... to the suite"1488 def test_addTest__TestCase(self):1489 class Foo(unittest.TestCase):1490 def test(self): pass1491 1492 test = Foo('test')1493 suite = unittest.TestSuite()1494 1495 suite.addTest(test)1496 1497 self.assertEqual(suite.countTestCases(), 1)1498 self.assertEqual(list(suite), [test])1499 1500 # "Add a ... TestSuite to the suite"1501 def test_addTest__TestSuite(self):1502 class Foo(unittest.TestCase):1503 def test(self): pass1504 1505 suite_2 = unittest.TestSuite([Foo('test')])1506 1507 suite = unittest.TestSuite()1508 suite.addTest(suite_2)1509 1510 self.assertEqual(suite.countTestCases(), 1)1511 self.assertEqual(list(suite), [suite_2])1512 1513 # "Add all the tests from an iterable of TestCase and TestSuite1514 # instances to this test suite."1515 #1516 # "This is equivalent to iterating over tests, calling addTest() for1517 # each element"1518 def test_addTests(self):1519 class Foo(unittest.TestCase):1520 def test_1(self): pass1521 def test_2(self): pass1522 1523 test_1 = Foo('test_1')1524 test_2 = Foo('test_2')1525 inner_suite = unittest.TestSuite([test_2])1526 1527 def gen():1528 yield test_11529 yield test_21530 yield inner_suite1531 1532 suite_1 = unittest.TestSuite()1533 suite_1.addTests(gen())1534 1535 self.assertEqual(list(suite_1), list(gen()))1536 1537 # "This is equivalent to iterating over tests, calling addTest() for1538 # each element"1539 suite_2 = unittest.TestSuite()1540 for t in gen():1541 suite_2.addTest(t)1542 1543 self.assertEqual(suite_1, suite_2)1544 1545 # "Add all the tests from an iterable of TestCase and TestSuite1546 # instances to this test suite."1547 #1548 # What happens if it doesn't get an iterable?1549 def test_addTest__noniterable(self):1550 suite = unittest.TestSuite()1551 1552 try:1553 suite.addTests(5)1554 except TypeError:1555 pass1556 else:1557 self.fail("Failed to raise TypeError")1558 1559 def test_addTest__noncallable(self):1560 suite = unittest.TestSuite()1561 self.assertRaises(TypeError, suite.addTest, 5)1562 1563 def test_addTest__casesuiteclass(self):1564 suite = unittest.TestSuite()1565 self.assertRaises(TypeError, suite.addTest, Test_TestSuite)1566 self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)1567 1568 def test_addTests__string(self):1569 suite = unittest.TestSuite()1570 self.assertRaises(TypeError, suite.addTests, "foo")1571 1572 1573 class Test_FunctionTestCase(TestCase):1574 1575 # "Return the number of tests represented by the this test object. For1576 # TestCase instances, this will always be 1"1577 def test_countTestCases(self):1578 test = unittest.FunctionTestCase(lambda: None)1579 1580 self.assertEqual(test.countTestCases(), 1)1581 1582 # "When a setUp() method is defined, the test runner will run that method1583 # prior to each test. Likewise, if a tearDown() method is defined, the1584 # test runner will invoke that method after each test. In the example,1585 # setUp() was used to create a fresh sequence for each test."1586 #1587 # Make sure the proper call order is maintained, even if setUp() raises1588 # an exception.1589 def test_run_call_order__error_in_setUp(self):1590 events = []1591 result = LoggingResult(events)1592 1593 def setUp():1594 events.append('setUp')1595 raise RuntimeError('raised by setUp')1596 1597 def test():1598 events.append('test')1599 1600 def tearDown():1601 events.append('tearDown')1602 1603 expected = ['startTest', 'setUp', 'addError', 'stopTest']1604 unittest.FunctionTestCase(test, setUp, tearDown).run(result)1605 self.assertEqual(events, expected)1606 1607 # "When a setUp() method is defined, the test runner will run that method1608 # prior to each test. Likewise, if a tearDown() method is defined, the1609 # test runner will invoke that method after each test. In the example,1610 # setUp() was used to create a fresh sequence for each test."1611 #1612 # Make sure the proper call order is maintained, even if the test raises1613 # an error (as opposed to a failure).1614 def test_run_call_order__error_in_test(self):1615 events = []1616 result = LoggingResult(events)1617 1618 def setUp():1619 events.append('setUp')1620 1621 def test():1622 events.append('test')1623 raise RuntimeError('raised by test')1624 1625 def tearDown():1626 events.append('tearDown')1627 1628 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',1629 'stopTest']1630 unittest.FunctionTestCase(test, setUp, tearDown).run(result)1631 self.assertEqual(events, expected)1632 1633 # "When a setUp() method is defined, the test runner will run that method1634 # prior to each test. Likewise, if a tearDown() method is defined, the1635 # test runner will invoke that method after each test. In the example,1636 # setUp() was used to create a fresh sequence for each test."1637 #1638 # Make sure the proper call order is maintained, even if the test signals1639 # a failure (as opposed to an error).1640 def test_run_call_order__failure_in_test(self):1641 events = []1642 result = LoggingResult(events)1643 1644 def setUp():1645 events.append('setUp')1646 1647 def test():1648 events.append('test')1649 self.fail('raised by test')1650 1651 def tearDown():1652 events.append('tearDown')1653 1654 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',1655 'stopTest']1656 unittest.FunctionTestCase(test, setUp, tearDown).run(result)1657 self.assertEqual(events, expected)1658 1659 # "When a setUp() method is defined, the test runner will run that method1660 # prior to each test. Likewise, if a tearDown() method is defined, the1661 # test runner will invoke that method after each test. In the example,1662 # setUp() was used to create a fresh sequence for each test."1663 #1664 # Make sure the proper call order is maintained, even if tearDown() raises1665 # an exception.1666 def test_run_call_order__error_in_tearDown(self):1667 events = []1668 result = LoggingResult(events)1669 1670 def setUp():1671 events.append('setUp')1672 1673 def test():1674 events.append('test')1675 1676 def tearDown():1677 events.append('tearDown')1678 raise RuntimeError('raised by tearDown')1679 1680 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',1681 'stopTest']1682 unittest.FunctionTestCase(test, setUp, tearDown).run(result)1683 self.assertEqual(events, expected)1684 1685 # "Return a string identifying the specific test case."1686 #1687 # Because of the vague nature of the docs, I'm not going to lock this1688 # test down too much. Really all that can be asserted is that the id()1689 # will be a string (either 8-byte or unicode -- again, because the docs1690 # just say "string")1691 def test_id(self):1692 test = unittest.FunctionTestCase(lambda: None)1693 1694 self.failUnless(isinstance(test.id(), basestring))1695 1696 # "Returns a one-line description of the test, or None if no description1697 # has been provided. The default implementation of this method returns1698 # the first line of the test method's docstring, if available, or None."1699 def test_shortDescription__no_docstring(self):1700 test = unittest.FunctionTestCase(lambda: None)1701 1702 self.assertEqual(test.shortDescription(), None)1703 1704 # "Returns a one-line description of the test, or None if no description1705 # has been provided. The default implementation of this method returns1706 # the first line of the test method's docstring, if available, or None."1707 def test_shortDescription__singleline_docstring(self):1708 desc = "this tests foo"1709 test = unittest.FunctionTestCase(lambda: None, description=desc)1710 1711 self.assertEqual(test.shortDescription(), "this tests foo")1712 1713 class Test_TestResult(TestCase):1714 # Note: there are not separate tests for TestResult.wasSuccessful(),1715 # TestResult.errors, TestResult.failures, TestResult.testsRun or1716 # TestResult.shouldStop because these only have meaning in terms of1717 # other TestResult methods.1718 #1719 # Accordingly, tests for the aforenamed attributes are incorporated1720 # in with the tests for the defining methods.1721 ################################################################1722 1723 def test_init(self):1724 result = unittest.TestResult()1725 1726 self.failUnless(result.wasSuccessful())1727 self.assertEqual(len(result.errors), 0)1728 self.assertEqual(len(result.failures), 0)1729 self.assertEqual(result.testsRun, 0)1730 self.assertEqual(result.shouldStop, False)1731 1732 # "This method can be called to signal that the set of tests being1733 # run should be aborted by setting the TestResult's shouldStop1734 # attribute to True."1735 def test_stop(self):1736 result = unittest.TestResult()1737 1738 result.stop()1739 1740 self.assertEqual(result.shouldStop, True)1741 1742 # "Called when the test case test is about to be run. The default1743 # implementation simply increments the instance's testsRun counter."1744 def test_startTest(self):1745 class Foo(unittest.TestCase):1746 def test_1(self):1747 pass1748 1749 test = Foo('test_1')1750 1751 result = unittest.TestResult()1752 1753 result.startTest(test)1754 1755 self.failUnless(result.wasSuccessful())1756 self.assertEqual(len(result.errors), 0)1757 self.assertEqual(len(result.failures), 0)1758 self.assertEqual(result.testsRun, 1)1759 self.assertEqual(result.shouldStop, False)1760 1761 result.stopTest(test)1762 1763 # "Called after the test case test has been executed, regardless of1764 # the outcome. The default implementation does nothing."1765 def test_stopTest(self):1766 class Foo(unittest.TestCase):1767 def test_1(self):1768 pass1769 1770 test = Foo('test_1')1771 1772 result = unittest.TestResult()1773 1774 result.startTest(test)1775 1776 self.failUnless(result.wasSuccessful())1777 self.assertEqual(len(result.errors), 0)1778 self.assertEqual(len(result.failures), 0)1779 self.assertEqual(result.testsRun, 1)1780 self.assertEqual(result.shouldStop, False)1781 1782 result.stopTest(test)1783 1784 # Same tests as above; make sure nothing has changed1785 self.failUnless(result.wasSuccessful())1786 self.assertEqual(len(result.errors), 0)1787 self.assertEqual(len(result.failures), 0)1788 self.assertEqual(result.testsRun, 1)1789 self.assertEqual(result.shouldStop, False)1790 1791 # "addSuccess(test)"1792 # ...1793 # "Called when the test case test succeeds"1794 # ...1795 # "wasSuccessful() - Returns True if all tests run so far have passed,1796 # otherwise returns False"1797 # ...1798 # "testsRun - The total number of tests run so far."1799 # ...1800 # "errors - A list containing 2-tuples of TestCase instances and1801 # formatted tracebacks. Each tuple represents a test which raised an1802 # unexpected exception. Contains formatted1803 # tracebacks instead of sys.exc_info() results."1804 # ...1805 # "failures - A list containing 2-tuples of TestCase instances and1806 # formatted tracebacks. Each tuple represents a test where a failure was1807 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()1808 # methods. Contains formatted tracebacks instead1809 # of sys.exc_info() results."1810 def test_addSuccess(self):1811 class Foo(unittest.TestCase):1812 def test_1(self):1813 pass1814 1815 test = Foo('test_1')1816 1817 result = unittest.TestResult()1818 1819 result.startTest(test)1820 result.addSuccess(test)1821 result.stopTest(test)1822 1823 self.failUnless(result.wasSuccessful())1824 self.assertEqual(len(result.errors), 0)1825 self.assertEqual(len(result.failures), 0)1826 self.assertEqual(result.testsRun, 1)1827 self.assertEqual(result.shouldStop, False)1828 1829 # "addFailure(test, err)"1830 # ...1831 # "Called when the test case test signals a failure. err is a tuple of1832 # the form returned by sys.exc_info(): (type, value, traceback)"1833 # ...1834 # "wasSuccessful() - Returns True if all tests run so far have passed,1835 # otherwise returns False"1836 # ...1837 # "testsRun - The total number of tests run so far."1838 # ...1839 # "errors - A list containing 2-tuples of TestCase instances and1840 # formatted tracebacks. Each tuple represents a test which raised an1841 # unexpected exception. Contains formatted1842 # tracebacks instead of sys.exc_info() results."1843 # ...1844 # "failures - A list containing 2-tuples of TestCase instances and1845 # formatted tracebacks. Each tuple represents a test where a failure was1846 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()1847 # methods. Contains formatted tracebacks instead1848 # of sys.exc_info() results."1849 def test_addFailure(self):1850 import sys1851 1852 class Foo(unittest.TestCase):1853 def test_1(self):1854 pass1855 1856 test = Foo('test_1')1857 try:1858 test.fail("foo")1859 except:1860 exc_info_tuple = sys.exc_info()1861 1862 result = unittest.TestResult()1863 1864 result.startTest(test)1865 result.addFailure(test, exc_info_tuple)1866 result.stopTest(test)1867 1868 self.failIf(result.wasSuccessful())1869 self.assertEqual(len(result.errors), 0)1870 self.assertEqual(len(result.failures), 1)1871 self.assertEqual(result.testsRun, 1)1872 self.assertEqual(result.shouldStop, False)1873 1874 test_case, formatted_exc = result.failures[0]1875 self.failUnless(test_case is test)1876 self.failUnless(isinstance(formatted_exc, str))1877 1878 # "addError(test, err)"1879 # ...1880 # "Called when the test case test raises an unexpected exception err1881 # is a tuple of the form returned by sys.exc_info():1882 # (type, value, traceback)"1883 # ...1884 # "wasSuccessful() - Returns True if all tests run so far have passed,1885 # otherwise returns False"1886 # ...1887 # "testsRun - The total number of tests run so far."1888 # ...1889 # "errors - A list containing 2-tuples of TestCase instances and1890 # formatted tracebacks. Each tuple represents a test which raised an1891 # unexpected exception. Contains formatted1892 # tracebacks instead of sys.exc_info() results."1893 # ...1894 # "failures - A list containing 2-tuples of TestCase instances and1895 # formatted tracebacks. Each tuple represents a test where a failure was1896 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()1897 # methods. Contains formatted tracebacks instead1898 # of sys.exc_info() results."1899 def test_addError(self):1900 import sys1901 1902 class Foo(unittest.TestCase):1903 def test_1(self):1904 pass1905 1906 test = Foo('test_1')1907 try:1908 raise TypeError()1909 except:1910 exc_info_tuple = sys.exc_info()1911 1912 result = unittest.TestResult()1913 1914 result.startTest(test)1915 result.addError(test, exc_info_tuple)1916 result.stopTest(test)1917 1918 self.failIf(result.wasSuccessful())1919 self.assertEqual(len(result.errors), 1)1920 self.assertEqual(len(result.failures), 0)1921 self.assertEqual(result.testsRun, 1)1922 self.assertEqual(result.shouldStop, False)1923 1924 test_case, formatted_exc = result.errors[0]1925 self.failUnless(test_case is test)1926 self.failUnless(isinstance(formatted_exc, str))1927 1928 ### Support code for Test_TestCase1929 ################################################################1930 1931 class Foo(unittest.TestCase):1932 def runTest(self): pass1933 def test1(self): pass1934 1935 class Bar(Foo):1936 def test2(self): pass1937 1938 ################################################################1939 ### /Support code for Test_TestCase1940 1941 class Test_TestCase(TestCase, TestEquality, TestHashing):1942 1943 ### Set up attributes used by inherited tests1944 ################################################################1945 1946 # Used by TestHashing.test_hash and TestEquality.test_eq1947 eq_pairs = [(Foo('test1'), Foo('test1'))]1948 1949 # Used by TestEquality.test_ne1950 ne_pairs = [(Foo('test1'), Foo('runTest'))1951 ,(Foo('test1'), Bar('test1'))1952 ,(Foo('test1'), Bar('test2'))]1953 1954 ################################################################1955 ### /Set up attributes used by inherited tests1956 1957 1958 # "class TestCase([methodName])"1959 # ...1960 # "Each instance of TestCase will run a single test method: the1961 # method named methodName."1962 # ...1963 # "methodName defaults to "runTest"."1964 #1965 # Make sure it really is optional, and that it defaults to the proper1966 # thing.1967 def test_init__no_test_name(self):1968 class Test(unittest.TestCase):1969 def runTest(self): raise MyException()1970 def test(self): pass1971 1972 self.assertEqual(Test().id()[-13:], '.Test.runTest')1973 1974 # "class TestCase([methodName])"1975 # ...1976 # "Each instance of TestCase will run a single test method: the1977 # method named methodName."1978 def test_init__test_name__valid(self):1979 class Test(unittest.TestCase):1980 def runTest(self): raise MyException()1981 def test(self): pass1982 1983 self.assertEqual(Test('test').id()[-10:], '.Test.test')1984 1985 # "class TestCase([methodName])"1986 # ...1987 # "Each instance of TestCase will run a single test method: the1988 # method named methodName."1989 def test_init__test_name__invalid(self):1990 class Test(unittest.TestCase):1991 def runTest(self): raise MyException()1992 def test(self): pass1993 1994 try:1995 Test('testfoo')1996 except ValueError:1997 pass1998 else:1999 self.fail("Failed to raise ValueError")2000 2001 # "Return the number of tests represented by the this test object. For2002 # TestCase instances, this will always be 1"2003 def test_countTestCases(self):2004 class Foo(unittest.TestCase):2005 def test(self): pass2006 2007 self.assertEqual(Foo('test').countTestCases(), 1)2008 2009 # "Return the default type of test result object to be used to run this2010 # test. For TestCase instances, this will always be2011 # unittest.TestResult; subclasses of TestCase should2012 # override this as necessary."2013 def test_defaultTestResult(self):2014 class Foo(unittest.TestCase):2015 def runTest(self):2016 pass2017 2018 result = Foo().defaultTestResult()2019 self.assertEqual(type(result), unittest.TestResult)2020 2021 # "When a setUp() method is defined, the test runner will run that method2022 # prior to each test. Likewise, if a tearDown() method is defined, the2023 # test runner will invoke that method after each test. In the example,2024 # setUp() was used to create a fresh sequence for each test."2025 #2026 # Make sure the proper call order is maintained, even if setUp() raises2027 # an exception.2028 def test_run_call_order__error_in_setUp(self):2029 events = []2030 result = LoggingResult(events)2031 2032 class Foo(unittest.TestCase):2033 def setUp(self):2034 events.append('setUp')2035 raise RuntimeError('raised by Foo.setUp')2036 2037 def test(self):2038 events.append('test')2039 2040 def tearDown(self):2041 events.append('tearDown')2042 2043 Foo('test').run(result)2044 expected = ['startTest', 'setUp', 'addError', 'stopTest']2045 self.assertEqual(events, expected)2046 2047 # "When a setUp() method is defined, the test runner will run that method2048 # prior to each test. Likewise, if a tearDown() method is defined, the2049 # test runner will invoke that method after each test. In the example,2050 # setUp() was used to create a fresh sequence for each test."2051 #2052 # Make sure the proper call order is maintained, even if the test raises2053 # an error (as opposed to a failure).2054 def test_run_call_order__error_in_test(self):2055 events = []2056 result = LoggingResult(events)2057 2058 class Foo(unittest.TestCase):2059 def setUp(self):2060 events.append('setUp')2061 2062 def test(self):2063 events.append('test')2064 raise RuntimeError('raised by Foo.test')2065 2066 def tearDown(self):2067 events.append('tearDown')2068 2069 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',2070 'stopTest']2071 Foo('test').run(result)2072 self.assertEqual(events, expected)2073 2074 # "When a setUp() method is defined, the test runner will run that method2075 # prior to each test. Likewise, if a tearDown() method is defined, the2076 # test runner will invoke that method after each test. In the example,2077 # setUp() was used to create a fresh sequence for each test."2078 #2079 # Make sure the proper call order is maintained, even if the test signals2080 # a failure (as opposed to an error).2081 def test_run_call_order__failure_in_test(self):2082 events = []2083 result = LoggingResult(events)2084 2085 class Foo(unittest.TestCase):2086 def setUp(self):2087 events.append('setUp')2088 2089 def test(self):2090 events.append('test')2091 self.fail('raised by Foo.test')2092 2093 def tearDown(self):2094 events.append('tearDown')2095 2096 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',2097 'stopTest']2098 Foo('test').run(result)2099 self.assertEqual(events, expected)2100 2101 # "When a setUp() method is defined, the test runner will run that method2102 # prior to each test. Likewise, if a tearDown() method is defined, the2103 # test runner will invoke that method after each test. In the example,2104 # setUp() was used to create a fresh sequence for each test."2105 #2106 # Make sure the proper call order is maintained, even if tearDown() raises2107 # an exception.2108 def test_run_call_order__error_in_tearDown(self):2109 events = []2110 result = LoggingResult(events)2111 2112 class Foo(unittest.TestCase):2113 def setUp(self):2114 events.append('setUp')2115 2116 def test(self):2117 events.append('test')2118 2119 def tearDown(self):2120 events.append('tearDown')2121 raise RuntimeError('raised by Foo.tearDown')2122 2123 Foo('test').run(result)2124 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',2125 'stopTest']2126 self.assertEqual(events, expected)2127 2128 # "This class attribute gives the exception raised by the test() method.2129 # If a test framework needs to use a specialized exception, possibly to2130 # carry additional information, it must subclass this exception in2131 # order to ``play fair'' with the framework. The initial value of this2132 # attribute is AssertionError"2133 def test_failureException__default(self):2134 class Foo(unittest.TestCase):2135 def test(self):2136 pass2137 2138 self.failUnless(Foo('test').failureException is AssertionError)2139 2140 # "This class attribute gives the exception raised by the test() method.2141 # If a test framework needs to use a specialized exception, possibly to2142 # carry additional information, it must subclass this exception in2143 # order to ``play fair'' with the framework."2144 #2145 # Make sure TestCase.run() respects the designated failureException2146 def test_failureException__subclassing__explicit_raise(self):2147 events = []2148 result = LoggingResult(events)2149 2150 class Foo(unittest.TestCase):2151 def test(self):2152 raise RuntimeError()2153 2154 failureException = RuntimeError2155 2156 self.failUnless(Foo('test').failureException is RuntimeError)2157 2158 2159 Foo('test').run(result)2160 expected = ['startTest', 'addFailure', 'stopTest']2161 self.assertEqual(events, expected)2162 2163 # "This class attribute gives the exception raised by the test() method.2164 # If a test framework needs to use a specialized exception, possibly to2165 # carry additional information, it must subclass this exception in2166 # order to ``play fair'' with the framework."2167 #2168 # Make sure TestCase.run() respects the designated failureException2169 def test_failureException__subclassing__implicit_raise(self):2170 events = []2171 result = LoggingResult(events)2172 2173 class Foo(unittest.TestCase):2174 def test(self):2175 self.fail("foo")2176 2177 failureException = RuntimeError2178 2179 self.failUnless(Foo('test').failureException is RuntimeError)2180 2181 2182 Foo('test').run(result)2183 expected = ['startTest', 'addFailure', 'stopTest']2184 self.assertEqual(events, expected)2185 2186 # "The default implementation does nothing."2187 def test_setUp(self):2188 class Foo(unittest.TestCase):2189 def runTest(self):2190 pass2191 2192 # ... and nothing should happen2193 Foo().setUp()2194 2195 # "The default implementation does nothing."2196 def test_tearDown(self):2197 class Foo(unittest.TestCase):2198 def runTest(self):2199 pass2200 2201 # ... and nothing should happen2202 Foo().tearDown()2203 2204 # "Return a string identifying the specific test case."2205 #2206 # Because of the vague nature of the docs, I'm not going to lock this2207 # test down too much. Really all that can be asserted is that the id()2208 # will be a string (either 8-byte or unicode -- again, because the docs2209 # just say "string")2210 def test_id(self):2211 class Foo(unittest.TestCase):2212 def runTest(self):2213 pass2214 2215 self.failUnless(isinstance(Foo().id(), basestring))2216 2217 # "Returns a one-line description of the test, or None if no description2218 # has been provided. The default implementation of this method returns2219 # the first line of the test method's docstring, if available, or None."2220 def test_shortDescription__no_docstring(self):2221 class Foo(unittest.TestCase):2222 def runTest(self):2223 pass2224 2225 self.assertEqual(Foo().shortDescription(), None)2226 2227 # "Returns a one-line description of the test, or None if no description2228 # has been provided. The default implementation of this method returns2229 # the first line of the test method's docstring, if available, or None."2230 def test_shortDescription__singleline_docstring(self):2231 class Foo(unittest.TestCase):2232 def runTest(self):2233 "this tests foo"2234 pass2235 2236 self.assertEqual(Foo().shortDescription(), "this tests foo")2237 2238 # "Returns a one-line description of the test, or None if no description2239 # has been provided. The default implementation of this method returns2240 # the first line of the test method's docstring, if available, or None."2241 def test_shortDescription__multiline_docstring(self):2242 class Foo(unittest.TestCase):2243 def runTest(self):2244 """this tests foo2245 blah, bar and baz are also tested"""2246 pass2247 2248 self.assertEqual(Foo().shortDescription(), "this tests foo")2249 2250 # "If result is omitted or None, a temporary result object is created2251 # and used, but is not made available to the caller"2252 def test_run__uses_defaultTestResult(self):2253 events = []2254 2255 class Foo(unittest.TestCase):2256 def test(self):2257 events.append('test')2258 2259 def defaultTestResult(self):2260 return LoggingResult(events)2261 2262 # Make run() find a result object on its own2263 Foo('test').run()2264 2265 expected = ['startTest', 'test', 'stopTest']2266 self.assertEqual(events, expected)2267 2268 class Test_Assertions(TestCase):2269 def test_AlmostEqual(self):2270 self.failUnlessAlmostEqual(1.00000001, 1.0)2271 self.failIfAlmostEqual(1.0000001, 1.0)2272 self.assertRaises(AssertionError,2273 self.failUnlessAlmostEqual, 1.0000001, 1.0)2274 self.assertRaises(AssertionError,2275 self.failIfAlmostEqual, 1.00000001, 1.0)2276 2277 self.failUnlessAlmostEqual(1.1, 1.0, places=0)2278 self.assertRaises(AssertionError,2279 self.failUnlessAlmostEqual, 1.1, 1.0, places=1)2280 2281 self.failUnlessAlmostEqual(0, .1+.1j, places=0)2282 self.failIfAlmostEqual(0, .1+.1j, places=1)2283 self.assertRaises(AssertionError,2284 self.failUnlessAlmostEqual, 0, .1+.1j, places=1)2285 self.assertRaises(AssertionError,2286 self.failIfAlmostEqual, 0, .1+.1j, places=0)2287 2288 2289 2290 ######################################################################2291 ## Main2292 ######################################################################2293 2294 def test_main():2295 test_support.run_unittest(Test_TestCase, Test_TestLoader,2296 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,2297 Test_Assertions)2298 10 2299 11 if __name__ == "__main__":
Note:
See TracChangeset
for help on using the changeset viewer.