Jim Fulton | fafd874 | 2004-08-28 15:22:12 +0000 | [diff] [blame] | 1 | """Test script for unittest. |
| 2 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 3 | By Collin Winter <collinw at gmail.com> |
| 4 | |
| 5 | Still need testing: |
| 6 | TestCase.{assert,fail}* methods (some are tested implicitly) |
Jim Fulton | fafd874 | 2004-08-28 15:22:12 +0000 | [diff] [blame] | 7 | """ |
| 8 | |
Benjamin Peterson | bed7d04 | 2009-07-19 21:01:52 +0000 | [diff] [blame] | 9 | import builtins |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 10 | import os |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 11 | import re |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 12 | import sys |
Benjamin Peterson | 6bcbad5 | 2009-06-30 23:45:41 +0000 | [diff] [blame] | 13 | import warnings |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 14 | from test import support |
Jim Fulton | fafd874 | 2004-08-28 15:22:12 +0000 | [diff] [blame] | 15 | import unittest |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 16 | from unittest import TestCase, TestProgram |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 17 | import types |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 18 | from copy import deepcopy |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 19 | import io |
Antoine Pitrou | c63ecee | 2009-11-10 21:34:48 +0000 | [diff] [blame] | 20 | import pickle |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame^] | 21 | import warnings |
| 22 | |
Jim Fulton | fafd874 | 2004-08-28 15:22:12 +0000 | [diff] [blame] | 23 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 24 | ### Support code |
| 25 | ################################################################ |
Jim Fulton | fafd874 | 2004-08-28 15:22:12 +0000 | [diff] [blame] | 26 | |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame^] | 27 | def resultFactory(*_): |
| 28 | return unittest.TestResult() |
| 29 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 30 | class LoggingResult(unittest.TestResult): |
| 31 | def __init__(self, log): |
| 32 | self._events = log |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 33 | super().__init__() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 34 | |
| 35 | def startTest(self, test): |
| 36 | self._events.append('startTest') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 37 | super().startTest(test) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 38 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 39 | def startTestRun(self): |
| 40 | self._events.append('startTestRun') |
| 41 | super(LoggingResult, self).startTestRun() |
| 42 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 43 | def stopTest(self, test): |
| 44 | self._events.append('stopTest') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 45 | super().stopTest(test) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 46 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 47 | def stopTestRun(self): |
| 48 | self._events.append('stopTestRun') |
| 49 | super(LoggingResult, self).stopTestRun() |
| 50 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 51 | def addFailure(self, *args): |
| 52 | self._events.append('addFailure') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 53 | super().addFailure(*args) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 54 | |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 55 | def addSuccess(self, *args): |
| 56 | self._events.append('addSuccess') |
| 57 | super(LoggingResult, self).addSuccess(*args) |
| 58 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 59 | def addError(self, *args): |
| 60 | self._events.append('addError') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 61 | super().addError(*args) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 62 | |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 63 | def addSkip(self, *args): |
| 64 | self._events.append('addSkip') |
| 65 | super(LoggingResult, self).addSkip(*args) |
| 66 | |
| 67 | def addExpectedFailure(self, *args): |
| 68 | self._events.append('addExpectedFailure') |
| 69 | super(LoggingResult, self).addExpectedFailure(*args) |
| 70 | |
| 71 | def addUnexpectedSuccess(self, *args): |
| 72 | self._events.append('addUnexpectedSuccess') |
| 73 | super(LoggingResult, self).addUnexpectedSuccess(*args) |
| 74 | |
| 75 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 76 | class TestEquality(object): |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 77 | """Used as a mixin for TestCase""" |
| 78 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 79 | # Check for a valid __eq__ implementation |
| 80 | def test_eq(self): |
| 81 | for obj_1, obj_2 in self.eq_pairs: |
| 82 | self.assertEqual(obj_1, obj_2) |
| 83 | self.assertEqual(obj_2, obj_1) |
| 84 | |
| 85 | # Check for a valid __ne__ implementation |
| 86 | def test_ne(self): |
| 87 | for obj_1, obj_2 in self.ne_pairs: |
Benjamin Peterson | e1759f8 | 2009-06-30 23:35:19 +0000 | [diff] [blame] | 88 | self.assertNotEqual(obj_1, obj_2) |
| 89 | self.assertNotEqual(obj_2, obj_1) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 90 | |
| 91 | class TestHashing(object): |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 92 | """Used as a mixin for TestCase""" |
| 93 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 94 | # Check for a valid __hash__ implementation |
| 95 | def test_hash(self): |
| 96 | for obj_1, obj_2 in self.eq_pairs: |
| 97 | try: |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 98 | if not hash(obj_1) == hash(obj_2): |
| 99 | self.fail("%r and %r do not hash equal" % (obj_1, obj_2)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 100 | except KeyboardInterrupt: |
| 101 | raise |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 102 | except Exception as e: |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 103 | self.fail("Problem hashing %r and %r: %s" % (obj_1, obj_2, e)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 104 | |
| 105 | for obj_1, obj_2 in self.ne_pairs: |
| 106 | try: |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 107 | if hash(obj_1) == hash(obj_2): |
| 108 | self.fail("%s and %s hash equal, but shouldn't" % |
| 109 | (obj_1, obj_2)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 110 | except KeyboardInterrupt: |
| 111 | raise |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 112 | except Exception as e: |
| 113 | self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e)) |
| 114 | |
| 115 | |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 116 | # List subclass we can add attributes to. |
| 117 | class MyClassSuite(list): |
| 118 | |
Benjamin Peterson | 14a3dd7 | 2009-05-25 00:51:58 +0000 | [diff] [blame] | 119 | def __init__(self, tests): |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 120 | super(MyClassSuite, self).__init__(tests) |
| 121 | |
| 122 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 123 | ################################################################ |
| 124 | ### /Support code |
| 125 | |
| 126 | class Test_TestLoader(TestCase): |
| 127 | |
| 128 | ### Tests for TestLoader.loadTestsFromTestCase |
| 129 | ################################################################ |
| 130 | |
| 131 | # "Return a suite of all tests cases contained in the TestCase-derived |
| 132 | # class testCaseClass" |
| 133 | def test_loadTestsFromTestCase(self): |
| 134 | class Foo(unittest.TestCase): |
| 135 | def test_1(self): pass |
| 136 | def test_2(self): pass |
| 137 | def foo_bar(self): pass |
| 138 | |
| 139 | tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')]) |
| 140 | |
| 141 | loader = unittest.TestLoader() |
| 142 | self.assertEqual(loader.loadTestsFromTestCase(Foo), tests) |
| 143 | |
| 144 | # "Return a suite of all tests cases contained in the TestCase-derived |
| 145 | # class testCaseClass" |
| 146 | # |
| 147 | # Make sure it does the right thing even if no tests were found |
| 148 | def test_loadTestsFromTestCase__no_matches(self): |
| 149 | class Foo(unittest.TestCase): |
| 150 | def foo_bar(self): pass |
| 151 | |
| 152 | empty_suite = unittest.TestSuite() |
| 153 | |
| 154 | loader = unittest.TestLoader() |
| 155 | self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite) |
| 156 | |
| 157 | # "Return a suite of all tests cases contained in the TestCase-derived |
| 158 | # class testCaseClass" |
| 159 | # |
| 160 | # What happens if loadTestsFromTestCase() is given an object |
| 161 | # that isn't a subclass of TestCase? Specifically, what happens |
| 162 | # if testCaseClass is a subclass of TestSuite? |
| 163 | # |
| 164 | # This is checked for specifically in the code, so we better add a |
| 165 | # test for it. |
| 166 | def test_loadTestsFromTestCase__TestSuite_subclass(self): |
| 167 | class NotATestCase(unittest.TestSuite): |
| 168 | pass |
| 169 | |
| 170 | loader = unittest.TestLoader() |
| 171 | try: |
| 172 | loader.loadTestsFromTestCase(NotATestCase) |
| 173 | except TypeError: |
| 174 | pass |
| 175 | else: |
| 176 | self.fail('Should raise TypeError') |
| 177 | |
| 178 | # "Return a suite of all tests cases contained in the TestCase-derived |
| 179 | # class testCaseClass" |
| 180 | # |
| 181 | # Make sure loadTestsFromTestCase() picks up the default test method |
| 182 | # name (as specified by TestCase), even though the method name does |
| 183 | # not match the default TestLoader.testMethodPrefix string |
| 184 | def test_loadTestsFromTestCase__default_method_name(self): |
| 185 | class Foo(unittest.TestCase): |
| 186 | def runTest(self): |
| 187 | pass |
| 188 | |
| 189 | loader = unittest.TestLoader() |
| 190 | # This has to be false for the test to succeed |
Benjamin Peterson | e1759f8 | 2009-06-30 23:35:19 +0000 | [diff] [blame] | 191 | self.assertFalse('runTest'.startswith(loader.testMethodPrefix)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 192 | |
| 193 | suite = loader.loadTestsFromTestCase(Foo) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 194 | self.assertIsInstance(suite, loader.suiteClass) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 195 | self.assertEqual(list(suite), [Foo('runTest')]) |
| 196 | |
| 197 | ################################################################ |
| 198 | ### /Tests for TestLoader.loadTestsFromTestCase |
| 199 | |
| 200 | ### Tests for TestLoader.loadTestsFromModule |
| 201 | ################################################################ |
| 202 | |
| 203 | # "This method searches `module` for classes derived from TestCase" |
| 204 | def test_loadTestsFromModule__TestCase_subclass(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 205 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 206 | class MyTestCase(unittest.TestCase): |
| 207 | def test(self): |
| 208 | pass |
| 209 | m.testcase_1 = MyTestCase |
| 210 | |
| 211 | loader = unittest.TestLoader() |
| 212 | suite = loader.loadTestsFromModule(m) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 213 | self.assertIsInstance(suite, loader.suiteClass) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 214 | |
| 215 | expected = [loader.suiteClass([MyTestCase('test')])] |
| 216 | self.assertEqual(list(suite), expected) |
| 217 | |
| 218 | # "This method searches `module` for classes derived from TestCase" |
| 219 | # |
| 220 | # What happens if no tests are found (no TestCase instances)? |
| 221 | def test_loadTestsFromModule__no_TestCase_instances(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 222 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 223 | |
| 224 | loader = unittest.TestLoader() |
| 225 | suite = loader.loadTestsFromModule(m) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 226 | self.assertIsInstance(suite, loader.suiteClass) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 227 | self.assertEqual(list(suite), []) |
| 228 | |
| 229 | # "This method searches `module` for classes derived from TestCase" |
| 230 | # |
| 231 | # What happens if no tests are found (TestCases instances, but no tests)? |
| 232 | def test_loadTestsFromModule__no_TestCase_tests(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 233 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 234 | class MyTestCase(unittest.TestCase): |
| 235 | pass |
| 236 | m.testcase_1 = MyTestCase |
| 237 | |
| 238 | loader = unittest.TestLoader() |
| 239 | suite = loader.loadTestsFromModule(m) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 240 | self.assertIsInstance(suite, loader.suiteClass) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 241 | |
| 242 | self.assertEqual(list(suite), [loader.suiteClass()]) |
| 243 | |
| 244 | # "This method searches `module` for classes derived from TestCase"s |
| 245 | # |
| 246 | # What happens if loadTestsFromModule() is given something other |
| 247 | # than a module? |
| 248 | # |
| 249 | # XXX Currently, it succeeds anyway. This flexibility |
| 250 | # should either be documented or loadTestsFromModule() should |
| 251 | # raise a TypeError |
| 252 | # |
| 253 | # XXX Certain people are using this behaviour. We'll add a test for it |
| 254 | def test_loadTestsFromModule__not_a_module(self): |
| 255 | class MyTestCase(unittest.TestCase): |
| 256 | def test(self): |
| 257 | pass |
| 258 | |
| 259 | class NotAModule(object): |
| 260 | test_2 = MyTestCase |
| 261 | |
| 262 | loader = unittest.TestLoader() |
| 263 | suite = loader.loadTestsFromModule(NotAModule) |
| 264 | |
| 265 | reference = [unittest.TestSuite([MyTestCase('test')])] |
| 266 | self.assertEqual(list(suite), reference) |
| 267 | |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 268 | |
| 269 | # Check that loadTestsFromModule honors (or not) a module |
| 270 | # with a load_tests function. |
| 271 | def test_loadTestsFromModule__load_tests(self): |
| 272 | m = types.ModuleType('m') |
| 273 | class MyTestCase(unittest.TestCase): |
| 274 | def test(self): |
| 275 | pass |
| 276 | m.testcase_1 = MyTestCase |
| 277 | |
| 278 | load_tests_args = [] |
| 279 | def load_tests(loader, tests, pattern): |
Michael Foord | 41647d6 | 2010-02-06 00:26:13 +0000 | [diff] [blame] | 280 | self.assertIsInstance(tests, unittest.TestSuite) |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 281 | load_tests_args.extend((loader, tests, pattern)) |
| 282 | return tests |
| 283 | m.load_tests = load_tests |
| 284 | |
| 285 | loader = unittest.TestLoader() |
| 286 | suite = loader.loadTestsFromModule(m) |
Michael Foord | 41647d6 | 2010-02-06 00:26:13 +0000 | [diff] [blame] | 287 | self.assertIsInstance(suite, unittest.TestSuite) |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 288 | self.assertEquals(load_tests_args, [loader, suite, None]) |
| 289 | |
| 290 | load_tests_args = [] |
| 291 | suite = loader.loadTestsFromModule(m, use_load_tests=False) |
| 292 | self.assertEquals(load_tests_args, []) |
| 293 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 294 | ################################################################ |
| 295 | ### /Tests for TestLoader.loadTestsFromModule() |
| 296 | |
| 297 | ### Tests for TestLoader.loadTestsFromName() |
| 298 | ################################################################ |
| 299 | |
| 300 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 301 | # a module, a test case class, a TestSuite instance, a test method |
| 302 | # within a test case class, or a callable object which returns a |
| 303 | # TestCase or TestSuite instance." |
| 304 | # |
| 305 | # Is ValueError raised in response to an empty name? |
| 306 | def test_loadTestsFromName__empty_name(self): |
| 307 | loader = unittest.TestLoader() |
| 308 | |
| 309 | try: |
| 310 | loader.loadTestsFromName('') |
| 311 | except ValueError as e: |
| 312 | self.assertEqual(str(e), "Empty module name") |
| 313 | else: |
| 314 | self.fail("TestLoader.loadTestsFromName failed to raise ValueError") |
| 315 | |
| 316 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 317 | # a module, a test case class, a TestSuite instance, a test method |
| 318 | # within a test case class, or a callable object which returns a |
| 319 | # TestCase or TestSuite instance." |
| 320 | # |
| 321 | # What happens when the name contains invalid characters? |
| 322 | def test_loadTestsFromName__malformed_name(self): |
| 323 | loader = unittest.TestLoader() |
| 324 | |
| 325 | # XXX Should this raise ValueError or ImportError? |
| 326 | try: |
| 327 | loader.loadTestsFromName('abc () //') |
| 328 | except ValueError: |
| 329 | pass |
| 330 | except ImportError: |
| 331 | pass |
| 332 | else: |
| 333 | self.fail("TestLoader.loadTestsFromName failed to raise ValueError") |
| 334 | |
| 335 | # "The specifier name is a ``dotted name'' that may resolve ... to a |
| 336 | # module" |
| 337 | # |
| 338 | # What happens when a module by that name can't be found? |
| 339 | def test_loadTestsFromName__unknown_module_name(self): |
| 340 | loader = unittest.TestLoader() |
| 341 | |
| 342 | try: |
| 343 | loader.loadTestsFromName('sdasfasfasdf') |
| 344 | except ImportError as e: |
| 345 | self.assertEqual(str(e), "No module named sdasfasfasdf") |
| 346 | else: |
| 347 | self.fail("TestLoader.loadTestsFromName failed to raise ImportError") |
| 348 | |
| 349 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 350 | # a module, a test case class, a TestSuite instance, a test method |
| 351 | # within a test case class, or a callable object which returns a |
| 352 | # TestCase or TestSuite instance." |
| 353 | # |
| 354 | # What happens when the module is found, but the attribute can't? |
| 355 | def test_loadTestsFromName__unknown_attr_name(self): |
| 356 | loader = unittest.TestLoader() |
| 357 | |
| 358 | try: |
| 359 | loader.loadTestsFromName('unittest.sdasfasfasdf') |
| 360 | except AttributeError as e: |
| 361 | self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") |
| 362 | else: |
| 363 | self.fail("TestLoader.loadTestsFromName failed to raise AttributeError") |
| 364 | |
| 365 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 366 | # a module, a test case class, a TestSuite instance, a test method |
| 367 | # within a test case class, or a callable object which returns a |
| 368 | # TestCase or TestSuite instance." |
| 369 | # |
| 370 | # What happens when we provide the module, but the attribute can't be |
| 371 | # found? |
| 372 | def test_loadTestsFromName__relative_unknown_name(self): |
| 373 | loader = unittest.TestLoader() |
| 374 | |
| 375 | try: |
| 376 | loader.loadTestsFromName('sdasfasfasdf', unittest) |
| 377 | except AttributeError as e: |
| 378 | self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") |
| 379 | else: |
| 380 | self.fail("TestLoader.loadTestsFromName failed to raise AttributeError") |
| 381 | |
| 382 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 383 | # a module, a test case class, a TestSuite instance, a test method |
| 384 | # within a test case class, or a callable object which returns a |
| 385 | # TestCase or TestSuite instance." |
| 386 | # ... |
| 387 | # "The method optionally resolves name relative to the given module" |
| 388 | # |
| 389 | # Does loadTestsFromName raise ValueError when passed an empty |
| 390 | # name relative to a provided module? |
| 391 | # |
| 392 | # XXX Should probably raise a ValueError instead of an AttributeError |
| 393 | def test_loadTestsFromName__relative_empty_name(self): |
| 394 | loader = unittest.TestLoader() |
| 395 | |
| 396 | try: |
| 397 | loader.loadTestsFromName('', unittest) |
| 398 | except AttributeError as e: |
| 399 | pass |
| 400 | else: |
| 401 | self.fail("Failed to raise AttributeError") |
| 402 | |
| 403 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 404 | # a module, a test case class, a TestSuite instance, a test method |
| 405 | # within a test case class, or a callable object which returns a |
| 406 | # TestCase or TestSuite instance." |
| 407 | # ... |
| 408 | # "The method optionally resolves name relative to the given module" |
| 409 | # |
| 410 | # What happens when an impossible name is given, relative to the provided |
| 411 | # `module`? |
| 412 | def test_loadTestsFromName__relative_malformed_name(self): |
| 413 | loader = unittest.TestLoader() |
| 414 | |
| 415 | # XXX Should this raise AttributeError or ValueError? |
| 416 | try: |
| 417 | loader.loadTestsFromName('abc () //', unittest) |
| 418 | except ValueError: |
| 419 | pass |
| 420 | except AttributeError: |
| 421 | pass |
| 422 | else: |
| 423 | self.fail("TestLoader.loadTestsFromName failed to raise ValueError") |
| 424 | |
| 425 | # "The method optionally resolves name relative to the given module" |
| 426 | # |
| 427 | # Does loadTestsFromName raise TypeError when the `module` argument |
| 428 | # isn't a module object? |
| 429 | # |
| 430 | # XXX Accepts the not-a-module object, ignorning the object's type |
| 431 | # This should raise an exception or the method name should be changed |
| 432 | # |
| 433 | # XXX Some people are relying on this, so keep it for now |
| 434 | def test_loadTestsFromName__relative_not_a_module(self): |
| 435 | class MyTestCase(unittest.TestCase): |
| 436 | def test(self): |
| 437 | pass |
| 438 | |
| 439 | class NotAModule(object): |
| 440 | test_2 = MyTestCase |
| 441 | |
| 442 | loader = unittest.TestLoader() |
| 443 | suite = loader.loadTestsFromName('test_2', NotAModule) |
| 444 | |
| 445 | reference = [MyTestCase('test')] |
| 446 | self.assertEqual(list(suite), reference) |
| 447 | |
| 448 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 449 | # a module, a test case class, a TestSuite instance, a test method |
| 450 | # within a test case class, or a callable object which returns a |
| 451 | # TestCase or TestSuite instance." |
| 452 | # |
| 453 | # Does it raise an exception if the name resolves to an invalid |
| 454 | # object? |
| 455 | def test_loadTestsFromName__relative_bad_object(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 456 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 457 | m.testcase_1 = object() |
| 458 | |
| 459 | loader = unittest.TestLoader() |
| 460 | try: |
| 461 | loader.loadTestsFromName('testcase_1', m) |
| 462 | except TypeError: |
| 463 | pass |
| 464 | else: |
| 465 | self.fail("Should have raised TypeError") |
| 466 | |
| 467 | # "The specifier name is a ``dotted name'' that may |
| 468 | # resolve either to ... a test case class" |
| 469 | def test_loadTestsFromName__relative_TestCase_subclass(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 470 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 471 | class MyTestCase(unittest.TestCase): |
| 472 | def test(self): |
| 473 | pass |
| 474 | m.testcase_1 = MyTestCase |
| 475 | |
| 476 | loader = unittest.TestLoader() |
| 477 | suite = loader.loadTestsFromName('testcase_1', m) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 478 | self.assertIsInstance(suite, loader.suiteClass) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 479 | self.assertEqual(list(suite), [MyTestCase('test')]) |
| 480 | |
| 481 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 482 | # a module, a test case class, a TestSuite instance, a test method |
| 483 | # within a test case class, or a callable object which returns a |
| 484 | # TestCase or TestSuite instance." |
| 485 | def test_loadTestsFromName__relative_TestSuite(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 486 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 487 | class MyTestCase(unittest.TestCase): |
| 488 | def test(self): |
| 489 | pass |
| 490 | m.testsuite = unittest.TestSuite([MyTestCase('test')]) |
| 491 | |
| 492 | loader = unittest.TestLoader() |
| 493 | suite = loader.loadTestsFromName('testsuite', m) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 494 | self.assertIsInstance(suite, loader.suiteClass) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 495 | |
| 496 | self.assertEqual(list(suite), [MyTestCase('test')]) |
| 497 | |
| 498 | # "The specifier name is a ``dotted name'' that may resolve ... to |
| 499 | # ... a test method within a test case class" |
| 500 | def test_loadTestsFromName__relative_testmethod(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 501 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 502 | class MyTestCase(unittest.TestCase): |
| 503 | def test(self): |
| 504 | pass |
| 505 | m.testcase_1 = MyTestCase |
| 506 | |
| 507 | loader = unittest.TestLoader() |
| 508 | suite = loader.loadTestsFromName('testcase_1.test', m) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 509 | self.assertIsInstance(suite, loader.suiteClass) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 510 | |
| 511 | self.assertEqual(list(suite), [MyTestCase('test')]) |
| 512 | |
| 513 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 514 | # a module, a test case class, a TestSuite instance, a test method |
| 515 | # within a test case class, or a callable object which returns a |
| 516 | # TestCase or TestSuite instance." |
| 517 | # |
| 518 | # Does loadTestsFromName() raise the proper exception when trying to |
| 519 | # resolve "a test method within a test case class" that doesn't exist |
| 520 | # for the given name (relative to a provided module)? |
| 521 | def test_loadTestsFromName__relative_invalid_testmethod(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 522 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 523 | class MyTestCase(unittest.TestCase): |
| 524 | def test(self): |
| 525 | pass |
| 526 | m.testcase_1 = MyTestCase |
| 527 | |
| 528 | loader = unittest.TestLoader() |
| 529 | try: |
| 530 | loader.loadTestsFromName('testcase_1.testfoo', m) |
| 531 | except AttributeError as e: |
| 532 | self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'") |
| 533 | else: |
| 534 | self.fail("Failed to raise AttributeError") |
| 535 | |
| 536 | # "The specifier name is a ``dotted name'' that may resolve ... to |
| 537 | # ... a callable object which returns a ... TestSuite instance" |
| 538 | def test_loadTestsFromName__callable__TestSuite(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 539 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 540 | testcase_1 = unittest.FunctionTestCase(lambda: None) |
| 541 | testcase_2 = unittest.FunctionTestCase(lambda: None) |
| 542 | def return_TestSuite(): |
| 543 | return unittest.TestSuite([testcase_1, testcase_2]) |
| 544 | m.return_TestSuite = return_TestSuite |
| 545 | |
| 546 | loader = unittest.TestLoader() |
| 547 | suite = loader.loadTestsFromName('return_TestSuite', m) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 548 | self.assertIsInstance(suite, loader.suiteClass) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 549 | self.assertEqual(list(suite), [testcase_1, testcase_2]) |
| 550 | |
| 551 | # "The specifier name is a ``dotted name'' that may resolve ... to |
| 552 | # ... a callable object which returns a TestCase ... instance" |
| 553 | def test_loadTestsFromName__callable__TestCase_instance(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 554 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 555 | testcase_1 = unittest.FunctionTestCase(lambda: None) |
| 556 | def return_TestCase(): |
| 557 | return testcase_1 |
| 558 | m.return_TestCase = return_TestCase |
| 559 | |
| 560 | loader = unittest.TestLoader() |
| 561 | suite = loader.loadTestsFromName('return_TestCase', m) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 562 | self.assertIsInstance(suite, loader.suiteClass) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 563 | self.assertEqual(list(suite), [testcase_1]) |
| 564 | |
| 565 | # "The specifier name is a ``dotted name'' that may resolve ... to |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 566 | # ... a callable object which returns a TestCase ... instance" |
| 567 | #***************************************************************** |
| 568 | #Override the suiteClass attribute to ensure that the suiteClass |
| 569 | #attribute is used |
| 570 | def test_loadTestsFromName__callable__TestCase_instance_ProperSuiteClass(self): |
| 571 | class SubTestSuite(unittest.TestSuite): |
| 572 | pass |
| 573 | m = types.ModuleType('m') |
| 574 | testcase_1 = unittest.FunctionTestCase(lambda: None) |
| 575 | def return_TestCase(): |
| 576 | return testcase_1 |
| 577 | m.return_TestCase = return_TestCase |
| 578 | |
| 579 | loader = unittest.TestLoader() |
| 580 | loader.suiteClass = SubTestSuite |
| 581 | suite = loader.loadTestsFromName('return_TestCase', m) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 582 | self.assertIsInstance(suite, loader.suiteClass) |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 583 | self.assertEqual(list(suite), [testcase_1]) |
| 584 | |
| 585 | # "The specifier name is a ``dotted name'' that may resolve ... to |
| 586 | # ... a test method within a test case class" |
| 587 | #***************************************************************** |
| 588 | #Override the suiteClass attribute to ensure that the suiteClass |
| 589 | #attribute is used |
| 590 | def test_loadTestsFromName__relative_testmethod_ProperSuiteClass(self): |
| 591 | class SubTestSuite(unittest.TestSuite): |
| 592 | pass |
| 593 | m = types.ModuleType('m') |
| 594 | class MyTestCase(unittest.TestCase): |
| 595 | def test(self): |
| 596 | pass |
| 597 | m.testcase_1 = MyTestCase |
| 598 | |
| 599 | loader = unittest.TestLoader() |
| 600 | loader.suiteClass=SubTestSuite |
| 601 | suite = loader.loadTestsFromName('testcase_1.test', m) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 602 | self.assertIsInstance(suite, loader.suiteClass) |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 603 | |
| 604 | self.assertEqual(list(suite), [MyTestCase('test')]) |
| 605 | |
| 606 | # "The specifier name is a ``dotted name'' that may resolve ... to |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 607 | # ... a callable object which returns a TestCase or TestSuite instance" |
| 608 | # |
| 609 | # What happens if the callable returns something else? |
| 610 | def test_loadTestsFromName__callable__wrong_type(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 611 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 612 | def return_wrong(): |
| 613 | return 6 |
| 614 | m.return_wrong = return_wrong |
| 615 | |
| 616 | loader = unittest.TestLoader() |
| 617 | try: |
| 618 | suite = loader.loadTestsFromName('return_wrong', m) |
| 619 | except TypeError: |
| 620 | pass |
| 621 | else: |
| 622 | self.fail("TestLoader.loadTestsFromName failed to raise TypeError") |
| 623 | |
| 624 | # "The specifier can refer to modules and packages which have not been |
| 625 | # imported; they will be imported as a side-effect" |
| 626 | def test_loadTestsFromName__module_not_loaded(self): |
| 627 | # We're going to try to load this module as a side-effect, so it |
| 628 | # better not be loaded before we try. |
| 629 | # |
| 630 | # Why pick audioop? Google shows it isn't used very often, so there's |
| 631 | # a good chance that it won't be imported when this test is run |
| 632 | module_name = 'audioop' |
| 633 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 634 | if module_name in sys.modules: |
| 635 | del sys.modules[module_name] |
| 636 | |
| 637 | loader = unittest.TestLoader() |
| 638 | try: |
| 639 | suite = loader.loadTestsFromName(module_name) |
| 640 | |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 641 | self.assertIsInstance(suite, loader.suiteClass) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 642 | self.assertEqual(list(suite), []) |
| 643 | |
| 644 | # audioop should now be loaded, thanks to loadTestsFromName() |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 645 | self.assertIn(module_name, sys.modules) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 646 | finally: |
Guido van Rossum | 360e4b8 | 2007-05-14 22:51:27 +0000 | [diff] [blame] | 647 | if module_name in sys.modules: |
| 648 | del sys.modules[module_name] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 649 | |
| 650 | ################################################################ |
| 651 | ### Tests for TestLoader.loadTestsFromName() |
| 652 | |
| 653 | ### Tests for TestLoader.loadTestsFromNames() |
| 654 | ################################################################ |
| 655 | |
| 656 | # "Similar to loadTestsFromName(), but takes a sequence of names rather |
| 657 | # than a single name." |
| 658 | # |
| 659 | # What happens if that sequence of names is empty? |
| 660 | def test_loadTestsFromNames__empty_name_list(self): |
| 661 | loader = unittest.TestLoader() |
| 662 | |
| 663 | suite = loader.loadTestsFromNames([]) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 664 | self.assertIsInstance(suite, loader.suiteClass) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 665 | self.assertEqual(list(suite), []) |
| 666 | |
| 667 | # "Similar to loadTestsFromName(), but takes a sequence of names rather |
| 668 | # than a single name." |
| 669 | # ... |
| 670 | # "The method optionally resolves name relative to the given module" |
| 671 | # |
| 672 | # What happens if that sequence of names is empty? |
| 673 | # |
| 674 | # XXX Should this raise a ValueError or just return an empty TestSuite? |
| 675 | def test_loadTestsFromNames__relative_empty_name_list(self): |
| 676 | loader = unittest.TestLoader() |
| 677 | |
| 678 | suite = loader.loadTestsFromNames([], unittest) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 679 | self.assertIsInstance(suite, loader.suiteClass) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 680 | self.assertEqual(list(suite), []) |
| 681 | |
| 682 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 683 | # a module, a test case class, a TestSuite instance, a test method |
| 684 | # within a test case class, or a callable object which returns a |
| 685 | # TestCase or TestSuite instance." |
| 686 | # |
| 687 | # Is ValueError raised in response to an empty name? |
| 688 | def test_loadTestsFromNames__empty_name(self): |
| 689 | loader = unittest.TestLoader() |
| 690 | |
| 691 | try: |
| 692 | loader.loadTestsFromNames(['']) |
| 693 | except ValueError as e: |
| 694 | self.assertEqual(str(e), "Empty module name") |
| 695 | else: |
| 696 | self.fail("TestLoader.loadTestsFromNames failed to raise ValueError") |
| 697 | |
| 698 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 699 | # a module, a test case class, a TestSuite instance, a test method |
| 700 | # within a test case class, or a callable object which returns a |
| 701 | # TestCase or TestSuite instance." |
| 702 | # |
| 703 | # What happens when presented with an impossible module name? |
| 704 | def test_loadTestsFromNames__malformed_name(self): |
| 705 | loader = unittest.TestLoader() |
| 706 | |
| 707 | # XXX Should this raise ValueError or ImportError? |
| 708 | try: |
| 709 | loader.loadTestsFromNames(['abc () //']) |
| 710 | except ValueError: |
| 711 | pass |
| 712 | except ImportError: |
| 713 | pass |
| 714 | else: |
| 715 | self.fail("TestLoader.loadTestsFromNames failed to raise ValueError") |
| 716 | |
| 717 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 718 | # a module, a test case class, a TestSuite instance, a test method |
| 719 | # within a test case class, or a callable object which returns a |
| 720 | # TestCase or TestSuite instance." |
| 721 | # |
| 722 | # What happens when no module can be found for the given name? |
| 723 | def test_loadTestsFromNames__unknown_module_name(self): |
| 724 | loader = unittest.TestLoader() |
| 725 | |
| 726 | try: |
| 727 | loader.loadTestsFromNames(['sdasfasfasdf']) |
| 728 | except ImportError as e: |
| 729 | self.assertEqual(str(e), "No module named sdasfasfasdf") |
| 730 | else: |
| 731 | self.fail("TestLoader.loadTestsFromNames failed to raise ImportError") |
| 732 | |
| 733 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 734 | # a module, a test case class, a TestSuite instance, a test method |
| 735 | # within a test case class, or a callable object which returns a |
| 736 | # TestCase or TestSuite instance." |
| 737 | # |
| 738 | # What happens when the module can be found, but not the attribute? |
| 739 | def test_loadTestsFromNames__unknown_attr_name(self): |
| 740 | loader = unittest.TestLoader() |
| 741 | |
| 742 | try: |
| 743 | loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest']) |
| 744 | except AttributeError as e: |
| 745 | self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") |
| 746 | else: |
| 747 | self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError") |
| 748 | |
| 749 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 750 | # a module, a test case class, a TestSuite instance, a test method |
| 751 | # within a test case class, or a callable object which returns a |
| 752 | # TestCase or TestSuite instance." |
| 753 | # ... |
| 754 | # "The method optionally resolves name relative to the given module" |
| 755 | # |
| 756 | # What happens when given an unknown attribute on a specified `module` |
| 757 | # argument? |
| 758 | def test_loadTestsFromNames__unknown_name_relative_1(self): |
| 759 | loader = unittest.TestLoader() |
| 760 | |
| 761 | try: |
| 762 | loader.loadTestsFromNames(['sdasfasfasdf'], unittest) |
| 763 | except AttributeError as e: |
| 764 | self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") |
| 765 | else: |
| 766 | self.fail("TestLoader.loadTestsFromName failed to raise AttributeError") |
| 767 | |
| 768 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 769 | # a module, a test case class, a TestSuite instance, a test method |
| 770 | # within a test case class, or a callable object which returns a |
| 771 | # TestCase or TestSuite instance." |
| 772 | # ... |
| 773 | # "The method optionally resolves name relative to the given module" |
| 774 | # |
| 775 | # Do unknown attributes (relative to a provided module) still raise an |
| 776 | # exception even in the presence of valid attribute names? |
| 777 | def test_loadTestsFromNames__unknown_name_relative_2(self): |
| 778 | loader = unittest.TestLoader() |
| 779 | |
| 780 | try: |
| 781 | loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest) |
| 782 | except AttributeError as e: |
| 783 | self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") |
| 784 | else: |
| 785 | self.fail("TestLoader.loadTestsFromName failed to raise AttributeError") |
| 786 | |
| 787 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 788 | # a module, a test case class, a TestSuite instance, a test method |
| 789 | # within a test case class, or a callable object which returns a |
| 790 | # TestCase or TestSuite instance." |
| 791 | # ... |
| 792 | # "The method optionally resolves name relative to the given module" |
| 793 | # |
| 794 | # What happens when faced with the empty string? |
| 795 | # |
| 796 | # XXX This currently raises AttributeError, though ValueError is probably |
| 797 | # more appropriate |
| 798 | def test_loadTestsFromNames__relative_empty_name(self): |
| 799 | loader = unittest.TestLoader() |
| 800 | |
| 801 | try: |
| 802 | loader.loadTestsFromNames([''], unittest) |
| 803 | except AttributeError: |
| 804 | pass |
| 805 | else: |
| 806 | self.fail("Failed to raise ValueError") |
| 807 | |
| 808 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 809 | # a module, a test case class, a TestSuite instance, a test method |
| 810 | # within a test case class, or a callable object which returns a |
| 811 | # TestCase or TestSuite instance." |
| 812 | # ... |
| 813 | # "The method optionally resolves name relative to the given module" |
| 814 | # |
| 815 | # What happens when presented with an impossible attribute name? |
| 816 | def test_loadTestsFromNames__relative_malformed_name(self): |
| 817 | loader = unittest.TestLoader() |
| 818 | |
| 819 | # XXX Should this raise AttributeError or ValueError? |
| 820 | try: |
| 821 | loader.loadTestsFromNames(['abc () //'], unittest) |
| 822 | except AttributeError: |
| 823 | pass |
| 824 | except ValueError: |
| 825 | pass |
| 826 | else: |
| 827 | self.fail("TestLoader.loadTestsFromNames failed to raise ValueError") |
| 828 | |
| 829 | # "The method optionally resolves name relative to the given module" |
| 830 | # |
| 831 | # Does loadTestsFromNames() make sure the provided `module` is in fact |
| 832 | # a module? |
| 833 | # |
| 834 | # XXX This validation is currently not done. This flexibility should |
| 835 | # either be documented or a TypeError should be raised. |
| 836 | def test_loadTestsFromNames__relative_not_a_module(self): |
| 837 | class MyTestCase(unittest.TestCase): |
| 838 | def test(self): |
| 839 | pass |
| 840 | |
| 841 | class NotAModule(object): |
| 842 | test_2 = MyTestCase |
| 843 | |
| 844 | loader = unittest.TestLoader() |
| 845 | suite = loader.loadTestsFromNames(['test_2'], NotAModule) |
| 846 | |
| 847 | reference = [unittest.TestSuite([MyTestCase('test')])] |
| 848 | self.assertEqual(list(suite), reference) |
| 849 | |
| 850 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 851 | # a module, a test case class, a TestSuite instance, a test method |
| 852 | # within a test case class, or a callable object which returns a |
| 853 | # TestCase or TestSuite instance." |
| 854 | # |
| 855 | # Does it raise an exception if the name resolves to an invalid |
| 856 | # object? |
| 857 | def test_loadTestsFromNames__relative_bad_object(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 858 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 859 | m.testcase_1 = object() |
| 860 | |
| 861 | loader = unittest.TestLoader() |
| 862 | try: |
| 863 | loader.loadTestsFromNames(['testcase_1'], m) |
| 864 | except TypeError: |
| 865 | pass |
| 866 | else: |
| 867 | self.fail("Should have raised TypeError") |
| 868 | |
| 869 | # "The specifier name is a ``dotted name'' that may resolve ... to |
| 870 | # ... a test case class" |
| 871 | def test_loadTestsFromNames__relative_TestCase_subclass(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 872 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 873 | class MyTestCase(unittest.TestCase): |
| 874 | def test(self): |
| 875 | pass |
| 876 | m.testcase_1 = MyTestCase |
| 877 | |
| 878 | loader = unittest.TestLoader() |
| 879 | suite = loader.loadTestsFromNames(['testcase_1'], m) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 880 | self.assertIsInstance(suite, loader.suiteClass) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 881 | |
| 882 | expected = loader.suiteClass([MyTestCase('test')]) |
| 883 | self.assertEqual(list(suite), [expected]) |
| 884 | |
| 885 | # "The specifier name is a ``dotted name'' that may resolve ... to |
| 886 | # ... a TestSuite instance" |
| 887 | def test_loadTestsFromNames__relative_TestSuite(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 888 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 889 | class MyTestCase(unittest.TestCase): |
| 890 | def test(self): |
| 891 | pass |
| 892 | m.testsuite = unittest.TestSuite([MyTestCase('test')]) |
| 893 | |
| 894 | loader = unittest.TestLoader() |
| 895 | suite = loader.loadTestsFromNames(['testsuite'], m) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 896 | self.assertIsInstance(suite, loader.suiteClass) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 897 | |
| 898 | self.assertEqual(list(suite), [m.testsuite]) |
| 899 | |
| 900 | # "The specifier name is a ``dotted name'' that may resolve ... to ... a |
| 901 | # test method within a test case class" |
| 902 | def test_loadTestsFromNames__relative_testmethod(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 903 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 904 | class MyTestCase(unittest.TestCase): |
| 905 | def test(self): |
| 906 | pass |
| 907 | m.testcase_1 = MyTestCase |
| 908 | |
| 909 | loader = unittest.TestLoader() |
| 910 | suite = loader.loadTestsFromNames(['testcase_1.test'], m) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 911 | self.assertIsInstance(suite, loader.suiteClass) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 912 | |
| 913 | ref_suite = unittest.TestSuite([MyTestCase('test')]) |
| 914 | self.assertEqual(list(suite), [ref_suite]) |
| 915 | |
| 916 | # "The specifier name is a ``dotted name'' that may resolve ... to ... a |
| 917 | # test method within a test case class" |
| 918 | # |
| 919 | # Does the method gracefully handle names that initially look like they |
| 920 | # resolve to "a test method within a test case class" but don't? |
| 921 | def test_loadTestsFromNames__relative_invalid_testmethod(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 922 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 923 | class MyTestCase(unittest.TestCase): |
| 924 | def test(self): |
| 925 | pass |
| 926 | m.testcase_1 = MyTestCase |
| 927 | |
| 928 | loader = unittest.TestLoader() |
| 929 | try: |
| 930 | loader.loadTestsFromNames(['testcase_1.testfoo'], m) |
| 931 | except AttributeError as e: |
| 932 | self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'") |
| 933 | else: |
| 934 | self.fail("Failed to raise AttributeError") |
| 935 | |
| 936 | # "The specifier name is a ``dotted name'' that may resolve ... to |
| 937 | # ... a callable object which returns a ... TestSuite instance" |
| 938 | def test_loadTestsFromNames__callable__TestSuite(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 939 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 940 | testcase_1 = unittest.FunctionTestCase(lambda: None) |
| 941 | testcase_2 = unittest.FunctionTestCase(lambda: None) |
| 942 | def return_TestSuite(): |
| 943 | return unittest.TestSuite([testcase_1, testcase_2]) |
| 944 | m.return_TestSuite = return_TestSuite |
| 945 | |
| 946 | loader = unittest.TestLoader() |
| 947 | suite = loader.loadTestsFromNames(['return_TestSuite'], m) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 948 | self.assertIsInstance(suite, loader.suiteClass) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 949 | |
| 950 | expected = unittest.TestSuite([testcase_1, testcase_2]) |
| 951 | self.assertEqual(list(suite), [expected]) |
| 952 | |
| 953 | # "The specifier name is a ``dotted name'' that may resolve ... to |
| 954 | # ... a callable object which returns a TestCase ... instance" |
| 955 | def test_loadTestsFromNames__callable__TestCase_instance(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 956 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 957 | testcase_1 = unittest.FunctionTestCase(lambda: None) |
| 958 | def return_TestCase(): |
| 959 | return testcase_1 |
| 960 | m.return_TestCase = return_TestCase |
| 961 | |
| 962 | loader = unittest.TestLoader() |
| 963 | suite = loader.loadTestsFromNames(['return_TestCase'], m) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 964 | self.assertIsInstance(suite, loader.suiteClass) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 965 | |
| 966 | ref_suite = unittest.TestSuite([testcase_1]) |
| 967 | self.assertEqual(list(suite), [ref_suite]) |
| 968 | |
| 969 | # "The specifier name is a ``dotted name'' that may resolve ... to |
| 970 | # ... a callable object which returns a TestCase or TestSuite instance" |
| 971 | # |
| 972 | # Are staticmethods handled correctly? |
| 973 | def test_loadTestsFromNames__callable__call_staticmethod(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 974 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 975 | class Test1(unittest.TestCase): |
| 976 | def test(self): |
| 977 | pass |
| 978 | |
| 979 | testcase_1 = Test1('test') |
| 980 | class Foo(unittest.TestCase): |
| 981 | @staticmethod |
| 982 | def foo(): |
| 983 | return testcase_1 |
| 984 | m.Foo = Foo |
| 985 | |
| 986 | loader = unittest.TestLoader() |
| 987 | suite = loader.loadTestsFromNames(['Foo.foo'], m) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 988 | self.assertIsInstance(suite, loader.suiteClass) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 989 | |
| 990 | ref_suite = unittest.TestSuite([testcase_1]) |
| 991 | self.assertEqual(list(suite), [ref_suite]) |
| 992 | |
| 993 | # "The specifier name is a ``dotted name'' that may resolve ... to |
| 994 | # ... a callable object which returns a TestCase or TestSuite instance" |
| 995 | # |
| 996 | # What happens when the callable returns something else? |
| 997 | def test_loadTestsFromNames__callable__wrong_type(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 998 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 999 | def return_wrong(): |
| 1000 | return 6 |
| 1001 | m.return_wrong = return_wrong |
| 1002 | |
| 1003 | loader = unittest.TestLoader() |
| 1004 | try: |
| 1005 | suite = loader.loadTestsFromNames(['return_wrong'], m) |
| 1006 | except TypeError: |
| 1007 | pass |
| 1008 | else: |
| 1009 | self.fail("TestLoader.loadTestsFromNames failed to raise TypeError") |
| 1010 | |
| 1011 | # "The specifier can refer to modules and packages which have not been |
| 1012 | # imported; they will be imported as a side-effect" |
| 1013 | def test_loadTestsFromNames__module_not_loaded(self): |
| 1014 | # We're going to try to load this module as a side-effect, so it |
| 1015 | # better not be loaded before we try. |
| 1016 | # |
| 1017 | # Why pick audioop? Google shows it isn't used very often, so there's |
| 1018 | # a good chance that it won't be imported when this test is run |
| 1019 | module_name = 'audioop' |
| 1020 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1021 | if module_name in sys.modules: |
| 1022 | del sys.modules[module_name] |
| 1023 | |
| 1024 | loader = unittest.TestLoader() |
| 1025 | try: |
| 1026 | suite = loader.loadTestsFromNames([module_name]) |
| 1027 | |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 1028 | self.assertIsInstance(suite, loader.suiteClass) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1029 | self.assertEqual(list(suite), [unittest.TestSuite()]) |
| 1030 | |
| 1031 | # audioop should now be loaded, thanks to loadTestsFromName() |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 1032 | self.assertIn(module_name, sys.modules) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1033 | finally: |
Guido van Rossum | 360e4b8 | 2007-05-14 22:51:27 +0000 | [diff] [blame] | 1034 | if module_name in sys.modules: |
| 1035 | del sys.modules[module_name] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1036 | |
| 1037 | ################################################################ |
| 1038 | ### /Tests for TestLoader.loadTestsFromNames() |
| 1039 | |
| 1040 | ### Tests for TestLoader.getTestCaseNames() |
| 1041 | ################################################################ |
| 1042 | |
| 1043 | # "Return a sorted sequence of method names found within testCaseClass" |
| 1044 | # |
| 1045 | # Test.foobar is defined to make sure getTestCaseNames() respects |
| 1046 | # loader.testMethodPrefix |
| 1047 | def test_getTestCaseNames(self): |
| 1048 | class Test(unittest.TestCase): |
| 1049 | def test_1(self): pass |
| 1050 | def test_2(self): pass |
| 1051 | def foobar(self): pass |
| 1052 | |
| 1053 | loader = unittest.TestLoader() |
| 1054 | |
| 1055 | self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2']) |
| 1056 | |
| 1057 | # "Return a sorted sequence of method names found within testCaseClass" |
| 1058 | # |
| 1059 | # Does getTestCaseNames() behave appropriately if no tests are found? |
| 1060 | def test_getTestCaseNames__no_tests(self): |
| 1061 | class Test(unittest.TestCase): |
| 1062 | def foobar(self): pass |
| 1063 | |
| 1064 | loader = unittest.TestLoader() |
| 1065 | |
| 1066 | self.assertEqual(loader.getTestCaseNames(Test), []) |
| 1067 | |
| 1068 | # "Return a sorted sequence of method names found within testCaseClass" |
| 1069 | # |
| 1070 | # Are not-TestCases handled gracefully? |
| 1071 | # |
| 1072 | # XXX This should raise a TypeError, not return a list |
| 1073 | # |
| 1074 | # XXX It's too late in the 2.5 release cycle to fix this, but it should |
| 1075 | # probably be revisited for 2.6 |
| 1076 | def test_getTestCaseNames__not_a_TestCase(self): |
| 1077 | class BadCase(int): |
| 1078 | def test_foo(self): |
| 1079 | pass |
| 1080 | |
| 1081 | loader = unittest.TestLoader() |
| 1082 | names = loader.getTestCaseNames(BadCase) |
| 1083 | |
| 1084 | self.assertEqual(names, ['test_foo']) |
| 1085 | |
| 1086 | # "Return a sorted sequence of method names found within testCaseClass" |
| 1087 | # |
| 1088 | # Make sure inherited names are handled. |
| 1089 | # |
| 1090 | # TestP.foobar is defined to make sure getTestCaseNames() respects |
| 1091 | # loader.testMethodPrefix |
| 1092 | def test_getTestCaseNames__inheritance(self): |
| 1093 | class TestP(unittest.TestCase): |
| 1094 | def test_1(self): pass |
| 1095 | def test_2(self): pass |
| 1096 | def foobar(self): pass |
| 1097 | |
| 1098 | class TestC(TestP): |
| 1099 | def test_1(self): pass |
| 1100 | def test_3(self): pass |
| 1101 | |
| 1102 | loader = unittest.TestLoader() |
| 1103 | |
| 1104 | names = ['test_1', 'test_2', 'test_3'] |
| 1105 | self.assertEqual(loader.getTestCaseNames(TestC), names) |
| 1106 | |
| 1107 | ################################################################ |
| 1108 | ### /Tests for TestLoader.getTestCaseNames() |
| 1109 | |
| 1110 | ### Tests for TestLoader.testMethodPrefix |
| 1111 | ################################################################ |
| 1112 | |
| 1113 | # "String giving the prefix of method names which will be interpreted as |
| 1114 | # test methods" |
| 1115 | # |
| 1116 | # Implicit in the documentation is that testMethodPrefix is respected by |
| 1117 | # all loadTestsFrom* methods. |
| 1118 | def test_testMethodPrefix__loadTestsFromTestCase(self): |
| 1119 | class Foo(unittest.TestCase): |
| 1120 | def test_1(self): pass |
| 1121 | def test_2(self): pass |
| 1122 | def foo_bar(self): pass |
| 1123 | |
| 1124 | tests_1 = unittest.TestSuite([Foo('foo_bar')]) |
| 1125 | tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')]) |
| 1126 | |
| 1127 | loader = unittest.TestLoader() |
| 1128 | loader.testMethodPrefix = 'foo' |
| 1129 | self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1) |
| 1130 | |
| 1131 | loader.testMethodPrefix = 'test' |
| 1132 | self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2) |
| 1133 | |
| 1134 | # "String giving the prefix of method names which will be interpreted as |
| 1135 | # test methods" |
| 1136 | # |
| 1137 | # Implicit in the documentation is that testMethodPrefix is respected by |
| 1138 | # all loadTestsFrom* methods. |
| 1139 | def test_testMethodPrefix__loadTestsFromModule(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 1140 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1141 | class Foo(unittest.TestCase): |
| 1142 | def test_1(self): pass |
| 1143 | def test_2(self): pass |
| 1144 | def foo_bar(self): pass |
| 1145 | m.Foo = Foo |
| 1146 | |
| 1147 | tests_1 = [unittest.TestSuite([Foo('foo_bar')])] |
| 1148 | tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])] |
| 1149 | |
| 1150 | loader = unittest.TestLoader() |
| 1151 | loader.testMethodPrefix = 'foo' |
| 1152 | self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1) |
| 1153 | |
| 1154 | loader.testMethodPrefix = 'test' |
| 1155 | self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2) |
| 1156 | |
| 1157 | # "String giving the prefix of method names which will be interpreted as |
| 1158 | # test methods" |
| 1159 | # |
| 1160 | # Implicit in the documentation is that testMethodPrefix is respected by |
| 1161 | # all loadTestsFrom* methods. |
| 1162 | def test_testMethodPrefix__loadTestsFromName(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 1163 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1164 | class Foo(unittest.TestCase): |
| 1165 | def test_1(self): pass |
| 1166 | def test_2(self): pass |
| 1167 | def foo_bar(self): pass |
| 1168 | m.Foo = Foo |
| 1169 | |
| 1170 | tests_1 = unittest.TestSuite([Foo('foo_bar')]) |
| 1171 | tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')]) |
| 1172 | |
| 1173 | loader = unittest.TestLoader() |
| 1174 | loader.testMethodPrefix = 'foo' |
| 1175 | self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1) |
| 1176 | |
| 1177 | loader.testMethodPrefix = 'test' |
| 1178 | self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2) |
| 1179 | |
| 1180 | # "String giving the prefix of method names which will be interpreted as |
| 1181 | # test methods" |
| 1182 | # |
| 1183 | # Implicit in the documentation is that testMethodPrefix is respected by |
| 1184 | # all loadTestsFrom* methods. |
| 1185 | def test_testMethodPrefix__loadTestsFromNames(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 1186 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1187 | class Foo(unittest.TestCase): |
| 1188 | def test_1(self): pass |
| 1189 | def test_2(self): pass |
| 1190 | def foo_bar(self): pass |
| 1191 | m.Foo = Foo |
| 1192 | |
| 1193 | tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])]) |
| 1194 | tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')]) |
| 1195 | tests_2 = unittest.TestSuite([tests_2]) |
| 1196 | |
| 1197 | loader = unittest.TestLoader() |
| 1198 | loader.testMethodPrefix = 'foo' |
| 1199 | self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1) |
| 1200 | |
| 1201 | loader.testMethodPrefix = 'test' |
| 1202 | self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2) |
| 1203 | |
| 1204 | # "The default value is 'test'" |
| 1205 | def test_testMethodPrefix__default_value(self): |
| 1206 | loader = unittest.TestLoader() |
Guido van Rossum | e61fd5b | 2007-07-11 12:20:59 +0000 | [diff] [blame] | 1207 | self.assertEqual(loader.testMethodPrefix, 'test') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1208 | |
| 1209 | ################################################################ |
| 1210 | ### /Tests for TestLoader.testMethodPrefix |
| 1211 | |
| 1212 | ### Tests for TestLoader.sortTestMethodsUsing |
| 1213 | ################################################################ |
| 1214 | |
| 1215 | # "Function to be used to compare method names when sorting them in |
| 1216 | # getTestCaseNames() and all the loadTestsFromX() methods" |
| 1217 | def test_sortTestMethodsUsing__loadTestsFromTestCase(self): |
| 1218 | def reversed_cmp(x, y): |
Mark Dickinson | a56c467 | 2009-01-27 18:17:45 +0000 | [diff] [blame] | 1219 | return -((x > y) - (x < y)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1220 | |
| 1221 | class Foo(unittest.TestCase): |
| 1222 | def test_1(self): pass |
| 1223 | def test_2(self): pass |
| 1224 | |
| 1225 | loader = unittest.TestLoader() |
| 1226 | loader.sortTestMethodsUsing = reversed_cmp |
| 1227 | |
| 1228 | tests = loader.suiteClass([Foo('test_2'), Foo('test_1')]) |
| 1229 | self.assertEqual(loader.loadTestsFromTestCase(Foo), tests) |
| 1230 | |
| 1231 | # "Function to be used to compare method names when sorting them in |
| 1232 | # getTestCaseNames() and all the loadTestsFromX() methods" |
| 1233 | def test_sortTestMethodsUsing__loadTestsFromModule(self): |
| 1234 | def reversed_cmp(x, y): |
Mark Dickinson | a56c467 | 2009-01-27 18:17:45 +0000 | [diff] [blame] | 1235 | return -((x > y) - (x < y)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1236 | |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 1237 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1238 | class Foo(unittest.TestCase): |
| 1239 | def test_1(self): pass |
| 1240 | def test_2(self): pass |
| 1241 | m.Foo = Foo |
| 1242 | |
| 1243 | loader = unittest.TestLoader() |
| 1244 | loader.sortTestMethodsUsing = reversed_cmp |
| 1245 | |
| 1246 | tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])] |
| 1247 | self.assertEqual(list(loader.loadTestsFromModule(m)), tests) |
| 1248 | |
| 1249 | # "Function to be used to compare method names when sorting them in |
| 1250 | # getTestCaseNames() and all the loadTestsFromX() methods" |
| 1251 | def test_sortTestMethodsUsing__loadTestsFromName(self): |
| 1252 | def reversed_cmp(x, y): |
Mark Dickinson | a56c467 | 2009-01-27 18:17:45 +0000 | [diff] [blame] | 1253 | return -((x > y) - (x < y)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1254 | |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 1255 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1256 | class Foo(unittest.TestCase): |
| 1257 | def test_1(self): pass |
| 1258 | def test_2(self): pass |
| 1259 | m.Foo = Foo |
| 1260 | |
| 1261 | loader = unittest.TestLoader() |
| 1262 | loader.sortTestMethodsUsing = reversed_cmp |
| 1263 | |
| 1264 | tests = loader.suiteClass([Foo('test_2'), Foo('test_1')]) |
| 1265 | self.assertEqual(loader.loadTestsFromName('Foo', m), tests) |
| 1266 | |
| 1267 | # "Function to be used to compare method names when sorting them in |
| 1268 | # getTestCaseNames() and all the loadTestsFromX() methods" |
| 1269 | def test_sortTestMethodsUsing__loadTestsFromNames(self): |
| 1270 | def reversed_cmp(x, y): |
Mark Dickinson | a56c467 | 2009-01-27 18:17:45 +0000 | [diff] [blame] | 1271 | return -((x > y) - (x < y)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1272 | |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 1273 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1274 | class Foo(unittest.TestCase): |
| 1275 | def test_1(self): pass |
| 1276 | def test_2(self): pass |
| 1277 | m.Foo = Foo |
| 1278 | |
| 1279 | loader = unittest.TestLoader() |
| 1280 | loader.sortTestMethodsUsing = reversed_cmp |
| 1281 | |
| 1282 | tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])] |
| 1283 | self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests) |
| 1284 | |
| 1285 | # "Function to be used to compare method names when sorting them in |
| 1286 | # getTestCaseNames()" |
| 1287 | # |
| 1288 | # Does it actually affect getTestCaseNames()? |
| 1289 | def test_sortTestMethodsUsing__getTestCaseNames(self): |
| 1290 | def reversed_cmp(x, y): |
Mark Dickinson | a56c467 | 2009-01-27 18:17:45 +0000 | [diff] [blame] | 1291 | return -((x > y) - (x < y)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1292 | |
| 1293 | class Foo(unittest.TestCase): |
| 1294 | def test_1(self): pass |
| 1295 | def test_2(self): pass |
| 1296 | |
| 1297 | loader = unittest.TestLoader() |
| 1298 | loader.sortTestMethodsUsing = reversed_cmp |
| 1299 | |
| 1300 | test_names = ['test_2', 'test_1'] |
| 1301 | self.assertEqual(loader.getTestCaseNames(Foo), test_names) |
| 1302 | |
| 1303 | # "The default value is the built-in cmp() function" |
Mark Dickinson | a56c467 | 2009-01-27 18:17:45 +0000 | [diff] [blame] | 1304 | # Since cmp is now defunct, we simply verify that the results |
| 1305 | # occur in the same order as they would with the default sort. |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1306 | def test_sortTestMethodsUsing__default_value(self): |
| 1307 | loader = unittest.TestLoader() |
Mark Dickinson | a56c467 | 2009-01-27 18:17:45 +0000 | [diff] [blame] | 1308 | |
| 1309 | class Foo(unittest.TestCase): |
| 1310 | def test_2(self): pass |
| 1311 | def test_3(self): pass |
| 1312 | def test_1(self): pass |
| 1313 | |
| 1314 | test_names = ['test_2', 'test_3', 'test_1'] |
| 1315 | self.assertEqual(loader.getTestCaseNames(Foo), sorted(test_names)) |
| 1316 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1317 | |
| 1318 | # "it can be set to None to disable the sort." |
| 1319 | # |
| 1320 | # XXX How is this different from reassigning cmp? Are the tests returned |
| 1321 | # in a random order or something? This behaviour should die |
| 1322 | def test_sortTestMethodsUsing__None(self): |
| 1323 | class Foo(unittest.TestCase): |
| 1324 | def test_1(self): pass |
| 1325 | def test_2(self): pass |
| 1326 | |
| 1327 | loader = unittest.TestLoader() |
| 1328 | loader.sortTestMethodsUsing = None |
| 1329 | |
| 1330 | test_names = ['test_2', 'test_1'] |
| 1331 | self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names)) |
| 1332 | |
| 1333 | ################################################################ |
| 1334 | ### /Tests for TestLoader.sortTestMethodsUsing |
| 1335 | |
| 1336 | ### Tests for TestLoader.suiteClass |
| 1337 | ################################################################ |
| 1338 | |
| 1339 | # "Callable object that constructs a test suite from a list of tests." |
| 1340 | def test_suiteClass__loadTestsFromTestCase(self): |
| 1341 | class Foo(unittest.TestCase): |
| 1342 | def test_1(self): pass |
| 1343 | def test_2(self): pass |
| 1344 | def foo_bar(self): pass |
| 1345 | |
| 1346 | tests = [Foo('test_1'), Foo('test_2')] |
| 1347 | |
| 1348 | loader = unittest.TestLoader() |
Benjamin Peterson | 14a3dd7 | 2009-05-25 00:51:58 +0000 | [diff] [blame] | 1349 | loader.suiteClass = list |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1350 | self.assertEqual(loader.loadTestsFromTestCase(Foo), tests) |
| 1351 | |
| 1352 | # It is implicit in the documentation for TestLoader.suiteClass that |
| 1353 | # all TestLoader.loadTestsFrom* methods respect it. Let's make sure |
| 1354 | def test_suiteClass__loadTestsFromModule(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 1355 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1356 | class Foo(unittest.TestCase): |
| 1357 | def test_1(self): pass |
| 1358 | def test_2(self): pass |
| 1359 | def foo_bar(self): pass |
| 1360 | m.Foo = Foo |
| 1361 | |
Benjamin Peterson | 14a3dd7 | 2009-05-25 00:51:58 +0000 | [diff] [blame] | 1362 | tests = [[Foo('test_1'), Foo('test_2')]] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1363 | |
| 1364 | loader = unittest.TestLoader() |
| 1365 | loader.suiteClass = list |
| 1366 | self.assertEqual(loader.loadTestsFromModule(m), tests) |
| 1367 | |
| 1368 | # It is implicit in the documentation for TestLoader.suiteClass that |
| 1369 | # all TestLoader.loadTestsFrom* methods respect it. Let's make sure |
| 1370 | def test_suiteClass__loadTestsFromName(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 1371 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1372 | class Foo(unittest.TestCase): |
| 1373 | def test_1(self): pass |
| 1374 | def test_2(self): pass |
| 1375 | def foo_bar(self): pass |
| 1376 | m.Foo = Foo |
| 1377 | |
| 1378 | tests = [Foo('test_1'), Foo('test_2')] |
| 1379 | |
| 1380 | loader = unittest.TestLoader() |
Benjamin Peterson | 14a3dd7 | 2009-05-25 00:51:58 +0000 | [diff] [blame] | 1381 | loader.suiteClass = list |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1382 | self.assertEqual(loader.loadTestsFromName('Foo', m), tests) |
| 1383 | |
| 1384 | # It is implicit in the documentation for TestLoader.suiteClass that |
| 1385 | # all TestLoader.loadTestsFrom* methods respect it. Let's make sure |
| 1386 | def test_suiteClass__loadTestsFromNames(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 1387 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1388 | class Foo(unittest.TestCase): |
| 1389 | def test_1(self): pass |
| 1390 | def test_2(self): pass |
| 1391 | def foo_bar(self): pass |
| 1392 | m.Foo = Foo |
| 1393 | |
Benjamin Peterson | 14a3dd7 | 2009-05-25 00:51:58 +0000 | [diff] [blame] | 1394 | tests = [[Foo('test_1'), Foo('test_2')]] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1395 | |
| 1396 | loader = unittest.TestLoader() |
| 1397 | loader.suiteClass = list |
| 1398 | self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests) |
| 1399 | |
| 1400 | # "The default value is the TestSuite class" |
| 1401 | def test_suiteClass__default_value(self): |
| 1402 | loader = unittest.TestLoader() |
Benjamin Peterson | e1759f8 | 2009-06-30 23:35:19 +0000 | [diff] [blame] | 1403 | self.assertTrue(loader.suiteClass is unittest.TestSuite) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1404 | |
| 1405 | ################################################################ |
| 1406 | ### /Tests for TestLoader.suiteClass |
| 1407 | |
| 1408 | ### Support code for Test_TestSuite |
| 1409 | ################################################################ |
| 1410 | |
| 1411 | class Foo(unittest.TestCase): |
| 1412 | def test_1(self): pass |
| 1413 | def test_2(self): pass |
| 1414 | def test_3(self): pass |
| 1415 | def runTest(self): pass |
| 1416 | |
| 1417 | def _mk_TestSuite(*names): |
| 1418 | return unittest.TestSuite(Foo(n) for n in names) |
| 1419 | |
| 1420 | ################################################################ |
| 1421 | ### /Support code for Test_TestSuite |
| 1422 | |
| 1423 | class Test_TestSuite(TestCase, TestEquality): |
| 1424 | |
| 1425 | ### Set up attributes needed by inherited tests |
| 1426 | ################################################################ |
| 1427 | |
| 1428 | # Used by TestEquality.test_eq |
| 1429 | eq_pairs = [(unittest.TestSuite(), unittest.TestSuite()) |
| 1430 | ,(unittest.TestSuite(), unittest.TestSuite([])) |
| 1431 | ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))] |
| 1432 | |
| 1433 | # Used by TestEquality.test_ne |
| 1434 | ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1')) |
| 1435 | ,(unittest.TestSuite([]), _mk_TestSuite('test_1')) |
| 1436 | ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3')) |
| 1437 | ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))] |
| 1438 | |
| 1439 | ################################################################ |
| 1440 | ### /Set up attributes needed by inherited tests |
| 1441 | |
| 1442 | ### Tests for TestSuite.__init__ |
| 1443 | ################################################################ |
| 1444 | |
| 1445 | # "class TestSuite([tests])" |
| 1446 | # |
| 1447 | # The tests iterable should be optional |
| 1448 | def test_init__tests_optional(self): |
| 1449 | suite = unittest.TestSuite() |
| 1450 | |
| 1451 | self.assertEqual(suite.countTestCases(), 0) |
| 1452 | |
| 1453 | # "class TestSuite([tests])" |
| 1454 | # ... |
| 1455 | # "If tests is given, it must be an iterable of individual test cases |
| 1456 | # or other test suites that will be used to build the suite initially" |
| 1457 | # |
| 1458 | # TestSuite should deal with empty tests iterables by allowing the |
| 1459 | # creation of an empty suite |
| 1460 | def test_init__empty_tests(self): |
| 1461 | suite = unittest.TestSuite([]) |
| 1462 | |
| 1463 | self.assertEqual(suite.countTestCases(), 0) |
| 1464 | |
| 1465 | # "class TestSuite([tests])" |
| 1466 | # ... |
| 1467 | # "If tests is given, it must be an iterable of individual test cases |
| 1468 | # or other test suites that will be used to build the suite initially" |
| 1469 | # |
| 1470 | # TestSuite should allow any iterable to provide tests |
| 1471 | def test_init__tests_from_any_iterable(self): |
| 1472 | def tests(): |
| 1473 | yield unittest.FunctionTestCase(lambda: None) |
| 1474 | yield unittest.FunctionTestCase(lambda: None) |
| 1475 | |
| 1476 | suite_1 = unittest.TestSuite(tests()) |
| 1477 | self.assertEqual(suite_1.countTestCases(), 2) |
| 1478 | |
| 1479 | suite_2 = unittest.TestSuite(suite_1) |
| 1480 | self.assertEqual(suite_2.countTestCases(), 2) |
| 1481 | |
| 1482 | suite_3 = unittest.TestSuite(set(suite_1)) |
| 1483 | self.assertEqual(suite_3.countTestCases(), 2) |
| 1484 | |
| 1485 | # "class TestSuite([tests])" |
| 1486 | # ... |
| 1487 | # "If tests is given, it must be an iterable of individual test cases |
| 1488 | # or other test suites that will be used to build the suite initially" |
| 1489 | # |
| 1490 | # Does TestSuite() also allow other TestSuite() instances to be present |
| 1491 | # in the tests iterable? |
| 1492 | def test_init__TestSuite_instances_in_tests(self): |
| 1493 | def tests(): |
| 1494 | ftc = unittest.FunctionTestCase(lambda: None) |
| 1495 | yield unittest.TestSuite([ftc]) |
| 1496 | yield unittest.FunctionTestCase(lambda: None) |
| 1497 | |
| 1498 | suite = unittest.TestSuite(tests()) |
| 1499 | self.assertEqual(suite.countTestCases(), 2) |
| 1500 | |
| 1501 | ################################################################ |
| 1502 | ### /Tests for TestSuite.__init__ |
| 1503 | |
| 1504 | # Container types should support the iter protocol |
| 1505 | def test_iter(self): |
| 1506 | test1 = unittest.FunctionTestCase(lambda: None) |
| 1507 | test2 = unittest.FunctionTestCase(lambda: None) |
| 1508 | suite = unittest.TestSuite((test1, test2)) |
| 1509 | |
| 1510 | self.assertEqual(list(suite), [test1, test2]) |
| 1511 | |
| 1512 | # "Return the number of tests represented by the this test object. |
| 1513 | # ...this method is also implemented by the TestSuite class, which can |
| 1514 | # return larger [greater than 1] values" |
| 1515 | # |
| 1516 | # Presumably an empty TestSuite returns 0? |
| 1517 | def test_countTestCases_zero_simple(self): |
| 1518 | suite = unittest.TestSuite() |
| 1519 | |
| 1520 | self.assertEqual(suite.countTestCases(), 0) |
| 1521 | |
| 1522 | # "Return the number of tests represented by the this test object. |
| 1523 | # ...this method is also implemented by the TestSuite class, which can |
| 1524 | # return larger [greater than 1] values" |
| 1525 | # |
| 1526 | # Presumably an empty TestSuite (even if it contains other empty |
| 1527 | # TestSuite instances) returns 0? |
| 1528 | def test_countTestCases_zero_nested(self): |
| 1529 | class Test1(unittest.TestCase): |
| 1530 | def test(self): |
| 1531 | pass |
| 1532 | |
| 1533 | suite = unittest.TestSuite([unittest.TestSuite()]) |
| 1534 | |
| 1535 | self.assertEqual(suite.countTestCases(), 0) |
| 1536 | |
| 1537 | # "Return the number of tests represented by the this test object. |
| 1538 | # ...this method is also implemented by the TestSuite class, which can |
| 1539 | # return larger [greater than 1] values" |
| 1540 | def test_countTestCases_simple(self): |
| 1541 | test1 = unittest.FunctionTestCase(lambda: None) |
| 1542 | test2 = unittest.FunctionTestCase(lambda: None) |
| 1543 | suite = unittest.TestSuite((test1, test2)) |
| 1544 | |
| 1545 | self.assertEqual(suite.countTestCases(), 2) |
| 1546 | |
| 1547 | # "Return the number of tests represented by the this test object. |
| 1548 | # ...this method is also implemented by the TestSuite class, which can |
| 1549 | # return larger [greater than 1] values" |
| 1550 | # |
| 1551 | # Make sure this holds for nested TestSuite instances, too |
| 1552 | def test_countTestCases_nested(self): |
| 1553 | class Test1(unittest.TestCase): |
| 1554 | def test1(self): pass |
| 1555 | def test2(self): pass |
| 1556 | |
| 1557 | test2 = unittest.FunctionTestCase(lambda: None) |
| 1558 | test3 = unittest.FunctionTestCase(lambda: None) |
| 1559 | child = unittest.TestSuite((Test1('test2'), test2)) |
| 1560 | parent = unittest.TestSuite((test3, child, Test1('test1'))) |
| 1561 | |
| 1562 | self.assertEqual(parent.countTestCases(), 4) |
| 1563 | |
| 1564 | # "Run the tests associated with this suite, collecting the result into |
| 1565 | # the test result object passed as result." |
| 1566 | # |
| 1567 | # And if there are no tests? What then? |
| 1568 | def test_run__empty_suite(self): |
| 1569 | events = [] |
| 1570 | result = LoggingResult(events) |
| 1571 | |
| 1572 | suite = unittest.TestSuite() |
| 1573 | |
| 1574 | suite.run(result) |
| 1575 | |
| 1576 | self.assertEqual(events, []) |
| 1577 | |
| 1578 | # "Note that unlike TestCase.run(), TestSuite.run() requires the |
| 1579 | # "result object to be passed in." |
| 1580 | def test_run__requires_result(self): |
| 1581 | suite = unittest.TestSuite() |
| 1582 | |
| 1583 | try: |
| 1584 | suite.run() |
| 1585 | except TypeError: |
| 1586 | pass |
| 1587 | else: |
| 1588 | self.fail("Failed to raise TypeError") |
| 1589 | |
| 1590 | # "Run the tests associated with this suite, collecting the result into |
| 1591 | # the test result object passed as result." |
| 1592 | def test_run(self): |
| 1593 | events = [] |
| 1594 | result = LoggingResult(events) |
| 1595 | |
| 1596 | class LoggingCase(unittest.TestCase): |
| 1597 | def run(self, result): |
| 1598 | events.append('run %s' % self._testMethodName) |
| 1599 | |
| 1600 | def test1(self): pass |
| 1601 | def test2(self): pass |
| 1602 | |
| 1603 | tests = [LoggingCase('test1'), LoggingCase('test2')] |
| 1604 | |
| 1605 | unittest.TestSuite(tests).run(result) |
| 1606 | |
| 1607 | self.assertEqual(events, ['run test1', 'run test2']) |
| 1608 | |
| 1609 | # "Add a TestCase ... to the suite" |
| 1610 | def test_addTest__TestCase(self): |
| 1611 | class Foo(unittest.TestCase): |
| 1612 | def test(self): pass |
| 1613 | |
| 1614 | test = Foo('test') |
| 1615 | suite = unittest.TestSuite() |
| 1616 | |
| 1617 | suite.addTest(test) |
| 1618 | |
| 1619 | self.assertEqual(suite.countTestCases(), 1) |
| 1620 | self.assertEqual(list(suite), [test]) |
| 1621 | |
| 1622 | # "Add a ... TestSuite to the suite" |
| 1623 | def test_addTest__TestSuite(self): |
| 1624 | class Foo(unittest.TestCase): |
| 1625 | def test(self): pass |
| 1626 | |
| 1627 | suite_2 = unittest.TestSuite([Foo('test')]) |
| 1628 | |
| 1629 | suite = unittest.TestSuite() |
| 1630 | suite.addTest(suite_2) |
| 1631 | |
| 1632 | self.assertEqual(suite.countTestCases(), 1) |
| 1633 | self.assertEqual(list(suite), [suite_2]) |
| 1634 | |
| 1635 | # "Add all the tests from an iterable of TestCase and TestSuite |
| 1636 | # instances to this test suite." |
| 1637 | # |
| 1638 | # "This is equivalent to iterating over tests, calling addTest() for |
| 1639 | # each element" |
| 1640 | def test_addTests(self): |
| 1641 | class Foo(unittest.TestCase): |
| 1642 | def test_1(self): pass |
| 1643 | def test_2(self): pass |
| 1644 | |
| 1645 | test_1 = Foo('test_1') |
| 1646 | test_2 = Foo('test_2') |
| 1647 | inner_suite = unittest.TestSuite([test_2]) |
| 1648 | |
| 1649 | def gen(): |
| 1650 | yield test_1 |
| 1651 | yield test_2 |
| 1652 | yield inner_suite |
| 1653 | |
| 1654 | suite_1 = unittest.TestSuite() |
| 1655 | suite_1.addTests(gen()) |
| 1656 | |
| 1657 | self.assertEqual(list(suite_1), list(gen())) |
| 1658 | |
| 1659 | # "This is equivalent to iterating over tests, calling addTest() for |
| 1660 | # each element" |
| 1661 | suite_2 = unittest.TestSuite() |
| 1662 | for t in gen(): |
| 1663 | suite_2.addTest(t) |
| 1664 | |
| 1665 | self.assertEqual(suite_1, suite_2) |
| 1666 | |
| 1667 | # "Add all the tests from an iterable of TestCase and TestSuite |
| 1668 | # instances to this test suite." |
| 1669 | # |
| 1670 | # What happens if it doesn't get an iterable? |
| 1671 | def test_addTest__noniterable(self): |
| 1672 | suite = unittest.TestSuite() |
| 1673 | |
| 1674 | try: |
| 1675 | suite.addTests(5) |
| 1676 | except TypeError: |
| 1677 | pass |
| 1678 | else: |
| 1679 | self.fail("Failed to raise TypeError") |
| 1680 | |
| 1681 | def test_addTest__noncallable(self): |
| 1682 | suite = unittest.TestSuite() |
| 1683 | self.assertRaises(TypeError, suite.addTest, 5) |
| 1684 | |
| 1685 | def test_addTest__casesuiteclass(self): |
| 1686 | suite = unittest.TestSuite() |
| 1687 | self.assertRaises(TypeError, suite.addTest, Test_TestSuite) |
| 1688 | self.assertRaises(TypeError, suite.addTest, unittest.TestSuite) |
| 1689 | |
| 1690 | def test_addTests__string(self): |
| 1691 | suite = unittest.TestSuite() |
| 1692 | self.assertRaises(TypeError, suite.addTests, "foo") |
| 1693 | |
| 1694 | |
| 1695 | class Test_FunctionTestCase(TestCase): |
| 1696 | |
| 1697 | # "Return the number of tests represented by the this test object. For |
| 1698 | # TestCase instances, this will always be 1" |
| 1699 | def test_countTestCases(self): |
| 1700 | test = unittest.FunctionTestCase(lambda: None) |
| 1701 | |
| 1702 | self.assertEqual(test.countTestCases(), 1) |
| 1703 | |
| 1704 | # "When a setUp() method is defined, the test runner will run that method |
| 1705 | # prior to each test. Likewise, if a tearDown() method is defined, the |
| 1706 | # test runner will invoke that method after each test. In the example, |
| 1707 | # setUp() was used to create a fresh sequence for each test." |
| 1708 | # |
| 1709 | # Make sure the proper call order is maintained, even if setUp() raises |
| 1710 | # an exception. |
| 1711 | def test_run_call_order__error_in_setUp(self): |
| 1712 | events = [] |
| 1713 | result = LoggingResult(events) |
| 1714 | |
| 1715 | def setUp(): |
| 1716 | events.append('setUp') |
| 1717 | raise RuntimeError('raised by setUp') |
| 1718 | |
| 1719 | def test(): |
| 1720 | events.append('test') |
| 1721 | |
| 1722 | def tearDown(): |
| 1723 | events.append('tearDown') |
| 1724 | |
| 1725 | expected = ['startTest', 'setUp', 'addError', 'stopTest'] |
| 1726 | unittest.FunctionTestCase(test, setUp, tearDown).run(result) |
| 1727 | self.assertEqual(events, expected) |
| 1728 | |
| 1729 | # "When a setUp() method is defined, the test runner will run that method |
| 1730 | # prior to each test. Likewise, if a tearDown() method is defined, the |
| 1731 | # test runner will invoke that method after each test. In the example, |
| 1732 | # setUp() was used to create a fresh sequence for each test." |
| 1733 | # |
| 1734 | # Make sure the proper call order is maintained, even if the test raises |
| 1735 | # an error (as opposed to a failure). |
| 1736 | def test_run_call_order__error_in_test(self): |
| 1737 | events = [] |
| 1738 | result = LoggingResult(events) |
| 1739 | |
| 1740 | def setUp(): |
| 1741 | events.append('setUp') |
| 1742 | |
| 1743 | def test(): |
| 1744 | events.append('test') |
| 1745 | raise RuntimeError('raised by test') |
| 1746 | |
| 1747 | def tearDown(): |
| 1748 | events.append('tearDown') |
| 1749 | |
| 1750 | expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown', |
| 1751 | 'stopTest'] |
| 1752 | unittest.FunctionTestCase(test, setUp, tearDown).run(result) |
| 1753 | self.assertEqual(events, expected) |
| 1754 | |
| 1755 | # "When a setUp() method is defined, the test runner will run that method |
| 1756 | # prior to each test. Likewise, if a tearDown() method is defined, the |
| 1757 | # test runner will invoke that method after each test. In the example, |
| 1758 | # setUp() was used to create a fresh sequence for each test." |
| 1759 | # |
| 1760 | # Make sure the proper call order is maintained, even if the test signals |
| 1761 | # a failure (as opposed to an error). |
| 1762 | def test_run_call_order__failure_in_test(self): |
| 1763 | events = [] |
| 1764 | result = LoggingResult(events) |
| 1765 | |
| 1766 | def setUp(): |
| 1767 | events.append('setUp') |
| 1768 | |
| 1769 | def test(): |
| 1770 | events.append('test') |
| 1771 | self.fail('raised by test') |
| 1772 | |
| 1773 | def tearDown(): |
| 1774 | events.append('tearDown') |
| 1775 | |
| 1776 | expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown', |
| 1777 | 'stopTest'] |
| 1778 | unittest.FunctionTestCase(test, setUp, tearDown).run(result) |
| 1779 | self.assertEqual(events, expected) |
| 1780 | |
| 1781 | # "When a setUp() method is defined, the test runner will run that method |
| 1782 | # prior to each test. Likewise, if a tearDown() method is defined, the |
| 1783 | # test runner will invoke that method after each test. In the example, |
| 1784 | # setUp() was used to create a fresh sequence for each test." |
| 1785 | # |
| 1786 | # Make sure the proper call order is maintained, even if tearDown() raises |
| 1787 | # an exception. |
| 1788 | def test_run_call_order__error_in_tearDown(self): |
| 1789 | events = [] |
| 1790 | result = LoggingResult(events) |
| 1791 | |
| 1792 | def setUp(): |
| 1793 | events.append('setUp') |
| 1794 | |
| 1795 | def test(): |
| 1796 | events.append('test') |
| 1797 | |
| 1798 | def tearDown(): |
| 1799 | events.append('tearDown') |
| 1800 | raise RuntimeError('raised by tearDown') |
| 1801 | |
| 1802 | expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError', |
| 1803 | 'stopTest'] |
| 1804 | unittest.FunctionTestCase(test, setUp, tearDown).run(result) |
| 1805 | self.assertEqual(events, expected) |
| 1806 | |
| 1807 | # "Return a string identifying the specific test case." |
| 1808 | # |
| 1809 | # Because of the vague nature of the docs, I'm not going to lock this |
| 1810 | # test down too much. Really all that can be asserted is that the id() |
| 1811 | # will be a string (either 8-byte or unicode -- again, because the docs |
| 1812 | # just say "string") |
| 1813 | def test_id(self): |
| 1814 | test = unittest.FunctionTestCase(lambda: None) |
| 1815 | |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 1816 | self.assertIsInstance(test.id(), str) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1817 | |
| 1818 | # "Returns a one-line description of the test, or None if no description |
| 1819 | # has been provided. The default implementation of this method returns |
| 1820 | # the first line of the test method's docstring, if available, or None." |
| 1821 | def test_shortDescription__no_docstring(self): |
| 1822 | test = unittest.FunctionTestCase(lambda: None) |
| 1823 | |
| 1824 | self.assertEqual(test.shortDescription(), None) |
| 1825 | |
| 1826 | # "Returns a one-line description of the test, or None if no description |
| 1827 | # has been provided. The default implementation of this method returns |
| 1828 | # the first line of the test method's docstring, if available, or None." |
| 1829 | def test_shortDescription__singleline_docstring(self): |
| 1830 | desc = "this tests foo" |
| 1831 | test = unittest.FunctionTestCase(lambda: None, description=desc) |
| 1832 | |
| 1833 | self.assertEqual(test.shortDescription(), "this tests foo") |
| 1834 | |
| 1835 | class Test_TestResult(TestCase): |
| 1836 | # Note: there are not separate tests for TestResult.wasSuccessful(), |
| 1837 | # TestResult.errors, TestResult.failures, TestResult.testsRun or |
| 1838 | # TestResult.shouldStop because these only have meaning in terms of |
| 1839 | # other TestResult methods. |
| 1840 | # |
| 1841 | # Accordingly, tests for the aforenamed attributes are incorporated |
| 1842 | # in with the tests for the defining methods. |
| 1843 | ################################################################ |
| 1844 | |
| 1845 | def test_init(self): |
| 1846 | result = unittest.TestResult() |
| 1847 | |
Benjamin Peterson | e1759f8 | 2009-06-30 23:35:19 +0000 | [diff] [blame] | 1848 | self.assertTrue(result.wasSuccessful()) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1849 | self.assertEqual(len(result.errors), 0) |
| 1850 | self.assertEqual(len(result.failures), 0) |
| 1851 | self.assertEqual(result.testsRun, 0) |
| 1852 | self.assertEqual(result.shouldStop, False) |
| 1853 | |
| 1854 | # "This method can be called to signal that the set of tests being |
| 1855 | # run should be aborted by setting the TestResult's shouldStop |
| 1856 | # attribute to True." |
| 1857 | def test_stop(self): |
| 1858 | result = unittest.TestResult() |
| 1859 | |
| 1860 | result.stop() |
| 1861 | |
| 1862 | self.assertEqual(result.shouldStop, True) |
| 1863 | |
| 1864 | # "Called when the test case test is about to be run. The default |
| 1865 | # implementation simply increments the instance's testsRun counter." |
| 1866 | def test_startTest(self): |
| 1867 | class Foo(unittest.TestCase): |
| 1868 | def test_1(self): |
| 1869 | pass |
| 1870 | |
| 1871 | test = Foo('test_1') |
| 1872 | |
| 1873 | result = unittest.TestResult() |
| 1874 | |
| 1875 | result.startTest(test) |
| 1876 | |
Benjamin Peterson | e1759f8 | 2009-06-30 23:35:19 +0000 | [diff] [blame] | 1877 | self.assertTrue(result.wasSuccessful()) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1878 | self.assertEqual(len(result.errors), 0) |
| 1879 | self.assertEqual(len(result.failures), 0) |
| 1880 | self.assertEqual(result.testsRun, 1) |
| 1881 | self.assertEqual(result.shouldStop, False) |
| 1882 | |
| 1883 | result.stopTest(test) |
| 1884 | |
| 1885 | # "Called after the test case test has been executed, regardless of |
| 1886 | # the outcome. The default implementation does nothing." |
| 1887 | def test_stopTest(self): |
| 1888 | class Foo(unittest.TestCase): |
| 1889 | def test_1(self): |
| 1890 | pass |
| 1891 | |
| 1892 | test = Foo('test_1') |
| 1893 | |
| 1894 | result = unittest.TestResult() |
| 1895 | |
| 1896 | result.startTest(test) |
| 1897 | |
Benjamin Peterson | e1759f8 | 2009-06-30 23:35:19 +0000 | [diff] [blame] | 1898 | self.assertTrue(result.wasSuccessful()) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1899 | self.assertEqual(len(result.errors), 0) |
| 1900 | self.assertEqual(len(result.failures), 0) |
| 1901 | self.assertEqual(result.testsRun, 1) |
| 1902 | self.assertEqual(result.shouldStop, False) |
| 1903 | |
| 1904 | result.stopTest(test) |
| 1905 | |
| 1906 | # Same tests as above; make sure nothing has changed |
Benjamin Peterson | e1759f8 | 2009-06-30 23:35:19 +0000 | [diff] [blame] | 1907 | self.assertTrue(result.wasSuccessful()) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1908 | self.assertEqual(len(result.errors), 0) |
| 1909 | self.assertEqual(len(result.failures), 0) |
| 1910 | self.assertEqual(result.testsRun, 1) |
| 1911 | self.assertEqual(result.shouldStop, False) |
| 1912 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1913 | # "Called before and after tests are run. The default implementation does nothing." |
| 1914 | def test_startTestRun_stopTestRun(self): |
| 1915 | result = unittest.TestResult() |
| 1916 | result.startTestRun() |
| 1917 | result.stopTestRun() |
| 1918 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1919 | # "addSuccess(test)" |
| 1920 | # ... |
| 1921 | # "Called when the test case test succeeds" |
| 1922 | # ... |
| 1923 | # "wasSuccessful() - Returns True if all tests run so far have passed, |
| 1924 | # otherwise returns False" |
| 1925 | # ... |
| 1926 | # "testsRun - The total number of tests run so far." |
| 1927 | # ... |
| 1928 | # "errors - A list containing 2-tuples of TestCase instances and |
| 1929 | # formatted tracebacks. Each tuple represents a test which raised an |
| 1930 | # unexpected exception. Contains formatted |
| 1931 | # tracebacks instead of sys.exc_info() results." |
| 1932 | # ... |
| 1933 | # "failures - A list containing 2-tuples of TestCase instances and |
| 1934 | # formatted tracebacks. Each tuple represents a test where a failure was |
| 1935 | # explicitly signalled using the TestCase.fail*() or TestCase.assert*() |
| 1936 | # methods. Contains formatted tracebacks instead |
| 1937 | # of sys.exc_info() results." |
| 1938 | def test_addSuccess(self): |
| 1939 | class Foo(unittest.TestCase): |
| 1940 | def test_1(self): |
| 1941 | pass |
| 1942 | |
| 1943 | test = Foo('test_1') |
| 1944 | |
| 1945 | result = unittest.TestResult() |
| 1946 | |
| 1947 | result.startTest(test) |
| 1948 | result.addSuccess(test) |
| 1949 | result.stopTest(test) |
| 1950 | |
Benjamin Peterson | e1759f8 | 2009-06-30 23:35:19 +0000 | [diff] [blame] | 1951 | self.assertTrue(result.wasSuccessful()) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1952 | self.assertEqual(len(result.errors), 0) |
| 1953 | self.assertEqual(len(result.failures), 0) |
| 1954 | self.assertEqual(result.testsRun, 1) |
| 1955 | self.assertEqual(result.shouldStop, False) |
| 1956 | |
| 1957 | # "addFailure(test, err)" |
| 1958 | # ... |
| 1959 | # "Called when the test case test signals a failure. err is a tuple of |
| 1960 | # the form returned by sys.exc_info(): (type, value, traceback)" |
| 1961 | # ... |
| 1962 | # "wasSuccessful() - Returns True if all tests run so far have passed, |
| 1963 | # otherwise returns False" |
| 1964 | # ... |
| 1965 | # "testsRun - The total number of tests run so far." |
| 1966 | # ... |
| 1967 | # "errors - A list containing 2-tuples of TestCase instances and |
| 1968 | # formatted tracebacks. Each tuple represents a test which raised an |
| 1969 | # unexpected exception. Contains formatted |
| 1970 | # tracebacks instead of sys.exc_info() results." |
| 1971 | # ... |
| 1972 | # "failures - A list containing 2-tuples of TestCase instances and |
| 1973 | # formatted tracebacks. Each tuple represents a test where a failure was |
| 1974 | # explicitly signalled using the TestCase.fail*() or TestCase.assert*() |
| 1975 | # methods. Contains formatted tracebacks instead |
| 1976 | # of sys.exc_info() results." |
| 1977 | def test_addFailure(self): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1978 | class Foo(unittest.TestCase): |
| 1979 | def test_1(self): |
| 1980 | pass |
| 1981 | |
| 1982 | test = Foo('test_1') |
| 1983 | try: |
| 1984 | test.fail("foo") |
| 1985 | except: |
| 1986 | exc_info_tuple = sys.exc_info() |
| 1987 | |
| 1988 | result = unittest.TestResult() |
| 1989 | |
| 1990 | result.startTest(test) |
| 1991 | result.addFailure(test, exc_info_tuple) |
| 1992 | result.stopTest(test) |
| 1993 | |
Benjamin Peterson | e1759f8 | 2009-06-30 23:35:19 +0000 | [diff] [blame] | 1994 | self.assertFalse(result.wasSuccessful()) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1995 | self.assertEqual(len(result.errors), 0) |
| 1996 | self.assertEqual(len(result.failures), 1) |
| 1997 | self.assertEqual(result.testsRun, 1) |
| 1998 | self.assertEqual(result.shouldStop, False) |
| 1999 | |
| 2000 | test_case, formatted_exc = result.failures[0] |
Benjamin Peterson | e1759f8 | 2009-06-30 23:35:19 +0000 | [diff] [blame] | 2001 | self.assertTrue(test_case is test) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 2002 | self.assertIsInstance(formatted_exc, str) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2003 | |
| 2004 | # "addError(test, err)" |
| 2005 | # ... |
| 2006 | # "Called when the test case test raises an unexpected exception err |
| 2007 | # is a tuple of the form returned by sys.exc_info(): |
| 2008 | # (type, value, traceback)" |
| 2009 | # ... |
| 2010 | # "wasSuccessful() - Returns True if all tests run so far have passed, |
| 2011 | # otherwise returns False" |
| 2012 | # ... |
| 2013 | # "testsRun - The total number of tests run so far." |
| 2014 | # ... |
| 2015 | # "errors - A list containing 2-tuples of TestCase instances and |
| 2016 | # formatted tracebacks. Each tuple represents a test which raised an |
| 2017 | # unexpected exception. Contains formatted |
| 2018 | # tracebacks instead of sys.exc_info() results." |
| 2019 | # ... |
| 2020 | # "failures - A list containing 2-tuples of TestCase instances and |
| 2021 | # formatted tracebacks. Each tuple represents a test where a failure was |
| 2022 | # explicitly signalled using the TestCase.fail*() or TestCase.assert*() |
| 2023 | # methods. Contains formatted tracebacks instead |
| 2024 | # of sys.exc_info() results." |
| 2025 | def test_addError(self): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2026 | class Foo(unittest.TestCase): |
| 2027 | def test_1(self): |
| 2028 | pass |
| 2029 | |
| 2030 | test = Foo('test_1') |
| 2031 | try: |
| 2032 | raise TypeError() |
| 2033 | except: |
| 2034 | exc_info_tuple = sys.exc_info() |
| 2035 | |
| 2036 | result = unittest.TestResult() |
| 2037 | |
| 2038 | result.startTest(test) |
| 2039 | result.addError(test, exc_info_tuple) |
| 2040 | result.stopTest(test) |
| 2041 | |
Benjamin Peterson | e1759f8 | 2009-06-30 23:35:19 +0000 | [diff] [blame] | 2042 | self.assertFalse(result.wasSuccessful()) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2043 | self.assertEqual(len(result.errors), 1) |
| 2044 | self.assertEqual(len(result.failures), 0) |
| 2045 | self.assertEqual(result.testsRun, 1) |
| 2046 | self.assertEqual(result.shouldStop, False) |
| 2047 | |
| 2048 | test_case, formatted_exc = result.errors[0] |
Benjamin Peterson | e1759f8 | 2009-06-30 23:35:19 +0000 | [diff] [blame] | 2049 | self.assertTrue(test_case is test) |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 2050 | self.assertIsInstance(formatted_exc, str) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2051 | |
Michael Foord | 34c9462 | 2010-02-10 15:51:42 +0000 | [diff] [blame] | 2052 | def testGetDescriptionWithoutDocstring(self): |
Michael Foord | 0b581e5 | 2010-02-10 15:53:19 +0000 | [diff] [blame] | 2053 | result = unittest.TextTestResult(None, True, 1) |
Michael Foord | 34c9462 | 2010-02-10 15:51:42 +0000 | [diff] [blame] | 2054 | self.assertEqual( |
| 2055 | result.getDescription(self), |
| 2056 | 'testGetDescriptionWithoutDocstring (' + __name__ + |
| 2057 | '.Test_TestResult)') |
| 2058 | |
R. David Murray | 378c0cf | 2010-02-24 01:46:21 +0000 | [diff] [blame] | 2059 | @unittest.skipIf(sys.flags.optimize >= 2, |
| 2060 | "Docstrings are omitted with -O2 and above") |
Michael Foord | 34c9462 | 2010-02-10 15:51:42 +0000 | [diff] [blame] | 2061 | def testGetDescriptionWithOneLineDocstring(self): |
| 2062 | """Tests getDescription() for a method with a docstring.""" |
Michael Foord | 0b581e5 | 2010-02-10 15:53:19 +0000 | [diff] [blame] | 2063 | result = unittest.TextTestResult(None, True, 1) |
Michael Foord | 34c9462 | 2010-02-10 15:51:42 +0000 | [diff] [blame] | 2064 | self.assertEqual( |
| 2065 | result.getDescription(self), |
| 2066 | ('testGetDescriptionWithOneLineDocstring ' |
| 2067 | '(' + __name__ + '.Test_TestResult)\n' |
| 2068 | 'Tests getDescription() for a method with a docstring.')) |
| 2069 | |
R. David Murray | 378c0cf | 2010-02-24 01:46:21 +0000 | [diff] [blame] | 2070 | @unittest.skipIf(sys.flags.optimize >= 2, |
| 2071 | "Docstrings are omitted with -O2 and above") |
Michael Foord | 34c9462 | 2010-02-10 15:51:42 +0000 | [diff] [blame] | 2072 | def testGetDescriptionWithMultiLineDocstring(self): |
| 2073 | """Tests getDescription() for a method with a longer docstring. |
| 2074 | The second line of the docstring. |
| 2075 | """ |
Michael Foord | 0b581e5 | 2010-02-10 15:53:19 +0000 | [diff] [blame] | 2076 | result = unittest.TextTestResult(None, True, 1) |
Michael Foord | 34c9462 | 2010-02-10 15:51:42 +0000 | [diff] [blame] | 2077 | self.assertEqual( |
| 2078 | result.getDescription(self), |
| 2079 | ('testGetDescriptionWithMultiLineDocstring ' |
| 2080 | '(' + __name__ + '.Test_TestResult)\n' |
| 2081 | 'Tests getDescription() for a method with a longer ' |
| 2082 | 'docstring.')) |
| 2083 | |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame^] | 2084 | classDict = dict(unittest.TestResult.__dict__) |
| 2085 | for m in ('addSkip', 'addExpectedFailure', 'addUnexpectedSuccess', |
| 2086 | '__init__'): |
| 2087 | del classDict[m] |
| 2088 | |
| 2089 | def __init__(self, stream=None, descriptions=None, verbosity=None): |
| 2090 | self.failures = [] |
| 2091 | self.errors = [] |
| 2092 | self.testsRun = 0 |
| 2093 | self.shouldStop = False |
| 2094 | classDict['__init__'] = __init__ |
| 2095 | OldResult = type('OldResult', (object,), classDict) |
| 2096 | |
| 2097 | class Test_OldTestResult(unittest.TestCase): |
| 2098 | |
| 2099 | def assertOldResultWarning(self, test, failures): |
| 2100 | with warnings.catch_warnings(record=True) as log: |
| 2101 | result = OldResult() |
| 2102 | test.run(result) |
| 2103 | self.assertEqual(len(result.failures), failures) |
| 2104 | warning, = log |
| 2105 | self.assertIs(warning.category, RuntimeWarning) |
| 2106 | |
| 2107 | def testOldTestResult(self): |
| 2108 | class Test(unittest.TestCase): |
| 2109 | def testSkip(self): |
| 2110 | self.skipTest('foobar') |
| 2111 | @unittest.expectedFailure |
| 2112 | def testExpectedFail(self): |
| 2113 | raise TypeError |
| 2114 | @unittest.expectedFailure |
| 2115 | def testUnexpectedSuccess(self): |
| 2116 | pass |
| 2117 | |
| 2118 | for test_name, should_pass in (('testSkip', True), |
| 2119 | ('testExpectedFail', True), |
| 2120 | ('testUnexpectedSuccess', False)): |
| 2121 | test = Test(test_name) |
| 2122 | self.assertOldResultWarning(test, int(not should_pass)) |
| 2123 | |
| 2124 | def testOldTestTesultSetup(self): |
| 2125 | class Test(unittest.TestCase): |
| 2126 | def setUp(self): |
| 2127 | self.skipTest('no reason') |
| 2128 | def testFoo(self): |
| 2129 | pass |
| 2130 | self.assertOldResultWarning(Test('testFoo'), 0) |
| 2131 | |
| 2132 | def testOldTestResultClass(self): |
| 2133 | @unittest.skip('no reason') |
| 2134 | class Test(unittest.TestCase): |
| 2135 | def testFoo(self): |
| 2136 | pass |
| 2137 | self.assertOldResultWarning(Test('testFoo'), 0) |
| 2138 | |
| 2139 | def testOldResultWithRunner(self): |
| 2140 | class Test(unittest.TestCase): |
| 2141 | def testFoo(self): |
| 2142 | pass |
| 2143 | runner = unittest.TextTestRunner(resultclass=OldResult, |
| 2144 | stream=io.StringIO()) |
| 2145 | # This will raise an exception if TextTestRunner can't handle old |
| 2146 | # test result objects |
| 2147 | runner.run(Test('testFoo')) |
Michael Foord | 34c9462 | 2010-02-10 15:51:42 +0000 | [diff] [blame] | 2148 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2149 | ### Support code for Test_TestCase |
| 2150 | ################################################################ |
| 2151 | |
| 2152 | class Foo(unittest.TestCase): |
| 2153 | def runTest(self): pass |
| 2154 | def test1(self): pass |
| 2155 | |
| 2156 | class Bar(Foo): |
| 2157 | def test2(self): pass |
| 2158 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 2159 | class LoggingTestCase(unittest.TestCase): |
| 2160 | """A test case which logs its calls.""" |
| 2161 | |
| 2162 | def __init__(self, events): |
| 2163 | super(LoggingTestCase, self).__init__('test') |
| 2164 | self.events = events |
| 2165 | |
| 2166 | def setUp(self): |
| 2167 | self.events.append('setUp') |
| 2168 | |
| 2169 | def test(self): |
| 2170 | self.events.append('test') |
| 2171 | |
| 2172 | def tearDown(self): |
| 2173 | self.events.append('tearDown') |
| 2174 | |
| 2175 | class ResultWithNoStartTestRunStopTestRun(object): |
| 2176 | """An object honouring TestResult before startTestRun/stopTestRun.""" |
| 2177 | |
| 2178 | def __init__(self): |
| 2179 | self.failures = [] |
| 2180 | self.errors = [] |
| 2181 | self.testsRun = 0 |
| 2182 | self.skipped = [] |
| 2183 | self.expectedFailures = [] |
| 2184 | self.unexpectedSuccesses = [] |
| 2185 | self.shouldStop = False |
| 2186 | |
| 2187 | def startTest(self, test): |
| 2188 | pass |
| 2189 | |
| 2190 | def stopTest(self, test): |
| 2191 | pass |
| 2192 | |
| 2193 | def addError(self, test): |
| 2194 | pass |
| 2195 | |
| 2196 | def addFailure(self, test): |
| 2197 | pass |
| 2198 | |
| 2199 | def addSuccess(self, test): |
| 2200 | pass |
| 2201 | |
| 2202 | def wasSuccessful(self): |
| 2203 | return True |
| 2204 | |
| 2205 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2206 | ################################################################ |
| 2207 | ### /Support code for Test_TestCase |
| 2208 | |
| 2209 | class Test_TestCase(TestCase, TestEquality, TestHashing): |
| 2210 | |
| 2211 | ### Set up attributes used by inherited tests |
| 2212 | ################################################################ |
| 2213 | |
| 2214 | # Used by TestHashing.test_hash and TestEquality.test_eq |
| 2215 | eq_pairs = [(Foo('test1'), Foo('test1'))] |
| 2216 | |
| 2217 | # Used by TestEquality.test_ne |
| 2218 | ne_pairs = [(Foo('test1'), Foo('runTest')) |
| 2219 | ,(Foo('test1'), Bar('test1')) |
| 2220 | ,(Foo('test1'), Bar('test2'))] |
| 2221 | |
| 2222 | ################################################################ |
| 2223 | ### /Set up attributes used by inherited tests |
| 2224 | |
| 2225 | |
| 2226 | # "class TestCase([methodName])" |
| 2227 | # ... |
| 2228 | # "Each instance of TestCase will run a single test method: the |
| 2229 | # method named methodName." |
| 2230 | # ... |
| 2231 | # "methodName defaults to "runTest"." |
| 2232 | # |
| 2233 | # Make sure it really is optional, and that it defaults to the proper |
| 2234 | # thing. |
| 2235 | def test_init__no_test_name(self): |
| 2236 | class Test(unittest.TestCase): |
| 2237 | def runTest(self): raise MyException() |
| 2238 | def test(self): pass |
| 2239 | |
| 2240 | self.assertEqual(Test().id()[-13:], '.Test.runTest') |
| 2241 | |
| 2242 | # "class TestCase([methodName])" |
| 2243 | # ... |
| 2244 | # "Each instance of TestCase will run a single test method: the |
| 2245 | # method named methodName." |
| 2246 | def test_init__test_name__valid(self): |
| 2247 | class Test(unittest.TestCase): |
| 2248 | def runTest(self): raise MyException() |
| 2249 | def test(self): pass |
| 2250 | |
| 2251 | self.assertEqual(Test('test').id()[-10:], '.Test.test') |
| 2252 | |
| 2253 | # "class TestCase([methodName])" |
| 2254 | # ... |
| 2255 | # "Each instance of TestCase will run a single test method: the |
| 2256 | # method named methodName." |
| 2257 | def test_init__test_name__invalid(self): |
| 2258 | class Test(unittest.TestCase): |
| 2259 | def runTest(self): raise MyException() |
| 2260 | def test(self): pass |
| 2261 | |
| 2262 | try: |
| 2263 | Test('testfoo') |
| 2264 | except ValueError: |
| 2265 | pass |
| 2266 | else: |
| 2267 | self.fail("Failed to raise ValueError") |
| 2268 | |
| 2269 | # "Return the number of tests represented by the this test object. For |
| 2270 | # TestCase instances, this will always be 1" |
| 2271 | def test_countTestCases(self): |
| 2272 | class Foo(unittest.TestCase): |
| 2273 | def test(self): pass |
| 2274 | |
| 2275 | self.assertEqual(Foo('test').countTestCases(), 1) |
| 2276 | |
| 2277 | # "Return the default type of test result object to be used to run this |
| 2278 | # test. For TestCase instances, this will always be |
| 2279 | # unittest.TestResult; subclasses of TestCase should |
| 2280 | # override this as necessary." |
| 2281 | def test_defaultTestResult(self): |
| 2282 | class Foo(unittest.TestCase): |
| 2283 | def runTest(self): |
| 2284 | pass |
| 2285 | |
| 2286 | result = Foo().defaultTestResult() |
| 2287 | self.assertEqual(type(result), unittest.TestResult) |
| 2288 | |
| 2289 | # "When a setUp() method is defined, the test runner will run that method |
| 2290 | # prior to each test. Likewise, if a tearDown() method is defined, the |
| 2291 | # test runner will invoke that method after each test. In the example, |
| 2292 | # setUp() was used to create a fresh sequence for each test." |
| 2293 | # |
| 2294 | # Make sure the proper call order is maintained, even if setUp() raises |
| 2295 | # an exception. |
| 2296 | def test_run_call_order__error_in_setUp(self): |
| 2297 | events = [] |
| 2298 | result = LoggingResult(events) |
| 2299 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 2300 | class Foo(LoggingTestCase): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2301 | def setUp(self): |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 2302 | super(Foo, self).setUp() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2303 | raise RuntimeError('raised by Foo.setUp') |
| 2304 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 2305 | Foo(events).run(result) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2306 | expected = ['startTest', 'setUp', 'addError', 'stopTest'] |
| 2307 | self.assertEqual(events, expected) |
| 2308 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 2309 | # "With a temporary result stopTestRun is called when setUp errors. |
| 2310 | def test_run_call_order__error_in_setUp_default_result(self): |
| 2311 | events = [] |
| 2312 | |
| 2313 | class Foo(LoggingTestCase): |
| 2314 | def defaultTestResult(self): |
| 2315 | return LoggingResult(self.events) |
| 2316 | |
| 2317 | def setUp(self): |
| 2318 | super(Foo, self).setUp() |
| 2319 | raise RuntimeError('raised by Foo.setUp') |
| 2320 | |
| 2321 | Foo(events).run() |
| 2322 | expected = ['startTestRun', 'startTest', 'setUp', 'addError', |
| 2323 | 'stopTest', 'stopTestRun'] |
| 2324 | self.assertEqual(events, expected) |
| 2325 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2326 | # "When a setUp() method is defined, the test runner will run that method |
| 2327 | # prior to each test. Likewise, if a tearDown() method is defined, the |
| 2328 | # test runner will invoke that method after each test. In the example, |
| 2329 | # setUp() was used to create a fresh sequence for each test." |
| 2330 | # |
| 2331 | # Make sure the proper call order is maintained, even if the test raises |
| 2332 | # an error (as opposed to a failure). |
| 2333 | def test_run_call_order__error_in_test(self): |
| 2334 | events = [] |
| 2335 | result = LoggingResult(events) |
| 2336 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 2337 | class Foo(LoggingTestCase): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2338 | def test(self): |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 2339 | super(Foo, self).test() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2340 | raise RuntimeError('raised by Foo.test') |
| 2341 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2342 | expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown', |
| 2343 | 'stopTest'] |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 2344 | Foo(events).run(result) |
| 2345 | self.assertEqual(events, expected) |
| 2346 | |
| 2347 | # "With a default result, an error in the test still results in stopTestRun |
| 2348 | # being called." |
| 2349 | def test_run_call_order__error_in_test_default_result(self): |
| 2350 | events = [] |
| 2351 | |
| 2352 | class Foo(LoggingTestCase): |
| 2353 | def defaultTestResult(self): |
| 2354 | return LoggingResult(self.events) |
| 2355 | |
| 2356 | def test(self): |
| 2357 | super(Foo, self).test() |
| 2358 | raise RuntimeError('raised by Foo.test') |
| 2359 | |
| 2360 | expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError', |
| 2361 | 'tearDown', 'stopTest', 'stopTestRun'] |
| 2362 | Foo(events).run() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2363 | self.assertEqual(events, expected) |
| 2364 | |
| 2365 | # "When a setUp() method is defined, the test runner will run that method |
| 2366 | # prior to each test. Likewise, if a tearDown() method is defined, the |
| 2367 | # test runner will invoke that method after each test. In the example, |
| 2368 | # setUp() was used to create a fresh sequence for each test." |
| 2369 | # |
| 2370 | # Make sure the proper call order is maintained, even if the test signals |
| 2371 | # a failure (as opposed to an error). |
| 2372 | def test_run_call_order__failure_in_test(self): |
| 2373 | events = [] |
| 2374 | result = LoggingResult(events) |
| 2375 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 2376 | class Foo(LoggingTestCase): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2377 | def test(self): |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 2378 | super(Foo, self).test() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2379 | self.fail('raised by Foo.test') |
| 2380 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2381 | expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown', |
| 2382 | 'stopTest'] |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 2383 | Foo(events).run(result) |
| 2384 | self.assertEqual(events, expected) |
| 2385 | |
| 2386 | # "When a test fails with a default result stopTestRun is still called." |
| 2387 | def test_run_call_order__failure_in_test_default_result(self): |
| 2388 | |
| 2389 | class Foo(LoggingTestCase): |
| 2390 | def defaultTestResult(self): |
| 2391 | return LoggingResult(self.events) |
| 2392 | def test(self): |
| 2393 | super(Foo, self).test() |
| 2394 | self.fail('raised by Foo.test') |
| 2395 | |
| 2396 | expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure', |
| 2397 | 'tearDown', 'stopTest', 'stopTestRun'] |
| 2398 | events = [] |
| 2399 | Foo(events).run() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2400 | self.assertEqual(events, expected) |
| 2401 | |
| 2402 | # "When a setUp() method is defined, the test runner will run that method |
| 2403 | # prior to each test. Likewise, if a tearDown() method is defined, the |
| 2404 | # test runner will invoke that method after each test. In the example, |
| 2405 | # setUp() was used to create a fresh sequence for each test." |
| 2406 | # |
| 2407 | # Make sure the proper call order is maintained, even if tearDown() raises |
| 2408 | # an exception. |
| 2409 | def test_run_call_order__error_in_tearDown(self): |
| 2410 | events = [] |
| 2411 | result = LoggingResult(events) |
| 2412 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 2413 | class Foo(LoggingTestCase): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2414 | def tearDown(self): |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 2415 | super(Foo, self).tearDown() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2416 | raise RuntimeError('raised by Foo.tearDown') |
| 2417 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 2418 | Foo(events).run(result) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2419 | expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError', |
| 2420 | 'stopTest'] |
| 2421 | self.assertEqual(events, expected) |
| 2422 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 2423 | # "When tearDown errors with a default result stopTestRun is still called." |
| 2424 | def test_run_call_order__error_in_tearDown_default_result(self): |
| 2425 | |
| 2426 | class Foo(LoggingTestCase): |
| 2427 | def defaultTestResult(self): |
| 2428 | return LoggingResult(self.events) |
| 2429 | def tearDown(self): |
| 2430 | super(Foo, self).tearDown() |
| 2431 | raise RuntimeError('raised by Foo.tearDown') |
| 2432 | |
| 2433 | events = [] |
| 2434 | Foo(events).run() |
| 2435 | expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown', |
| 2436 | 'addError', 'stopTest', 'stopTestRun'] |
| 2437 | self.assertEqual(events, expected) |
| 2438 | |
| 2439 | # "TestCase.run() still works when the defaultTestResult is a TestResult |
| 2440 | # that does not support startTestRun and stopTestRun. |
| 2441 | def test_run_call_order_default_result(self): |
| 2442 | |
| 2443 | class Foo(unittest.TestCase): |
| 2444 | def defaultTestResult(self): |
| 2445 | return ResultWithNoStartTestRunStopTestRun() |
| 2446 | def test(self): |
| 2447 | pass |
| 2448 | |
| 2449 | Foo('test').run() |
| 2450 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2451 | # "This class attribute gives the exception raised by the test() method. |
| 2452 | # If a test framework needs to use a specialized exception, possibly to |
| 2453 | # carry additional information, it must subclass this exception in |
| 2454 | # order to ``play fair'' with the framework. The initial value of this |
| 2455 | # attribute is AssertionError" |
| 2456 | def test_failureException__default(self): |
| 2457 | class Foo(unittest.TestCase): |
| 2458 | def test(self): |
| 2459 | pass |
| 2460 | |
Benjamin Peterson | e1759f8 | 2009-06-30 23:35:19 +0000 | [diff] [blame] | 2461 | self.assertTrue(Foo('test').failureException is AssertionError) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2462 | |
| 2463 | # "This class attribute gives the exception raised by the test() method. |
| 2464 | # If a test framework needs to use a specialized exception, possibly to |
| 2465 | # carry additional information, it must subclass this exception in |
| 2466 | # order to ``play fair'' with the framework." |
| 2467 | # |
| 2468 | # Make sure TestCase.run() respects the designated failureException |
| 2469 | def test_failureException__subclassing__explicit_raise(self): |
| 2470 | events = [] |
| 2471 | result = LoggingResult(events) |
| 2472 | |
| 2473 | class Foo(unittest.TestCase): |
| 2474 | def test(self): |
| 2475 | raise RuntimeError() |
| 2476 | |
| 2477 | failureException = RuntimeError |
| 2478 | |
Benjamin Peterson | e1759f8 | 2009-06-30 23:35:19 +0000 | [diff] [blame] | 2479 | self.assertTrue(Foo('test').failureException is RuntimeError) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2480 | |
| 2481 | |
| 2482 | Foo('test').run(result) |
| 2483 | expected = ['startTest', 'addFailure', 'stopTest'] |
| 2484 | self.assertEqual(events, expected) |
| 2485 | |
| 2486 | # "This class attribute gives the exception raised by the test() method. |
| 2487 | # If a test framework needs to use a specialized exception, possibly to |
| 2488 | # carry additional information, it must subclass this exception in |
| 2489 | # order to ``play fair'' with the framework." |
| 2490 | # |
| 2491 | # Make sure TestCase.run() respects the designated failureException |
| 2492 | def test_failureException__subclassing__implicit_raise(self): |
| 2493 | events = [] |
| 2494 | result = LoggingResult(events) |
| 2495 | |
| 2496 | class Foo(unittest.TestCase): |
| 2497 | def test(self): |
| 2498 | self.fail("foo") |
| 2499 | |
| 2500 | failureException = RuntimeError |
| 2501 | |
Benjamin Peterson | e1759f8 | 2009-06-30 23:35:19 +0000 | [diff] [blame] | 2502 | self.assertTrue(Foo('test').failureException is RuntimeError) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2503 | |
| 2504 | |
| 2505 | Foo('test').run(result) |
| 2506 | expected = ['startTest', 'addFailure', 'stopTest'] |
| 2507 | self.assertEqual(events, expected) |
| 2508 | |
| 2509 | # "The default implementation does nothing." |
| 2510 | def test_setUp(self): |
| 2511 | class Foo(unittest.TestCase): |
| 2512 | def runTest(self): |
| 2513 | pass |
| 2514 | |
| 2515 | # ... and nothing should happen |
| 2516 | Foo().setUp() |
| 2517 | |
| 2518 | # "The default implementation does nothing." |
| 2519 | def test_tearDown(self): |
| 2520 | class Foo(unittest.TestCase): |
| 2521 | def runTest(self): |
| 2522 | pass |
| 2523 | |
| 2524 | # ... and nothing should happen |
| 2525 | Foo().tearDown() |
| 2526 | |
| 2527 | # "Return a string identifying the specific test case." |
| 2528 | # |
| 2529 | # Because of the vague nature of the docs, I'm not going to lock this |
| 2530 | # test down too much. Really all that can be asserted is that the id() |
| 2531 | # will be a string (either 8-byte or unicode -- again, because the docs |
| 2532 | # just say "string") |
| 2533 | def test_id(self): |
| 2534 | class Foo(unittest.TestCase): |
| 2535 | def runTest(self): |
| 2536 | pass |
| 2537 | |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 2538 | self.assertIsInstance(Foo().id(), str) |
| 2539 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2540 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2541 | # "If result is omitted or None, a temporary result object is created |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 2542 | # and used, but is not made available to the caller. As TestCase owns the |
| 2543 | # temporary result startTestRun and stopTestRun are called. |
| 2544 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2545 | def test_run__uses_defaultTestResult(self): |
| 2546 | events = [] |
| 2547 | |
| 2548 | class Foo(unittest.TestCase): |
| 2549 | def test(self): |
| 2550 | events.append('test') |
| 2551 | |
| 2552 | def defaultTestResult(self): |
| 2553 | return LoggingResult(events) |
| 2554 | |
| 2555 | # Make run() find a result object on its own |
| 2556 | Foo('test').run() |
| 2557 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 2558 | expected = ['startTestRun', 'startTest', 'test', 'addSuccess', |
| 2559 | 'stopTest', 'stopTestRun'] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2560 | self.assertEqual(events, expected) |
Jim Fulton | fafd874 | 2004-08-28 15:22:12 +0000 | [diff] [blame] | 2561 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2562 | def testShortDescriptionWithoutDocstring(self): |
Michael Foord | 34c9462 | 2010-02-10 15:51:42 +0000 | [diff] [blame] | 2563 | self.assertIsNone(self.shortDescription()) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2564 | |
R. David Murray | 378c0cf | 2010-02-24 01:46:21 +0000 | [diff] [blame] | 2565 | @unittest.skipIf(sys.flags.optimize >= 2, |
| 2566 | "Docstrings are omitted with -O2 and above") |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2567 | def testShortDescriptionWithOneLineDocstring(self): |
| 2568 | """Tests shortDescription() for a method with a docstring.""" |
| 2569 | self.assertEqual( |
| 2570 | self.shortDescription(), |
Michael Foord | 34c9462 | 2010-02-10 15:51:42 +0000 | [diff] [blame] | 2571 | 'Tests shortDescription() for a method with a docstring.') |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2572 | |
R. David Murray | 378c0cf | 2010-02-24 01:46:21 +0000 | [diff] [blame] | 2573 | @unittest.skipIf(sys.flags.optimize >= 2, |
| 2574 | "Docstrings are omitted with -O2 and above") |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2575 | def testShortDescriptionWithMultiLineDocstring(self): |
| 2576 | """Tests shortDescription() for a method with a longer docstring. |
| 2577 | |
| 2578 | This method ensures that only the first line of a docstring is |
| 2579 | returned used in the short description, no matter how long the |
| 2580 | whole thing is. |
| 2581 | """ |
| 2582 | self.assertEqual( |
| 2583 | self.shortDescription(), |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2584 | 'Tests shortDescription() for a method with a longer ' |
Michael Foord | 34c9462 | 2010-02-10 15:51:42 +0000 | [diff] [blame] | 2585 | 'docstring.') |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2586 | |
| 2587 | def testAddTypeEqualityFunc(self): |
| 2588 | class SadSnake(object): |
| 2589 | """Dummy class for test_addTypeEqualityFunc.""" |
| 2590 | s1, s2 = SadSnake(), SadSnake() |
| 2591 | self.assertFalse(s1 == s2) |
| 2592 | def AllSnakesCreatedEqual(a, b, msg=None): |
| 2593 | return type(a) == type(b) == SadSnake |
| 2594 | self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual) |
| 2595 | self.assertEqual(s1, s2) |
| 2596 | # No this doesn't clean up and remove the SadSnake equality func |
| 2597 | # from this TestCase instance but since its a local nothing else |
| 2598 | # will ever notice that. |
| 2599 | |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 2600 | def testAssertIs(self): |
| 2601 | thing = object() |
| 2602 | self.assertIs(thing, thing) |
| 2603 | self.assertRaises(self.failureException, self.assertIs, thing, object()) |
| 2604 | |
| 2605 | def testAssertIsNot(self): |
| 2606 | thing = object() |
| 2607 | self.assertIsNot(thing, object()) |
| 2608 | self.assertRaises(self.failureException, self.assertIsNot, thing, thing) |
| 2609 | |
Benjamin Peterson | 6e8c757 | 2009-10-04 20:19:21 +0000 | [diff] [blame] | 2610 | def testAssertIsInstance(self): |
| 2611 | thing = [] |
| 2612 | self.assertIsInstance(thing, list) |
| 2613 | self.assertRaises(self.failureException, self.assertIsInstance, |
| 2614 | thing, dict) |
| 2615 | |
| 2616 | def testAssertNotIsInstance(self): |
| 2617 | thing = [] |
| 2618 | self.assertNotIsInstance(thing, dict) |
| 2619 | self.assertRaises(self.failureException, self.assertNotIsInstance, |
| 2620 | thing, list) |
| 2621 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2622 | def testAssertIn(self): |
| 2623 | animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'} |
| 2624 | |
| 2625 | self.assertIn('a', 'abc') |
| 2626 | self.assertIn(2, [1, 2, 3]) |
| 2627 | self.assertIn('monkey', animals) |
| 2628 | |
| 2629 | self.assertNotIn('d', 'abc') |
| 2630 | self.assertNotIn(0, [1, 2, 3]) |
| 2631 | self.assertNotIn('otter', animals) |
| 2632 | |
| 2633 | self.assertRaises(self.failureException, self.assertIn, 'x', 'abc') |
| 2634 | self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3]) |
| 2635 | self.assertRaises(self.failureException, self.assertIn, 'elephant', |
| 2636 | animals) |
| 2637 | |
| 2638 | self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc') |
| 2639 | self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3]) |
| 2640 | self.assertRaises(self.failureException, self.assertNotIn, 'cow', |
| 2641 | animals) |
| 2642 | |
| 2643 | def testAssertDictContainsSubset(self): |
| 2644 | self.assertDictContainsSubset({}, {}) |
| 2645 | self.assertDictContainsSubset({}, {'a': 1}) |
| 2646 | self.assertDictContainsSubset({'a': 1}, {'a': 1}) |
| 2647 | self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2}) |
| 2648 | self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2}) |
| 2649 | |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame^] | 2650 | with self.assertRaises(self.failureException): |
| 2651 | self.assertDictContainsSubset({1: "one"}, {}) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2652 | |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame^] | 2653 | with self.assertRaises(self.failureException): |
| 2654 | self.assertDictContainsSubset({'a': 2}, {'a': 1}) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2655 | |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame^] | 2656 | with self.assertRaises(self.failureException): |
| 2657 | self.assertDictContainsSubset({'c': 1}, {'a': 1}) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2658 | |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame^] | 2659 | with self.assertRaises(self.failureException): |
| 2660 | self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1}) |
| 2661 | |
| 2662 | with self.assertRaises(self.failureException): |
| 2663 | self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1}) |
| 2664 | |
| 2665 | with warnings.catch_warnings(record=True): |
| 2666 | # silence the UnicodeWarning |
| 2667 | one = ''.join(chr(i) for i in range(255)) |
| 2668 | # this used to cause a UnicodeDecodeError constructing the failure msg |
| 2669 | with self.assertRaises(self.failureException): |
| 2670 | self.assertDictContainsSubset({'foo': one}, {'foo': '\uFFFD'}) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2671 | |
| 2672 | def testAssertEqual(self): |
| 2673 | equal_pairs = [ |
| 2674 | ((), ()), |
| 2675 | ({}, {}), |
| 2676 | ([], []), |
| 2677 | (set(), set()), |
| 2678 | (frozenset(), frozenset())] |
| 2679 | for a, b in equal_pairs: |
| 2680 | # This mess of try excepts is to test the assertEqual behavior |
| 2681 | # itself. |
| 2682 | try: |
| 2683 | self.assertEqual(a, b) |
| 2684 | except self.failureException: |
| 2685 | self.fail('assertEqual(%r, %r) failed' % (a, b)) |
| 2686 | try: |
| 2687 | self.assertEqual(a, b, msg='foo') |
| 2688 | except self.failureException: |
| 2689 | self.fail('assertEqual(%r, %r) with msg= failed' % (a, b)) |
| 2690 | try: |
| 2691 | self.assertEqual(a, b, 'foo') |
| 2692 | except self.failureException: |
| 2693 | self.fail('assertEqual(%r, %r) with third parameter failed' % |
| 2694 | (a, b)) |
| 2695 | |
| 2696 | unequal_pairs = [ |
| 2697 | ((), []), |
| 2698 | ({}, set()), |
| 2699 | (set([4,1]), frozenset([4,2])), |
| 2700 | (frozenset([4,5]), set([2,3])), |
| 2701 | (set([3,4]), set([5,4]))] |
| 2702 | for a, b in unequal_pairs: |
| 2703 | self.assertRaises(self.failureException, self.assertEqual, a, b) |
| 2704 | self.assertRaises(self.failureException, self.assertEqual, a, b, |
| 2705 | 'foo') |
| 2706 | self.assertRaises(self.failureException, self.assertEqual, a, b, |
| 2707 | msg='foo') |
| 2708 | |
| 2709 | def testEquality(self): |
| 2710 | self.assertListEqual([], []) |
| 2711 | self.assertTupleEqual((), ()) |
| 2712 | self.assertSequenceEqual([], ()) |
| 2713 | |
| 2714 | a = [0, 'a', []] |
| 2715 | b = [] |
| 2716 | self.assertRaises(unittest.TestCase.failureException, |
| 2717 | self.assertListEqual, a, b) |
| 2718 | self.assertRaises(unittest.TestCase.failureException, |
| 2719 | self.assertListEqual, tuple(a), tuple(b)) |
| 2720 | self.assertRaises(unittest.TestCase.failureException, |
| 2721 | self.assertSequenceEqual, a, tuple(b)) |
| 2722 | |
| 2723 | b.extend(a) |
| 2724 | self.assertListEqual(a, b) |
| 2725 | self.assertTupleEqual(tuple(a), tuple(b)) |
| 2726 | self.assertSequenceEqual(a, tuple(b)) |
| 2727 | self.assertSequenceEqual(tuple(a), b) |
| 2728 | |
| 2729 | self.assertRaises(self.failureException, self.assertListEqual, |
| 2730 | a, tuple(b)) |
| 2731 | self.assertRaises(self.failureException, self.assertTupleEqual, |
| 2732 | tuple(a), b) |
| 2733 | self.assertRaises(self.failureException, self.assertListEqual, None, b) |
| 2734 | self.assertRaises(self.failureException, self.assertTupleEqual, None, |
| 2735 | tuple(b)) |
| 2736 | self.assertRaises(self.failureException, self.assertSequenceEqual, |
| 2737 | None, tuple(b)) |
| 2738 | self.assertRaises(self.failureException, self.assertListEqual, 1, 1) |
| 2739 | self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1) |
| 2740 | self.assertRaises(self.failureException, self.assertSequenceEqual, |
| 2741 | 1, 1) |
| 2742 | |
| 2743 | self.assertDictEqual({}, {}) |
| 2744 | |
| 2745 | c = { 'x': 1 } |
| 2746 | d = {} |
| 2747 | self.assertRaises(unittest.TestCase.failureException, |
| 2748 | self.assertDictEqual, c, d) |
| 2749 | |
| 2750 | d.update(c) |
| 2751 | self.assertDictEqual(c, d) |
| 2752 | |
| 2753 | d['x'] = 0 |
| 2754 | self.assertRaises(unittest.TestCase.failureException, |
| 2755 | self.assertDictEqual, c, d, 'These are unequal') |
| 2756 | |
| 2757 | self.assertRaises(self.failureException, self.assertDictEqual, None, d) |
| 2758 | self.assertRaises(self.failureException, self.assertDictEqual, [], d) |
| 2759 | self.assertRaises(self.failureException, self.assertDictEqual, 1, 1) |
| 2760 | |
| 2761 | self.assertSameElements([1, 2, 3], [3, 2, 1]) |
| 2762 | self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3]) |
| 2763 | self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo']) |
| 2764 | self.assertRaises(self.failureException, self.assertSameElements, |
| 2765 | [10], [10, 11]) |
| 2766 | self.assertRaises(self.failureException, self.assertSameElements, |
| 2767 | [10, 11], [10]) |
| 2768 | |
| 2769 | # Test that sequences of unhashable objects can be tested for sameness: |
| 2770 | self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]]) |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 2771 | |
Benjamin Peterson | 3bb6b7a | 2009-04-04 16:46:24 +0000 | [diff] [blame] | 2772 | self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}]) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2773 | self.assertRaises(self.failureException, self.assertSameElements, |
| 2774 | [[1]], [[2]]) |
Michael Foord | a5809c8 | 2009-04-04 18:55:09 +0000 | [diff] [blame] | 2775 | self.assertRaises(self.failureException, self.assertSameElements, |
| 2776 | [{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 2}]) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2777 | |
| 2778 | def testAssertSetEqual(self): |
| 2779 | set1 = set() |
| 2780 | set2 = set() |
| 2781 | self.assertSetEqual(set1, set2) |
| 2782 | |
| 2783 | self.assertRaises(self.failureException, self.assertSetEqual, None, set2) |
| 2784 | self.assertRaises(self.failureException, self.assertSetEqual, [], set2) |
| 2785 | self.assertRaises(self.failureException, self.assertSetEqual, set1, None) |
| 2786 | self.assertRaises(self.failureException, self.assertSetEqual, set1, []) |
| 2787 | |
| 2788 | set1 = set(['a']) |
| 2789 | set2 = set() |
| 2790 | self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) |
| 2791 | |
| 2792 | set1 = set(['a']) |
| 2793 | set2 = set(['a']) |
| 2794 | self.assertSetEqual(set1, set2) |
| 2795 | |
| 2796 | set1 = set(['a']) |
| 2797 | set2 = set(['a', 'b']) |
| 2798 | self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) |
| 2799 | |
| 2800 | set1 = set(['a']) |
| 2801 | set2 = frozenset(['a', 'b']) |
| 2802 | self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) |
| 2803 | |
| 2804 | set1 = set(['a', 'b']) |
| 2805 | set2 = frozenset(['a', 'b']) |
| 2806 | self.assertSetEqual(set1, set2) |
| 2807 | |
| 2808 | set1 = set() |
| 2809 | set2 = "foo" |
| 2810 | self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) |
| 2811 | self.assertRaises(self.failureException, self.assertSetEqual, set2, set1) |
| 2812 | |
| 2813 | # make sure any string formatting is tuple-safe |
| 2814 | set1 = set([(0, 1), (2, 3)]) |
| 2815 | set2 = set([(4, 5)]) |
| 2816 | self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) |
| 2817 | |
| 2818 | def testInequality(self): |
| 2819 | # Try ints |
| 2820 | self.assertGreater(2, 1) |
| 2821 | self.assertGreaterEqual(2, 1) |
| 2822 | self.assertGreaterEqual(1, 1) |
| 2823 | self.assertLess(1, 2) |
| 2824 | self.assertLessEqual(1, 2) |
| 2825 | self.assertLessEqual(1, 1) |
| 2826 | self.assertRaises(self.failureException, self.assertGreater, 1, 2) |
| 2827 | self.assertRaises(self.failureException, self.assertGreater, 1, 1) |
| 2828 | self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2) |
| 2829 | self.assertRaises(self.failureException, self.assertLess, 2, 1) |
| 2830 | self.assertRaises(self.failureException, self.assertLess, 1, 1) |
| 2831 | self.assertRaises(self.failureException, self.assertLessEqual, 2, 1) |
| 2832 | |
| 2833 | # Try Floats |
| 2834 | self.assertGreater(1.1, 1.0) |
| 2835 | self.assertGreaterEqual(1.1, 1.0) |
| 2836 | self.assertGreaterEqual(1.0, 1.0) |
| 2837 | self.assertLess(1.0, 1.1) |
| 2838 | self.assertLessEqual(1.0, 1.1) |
| 2839 | self.assertLessEqual(1.0, 1.0) |
| 2840 | self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1) |
| 2841 | self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0) |
| 2842 | self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1) |
| 2843 | self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0) |
| 2844 | self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0) |
| 2845 | self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0) |
| 2846 | |
| 2847 | # Try Strings |
| 2848 | self.assertGreater('bug', 'ant') |
| 2849 | self.assertGreaterEqual('bug', 'ant') |
| 2850 | self.assertGreaterEqual('ant', 'ant') |
| 2851 | self.assertLess('ant', 'bug') |
| 2852 | self.assertLessEqual('ant', 'bug') |
| 2853 | self.assertLessEqual('ant', 'ant') |
| 2854 | self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug') |
| 2855 | self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant') |
| 2856 | self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug') |
| 2857 | self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant') |
| 2858 | self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant') |
| 2859 | self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant') |
| 2860 | |
| 2861 | # Try bytes |
| 2862 | self.assertGreater(b'bug', b'ant') |
| 2863 | self.assertGreaterEqual(b'bug', b'ant') |
| 2864 | self.assertGreaterEqual(b'ant', b'ant') |
| 2865 | self.assertLess(b'ant', b'bug') |
| 2866 | self.assertLessEqual(b'ant', b'bug') |
| 2867 | self.assertLessEqual(b'ant', b'ant') |
| 2868 | self.assertRaises(self.failureException, self.assertGreater, b'ant', b'bug') |
| 2869 | self.assertRaises(self.failureException, self.assertGreater, b'ant', b'ant') |
| 2870 | self.assertRaises(self.failureException, self.assertGreaterEqual, b'ant', |
| 2871 | b'bug') |
| 2872 | self.assertRaises(self.failureException, self.assertLess, b'bug', b'ant') |
| 2873 | self.assertRaises(self.failureException, self.assertLess, b'ant', b'ant') |
| 2874 | self.assertRaises(self.failureException, self.assertLessEqual, b'bug', b'ant') |
| 2875 | |
| 2876 | def testAssertMultiLineEqual(self): |
| 2877 | sample_text = """\ |
| 2878 | http://www.python.org/doc/2.3/lib/module-unittest.html |
| 2879 | test case |
| 2880 | A test case is the smallest unit of testing. [...] |
| 2881 | """ |
| 2882 | revised_sample_text = """\ |
| 2883 | http://www.python.org/doc/2.4.1/lib/module-unittest.html |
| 2884 | test case |
| 2885 | A test case is the smallest unit of testing. [...] You may provide your |
| 2886 | own implementation that does not subclass from TestCase, of course. |
| 2887 | """ |
| 2888 | sample_text_error = """ |
| 2889 | - http://www.python.org/doc/2.3/lib/module-unittest.html |
| 2890 | ? ^ |
| 2891 | + http://www.python.org/doc/2.4.1/lib/module-unittest.html |
| 2892 | ? ^^^ |
| 2893 | test case |
| 2894 | - A test case is the smallest unit of testing. [...] |
| 2895 | + A test case is the smallest unit of testing. [...] You may provide your |
| 2896 | ? +++++++++++++++++++++ |
| 2897 | + own implementation that does not subclass from TestCase, of course. |
| 2898 | """ |
| 2899 | |
| 2900 | try: |
| 2901 | self.assertMultiLineEqual(sample_text, revised_sample_text) |
| 2902 | except self.failureException as e: |
Michael Foord | 0283495 | 2010-02-08 23:10:39 +0000 | [diff] [blame] | 2903 | # no fair testing ourself with ourself, and assertEqual is used for strings |
| 2904 | # so can't use assertEqual either. Just use assertTrue. |
| 2905 | self.assertTrue(sample_text_error == str(e)) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2906 | |
| 2907 | def testAssertIsNone(self): |
| 2908 | self.assertIsNone(None) |
| 2909 | self.assertRaises(self.failureException, self.assertIsNone, False) |
| 2910 | self.assertIsNotNone('DjZoPloGears on Rails') |
| 2911 | self.assertRaises(self.failureException, self.assertIsNotNone, None) |
| 2912 | |
| 2913 | def testAssertRegexpMatches(self): |
| 2914 | self.assertRegexpMatches('asdfabasdf', r'ab+') |
| 2915 | self.assertRaises(self.failureException, self.assertRegexpMatches, |
| 2916 | 'saaas', r'aaaa') |
| 2917 | |
| 2918 | def testAssertRaisesRegexp(self): |
| 2919 | class ExceptionMock(Exception): |
| 2920 | pass |
| 2921 | |
| 2922 | def Stub(): |
| 2923 | raise ExceptionMock('We expect') |
| 2924 | |
| 2925 | self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub) |
| 2926 | self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub) |
| 2927 | |
| 2928 | def testAssertNotRaisesRegexp(self): |
| 2929 | self.assertRaisesRegexp( |
Benjamin Peterson | 4f75b64 | 2009-04-04 16:39:09 +0000 | [diff] [blame] | 2930 | self.failureException, '^Exception not raised by <lambda>$', |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2931 | self.assertRaisesRegexp, Exception, re.compile('x'), |
| 2932 | lambda: None) |
| 2933 | self.assertRaisesRegexp( |
Benjamin Peterson | 4f75b64 | 2009-04-04 16:39:09 +0000 | [diff] [blame] | 2934 | self.failureException, '^Exception not raised by <lambda>$', |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2935 | self.assertRaisesRegexp, Exception, 'x', |
| 2936 | lambda: None) |
| 2937 | |
| 2938 | def testAssertRaisesRegexpMismatch(self): |
| 2939 | def Stub(): |
| 2940 | raise Exception('Unexpected') |
| 2941 | |
| 2942 | self.assertRaisesRegexp( |
| 2943 | self.failureException, |
| 2944 | r'"\^Expected\$" does not match "Unexpected"', |
| 2945 | self.assertRaisesRegexp, Exception, '^Expected$', |
| 2946 | Stub) |
| 2947 | self.assertRaisesRegexp( |
| 2948 | self.failureException, |
| 2949 | r'"\^Expected\$" does not match "Unexpected"', |
| 2950 | self.assertRaisesRegexp, Exception, |
| 2951 | re.compile('^Expected$'), Stub) |
| 2952 | |
Kristján Valur Jónsson | 92a653a | 2009-11-13 16:10:13 +0000 | [diff] [blame] | 2953 | def testAssertRaisesExcValue(self): |
| 2954 | class ExceptionMock(Exception): |
| 2955 | pass |
| 2956 | |
| 2957 | def Stub(foo): |
| 2958 | raise ExceptionMock(foo) |
| 2959 | v = "particular value" |
| 2960 | |
| 2961 | ctx = self.assertRaises(ExceptionMock) |
| 2962 | with ctx: |
| 2963 | Stub(v) |
Ezio Melotti | 4900823 | 2010-02-08 21:57:48 +0000 | [diff] [blame] | 2964 | e = ctx.exception |
Ezio Melotti | e961593 | 2010-01-24 19:26:24 +0000 | [diff] [blame] | 2965 | self.assertIsInstance(e, ExceptionMock) |
Kristján Valur Jónsson | 92a653a | 2009-11-13 16:10:13 +0000 | [diff] [blame] | 2966 | self.assertEqual(e.args[0], v) |
| 2967 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2968 | def testSynonymAssertMethodNames(self): |
| 2969 | """Test undocumented method name synonyms. |
| 2970 | |
| 2971 | Please do not use these methods names in your own code. |
| 2972 | |
| 2973 | This test confirms their continued existence and functionality |
| 2974 | in order to avoid breaking existing code. |
| 2975 | """ |
| 2976 | self.assertNotEquals(3, 5) |
| 2977 | self.assertEquals(3, 3) |
| 2978 | self.assertAlmostEquals(2.0, 2.0) |
| 2979 | self.assertNotAlmostEquals(3.0, 5.0) |
| 2980 | self.assert_(True) |
| 2981 | |
| 2982 | def testPendingDeprecationMethodNames(self): |
| 2983 | """Test fail* methods pending deprecation, they will warn in 3.2. |
| 2984 | |
| 2985 | Do not use these methods. They will go away in 3.3. |
| 2986 | """ |
Benjamin Peterson | 6bcbad5 | 2009-06-30 23:45:41 +0000 | [diff] [blame] | 2987 | old = ( |
| 2988 | (self.failIfEqual, (3, 5)), |
| 2989 | (self.failUnlessEqual, (3, 3)), |
| 2990 | (self.failUnlessAlmostEqual, (2.0, 2.0)), |
| 2991 | (self.failIfAlmostEqual, (3.0, 5.0)), |
| 2992 | (self.failUnless, (True,)), |
| 2993 | (self.failUnlessRaises, (TypeError, lambda _: 3.14 + 'spam')), |
| 2994 | (self.failIf, (False,)) |
| 2995 | ) |
| 2996 | for meth, args in old: |
| 2997 | with warnings.catch_warnings(record=True) as w: |
| 2998 | meth(*args) |
| 2999 | self.assertEqual(len(w), 1) |
| 3000 | self.assertIs(w[0].category, DeprecationWarning) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 3001 | |
| 3002 | def testDeepcopy(self): |
| 3003 | # Issue: 5660 |
| 3004 | class TestableTest(TestCase): |
| 3005 | def testNothing(self): |
| 3006 | pass |
| 3007 | |
| 3008 | test = TestableTest('testNothing') |
| 3009 | |
| 3010 | # This shouldn't blow up |
| 3011 | deepcopy(test) |
| 3012 | |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 3013 | |
| 3014 | class Test_TestSkipping(TestCase): |
| 3015 | |
| 3016 | def test_skipping(self): |
| 3017 | class Foo(unittest.TestCase): |
| 3018 | def test_skip_me(self): |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 3019 | self.skipTest("skip") |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 3020 | events = [] |
| 3021 | result = LoggingResult(events) |
| 3022 | test = Foo("test_skip_me") |
| 3023 | test.run(result) |
| 3024 | self.assertEqual(events, ['startTest', 'addSkip', 'stopTest']) |
| 3025 | self.assertEqual(result.skipped, [(test, "skip")]) |
| 3026 | |
| 3027 | # Try letting setUp skip the test now. |
| 3028 | class Foo(unittest.TestCase): |
| 3029 | def setUp(self): |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 3030 | self.skipTest("testing") |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 3031 | def test_nothing(self): pass |
| 3032 | events = [] |
| 3033 | result = LoggingResult(events) |
| 3034 | test = Foo("test_nothing") |
| 3035 | test.run(result) |
| 3036 | self.assertEqual(events, ['startTest', 'addSkip', 'stopTest']) |
| 3037 | self.assertEqual(result.skipped, [(test, "testing")]) |
| 3038 | self.assertEqual(result.testsRun, 1) |
| 3039 | |
| 3040 | def test_skipping_decorators(self): |
| 3041 | op_table = ((unittest.skipUnless, False, True), |
| 3042 | (unittest.skipIf, True, False)) |
| 3043 | for deco, do_skip, dont_skip in op_table: |
| 3044 | class Foo(unittest.TestCase): |
| 3045 | @deco(do_skip, "testing") |
| 3046 | def test_skip(self): pass |
| 3047 | |
| 3048 | @deco(dont_skip, "testing") |
| 3049 | def test_dont_skip(self): pass |
| 3050 | test_do_skip = Foo("test_skip") |
| 3051 | test_dont_skip = Foo("test_dont_skip") |
Benjamin Peterson | 14a3dd7 | 2009-05-25 00:51:58 +0000 | [diff] [blame] | 3052 | suite = unittest.TestSuite([test_do_skip, test_dont_skip]) |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 3053 | events = [] |
| 3054 | result = LoggingResult(events) |
| 3055 | suite.run(result) |
| 3056 | self.assertEqual(len(result.skipped), 1) |
| 3057 | expected = ['startTest', 'addSkip', 'stopTest', |
| 3058 | 'startTest', 'addSuccess', 'stopTest'] |
| 3059 | self.assertEqual(events, expected) |
| 3060 | self.assertEqual(result.testsRun, 2) |
| 3061 | self.assertEqual(result.skipped, [(test_do_skip, "testing")]) |
| 3062 | self.assertTrue(result.wasSuccessful()) |
| 3063 | |
| 3064 | def test_skip_class(self): |
| 3065 | @unittest.skip("testing") |
| 3066 | class Foo(unittest.TestCase): |
| 3067 | def test_1(self): |
| 3068 | record.append(1) |
| 3069 | record = [] |
| 3070 | result = unittest.TestResult() |
Benjamin Peterson | 14a3dd7 | 2009-05-25 00:51:58 +0000 | [diff] [blame] | 3071 | test = Foo("test_1") |
| 3072 | suite = unittest.TestSuite([test]) |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 3073 | suite.run(result) |
Benjamin Peterson | 14a3dd7 | 2009-05-25 00:51:58 +0000 | [diff] [blame] | 3074 | self.assertEqual(result.skipped, [(test, "testing")]) |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 3075 | self.assertEqual(record, []) |
| 3076 | |
| 3077 | def test_expected_failure(self): |
| 3078 | class Foo(unittest.TestCase): |
| 3079 | @unittest.expectedFailure |
| 3080 | def test_die(self): |
| 3081 | self.fail("help me!") |
| 3082 | events = [] |
| 3083 | result = LoggingResult(events) |
| 3084 | test = Foo("test_die") |
| 3085 | test.run(result) |
| 3086 | self.assertEqual(events, |
| 3087 | ['startTest', 'addExpectedFailure', 'stopTest']) |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 3088 | self.assertEqual(result.expectedFailures[0][0], test) |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 3089 | self.assertTrue(result.wasSuccessful()) |
| 3090 | |
| 3091 | def test_unexpected_success(self): |
| 3092 | class Foo(unittest.TestCase): |
| 3093 | @unittest.expectedFailure |
| 3094 | def test_die(self): |
| 3095 | pass |
| 3096 | events = [] |
| 3097 | result = LoggingResult(events) |
| 3098 | test = Foo("test_die") |
| 3099 | test.run(result) |
| 3100 | self.assertEqual(events, |
| 3101 | ['startTest', 'addUnexpectedSuccess', 'stopTest']) |
| 3102 | self.assertFalse(result.failures) |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 3103 | self.assertEqual(result.unexpectedSuccesses, [test]) |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 3104 | self.assertTrue(result.wasSuccessful()) |
| 3105 | |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame^] | 3106 | def test_skip_doesnt_run_setup(self): |
| 3107 | class Foo(unittest.TestCase): |
| 3108 | wasSetUp = False |
| 3109 | wasTornDown = False |
| 3110 | def setUp(self): |
| 3111 | Foo.wasSetUp = True |
| 3112 | def tornDown(self): |
| 3113 | Foo.wasTornDown = True |
| 3114 | @unittest.skip('testing') |
| 3115 | def test_1(self): |
| 3116 | pass |
| 3117 | |
| 3118 | result = unittest.TestResult() |
| 3119 | test = Foo("test_1") |
| 3120 | suite = unittest.TestSuite([test]) |
| 3121 | suite.run(result) |
| 3122 | self.assertEqual(result.skipped, [(test, "testing")]) |
| 3123 | self.assertFalse(Foo.wasSetUp) |
| 3124 | self.assertFalse(Foo.wasTornDown) |
| 3125 | |
| 3126 | def test_decorated_skip(self): |
| 3127 | def decorator(func): |
| 3128 | def inner(*a): |
| 3129 | return func(*a) |
| 3130 | return inner |
| 3131 | |
| 3132 | class Foo(unittest.TestCase): |
| 3133 | @decorator |
| 3134 | @unittest.skip('testing') |
| 3135 | def test_1(self): |
| 3136 | pass |
| 3137 | |
| 3138 | result = unittest.TestResult() |
| 3139 | test = Foo("test_1") |
| 3140 | suite = unittest.TestSuite([test]) |
| 3141 | suite.run(result) |
| 3142 | self.assertEqual(result.skipped, [(test, "testing")]) |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 3143 | |
| 3144 | |
Jeffrey Yasskin | aaaef11 | 2007-09-07 15:00:39 +0000 | [diff] [blame] | 3145 | class Test_Assertions(TestCase): |
| 3146 | def test_AlmostEqual(self): |
Benjamin Peterson | e1759f8 | 2009-06-30 23:35:19 +0000 | [diff] [blame] | 3147 | self.assertAlmostEqual(1.00000001, 1.0) |
| 3148 | self.assertNotAlmostEqual(1.0000001, 1.0) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 3149 | self.assertRaises(self.failureException, |
Benjamin Peterson | e1759f8 | 2009-06-30 23:35:19 +0000 | [diff] [blame] | 3150 | self.assertAlmostEqual, 1.0000001, 1.0) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 3151 | self.assertRaises(self.failureException, |
Benjamin Peterson | e1759f8 | 2009-06-30 23:35:19 +0000 | [diff] [blame] | 3152 | self.assertNotAlmostEqual, 1.00000001, 1.0) |
Jeffrey Yasskin | aaaef11 | 2007-09-07 15:00:39 +0000 | [diff] [blame] | 3153 | |
Benjamin Peterson | e1759f8 | 2009-06-30 23:35:19 +0000 | [diff] [blame] | 3154 | self.assertAlmostEqual(1.1, 1.0, places=0) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 3155 | self.assertRaises(self.failureException, |
Benjamin Peterson | e1759f8 | 2009-06-30 23:35:19 +0000 | [diff] [blame] | 3156 | self.assertAlmostEqual, 1.1, 1.0, places=1) |
Jeffrey Yasskin | aaaef11 | 2007-09-07 15:00:39 +0000 | [diff] [blame] | 3157 | |
Benjamin Peterson | e1759f8 | 2009-06-30 23:35:19 +0000 | [diff] [blame] | 3158 | self.assertAlmostEqual(0, .1+.1j, places=0) |
| 3159 | self.assertNotAlmostEqual(0, .1+.1j, places=1) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 3160 | self.assertRaises(self.failureException, |
Benjamin Peterson | e1759f8 | 2009-06-30 23:35:19 +0000 | [diff] [blame] | 3161 | self.assertAlmostEqual, 0, .1+.1j, places=1) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 3162 | self.assertRaises(self.failureException, |
Benjamin Peterson | e1759f8 | 2009-06-30 23:35:19 +0000 | [diff] [blame] | 3163 | self.assertNotAlmostEqual, 0, .1+.1j, places=0) |
Jeffrey Yasskin | aaaef11 | 2007-09-07 15:00:39 +0000 | [diff] [blame] | 3164 | |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 3165 | self.assertAlmostEqual(float('inf'), float('inf')) |
| 3166 | self.assertRaises(self.failureException, self.assertNotAlmostEqual, |
| 3167 | float('inf'), float('inf')) |
| 3168 | |
| 3169 | |
Antoine Pitrou | 5acd41e | 2008-12-28 14:29:00 +0000 | [diff] [blame] | 3170 | def test_assertRaises(self): |
| 3171 | def _raise(e): |
| 3172 | raise e |
| 3173 | self.assertRaises(KeyError, _raise, KeyError) |
| 3174 | self.assertRaises(KeyError, _raise, KeyError("key")) |
| 3175 | try: |
| 3176 | self.assertRaises(KeyError, lambda: None) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 3177 | except self.failureException as e: |
Ezio Melotti | b58e0bd | 2010-01-23 15:40:09 +0000 | [diff] [blame] | 3178 | self.assertIn("KeyError not raised", str(e)) |
Antoine Pitrou | 5acd41e | 2008-12-28 14:29:00 +0000 | [diff] [blame] | 3179 | else: |
| 3180 | self.fail("assertRaises() didn't fail") |
| 3181 | try: |
| 3182 | self.assertRaises(KeyError, _raise, ValueError) |
| 3183 | except ValueError: |
| 3184 | pass |
| 3185 | else: |
| 3186 | self.fail("assertRaises() didn't let exception pass through") |
Ezio Melotti | 4900823 | 2010-02-08 21:57:48 +0000 | [diff] [blame] | 3187 | with self.assertRaises(KeyError) as cm: |
| 3188 | try: |
| 3189 | raise KeyError |
| 3190 | except Exception as e: |
| 3191 | exc = e |
| 3192 | raise |
| 3193 | self.assertIs(cm.exception, exc) |
| 3194 | |
Antoine Pitrou | 5acd41e | 2008-12-28 14:29:00 +0000 | [diff] [blame] | 3195 | with self.assertRaises(KeyError): |
| 3196 | raise KeyError("key") |
| 3197 | try: |
| 3198 | with self.assertRaises(KeyError): |
| 3199 | pass |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 3200 | except self.failureException as e: |
Ezio Melotti | b58e0bd | 2010-01-23 15:40:09 +0000 | [diff] [blame] | 3201 | self.assertIn("KeyError not raised", str(e)) |
Antoine Pitrou | 5acd41e | 2008-12-28 14:29:00 +0000 | [diff] [blame] | 3202 | else: |
| 3203 | self.fail("assertRaises() didn't fail") |
| 3204 | try: |
| 3205 | with self.assertRaises(KeyError): |
| 3206 | raise ValueError |
| 3207 | except ValueError: |
| 3208 | pass |
| 3209 | else: |
| 3210 | self.fail("assertRaises() didn't let exception pass through") |
| 3211 | |
| 3212 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 3213 | class TestLongMessage(TestCase): |
| 3214 | """Test that the individual asserts honour longMessage. |
| 3215 | This actually tests all the message behaviour for |
| 3216 | asserts that use longMessage.""" |
| 3217 | |
| 3218 | def setUp(self): |
| 3219 | class TestableTestFalse(TestCase): |
| 3220 | longMessage = False |
| 3221 | failureException = self.failureException |
| 3222 | |
| 3223 | def testTest(self): |
| 3224 | pass |
| 3225 | |
| 3226 | class TestableTestTrue(TestCase): |
| 3227 | longMessage = True |
| 3228 | failureException = self.failureException |
| 3229 | |
| 3230 | def testTest(self): |
| 3231 | pass |
| 3232 | |
| 3233 | self.testableTrue = TestableTestTrue('testTest') |
| 3234 | self.testableFalse = TestableTestFalse('testTest') |
| 3235 | |
| 3236 | def testDefault(self): |
| 3237 | self.assertFalse(TestCase.longMessage) |
| 3238 | |
| 3239 | def test_formatMsg(self): |
| 3240 | self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo") |
| 3241 | self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo") |
| 3242 | |
| 3243 | self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo") |
| 3244 | self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo") |
| 3245 | |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame^] | 3246 | # This blows up if _formatMessage uses string concatenation |
| 3247 | self.testableTrue._formatMessage(object(), 'foo') |
| 3248 | |
| 3249 | def test_formatMessage_unicode_error(self): |
| 3250 | with warnings.catch_warnings(record=True): |
| 3251 | # This causes a UnicodeWarning due to its craziness |
| 3252 | one = ''.join(chr(i) for i in range(255)) |
| 3253 | # this used to cause a UnicodeDecodeError constructing msg |
| 3254 | self.testableTrue._formatMessage(one, '\uFFFD') |
| 3255 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 3256 | def assertMessages(self, methodName, args, errors): |
| 3257 | def getMethod(i): |
| 3258 | useTestableFalse = i < 2 |
| 3259 | if useTestableFalse: |
| 3260 | test = self.testableFalse |
| 3261 | else: |
| 3262 | test = self.testableTrue |
| 3263 | return getattr(test, methodName) |
| 3264 | |
| 3265 | for i, expected_regexp in enumerate(errors): |
| 3266 | testMethod = getMethod(i) |
| 3267 | kwargs = {} |
| 3268 | withMsg = i % 2 |
| 3269 | if withMsg: |
| 3270 | kwargs = {"msg": "oops"} |
| 3271 | |
| 3272 | with self.assertRaisesRegexp(self.failureException, |
| 3273 | expected_regexp=expected_regexp): |
| 3274 | testMethod(*args, **kwargs) |
| 3275 | |
| 3276 | def testAssertTrue(self): |
| 3277 | self.assertMessages('assertTrue', (False,), |
| 3278 | ["^False is not True$", "^oops$", "^False is not True$", |
| 3279 | "^False is not True : oops$"]) |
| 3280 | |
| 3281 | def testAssertFalse(self): |
| 3282 | self.assertMessages('assertFalse', (True,), |
| 3283 | ["^True is not False$", "^oops$", "^True is not False$", |
| 3284 | "^True is not False : oops$"]) |
| 3285 | |
| 3286 | def testNotEqual(self): |
| 3287 | self.assertMessages('assertNotEqual', (1, 1), |
| 3288 | ["^1 == 1$", "^oops$", "^1 == 1$", |
| 3289 | "^1 == 1 : oops$"]) |
| 3290 | |
| 3291 | def testAlmostEqual(self): |
| 3292 | self.assertMessages('assertAlmostEqual', (1, 2), |
| 3293 | ["^1 != 2 within 7 places$", "^oops$", |
| 3294 | "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"]) |
| 3295 | |
| 3296 | def testNotAlmostEqual(self): |
| 3297 | self.assertMessages('assertNotAlmostEqual', (1, 1), |
| 3298 | ["^1 == 1 within 7 places$", "^oops$", |
| 3299 | "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"]) |
| 3300 | |
| 3301 | def test_baseAssertEqual(self): |
| 3302 | self.assertMessages('_baseAssertEqual', (1, 2), |
| 3303 | ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"]) |
| 3304 | |
| 3305 | def testAssertSequenceEqual(self): |
| 3306 | # Error messages are multiline so not testing on full message |
| 3307 | # assertTupleEqual and assertListEqual delegate to this method |
| 3308 | self.assertMessages('assertSequenceEqual', ([], [None]), |
| 3309 | ["\+ \[None\]$", "^oops$", r"\+ \[None\]$", |
| 3310 | r"\+ \[None\] : oops$"]) |
| 3311 | |
| 3312 | def testAssertSetEqual(self): |
| 3313 | self.assertMessages('assertSetEqual', (set(), set([None])), |
| 3314 | ["None$", "^oops$", "None$", |
| 3315 | "None : oops$"]) |
| 3316 | |
| 3317 | def testAssertIn(self): |
| 3318 | self.assertMessages('assertIn', (None, []), |
| 3319 | ['^None not found in \[\]$', "^oops$", |
| 3320 | '^None not found in \[\]$', |
| 3321 | '^None not found in \[\] : oops$']) |
| 3322 | |
| 3323 | def testAssertNotIn(self): |
| 3324 | self.assertMessages('assertNotIn', (None, [None]), |
| 3325 | ['^None unexpectedly found in \[None\]$', "^oops$", |
| 3326 | '^None unexpectedly found in \[None\]$', |
| 3327 | '^None unexpectedly found in \[None\] : oops$']) |
| 3328 | |
| 3329 | def testAssertDictEqual(self): |
| 3330 | self.assertMessages('assertDictEqual', ({}, {'key': 'value'}), |
| 3331 | [r"\+ \{'key': 'value'\}$", "^oops$", |
| 3332 | "\+ \{'key': 'value'\}$", |
| 3333 | "\+ \{'key': 'value'\} : oops$"]) |
| 3334 | |
| 3335 | def testAssertDictContainsSubset(self): |
| 3336 | self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}), |
| 3337 | ["^Missing: 'key'$", "^oops$", |
| 3338 | "^Missing: 'key'$", |
| 3339 | "^Missing: 'key' : oops$"]) |
| 3340 | |
| 3341 | def testAssertSameElements(self): |
| 3342 | self.assertMessages('assertSameElements', ([], [None]), |
| 3343 | [r"\[None\]$", "^oops$", |
| 3344 | r"\[None\]$", |
| 3345 | r"\[None\] : oops$"]) |
| 3346 | |
| 3347 | def testAssertMultiLineEqual(self): |
| 3348 | self.assertMessages('assertMultiLineEqual', ("", "foo"), |
| 3349 | [r"\+ foo$", "^oops$", |
| 3350 | r"\+ foo$", |
| 3351 | r"\+ foo : oops$"]) |
| 3352 | |
| 3353 | def testAssertLess(self): |
| 3354 | self.assertMessages('assertLess', (2, 1), |
| 3355 | ["^2 not less than 1$", "^oops$", |
| 3356 | "^2 not less than 1$", "^2 not less than 1 : oops$"]) |
| 3357 | |
| 3358 | def testAssertLessEqual(self): |
| 3359 | self.assertMessages('assertLessEqual', (2, 1), |
| 3360 | ["^2 not less than or equal to 1$", "^oops$", |
| 3361 | "^2 not less than or equal to 1$", |
| 3362 | "^2 not less than or equal to 1 : oops$"]) |
| 3363 | |
| 3364 | def testAssertGreater(self): |
| 3365 | self.assertMessages('assertGreater', (1, 2), |
| 3366 | ["^1 not greater than 2$", "^oops$", |
| 3367 | "^1 not greater than 2$", |
| 3368 | "^1 not greater than 2 : oops$"]) |
| 3369 | |
| 3370 | def testAssertGreaterEqual(self): |
| 3371 | self.assertMessages('assertGreaterEqual', (1, 2), |
| 3372 | ["^1 not greater than or equal to 2$", "^oops$", |
| 3373 | "^1 not greater than or equal to 2$", |
| 3374 | "^1 not greater than or equal to 2 : oops$"]) |
| 3375 | |
| 3376 | def testAssertIsNone(self): |
| 3377 | self.assertMessages('assertIsNone', ('not None',), |
| 3378 | ["^'not None' is not None$", "^oops$", |
| 3379 | "^'not None' is not None$", |
| 3380 | "^'not None' is not None : oops$"]) |
| 3381 | |
| 3382 | def testAssertIsNotNone(self): |
| 3383 | self.assertMessages('assertIsNotNone', (None,), |
| 3384 | ["^unexpectedly None$", "^oops$", |
| 3385 | "^unexpectedly None$", |
| 3386 | "^unexpectedly None : oops$"]) |
| 3387 | |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 3388 | def testAssertIs(self): |
| 3389 | self.assertMessages('assertIs', (None, 'foo'), |
| 3390 | ["^None is not 'foo'$", "^oops$", |
| 3391 | "^None is not 'foo'$", |
| 3392 | "^None is not 'foo' : oops$"]) |
| 3393 | |
| 3394 | def testAssertIsNot(self): |
| 3395 | self.assertMessages('assertIsNot', (None, None), |
| 3396 | ["^unexpectedly identical: None$", "^oops$", |
| 3397 | "^unexpectedly identical: None$", |
| 3398 | "^unexpectedly identical: None : oops$"]) |
| 3399 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 3400 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 3401 | class TestCleanUp(TestCase): |
| 3402 | |
| 3403 | def testCleanUp(self): |
| 3404 | class TestableTest(TestCase): |
| 3405 | def testNothing(self): |
| 3406 | pass |
| 3407 | |
| 3408 | test = TestableTest('testNothing') |
| 3409 | self.assertEqual(test._cleanups, []) |
| 3410 | |
| 3411 | cleanups = [] |
| 3412 | |
| 3413 | def cleanup1(*args, **kwargs): |
| 3414 | cleanups.append((1, args, kwargs)) |
| 3415 | |
| 3416 | def cleanup2(*args, **kwargs): |
| 3417 | cleanups.append((2, args, kwargs)) |
| 3418 | |
| 3419 | test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye') |
| 3420 | test.addCleanup(cleanup2) |
| 3421 | |
| 3422 | self.assertEqual(test._cleanups, |
| 3423 | [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')), |
| 3424 | (cleanup2, (), {})]) |
| 3425 | |
| 3426 | result = test.doCleanups() |
| 3427 | self.assertTrue(result) |
| 3428 | |
| 3429 | self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))]) |
| 3430 | |
| 3431 | def testCleanUpWithErrors(self): |
| 3432 | class TestableTest(TestCase): |
| 3433 | def testNothing(self): |
| 3434 | pass |
| 3435 | |
| 3436 | class MockResult(object): |
| 3437 | errors = [] |
| 3438 | def addError(self, test, exc_info): |
| 3439 | self.errors.append((test, exc_info)) |
| 3440 | |
| 3441 | result = MockResult() |
| 3442 | test = TestableTest('testNothing') |
Benjamin Peterson | fa0d703 | 2009-06-01 22:42:33 +0000 | [diff] [blame] | 3443 | test._resultForDoCleanups = result |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 3444 | |
| 3445 | exc1 = Exception('foo') |
| 3446 | exc2 = Exception('bar') |
| 3447 | def cleanup1(): |
| 3448 | raise exc1 |
| 3449 | |
| 3450 | def cleanup2(): |
| 3451 | raise exc2 |
| 3452 | |
| 3453 | test.addCleanup(cleanup1) |
| 3454 | test.addCleanup(cleanup2) |
| 3455 | |
| 3456 | self.assertFalse(test.doCleanups()) |
| 3457 | |
| 3458 | (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors) |
| 3459 | self.assertEqual((test1, Type1, instance1), (test, Exception, exc1)) |
| 3460 | self.assertEqual((test2, Type2, instance2), (test, Exception, exc2)) |
| 3461 | |
| 3462 | def testCleanupInRun(self): |
| 3463 | blowUp = False |
| 3464 | ordering = [] |
| 3465 | |
| 3466 | class TestableTest(TestCase): |
| 3467 | def setUp(self): |
| 3468 | ordering.append('setUp') |
| 3469 | if blowUp: |
| 3470 | raise Exception('foo') |
| 3471 | |
| 3472 | def testNothing(self): |
| 3473 | ordering.append('test') |
| 3474 | |
| 3475 | def tearDown(self): |
| 3476 | ordering.append('tearDown') |
| 3477 | |
| 3478 | test = TestableTest('testNothing') |
| 3479 | |
| 3480 | def cleanup1(): |
| 3481 | ordering.append('cleanup1') |
| 3482 | def cleanup2(): |
| 3483 | ordering.append('cleanup2') |
| 3484 | test.addCleanup(cleanup1) |
| 3485 | test.addCleanup(cleanup2) |
| 3486 | |
| 3487 | def success(some_test): |
| 3488 | self.assertEqual(some_test, test) |
| 3489 | ordering.append('success') |
| 3490 | |
| 3491 | result = unittest.TestResult() |
| 3492 | result.addSuccess = success |
| 3493 | |
| 3494 | test.run(result) |
| 3495 | self.assertEqual(ordering, ['setUp', 'test', 'tearDown', |
| 3496 | 'cleanup2', 'cleanup1', 'success']) |
| 3497 | |
| 3498 | blowUp = True |
| 3499 | ordering = [] |
| 3500 | test = TestableTest('testNothing') |
| 3501 | test.addCleanup(cleanup1) |
| 3502 | test.run(result) |
| 3503 | self.assertEqual(ordering, ['setUp', 'cleanup1']) |
| 3504 | |
| 3505 | |
| 3506 | class Test_TestProgram(TestCase): |
| 3507 | |
| 3508 | # Horrible white box test |
| 3509 | def testNoExit(self): |
| 3510 | result = object() |
| 3511 | test = object() |
| 3512 | |
| 3513 | class FakeRunner(object): |
| 3514 | def run(self, test): |
| 3515 | self.test = test |
| 3516 | return result |
| 3517 | |
| 3518 | runner = FakeRunner() |
| 3519 | |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 3520 | oldParseArgs = TestProgram.parseArgs |
| 3521 | def restoreParseArgs(): |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 3522 | TestProgram.parseArgs = oldParseArgs |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 3523 | TestProgram.parseArgs = lambda *args: None |
| 3524 | self.addCleanup(restoreParseArgs) |
| 3525 | |
| 3526 | def removeTest(): |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 3527 | del TestProgram.test |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 3528 | TestProgram.test = test |
| 3529 | self.addCleanup(removeTest) |
| 3530 | |
| 3531 | program = TestProgram(testRunner=runner, exit=False, verbosity=2) |
| 3532 | |
| 3533 | self.assertEqual(program.result, result) |
| 3534 | self.assertEqual(runner.test, test) |
| 3535 | self.assertEqual(program.verbosity, 2) |
| 3536 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 3537 | class FooBar(unittest.TestCase): |
| 3538 | def testPass(self): |
| 3539 | assert True |
| 3540 | def testFail(self): |
| 3541 | assert False |
| 3542 | |
| 3543 | class FooBarLoader(unittest.TestLoader): |
| 3544 | """Test loader that returns a suite containing FooBar.""" |
| 3545 | def loadTestsFromModule(self, module): |
| 3546 | return self.suiteClass( |
| 3547 | [self.loadTestsFromTestCase(Test_TestProgram.FooBar)]) |
| 3548 | |
| 3549 | |
| 3550 | def test_NonExit(self): |
| 3551 | program = unittest.main(exit=False, |
| 3552 | argv=["foobar"], |
| 3553 | testRunner=unittest.TextTestRunner(stream=io.StringIO()), |
| 3554 | testLoader=self.FooBarLoader()) |
| 3555 | self.assertTrue(hasattr(program, 'result')) |
| 3556 | |
| 3557 | |
| 3558 | def test_Exit(self): |
| 3559 | self.assertRaises( |
| 3560 | SystemExit, |
| 3561 | unittest.main, |
| 3562 | argv=["foobar"], |
| 3563 | testRunner=unittest.TextTestRunner(stream=io.StringIO()), |
| 3564 | exit=True, |
| 3565 | testLoader=self.FooBarLoader()) |
| 3566 | |
| 3567 | |
| 3568 | def test_ExitAsDefault(self): |
| 3569 | self.assertRaises( |
| 3570 | SystemExit, |
| 3571 | unittest.main, |
| 3572 | argv=["foobar"], |
| 3573 | testRunner=unittest.TextTestRunner(stream=io.StringIO()), |
| 3574 | testLoader=self.FooBarLoader()) |
| 3575 | |
| 3576 | |
| 3577 | class Test_TextTestRunner(TestCase): |
| 3578 | """Tests for TextTestRunner.""" |
| 3579 | |
| 3580 | def test_works_with_result_without_startTestRun_stopTestRun(self): |
| 3581 | class OldTextResult(ResultWithNoStartTestRunStopTestRun): |
| 3582 | separator2 = '' |
| 3583 | def printErrors(self): |
| 3584 | pass |
| 3585 | |
| 3586 | class Runner(unittest.TextTestRunner): |
| 3587 | def __init__(self): |
| 3588 | super(Runner, self).__init__(io.StringIO()) |
| 3589 | |
| 3590 | def _makeResult(self): |
| 3591 | return OldTextResult() |
| 3592 | |
| 3593 | runner = Runner() |
| 3594 | runner.run(unittest.TestSuite()) |
| 3595 | |
| 3596 | def test_startTestRun_stopTestRun_called(self): |
| 3597 | class LoggingTextResult(LoggingResult): |
| 3598 | separator2 = '' |
| 3599 | def printErrors(self): |
| 3600 | pass |
| 3601 | |
| 3602 | class LoggingRunner(unittest.TextTestRunner): |
| 3603 | def __init__(self, events): |
| 3604 | super(LoggingRunner, self).__init__(io.StringIO()) |
| 3605 | self._events = events |
| 3606 | |
| 3607 | def _makeResult(self): |
| 3608 | return LoggingTextResult(self._events) |
| 3609 | |
| 3610 | events = [] |
| 3611 | runner = LoggingRunner(events) |
| 3612 | runner.run(unittest.TestSuite()) |
| 3613 | expected = ['startTestRun', 'stopTestRun'] |
| 3614 | self.assertEqual(events, expected) |
| 3615 | |
Antoine Pitrou | c63ecee | 2009-11-10 21:34:48 +0000 | [diff] [blame] | 3616 | def test_pickle_unpickle(self): |
| 3617 | # Issue #7197: a TextTestRunner should be (un)pickleable. This is |
| 3618 | # required by test_multiprocessing under Windows (in verbose mode). |
| 3619 | stream = io.StringIO("foo") |
| 3620 | runner = unittest.TextTestRunner(stream) |
| 3621 | for protocol in range(2, pickle.HIGHEST_PROTOCOL + 1): |
| 3622 | s = pickle.dumps(runner, protocol) |
| 3623 | obj = pickle.loads(s) |
| 3624 | # StringIO objects never compare equal, a cheap test instead. |
| 3625 | self.assertEqual(obj.stream.getvalue(), stream.getvalue()) |
| 3626 | |
Michael Foord | 34c9462 | 2010-02-10 15:51:42 +0000 | [diff] [blame] | 3627 | def test_resultclass(self): |
| 3628 | def MockResultClass(*args): |
| 3629 | return args |
| 3630 | STREAM = object() |
| 3631 | DESCRIPTIONS = object() |
| 3632 | VERBOSITY = object() |
| 3633 | runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY, |
| 3634 | resultclass=MockResultClass) |
| 3635 | self.assertEqual(runner.resultclass, MockResultClass) |
| 3636 | |
| 3637 | expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY) |
| 3638 | self.assertEqual(runner._makeResult(), expectedresult) |
| 3639 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 3640 | |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 3641 | class TestDiscovery(TestCase): |
| 3642 | |
| 3643 | # Heavily mocked tests so I can avoid hitting the filesystem |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 3644 | def test_get_name_from_path(self): |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 3645 | loader = unittest.TestLoader() |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 3646 | loader._top_level_dir = '/foo' |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 3647 | name = loader._get_name_from_path('/foo/bar/baz.py') |
| 3648 | self.assertEqual(name, 'bar.baz') |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 3649 | |
| 3650 | if not __debug__: |
| 3651 | # asserts are off |
| 3652 | return |
| 3653 | |
| 3654 | with self.assertRaises(AssertionError): |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 3655 | loader._get_name_from_path('/bar/baz.py') |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 3656 | |
| 3657 | def test_find_tests(self): |
| 3658 | loader = unittest.TestLoader() |
| 3659 | |
| 3660 | original_listdir = os.listdir |
| 3661 | def restore_listdir(): |
| 3662 | os.listdir = original_listdir |
| 3663 | original_isfile = os.path.isfile |
| 3664 | def restore_isfile(): |
| 3665 | os.path.isfile = original_isfile |
| 3666 | original_isdir = os.path.isdir |
| 3667 | def restore_isdir(): |
| 3668 | os.path.isdir = original_isdir |
| 3669 | |
| 3670 | path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir', |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 3671 | 'test.foo', 'test-not-a-module.py', 'another_dir'], |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 3672 | ['test3.py', 'test4.py', ]] |
| 3673 | os.listdir = lambda path: path_lists.pop(0) |
| 3674 | self.addCleanup(restore_listdir) |
| 3675 | |
| 3676 | def isdir(path): |
| 3677 | return path.endswith('dir') |
| 3678 | os.path.isdir = isdir |
| 3679 | self.addCleanup(restore_isdir) |
| 3680 | |
| 3681 | def isfile(path): |
| 3682 | # another_dir is not a package and so shouldn't be recursed into |
| 3683 | return not path.endswith('dir') and not 'another_dir' in path |
| 3684 | os.path.isfile = isfile |
| 3685 | self.addCleanup(restore_isfile) |
| 3686 | |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 3687 | loader._get_module_from_name = lambda path: path + ' module' |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 3688 | loader.loadTestsFromModule = lambda module: module + ' tests' |
| 3689 | |
| 3690 | loader._top_level_dir = '/foo' |
| 3691 | suite = list(loader._find_tests('/foo', 'test*.py')) |
| 3692 | |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 3693 | expected = [name + ' module tests' for name in |
| 3694 | ('test1', 'test2')] |
| 3695 | expected.extend([('test_dir.%s' % name) + ' module tests' for name in |
| 3696 | ('test3', 'test4')]) |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 3697 | self.assertEqual(suite, expected) |
| 3698 | |
| 3699 | def test_find_tests_with_package(self): |
| 3700 | loader = unittest.TestLoader() |
| 3701 | |
| 3702 | original_listdir = os.listdir |
| 3703 | def restore_listdir(): |
| 3704 | os.listdir = original_listdir |
| 3705 | original_isfile = os.path.isfile |
| 3706 | def restore_isfile(): |
| 3707 | os.path.isfile = original_isfile |
| 3708 | original_isdir = os.path.isdir |
| 3709 | def restore_isdir(): |
| 3710 | os.path.isdir = original_isdir |
| 3711 | |
| 3712 | directories = ['a_directory', 'test_directory', 'test_directory2'] |
| 3713 | path_lists = [directories, [], [], []] |
| 3714 | os.listdir = lambda path: path_lists.pop(0) |
| 3715 | self.addCleanup(restore_listdir) |
| 3716 | |
| 3717 | os.path.isdir = lambda path: True |
| 3718 | self.addCleanup(restore_isdir) |
| 3719 | |
| 3720 | os.path.isfile = lambda path: os.path.basename(path) not in directories |
| 3721 | self.addCleanup(restore_isfile) |
| 3722 | |
| 3723 | class Module(object): |
| 3724 | paths = [] |
| 3725 | load_tests_args = [] |
| 3726 | |
| 3727 | def __init__(self, path): |
| 3728 | self.path = path |
| 3729 | self.paths.append(path) |
| 3730 | if os.path.basename(path) == 'test_directory': |
| 3731 | def load_tests(loader, tests, pattern): |
| 3732 | self.load_tests_args.append((loader, tests, pattern)) |
| 3733 | return 'load_tests' |
| 3734 | self.load_tests = load_tests |
| 3735 | |
| 3736 | def __eq__(self, other): |
| 3737 | return self.path == other.path |
| 3738 | |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 3739 | loader._get_module_from_name = lambda name: Module(name) |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 3740 | def loadTestsFromModule(module, use_load_tests): |
| 3741 | if use_load_tests: |
| 3742 | raise self.failureException('use_load_tests should be False for packages') |
| 3743 | return module.path + ' module tests' |
| 3744 | loader.loadTestsFromModule = loadTestsFromModule |
| 3745 | |
| 3746 | loader._top_level_dir = '/foo' |
| 3747 | # this time no '.py' on the pattern so that it can match |
| 3748 | # a test package |
| 3749 | suite = list(loader._find_tests('/foo', 'test*')) |
| 3750 | |
| 3751 | # We should have loaded tests from the test_directory package by calling load_tests |
| 3752 | # and directly from the test_directory2 package |
| 3753 | self.assertEqual(suite, |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 3754 | ['load_tests', 'test_directory2' + ' module tests']) |
| 3755 | self.assertEqual(Module.paths, ['test_directory', 'test_directory2']) |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 3756 | |
| 3757 | # load_tests should have been called once with loader, tests and pattern |
| 3758 | self.assertEqual(Module.load_tests_args, |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 3759 | [(loader, 'test_directory' + ' module tests', 'test*')]) |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 3760 | |
| 3761 | def test_discover(self): |
| 3762 | loader = unittest.TestLoader() |
| 3763 | |
| 3764 | original_isfile = os.path.isfile |
| 3765 | def restore_isfile(): |
| 3766 | os.path.isfile = original_isfile |
| 3767 | |
| 3768 | os.path.isfile = lambda path: False |
| 3769 | self.addCleanup(restore_isfile) |
| 3770 | |
Nick Coghlan | 6ead552 | 2009-10-18 13:19:33 +0000 | [diff] [blame] | 3771 | orig_sys_path = sys.path[:] |
| 3772 | def restore_path(): |
| 3773 | sys.path[:] = orig_sys_path |
| 3774 | self.addCleanup(restore_path) |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 3775 | |
Nick Coghlan | 6ead552 | 2009-10-18 13:19:33 +0000 | [diff] [blame] | 3776 | full_path = os.path.abspath(os.path.normpath('/foo')) |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 3777 | with self.assertRaises(ImportError): |
| 3778 | loader.discover('/foo/bar', top_level_dir='/foo') |
| 3779 | |
| 3780 | self.assertEqual(loader._top_level_dir, full_path) |
| 3781 | self.assertIn(full_path, sys.path) |
| 3782 | |
| 3783 | os.path.isfile = lambda path: True |
| 3784 | _find_tests_args = [] |
| 3785 | def _find_tests(start_dir, pattern): |
| 3786 | _find_tests_args.append((start_dir, pattern)) |
| 3787 | return ['tests'] |
| 3788 | loader._find_tests = _find_tests |
| 3789 | loader.suiteClass = str |
| 3790 | |
| 3791 | suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar') |
| 3792 | |
| 3793 | top_level_dir = os.path.abspath(os.path.normpath('/foo/bar')) |
| 3794 | start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz')) |
| 3795 | self.assertEqual(suite, "['tests']") |
| 3796 | self.assertEqual(loader._top_level_dir, top_level_dir) |
| 3797 | self.assertEqual(_find_tests_args, [(start_dir, 'pattern')]) |
Nick Coghlan | 6ead552 | 2009-10-18 13:19:33 +0000 | [diff] [blame] | 3798 | self.assertIn(top_level_dir, sys.path) |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 3799 | |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 3800 | def test_discover_with_modules_that_fail_to_import(self): |
| 3801 | loader = unittest.TestLoader() |
| 3802 | |
| 3803 | listdir = os.listdir |
| 3804 | os.listdir = lambda _: ['test_this_does_not_exist.py'] |
| 3805 | isfile = os.path.isfile |
| 3806 | os.path.isfile = lambda _: True |
Nick Coghlan | 6ead552 | 2009-10-18 13:19:33 +0000 | [diff] [blame] | 3807 | orig_sys_path = sys.path[:] |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 3808 | def restore(): |
| 3809 | os.path.isfile = isfile |
| 3810 | os.listdir = listdir |
Nick Coghlan | 6ead552 | 2009-10-18 13:19:33 +0000 | [diff] [blame] | 3811 | sys.path[:] = orig_sys_path |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 3812 | self.addCleanup(restore) |
| 3813 | |
| 3814 | suite = loader.discover('.') |
Nick Coghlan | 6ead552 | 2009-10-18 13:19:33 +0000 | [diff] [blame] | 3815 | self.assertIn(os.getcwd(), sys.path) |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 3816 | self.assertEqual(suite.countTestCases(), 1) |
| 3817 | test = list(list(suite)[0])[0] # extract test from suite |
| 3818 | |
| 3819 | with self.assertRaises(ImportError): |
| 3820 | test.test_this_does_not_exist() |
| 3821 | |
Benjamin Peterson | d239775 | 2009-06-27 23:45:02 +0000 | [diff] [blame] | 3822 | def test_command_line_handling_parseArgs(self): |
| 3823 | # Haha - take that uninstantiable class |
| 3824 | program = object.__new__(TestProgram) |
| 3825 | |
| 3826 | args = [] |
| 3827 | def do_discovery(argv): |
| 3828 | args.extend(argv) |
| 3829 | program._do_discovery = do_discovery |
| 3830 | program.parseArgs(['something', 'discover']) |
| 3831 | self.assertEqual(args, []) |
| 3832 | |
| 3833 | program.parseArgs(['something', 'discover', 'foo', 'bar']) |
| 3834 | self.assertEqual(args, ['foo', 'bar']) |
| 3835 | |
| 3836 | def test_command_line_handling_do_discovery_too_many_arguments(self): |
| 3837 | class Stop(Exception): |
| 3838 | pass |
| 3839 | def usageExit(): |
| 3840 | raise Stop |
| 3841 | |
| 3842 | program = object.__new__(TestProgram) |
| 3843 | program.usageExit = usageExit |
| 3844 | |
| 3845 | with self.assertRaises(Stop): |
| 3846 | # too many args |
| 3847 | program._do_discovery(['one', 'two', 'three', 'four']) |
| 3848 | |
| 3849 | |
| 3850 | def test_command_line_handling_do_discovery_calls_loader(self): |
| 3851 | program = object.__new__(TestProgram) |
| 3852 | |
| 3853 | class Loader(object): |
| 3854 | args = [] |
| 3855 | def discover(self, start_dir, pattern, top_level_dir): |
| 3856 | self.args.append((start_dir, pattern, top_level_dir)) |
| 3857 | return 'tests' |
| 3858 | |
| 3859 | program._do_discovery(['-v'], Loader=Loader) |
| 3860 | self.assertEqual(program.verbosity, 2) |
| 3861 | self.assertEqual(program.test, 'tests') |
| 3862 | self.assertEqual(Loader.args, [('.', 'test*.py', None)]) |
| 3863 | |
| 3864 | Loader.args = [] |
| 3865 | program = object.__new__(TestProgram) |
| 3866 | program._do_discovery(['--verbose'], Loader=Loader) |
| 3867 | self.assertEqual(program.test, 'tests') |
| 3868 | self.assertEqual(Loader.args, [('.', 'test*.py', None)]) |
| 3869 | |
| 3870 | Loader.args = [] |
| 3871 | program = object.__new__(TestProgram) |
| 3872 | program._do_discovery([], Loader=Loader) |
| 3873 | self.assertEqual(program.test, 'tests') |
| 3874 | self.assertEqual(Loader.args, [('.', 'test*.py', None)]) |
| 3875 | |
| 3876 | Loader.args = [] |
| 3877 | program = object.__new__(TestProgram) |
| 3878 | program._do_discovery(['fish'], Loader=Loader) |
| 3879 | self.assertEqual(program.test, 'tests') |
| 3880 | self.assertEqual(Loader.args, [('fish', 'test*.py', None)]) |
| 3881 | |
| 3882 | Loader.args = [] |
| 3883 | program = object.__new__(TestProgram) |
| 3884 | program._do_discovery(['fish', 'eggs'], Loader=Loader) |
| 3885 | self.assertEqual(program.test, 'tests') |
| 3886 | self.assertEqual(Loader.args, [('fish', 'eggs', None)]) |
| 3887 | |
| 3888 | Loader.args = [] |
| 3889 | program = object.__new__(TestProgram) |
| 3890 | program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader) |
| 3891 | self.assertEqual(program.test, 'tests') |
| 3892 | self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')]) |
| 3893 | |
| 3894 | Loader.args = [] |
| 3895 | program = object.__new__(TestProgram) |
| 3896 | program._do_discovery(['-s', 'fish'], Loader=Loader) |
| 3897 | self.assertEqual(program.test, 'tests') |
| 3898 | self.assertEqual(Loader.args, [('fish', 'test*.py', None)]) |
| 3899 | |
| 3900 | Loader.args = [] |
| 3901 | program = object.__new__(TestProgram) |
| 3902 | program._do_discovery(['-t', 'fish'], Loader=Loader) |
| 3903 | self.assertEqual(program.test, 'tests') |
| 3904 | self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')]) |
| 3905 | |
| 3906 | Loader.args = [] |
| 3907 | program = object.__new__(TestProgram) |
| 3908 | program._do_discovery(['-p', 'fish'], Loader=Loader) |
| 3909 | self.assertEqual(program.test, 'tests') |
| 3910 | self.assertEqual(Loader.args, [('.', 'fish', None)]) |
| 3911 | |
| 3912 | Loader.args = [] |
| 3913 | program = object.__new__(TestProgram) |
| 3914 | program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader) |
| 3915 | self.assertEqual(program.test, 'tests') |
| 3916 | self.assertEqual(Loader.args, [('fish', 'eggs', None)]) |
| 3917 | self.assertEqual(program.verbosity, 2) |
| 3918 | |
| 3919 | |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame^] | 3920 | class TestSetups(unittest.TestCase): |
| 3921 | |
| 3922 | def getRunner(self): |
| 3923 | return unittest.TextTestRunner(resultclass=resultFactory, |
| 3924 | stream=io.StringIO()) |
| 3925 | def runTests(self, *cases): |
| 3926 | suite = unittest.TestSuite() |
| 3927 | for case in cases: |
| 3928 | tests = unittest.defaultTestLoader.loadTestsFromTestCase(case) |
| 3929 | suite.addTests(tests) |
| 3930 | |
| 3931 | runner = self.getRunner() |
| 3932 | |
| 3933 | # creating a nested suite exposes some potential bugs |
| 3934 | realSuite = unittest.TestSuite() |
| 3935 | realSuite.addTest(suite) |
| 3936 | # adding empty suites to the end exposes potential bugs |
| 3937 | suite.addTest(unittest.TestSuite()) |
| 3938 | realSuite.addTest(unittest.TestSuite()) |
| 3939 | return runner.run(realSuite) |
| 3940 | |
| 3941 | def test_setup_class(self): |
| 3942 | class Test(unittest.TestCase): |
| 3943 | setUpCalled = 0 |
| 3944 | @classmethod |
| 3945 | def setUpClass(cls): |
| 3946 | Test.setUpCalled += 1 |
| 3947 | unittest.TestCase.setUpClass() |
| 3948 | def test_one(self): |
| 3949 | pass |
| 3950 | def test_two(self): |
| 3951 | pass |
| 3952 | |
| 3953 | result = self.runTests(Test) |
| 3954 | |
| 3955 | self.assertEqual(Test.setUpCalled, 1) |
| 3956 | self.assertEqual(result.testsRun, 2) |
| 3957 | self.assertEqual(len(result.errors), 0) |
| 3958 | |
| 3959 | def test_teardown_class(self): |
| 3960 | class Test(unittest.TestCase): |
| 3961 | tearDownCalled = 0 |
| 3962 | @classmethod |
| 3963 | def tearDownClass(cls): |
| 3964 | Test.tearDownCalled += 1 |
| 3965 | unittest.TestCase.tearDownClass() |
| 3966 | def test_one(self): |
| 3967 | pass |
| 3968 | def test_two(self): |
| 3969 | pass |
| 3970 | |
| 3971 | result = self.runTests(Test) |
| 3972 | |
| 3973 | self.assertEqual(Test.tearDownCalled, 1) |
| 3974 | self.assertEqual(result.testsRun, 2) |
| 3975 | self.assertEqual(len(result.errors), 0) |
| 3976 | |
| 3977 | def test_teardown_class_two_classes(self): |
| 3978 | class Test(unittest.TestCase): |
| 3979 | tearDownCalled = 0 |
| 3980 | @classmethod |
| 3981 | def tearDownClass(cls): |
| 3982 | Test.tearDownCalled += 1 |
| 3983 | unittest.TestCase.tearDownClass() |
| 3984 | def test_one(self): |
| 3985 | pass |
| 3986 | def test_two(self): |
| 3987 | pass |
| 3988 | |
| 3989 | class Test2(unittest.TestCase): |
| 3990 | tearDownCalled = 0 |
| 3991 | @classmethod |
| 3992 | def tearDownClass(cls): |
| 3993 | Test2.tearDownCalled += 1 |
| 3994 | unittest.TestCase.tearDownClass() |
| 3995 | def test_one(self): |
| 3996 | pass |
| 3997 | def test_two(self): |
| 3998 | pass |
| 3999 | |
| 4000 | result = self.runTests(Test, Test2) |
| 4001 | |
| 4002 | self.assertEqual(Test.tearDownCalled, 1) |
| 4003 | self.assertEqual(Test2.tearDownCalled, 1) |
| 4004 | self.assertEqual(result.testsRun, 4) |
| 4005 | self.assertEqual(len(result.errors), 0) |
| 4006 | |
| 4007 | def test_error_in_setupclass(self): |
| 4008 | class BrokenTest(unittest.TestCase): |
| 4009 | @classmethod |
| 4010 | def setUpClass(cls): |
| 4011 | raise TypeError('foo') |
| 4012 | def test_one(self): |
| 4013 | pass |
| 4014 | def test_two(self): |
| 4015 | pass |
| 4016 | |
| 4017 | result = self.runTests(BrokenTest) |
| 4018 | |
| 4019 | self.assertEqual(result.testsRun, 0) |
| 4020 | self.assertEqual(len(result.errors), 1) |
| 4021 | error, _ = result.errors[0] |
| 4022 | self.assertEqual(str(error), |
| 4023 | 'classSetUp (%s.BrokenTest)' % __name__) |
| 4024 | |
| 4025 | def test_error_in_teardown_class(self): |
| 4026 | class Test(unittest.TestCase): |
| 4027 | tornDown = 0 |
| 4028 | @classmethod |
| 4029 | def tearDownClass(cls): |
| 4030 | Test.tornDown += 1 |
| 4031 | raise TypeError('foo') |
| 4032 | def test_one(self): |
| 4033 | pass |
| 4034 | def test_two(self): |
| 4035 | pass |
| 4036 | |
| 4037 | class Test2(unittest.TestCase): |
| 4038 | tornDown = 0 |
| 4039 | @classmethod |
| 4040 | def tearDownClass(cls): |
| 4041 | Test2.tornDown += 1 |
| 4042 | raise TypeError('foo') |
| 4043 | def test_one(self): |
| 4044 | pass |
| 4045 | def test_two(self): |
| 4046 | pass |
| 4047 | |
| 4048 | result = self.runTests(Test, Test2) |
| 4049 | self.assertEqual(result.testsRun, 4) |
| 4050 | self.assertEqual(len(result.errors), 2) |
| 4051 | self.assertEqual(Test.tornDown, 1) |
| 4052 | self.assertEqual(Test2.tornDown, 1) |
| 4053 | |
| 4054 | error, _ = result.errors[0] |
| 4055 | self.assertEqual(str(error), |
| 4056 | 'classTearDown (%s.Test)' % __name__) |
| 4057 | |
| 4058 | def test_class_not_torndown_when_setup_fails(self): |
| 4059 | class Test(unittest.TestCase): |
| 4060 | tornDown = False |
| 4061 | @classmethod |
| 4062 | def setUpClass(cls): |
| 4063 | raise TypeError |
| 4064 | @classmethod |
| 4065 | def tearDownClass(cls): |
| 4066 | Test.tornDown = True |
| 4067 | raise TypeError('foo') |
| 4068 | def test_one(self): |
| 4069 | pass |
| 4070 | |
| 4071 | self.runTests(Test) |
| 4072 | self.assertFalse(Test.tornDown) |
| 4073 | |
| 4074 | def test_class_not_setup_or_torndown_when_skipped(self): |
| 4075 | class Test(unittest.TestCase): |
| 4076 | classSetUp = False |
| 4077 | tornDown = False |
| 4078 | @classmethod |
| 4079 | def setUpClass(cls): |
| 4080 | Test.classSetUp = True |
| 4081 | @classmethod |
| 4082 | def tearDownClass(cls): |
| 4083 | Test.tornDown = True |
| 4084 | def test_one(self): |
| 4085 | pass |
| 4086 | |
| 4087 | Test = unittest.skip("hop")(Test) |
| 4088 | self.runTests(Test) |
| 4089 | self.assertFalse(Test.classSetUp) |
| 4090 | self.assertFalse(Test.tornDown) |
| 4091 | |
| 4092 | def test_setup_teardown_order_with_pathological_suite(self): |
| 4093 | results = [] |
| 4094 | |
| 4095 | class Module1(object): |
| 4096 | @staticmethod |
| 4097 | def setUpModule(): |
| 4098 | results.append('Module1.setUpModule') |
| 4099 | @staticmethod |
| 4100 | def tearDownModule(): |
| 4101 | results.append('Module1.tearDownModule') |
| 4102 | |
| 4103 | class Module2(object): |
| 4104 | @staticmethod |
| 4105 | def setUpModule(): |
| 4106 | results.append('Module2.setUpModule') |
| 4107 | @staticmethod |
| 4108 | def tearDownModule(): |
| 4109 | results.append('Module2.tearDownModule') |
| 4110 | |
| 4111 | class Test1(unittest.TestCase): |
| 4112 | @classmethod |
| 4113 | def setUpClass(cls): |
| 4114 | results.append('setup 1') |
| 4115 | @classmethod |
| 4116 | def tearDownClass(cls): |
| 4117 | results.append('teardown 1') |
| 4118 | def testOne(self): |
| 4119 | results.append('Test1.testOne') |
| 4120 | def testTwo(self): |
| 4121 | results.append('Test1.testTwo') |
| 4122 | |
| 4123 | class Test2(unittest.TestCase): |
| 4124 | @classmethod |
| 4125 | def setUpClass(cls): |
| 4126 | results.append('setup 2') |
| 4127 | @classmethod |
| 4128 | def tearDownClass(cls): |
| 4129 | results.append('teardown 2') |
| 4130 | def testOne(self): |
| 4131 | results.append('Test2.testOne') |
| 4132 | def testTwo(self): |
| 4133 | results.append('Test2.testTwo') |
| 4134 | |
| 4135 | class Test3(unittest.TestCase): |
| 4136 | @classmethod |
| 4137 | def setUpClass(cls): |
| 4138 | results.append('setup 3') |
| 4139 | @classmethod |
| 4140 | def tearDownClass(cls): |
| 4141 | results.append('teardown 3') |
| 4142 | def testOne(self): |
| 4143 | results.append('Test3.testOne') |
| 4144 | def testTwo(self): |
| 4145 | results.append('Test3.testTwo') |
| 4146 | |
| 4147 | Test1.__module__ = Test2.__module__ = 'Module' |
| 4148 | Test3.__module__ = 'Module2' |
| 4149 | sys.modules['Module'] = Module1 |
| 4150 | sys.modules['Module2'] = Module2 |
| 4151 | |
| 4152 | first = unittest.TestSuite((Test1('testOne'),)) |
| 4153 | second = unittest.TestSuite((Test1('testTwo'),)) |
| 4154 | third = unittest.TestSuite((Test2('testOne'),)) |
| 4155 | fourth = unittest.TestSuite((Test2('testTwo'),)) |
| 4156 | fifth = unittest.TestSuite((Test3('testOne'),)) |
| 4157 | sixth = unittest.TestSuite((Test3('testTwo'),)) |
| 4158 | suite = unittest.TestSuite((first, second, third, fourth, fifth, sixth)) |
| 4159 | |
| 4160 | runner = self.getRunner() |
| 4161 | result = runner.run(suite) |
| 4162 | self.assertEqual(result.testsRun, 6) |
| 4163 | self.assertEqual(len(result.errors), 0) |
| 4164 | |
| 4165 | self.assertEqual(results, |
| 4166 | ['Module1.setUpModule', 'setup 1', |
| 4167 | 'Test1.testOne', 'Test1.testTwo', 'teardown 1', |
| 4168 | 'setup 2', 'Test2.testOne', 'Test2.testTwo', |
| 4169 | 'teardown 2', 'Module1.tearDownModule', |
| 4170 | 'Module2.setUpModule', 'setup 3', |
| 4171 | 'Test3.testOne', 'Test3.testTwo', |
| 4172 | 'teardown 3', 'Module2.tearDownModule']) |
| 4173 | |
| 4174 | def test_setup_module(self): |
| 4175 | class Module(object): |
| 4176 | moduleSetup = 0 |
| 4177 | @staticmethod |
| 4178 | def setUpModule(): |
| 4179 | Module.moduleSetup += 1 |
| 4180 | |
| 4181 | class Test(unittest.TestCase): |
| 4182 | def test_one(self): |
| 4183 | pass |
| 4184 | def test_two(self): |
| 4185 | pass |
| 4186 | Test.__module__ = 'Module' |
| 4187 | sys.modules['Module'] = Module |
| 4188 | |
| 4189 | result = self.runTests(Test) |
| 4190 | self.assertEqual(Module.moduleSetup, 1) |
| 4191 | self.assertEqual(result.testsRun, 2) |
| 4192 | self.assertEqual(len(result.errors), 0) |
| 4193 | |
| 4194 | def test_error_in_setup_module(self): |
| 4195 | class Module(object): |
| 4196 | moduleSetup = 0 |
| 4197 | moduleTornDown = 0 |
| 4198 | @staticmethod |
| 4199 | def setUpModule(): |
| 4200 | Module.moduleSetup += 1 |
| 4201 | raise TypeError('foo') |
| 4202 | @staticmethod |
| 4203 | def tearDownModule(): |
| 4204 | Module.moduleTornDown += 1 |
| 4205 | |
| 4206 | class Test(unittest.TestCase): |
| 4207 | classSetUp = False |
| 4208 | classTornDown = False |
| 4209 | @classmethod |
| 4210 | def setUpClass(cls): |
| 4211 | Test.classSetUp = True |
| 4212 | @classmethod |
| 4213 | def tearDownClass(cls): |
| 4214 | Test.classTornDown = True |
| 4215 | def test_one(self): |
| 4216 | pass |
| 4217 | def test_two(self): |
| 4218 | pass |
| 4219 | |
| 4220 | class Test2(unittest.TestCase): |
| 4221 | def test_one(self): |
| 4222 | pass |
| 4223 | def test_two(self): |
| 4224 | pass |
| 4225 | Test.__module__ = 'Module' |
| 4226 | Test2.__module__ = 'Module' |
| 4227 | sys.modules['Module'] = Module |
| 4228 | |
| 4229 | result = self.runTests(Test, Test2) |
| 4230 | self.assertEqual(Module.moduleSetup, 1) |
| 4231 | self.assertEqual(Module.moduleTornDown, 0) |
| 4232 | self.assertEqual(result.testsRun, 0) |
| 4233 | self.assertFalse(Test.classSetUp) |
| 4234 | self.assertFalse(Test.classTornDown) |
| 4235 | self.assertEqual(len(result.errors), 1) |
| 4236 | error, _ = result.errors[0] |
| 4237 | self.assertEqual(str(error), 'setUpModule (Module)') |
| 4238 | |
| 4239 | def test_testcase_with_missing_module(self): |
| 4240 | class Test(unittest.TestCase): |
| 4241 | def test_one(self): |
| 4242 | pass |
| 4243 | def test_two(self): |
| 4244 | pass |
| 4245 | Test.__module__ = 'Module' |
| 4246 | sys.modules.pop('Module', None) |
| 4247 | |
| 4248 | result = self.runTests(Test) |
| 4249 | self.assertEqual(result.testsRun, 2) |
| 4250 | |
| 4251 | def test_teardown_module(self): |
| 4252 | class Module(object): |
| 4253 | moduleTornDown = 0 |
| 4254 | @staticmethod |
| 4255 | def tearDownModule(): |
| 4256 | Module.moduleTornDown += 1 |
| 4257 | |
| 4258 | class Test(unittest.TestCase): |
| 4259 | def test_one(self): |
| 4260 | pass |
| 4261 | def test_two(self): |
| 4262 | pass |
| 4263 | Test.__module__ = 'Module' |
| 4264 | sys.modules['Module'] = Module |
| 4265 | |
| 4266 | result = self.runTests(Test) |
| 4267 | self.assertEqual(Module.moduleTornDown, 1) |
| 4268 | self.assertEqual(result.testsRun, 2) |
| 4269 | self.assertEqual(len(result.errors), 0) |
| 4270 | |
| 4271 | def test_error_in_teardown_module(self): |
| 4272 | class Module(object): |
| 4273 | moduleTornDown = 0 |
| 4274 | @staticmethod |
| 4275 | def tearDownModule(): |
| 4276 | Module.moduleTornDown += 1 |
| 4277 | raise TypeError('foo') |
| 4278 | |
| 4279 | class Test(unittest.TestCase): |
| 4280 | classSetUp = False |
| 4281 | classTornDown = False |
| 4282 | @classmethod |
| 4283 | def setUpClass(cls): |
| 4284 | Test.classSetUp = True |
| 4285 | @classmethod |
| 4286 | def tearDownClass(cls): |
| 4287 | Test.classTornDown = True |
| 4288 | def test_one(self): |
| 4289 | pass |
| 4290 | def test_two(self): |
| 4291 | pass |
| 4292 | |
| 4293 | class Test2(unittest.TestCase): |
| 4294 | def test_one(self): |
| 4295 | pass |
| 4296 | def test_two(self): |
| 4297 | pass |
| 4298 | Test.__module__ = 'Module' |
| 4299 | Test2.__module__ = 'Module' |
| 4300 | sys.modules['Module'] = Module |
| 4301 | |
| 4302 | result = self.runTests(Test, Test2) |
| 4303 | self.assertEqual(Module.moduleTornDown, 1) |
| 4304 | self.assertEqual(result.testsRun, 4) |
| 4305 | self.assertTrue(Test.classSetUp) |
| 4306 | self.assertTrue(Test.classTornDown) |
| 4307 | self.assertEqual(len(result.errors), 1) |
| 4308 | error, _ = result.errors[0] |
| 4309 | self.assertEqual(str(error), 'tearDownModule (Module)') |
| 4310 | |
Jim Fulton | fafd874 | 2004-08-28 15:22:12 +0000 | [diff] [blame] | 4311 | ###################################################################### |
| 4312 | ## Main |
| 4313 | ###################################################################### |
| 4314 | |
| 4315 | def test_main(): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 4316 | support.run_unittest(Test_TestCase, Test_TestLoader, |
Jeffrey Yasskin | aaaef11 | 2007-09-07 15:00:39 +0000 | [diff] [blame] | 4317 | Test_TestSuite, Test_TestResult, Test_FunctionTestCase, |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 4318 | Test_TestSkipping, Test_Assertions, TestLongMessage, |
Benjamin Peterson | 847a411 | 2010-03-14 15:04:17 +0000 | [diff] [blame^] | 4319 | Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner, |
| 4320 | Test_OldTestResult, TestSetups) |
Jim Fulton | fafd874 | 2004-08-28 15:22:12 +0000 | [diff] [blame] | 4321 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 4322 | if __name__ == "__main__": |
Jim Fulton | fafd874 | 2004-08-28 15:22:12 +0000 | [diff] [blame] | 4323 | test_main() |