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 | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 9 | import re |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 10 | from test import support |
Jim Fulton | fafd874 | 2004-08-28 15:22:12 +0000 | [diff] [blame] | 11 | import unittest |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 12 | from unittest import TestCase |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 13 | import types |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 14 | from copy import deepcopy |
Jim Fulton | fafd874 | 2004-08-28 15:22:12 +0000 | [diff] [blame] | 15 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 16 | ### Support code |
| 17 | ################################################################ |
Jim Fulton | fafd874 | 2004-08-28 15:22:12 +0000 | [diff] [blame] | 18 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 19 | class LoggingResult(unittest.TestResult): |
| 20 | def __init__(self, log): |
| 21 | self._events = log |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 22 | super().__init__() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 23 | |
| 24 | def startTest(self, test): |
| 25 | self._events.append('startTest') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 26 | super().startTest(test) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 27 | |
| 28 | def stopTest(self, test): |
| 29 | self._events.append('stopTest') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 30 | super().stopTest(test) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 31 | |
| 32 | def addFailure(self, *args): |
| 33 | self._events.append('addFailure') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 34 | super().addFailure(*args) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 35 | |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 36 | def addSuccess(self, *args): |
| 37 | self._events.append('addSuccess') |
| 38 | super(LoggingResult, self).addSuccess(*args) |
| 39 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 40 | def addError(self, *args): |
| 41 | self._events.append('addError') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 42 | super().addError(*args) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 43 | |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 44 | def addSkip(self, *args): |
| 45 | self._events.append('addSkip') |
| 46 | super(LoggingResult, self).addSkip(*args) |
| 47 | |
| 48 | def addExpectedFailure(self, *args): |
| 49 | self._events.append('addExpectedFailure') |
| 50 | super(LoggingResult, self).addExpectedFailure(*args) |
| 51 | |
| 52 | def addUnexpectedSuccess(self, *args): |
| 53 | self._events.append('addUnexpectedSuccess') |
| 54 | super(LoggingResult, self).addUnexpectedSuccess(*args) |
| 55 | |
| 56 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 57 | class TestEquality(object): |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 58 | """Used as a mixin for TestCase""" |
| 59 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 60 | # Check for a valid __eq__ implementation |
| 61 | def test_eq(self): |
| 62 | for obj_1, obj_2 in self.eq_pairs: |
| 63 | self.assertEqual(obj_1, obj_2) |
| 64 | self.assertEqual(obj_2, obj_1) |
| 65 | |
| 66 | # Check for a valid __ne__ implementation |
| 67 | def test_ne(self): |
| 68 | for obj_1, obj_2 in self.ne_pairs: |
| 69 | self.failIfEqual(obj_1, obj_2) |
| 70 | self.failIfEqual(obj_2, obj_1) |
| 71 | |
| 72 | class TestHashing(object): |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 73 | """Used as a mixin for TestCase""" |
| 74 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 75 | # Check for a valid __hash__ implementation |
| 76 | def test_hash(self): |
| 77 | for obj_1, obj_2 in self.eq_pairs: |
| 78 | try: |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 79 | if not hash(obj_1) == hash(obj_2): |
| 80 | 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] | 81 | except KeyboardInterrupt: |
| 82 | raise |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 83 | except Exception as e: |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 84 | 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] | 85 | |
| 86 | for obj_1, obj_2 in self.ne_pairs: |
| 87 | try: |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 88 | if hash(obj_1) == hash(obj_2): |
| 89 | self.fail("%s and %s hash equal, but shouldn't" % |
| 90 | (obj_1, obj_2)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 91 | except KeyboardInterrupt: |
| 92 | raise |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 93 | except Exception as e: |
| 94 | self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e)) |
| 95 | |
| 96 | |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 97 | # List subclass we can add attributes to. |
| 98 | class MyClassSuite(list): |
| 99 | |
| 100 | def __init__(self, tests, klass): |
| 101 | super(MyClassSuite, self).__init__(tests) |
| 102 | |
| 103 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 104 | ################################################################ |
| 105 | ### /Support code |
| 106 | |
| 107 | class Test_TestLoader(TestCase): |
| 108 | |
| 109 | ### Tests for TestLoader.loadTestsFromTestCase |
| 110 | ################################################################ |
| 111 | |
| 112 | # "Return a suite of all tests cases contained in the TestCase-derived |
| 113 | # class testCaseClass" |
| 114 | def test_loadTestsFromTestCase(self): |
| 115 | class Foo(unittest.TestCase): |
| 116 | def test_1(self): pass |
| 117 | def test_2(self): pass |
| 118 | def foo_bar(self): pass |
| 119 | |
| 120 | tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')]) |
| 121 | |
| 122 | loader = unittest.TestLoader() |
| 123 | self.assertEqual(loader.loadTestsFromTestCase(Foo), tests) |
| 124 | |
| 125 | # "Return a suite of all tests cases contained in the TestCase-derived |
| 126 | # class testCaseClass" |
| 127 | # |
| 128 | # Make sure it does the right thing even if no tests were found |
| 129 | def test_loadTestsFromTestCase__no_matches(self): |
| 130 | class Foo(unittest.TestCase): |
| 131 | def foo_bar(self): pass |
| 132 | |
| 133 | empty_suite = unittest.TestSuite() |
| 134 | |
| 135 | loader = unittest.TestLoader() |
| 136 | self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite) |
| 137 | |
| 138 | # "Return a suite of all tests cases contained in the TestCase-derived |
| 139 | # class testCaseClass" |
| 140 | # |
| 141 | # What happens if loadTestsFromTestCase() is given an object |
| 142 | # that isn't a subclass of TestCase? Specifically, what happens |
| 143 | # if testCaseClass is a subclass of TestSuite? |
| 144 | # |
| 145 | # This is checked for specifically in the code, so we better add a |
| 146 | # test for it. |
| 147 | def test_loadTestsFromTestCase__TestSuite_subclass(self): |
| 148 | class NotATestCase(unittest.TestSuite): |
| 149 | pass |
| 150 | |
| 151 | loader = unittest.TestLoader() |
| 152 | try: |
| 153 | loader.loadTestsFromTestCase(NotATestCase) |
| 154 | except TypeError: |
| 155 | pass |
| 156 | else: |
| 157 | self.fail('Should raise TypeError') |
| 158 | |
| 159 | # "Return a suite of all tests cases contained in the TestCase-derived |
| 160 | # class testCaseClass" |
| 161 | # |
| 162 | # Make sure loadTestsFromTestCase() picks up the default test method |
| 163 | # name (as specified by TestCase), even though the method name does |
| 164 | # not match the default TestLoader.testMethodPrefix string |
| 165 | def test_loadTestsFromTestCase__default_method_name(self): |
| 166 | class Foo(unittest.TestCase): |
| 167 | def runTest(self): |
| 168 | pass |
| 169 | |
| 170 | loader = unittest.TestLoader() |
| 171 | # This has to be false for the test to succeed |
| 172 | self.failIf('runTest'.startswith(loader.testMethodPrefix)) |
| 173 | |
| 174 | suite = loader.loadTestsFromTestCase(Foo) |
| 175 | self.failUnless(isinstance(suite, loader.suiteClass)) |
| 176 | self.assertEqual(list(suite), [Foo('runTest')]) |
| 177 | |
| 178 | ################################################################ |
| 179 | ### /Tests for TestLoader.loadTestsFromTestCase |
| 180 | |
| 181 | ### Tests for TestLoader.loadTestsFromModule |
| 182 | ################################################################ |
| 183 | |
| 184 | # "This method searches `module` for classes derived from TestCase" |
| 185 | def test_loadTestsFromModule__TestCase_subclass(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 186 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 187 | class MyTestCase(unittest.TestCase): |
| 188 | def test(self): |
| 189 | pass |
| 190 | m.testcase_1 = MyTestCase |
| 191 | |
| 192 | loader = unittest.TestLoader() |
| 193 | suite = loader.loadTestsFromModule(m) |
| 194 | self.failUnless(isinstance(suite, loader.suiteClass)) |
| 195 | |
| 196 | expected = [loader.suiteClass([MyTestCase('test')])] |
| 197 | self.assertEqual(list(suite), expected) |
| 198 | |
| 199 | # "This method searches `module` for classes derived from TestCase" |
| 200 | # |
| 201 | # What happens if no tests are found (no TestCase instances)? |
| 202 | def test_loadTestsFromModule__no_TestCase_instances(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 203 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 204 | |
| 205 | loader = unittest.TestLoader() |
| 206 | suite = loader.loadTestsFromModule(m) |
| 207 | self.failUnless(isinstance(suite, loader.suiteClass)) |
| 208 | self.assertEqual(list(suite), []) |
| 209 | |
| 210 | # "This method searches `module` for classes derived from TestCase" |
| 211 | # |
| 212 | # What happens if no tests are found (TestCases instances, but no tests)? |
| 213 | def test_loadTestsFromModule__no_TestCase_tests(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 214 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 215 | class MyTestCase(unittest.TestCase): |
| 216 | pass |
| 217 | m.testcase_1 = MyTestCase |
| 218 | |
| 219 | loader = unittest.TestLoader() |
| 220 | suite = loader.loadTestsFromModule(m) |
| 221 | self.failUnless(isinstance(suite, loader.suiteClass)) |
| 222 | |
| 223 | self.assertEqual(list(suite), [loader.suiteClass()]) |
| 224 | |
| 225 | # "This method searches `module` for classes derived from TestCase"s |
| 226 | # |
| 227 | # What happens if loadTestsFromModule() is given something other |
| 228 | # than a module? |
| 229 | # |
| 230 | # XXX Currently, it succeeds anyway. This flexibility |
| 231 | # should either be documented or loadTestsFromModule() should |
| 232 | # raise a TypeError |
| 233 | # |
| 234 | # XXX Certain people are using this behaviour. We'll add a test for it |
| 235 | def test_loadTestsFromModule__not_a_module(self): |
| 236 | class MyTestCase(unittest.TestCase): |
| 237 | def test(self): |
| 238 | pass |
| 239 | |
| 240 | class NotAModule(object): |
| 241 | test_2 = MyTestCase |
| 242 | |
| 243 | loader = unittest.TestLoader() |
| 244 | suite = loader.loadTestsFromModule(NotAModule) |
| 245 | |
| 246 | reference = [unittest.TestSuite([MyTestCase('test')])] |
| 247 | self.assertEqual(list(suite), reference) |
| 248 | |
| 249 | ################################################################ |
| 250 | ### /Tests for TestLoader.loadTestsFromModule() |
| 251 | |
| 252 | ### Tests for TestLoader.loadTestsFromName() |
| 253 | ################################################################ |
| 254 | |
| 255 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 256 | # a module, a test case class, a TestSuite instance, a test method |
| 257 | # within a test case class, or a callable object which returns a |
| 258 | # TestCase or TestSuite instance." |
| 259 | # |
| 260 | # Is ValueError raised in response to an empty name? |
| 261 | def test_loadTestsFromName__empty_name(self): |
| 262 | loader = unittest.TestLoader() |
| 263 | |
| 264 | try: |
| 265 | loader.loadTestsFromName('') |
| 266 | except ValueError as e: |
| 267 | self.assertEqual(str(e), "Empty module name") |
| 268 | else: |
| 269 | self.fail("TestLoader.loadTestsFromName failed to raise ValueError") |
| 270 | |
| 271 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 272 | # a module, a test case class, a TestSuite instance, a test method |
| 273 | # within a test case class, or a callable object which returns a |
| 274 | # TestCase or TestSuite instance." |
| 275 | # |
| 276 | # What happens when the name contains invalid characters? |
| 277 | def test_loadTestsFromName__malformed_name(self): |
| 278 | loader = unittest.TestLoader() |
| 279 | |
| 280 | # XXX Should this raise ValueError or ImportError? |
| 281 | try: |
| 282 | loader.loadTestsFromName('abc () //') |
| 283 | except ValueError: |
| 284 | pass |
| 285 | except ImportError: |
| 286 | pass |
| 287 | else: |
| 288 | self.fail("TestLoader.loadTestsFromName failed to raise ValueError") |
| 289 | |
| 290 | # "The specifier name is a ``dotted name'' that may resolve ... to a |
| 291 | # module" |
| 292 | # |
| 293 | # What happens when a module by that name can't be found? |
| 294 | def test_loadTestsFromName__unknown_module_name(self): |
| 295 | loader = unittest.TestLoader() |
| 296 | |
| 297 | try: |
| 298 | loader.loadTestsFromName('sdasfasfasdf') |
| 299 | except ImportError as e: |
| 300 | self.assertEqual(str(e), "No module named sdasfasfasdf") |
| 301 | else: |
| 302 | self.fail("TestLoader.loadTestsFromName failed to raise ImportError") |
| 303 | |
| 304 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 305 | # a module, a test case class, a TestSuite instance, a test method |
| 306 | # within a test case class, or a callable object which returns a |
| 307 | # TestCase or TestSuite instance." |
| 308 | # |
| 309 | # What happens when the module is found, but the attribute can't? |
| 310 | def test_loadTestsFromName__unknown_attr_name(self): |
| 311 | loader = unittest.TestLoader() |
| 312 | |
| 313 | try: |
| 314 | loader.loadTestsFromName('unittest.sdasfasfasdf') |
| 315 | except AttributeError as e: |
| 316 | self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") |
| 317 | else: |
| 318 | self.fail("TestLoader.loadTestsFromName failed to raise AttributeError") |
| 319 | |
| 320 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 321 | # a module, a test case class, a TestSuite instance, a test method |
| 322 | # within a test case class, or a callable object which returns a |
| 323 | # TestCase or TestSuite instance." |
| 324 | # |
| 325 | # What happens when we provide the module, but the attribute can't be |
| 326 | # found? |
| 327 | def test_loadTestsFromName__relative_unknown_name(self): |
| 328 | loader = unittest.TestLoader() |
| 329 | |
| 330 | try: |
| 331 | loader.loadTestsFromName('sdasfasfasdf', unittest) |
| 332 | except AttributeError as e: |
| 333 | self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") |
| 334 | else: |
| 335 | self.fail("TestLoader.loadTestsFromName failed to raise AttributeError") |
| 336 | |
| 337 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 338 | # a module, a test case class, a TestSuite instance, a test method |
| 339 | # within a test case class, or a callable object which returns a |
| 340 | # TestCase or TestSuite instance." |
| 341 | # ... |
| 342 | # "The method optionally resolves name relative to the given module" |
| 343 | # |
| 344 | # Does loadTestsFromName raise ValueError when passed an empty |
| 345 | # name relative to a provided module? |
| 346 | # |
| 347 | # XXX Should probably raise a ValueError instead of an AttributeError |
| 348 | def test_loadTestsFromName__relative_empty_name(self): |
| 349 | loader = unittest.TestLoader() |
| 350 | |
| 351 | try: |
| 352 | loader.loadTestsFromName('', unittest) |
| 353 | except AttributeError as e: |
| 354 | pass |
| 355 | else: |
| 356 | self.fail("Failed to raise AttributeError") |
| 357 | |
| 358 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 359 | # a module, a test case class, a TestSuite instance, a test method |
| 360 | # within a test case class, or a callable object which returns a |
| 361 | # TestCase or TestSuite instance." |
| 362 | # ... |
| 363 | # "The method optionally resolves name relative to the given module" |
| 364 | # |
| 365 | # What happens when an impossible name is given, relative to the provided |
| 366 | # `module`? |
| 367 | def test_loadTestsFromName__relative_malformed_name(self): |
| 368 | loader = unittest.TestLoader() |
| 369 | |
| 370 | # XXX Should this raise AttributeError or ValueError? |
| 371 | try: |
| 372 | loader.loadTestsFromName('abc () //', unittest) |
| 373 | except ValueError: |
| 374 | pass |
| 375 | except AttributeError: |
| 376 | pass |
| 377 | else: |
| 378 | self.fail("TestLoader.loadTestsFromName failed to raise ValueError") |
| 379 | |
| 380 | # "The method optionally resolves name relative to the given module" |
| 381 | # |
| 382 | # Does loadTestsFromName raise TypeError when the `module` argument |
| 383 | # isn't a module object? |
| 384 | # |
| 385 | # XXX Accepts the not-a-module object, ignorning the object's type |
| 386 | # This should raise an exception or the method name should be changed |
| 387 | # |
| 388 | # XXX Some people are relying on this, so keep it for now |
| 389 | def test_loadTestsFromName__relative_not_a_module(self): |
| 390 | class MyTestCase(unittest.TestCase): |
| 391 | def test(self): |
| 392 | pass |
| 393 | |
| 394 | class NotAModule(object): |
| 395 | test_2 = MyTestCase |
| 396 | |
| 397 | loader = unittest.TestLoader() |
| 398 | suite = loader.loadTestsFromName('test_2', NotAModule) |
| 399 | |
| 400 | reference = [MyTestCase('test')] |
| 401 | self.assertEqual(list(suite), reference) |
| 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 | # Does it raise an exception if the name resolves to an invalid |
| 409 | # object? |
| 410 | def test_loadTestsFromName__relative_bad_object(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 411 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 412 | m.testcase_1 = object() |
| 413 | |
| 414 | loader = unittest.TestLoader() |
| 415 | try: |
| 416 | loader.loadTestsFromName('testcase_1', m) |
| 417 | except TypeError: |
| 418 | pass |
| 419 | else: |
| 420 | self.fail("Should have raised TypeError") |
| 421 | |
| 422 | # "The specifier name is a ``dotted name'' that may |
| 423 | # resolve either to ... a test case class" |
| 424 | def test_loadTestsFromName__relative_TestCase_subclass(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 425 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 426 | class MyTestCase(unittest.TestCase): |
| 427 | def test(self): |
| 428 | pass |
| 429 | m.testcase_1 = MyTestCase |
| 430 | |
| 431 | loader = unittest.TestLoader() |
| 432 | suite = loader.loadTestsFromName('testcase_1', m) |
| 433 | self.failUnless(isinstance(suite, loader.suiteClass)) |
| 434 | self.assertEqual(list(suite), [MyTestCase('test')]) |
| 435 | |
| 436 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 437 | # a module, a test case class, a TestSuite instance, a test method |
| 438 | # within a test case class, or a callable object which returns a |
| 439 | # TestCase or TestSuite instance." |
| 440 | def test_loadTestsFromName__relative_TestSuite(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 441 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 442 | class MyTestCase(unittest.TestCase): |
| 443 | def test(self): |
| 444 | pass |
| 445 | m.testsuite = unittest.TestSuite([MyTestCase('test')]) |
| 446 | |
| 447 | loader = unittest.TestLoader() |
| 448 | suite = loader.loadTestsFromName('testsuite', m) |
| 449 | self.failUnless(isinstance(suite, loader.suiteClass)) |
| 450 | |
| 451 | self.assertEqual(list(suite), [MyTestCase('test')]) |
| 452 | |
| 453 | # "The specifier name is a ``dotted name'' that may resolve ... to |
| 454 | # ... a test method within a test case class" |
| 455 | def test_loadTestsFromName__relative_testmethod(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 | class MyTestCase(unittest.TestCase): |
| 458 | def test(self): |
| 459 | pass |
| 460 | m.testcase_1 = MyTestCase |
| 461 | |
| 462 | loader = unittest.TestLoader() |
| 463 | suite = loader.loadTestsFromName('testcase_1.test', m) |
| 464 | self.failUnless(isinstance(suite, loader.suiteClass)) |
| 465 | |
| 466 | self.assertEqual(list(suite), [MyTestCase('test')]) |
| 467 | |
| 468 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 469 | # a module, a test case class, a TestSuite instance, a test method |
| 470 | # within a test case class, or a callable object which returns a |
| 471 | # TestCase or TestSuite instance." |
| 472 | # |
| 473 | # Does loadTestsFromName() raise the proper exception when trying to |
| 474 | # resolve "a test method within a test case class" that doesn't exist |
| 475 | # for the given name (relative to a provided module)? |
| 476 | def test_loadTestsFromName__relative_invalid_testmethod(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 477 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 478 | class MyTestCase(unittest.TestCase): |
| 479 | def test(self): |
| 480 | pass |
| 481 | m.testcase_1 = MyTestCase |
| 482 | |
| 483 | loader = unittest.TestLoader() |
| 484 | try: |
| 485 | loader.loadTestsFromName('testcase_1.testfoo', m) |
| 486 | except AttributeError as e: |
| 487 | self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'") |
| 488 | else: |
| 489 | self.fail("Failed to raise AttributeError") |
| 490 | |
| 491 | # "The specifier name is a ``dotted name'' that may resolve ... to |
| 492 | # ... a callable object which returns a ... TestSuite instance" |
| 493 | def test_loadTestsFromName__callable__TestSuite(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 494 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 495 | testcase_1 = unittest.FunctionTestCase(lambda: None) |
| 496 | testcase_2 = unittest.FunctionTestCase(lambda: None) |
| 497 | def return_TestSuite(): |
| 498 | return unittest.TestSuite([testcase_1, testcase_2]) |
| 499 | m.return_TestSuite = return_TestSuite |
| 500 | |
| 501 | loader = unittest.TestLoader() |
| 502 | suite = loader.loadTestsFromName('return_TestSuite', m) |
| 503 | self.failUnless(isinstance(suite, loader.suiteClass)) |
| 504 | self.assertEqual(list(suite), [testcase_1, testcase_2]) |
| 505 | |
| 506 | # "The specifier name is a ``dotted name'' that may resolve ... to |
| 507 | # ... a callable object which returns a TestCase ... instance" |
| 508 | def test_loadTestsFromName__callable__TestCase_instance(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 509 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 510 | testcase_1 = unittest.FunctionTestCase(lambda: None) |
| 511 | def return_TestCase(): |
| 512 | return testcase_1 |
| 513 | m.return_TestCase = return_TestCase |
| 514 | |
| 515 | loader = unittest.TestLoader() |
| 516 | suite = loader.loadTestsFromName('return_TestCase', m) |
| 517 | self.failUnless(isinstance(suite, loader.suiteClass)) |
| 518 | self.assertEqual(list(suite), [testcase_1]) |
| 519 | |
| 520 | # "The specifier name is a ``dotted name'' that may resolve ... to |
| 521 | # ... a callable object which returns a TestCase or TestSuite instance" |
| 522 | # |
| 523 | # What happens if the callable returns something else? |
| 524 | def test_loadTestsFromName__callable__wrong_type(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 525 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 526 | def return_wrong(): |
| 527 | return 6 |
| 528 | m.return_wrong = return_wrong |
| 529 | |
| 530 | loader = unittest.TestLoader() |
| 531 | try: |
| 532 | suite = loader.loadTestsFromName('return_wrong', m) |
| 533 | except TypeError: |
| 534 | pass |
| 535 | else: |
| 536 | self.fail("TestLoader.loadTestsFromName failed to raise TypeError") |
| 537 | |
| 538 | # "The specifier can refer to modules and packages which have not been |
| 539 | # imported; they will be imported as a side-effect" |
| 540 | def test_loadTestsFromName__module_not_loaded(self): |
| 541 | # We're going to try to load this module as a side-effect, so it |
| 542 | # better not be loaded before we try. |
| 543 | # |
| 544 | # Why pick audioop? Google shows it isn't used very often, so there's |
| 545 | # a good chance that it won't be imported when this test is run |
| 546 | module_name = 'audioop' |
| 547 | |
| 548 | import sys |
| 549 | if module_name in sys.modules: |
| 550 | del sys.modules[module_name] |
| 551 | |
| 552 | loader = unittest.TestLoader() |
| 553 | try: |
| 554 | suite = loader.loadTestsFromName(module_name) |
| 555 | |
| 556 | self.failUnless(isinstance(suite, loader.suiteClass)) |
| 557 | self.assertEqual(list(suite), []) |
| 558 | |
| 559 | # audioop should now be loaded, thanks to loadTestsFromName() |
| 560 | self.failUnless(module_name in sys.modules) |
| 561 | finally: |
Guido van Rossum | 360e4b8 | 2007-05-14 22:51:27 +0000 | [diff] [blame] | 562 | if module_name in sys.modules: |
| 563 | del sys.modules[module_name] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 564 | |
| 565 | ################################################################ |
| 566 | ### Tests for TestLoader.loadTestsFromName() |
| 567 | |
| 568 | ### Tests for TestLoader.loadTestsFromNames() |
| 569 | ################################################################ |
| 570 | |
| 571 | # "Similar to loadTestsFromName(), but takes a sequence of names rather |
| 572 | # than a single name." |
| 573 | # |
| 574 | # What happens if that sequence of names is empty? |
| 575 | def test_loadTestsFromNames__empty_name_list(self): |
| 576 | loader = unittest.TestLoader() |
| 577 | |
| 578 | suite = loader.loadTestsFromNames([]) |
| 579 | self.failUnless(isinstance(suite, loader.suiteClass)) |
| 580 | self.assertEqual(list(suite), []) |
| 581 | |
| 582 | # "Similar to loadTestsFromName(), but takes a sequence of names rather |
| 583 | # than a single name." |
| 584 | # ... |
| 585 | # "The method optionally resolves name relative to the given module" |
| 586 | # |
| 587 | # What happens if that sequence of names is empty? |
| 588 | # |
| 589 | # XXX Should this raise a ValueError or just return an empty TestSuite? |
| 590 | def test_loadTestsFromNames__relative_empty_name_list(self): |
| 591 | loader = unittest.TestLoader() |
| 592 | |
| 593 | suite = loader.loadTestsFromNames([], unittest) |
| 594 | self.failUnless(isinstance(suite, loader.suiteClass)) |
| 595 | self.assertEqual(list(suite), []) |
| 596 | |
| 597 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 598 | # a module, a test case class, a TestSuite instance, a test method |
| 599 | # within a test case class, or a callable object which returns a |
| 600 | # TestCase or TestSuite instance." |
| 601 | # |
| 602 | # Is ValueError raised in response to an empty name? |
| 603 | def test_loadTestsFromNames__empty_name(self): |
| 604 | loader = unittest.TestLoader() |
| 605 | |
| 606 | try: |
| 607 | loader.loadTestsFromNames(['']) |
| 608 | except ValueError as e: |
| 609 | self.assertEqual(str(e), "Empty module name") |
| 610 | else: |
| 611 | self.fail("TestLoader.loadTestsFromNames failed to raise ValueError") |
| 612 | |
| 613 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 614 | # a module, a test case class, a TestSuite instance, a test method |
| 615 | # within a test case class, or a callable object which returns a |
| 616 | # TestCase or TestSuite instance." |
| 617 | # |
| 618 | # What happens when presented with an impossible module name? |
| 619 | def test_loadTestsFromNames__malformed_name(self): |
| 620 | loader = unittest.TestLoader() |
| 621 | |
| 622 | # XXX Should this raise ValueError or ImportError? |
| 623 | try: |
| 624 | loader.loadTestsFromNames(['abc () //']) |
| 625 | except ValueError: |
| 626 | pass |
| 627 | except ImportError: |
| 628 | pass |
| 629 | else: |
| 630 | self.fail("TestLoader.loadTestsFromNames failed to raise ValueError") |
| 631 | |
| 632 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 633 | # a module, a test case class, a TestSuite instance, a test method |
| 634 | # within a test case class, or a callable object which returns a |
| 635 | # TestCase or TestSuite instance." |
| 636 | # |
| 637 | # What happens when no module can be found for the given name? |
| 638 | def test_loadTestsFromNames__unknown_module_name(self): |
| 639 | loader = unittest.TestLoader() |
| 640 | |
| 641 | try: |
| 642 | loader.loadTestsFromNames(['sdasfasfasdf']) |
| 643 | except ImportError as e: |
| 644 | self.assertEqual(str(e), "No module named sdasfasfasdf") |
| 645 | else: |
| 646 | self.fail("TestLoader.loadTestsFromNames failed to raise ImportError") |
| 647 | |
| 648 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 649 | # a module, a test case class, a TestSuite instance, a test method |
| 650 | # within a test case class, or a callable object which returns a |
| 651 | # TestCase or TestSuite instance." |
| 652 | # |
| 653 | # What happens when the module can be found, but not the attribute? |
| 654 | def test_loadTestsFromNames__unknown_attr_name(self): |
| 655 | loader = unittest.TestLoader() |
| 656 | |
| 657 | try: |
| 658 | loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest']) |
| 659 | except AttributeError as e: |
| 660 | self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") |
| 661 | else: |
| 662 | self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError") |
| 663 | |
| 664 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 665 | # a module, a test case class, a TestSuite instance, a test method |
| 666 | # within a test case class, or a callable object which returns a |
| 667 | # TestCase or TestSuite instance." |
| 668 | # ... |
| 669 | # "The method optionally resolves name relative to the given module" |
| 670 | # |
| 671 | # What happens when given an unknown attribute on a specified `module` |
| 672 | # argument? |
| 673 | def test_loadTestsFromNames__unknown_name_relative_1(self): |
| 674 | loader = unittest.TestLoader() |
| 675 | |
| 676 | try: |
| 677 | loader.loadTestsFromNames(['sdasfasfasdf'], unittest) |
| 678 | except AttributeError as e: |
| 679 | self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") |
| 680 | else: |
| 681 | self.fail("TestLoader.loadTestsFromName failed to raise AttributeError") |
| 682 | |
| 683 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 684 | # a module, a test case class, a TestSuite instance, a test method |
| 685 | # within a test case class, or a callable object which returns a |
| 686 | # TestCase or TestSuite instance." |
| 687 | # ... |
| 688 | # "The method optionally resolves name relative to the given module" |
| 689 | # |
| 690 | # Do unknown attributes (relative to a provided module) still raise an |
| 691 | # exception even in the presence of valid attribute names? |
| 692 | def test_loadTestsFromNames__unknown_name_relative_2(self): |
| 693 | loader = unittest.TestLoader() |
| 694 | |
| 695 | try: |
| 696 | loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest) |
| 697 | except AttributeError as e: |
| 698 | self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") |
| 699 | else: |
| 700 | self.fail("TestLoader.loadTestsFromName failed to raise AttributeError") |
| 701 | |
| 702 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 703 | # a module, a test case class, a TestSuite instance, a test method |
| 704 | # within a test case class, or a callable object which returns a |
| 705 | # TestCase or TestSuite instance." |
| 706 | # ... |
| 707 | # "The method optionally resolves name relative to the given module" |
| 708 | # |
| 709 | # What happens when faced with the empty string? |
| 710 | # |
| 711 | # XXX This currently raises AttributeError, though ValueError is probably |
| 712 | # more appropriate |
| 713 | def test_loadTestsFromNames__relative_empty_name(self): |
| 714 | loader = unittest.TestLoader() |
| 715 | |
| 716 | try: |
| 717 | loader.loadTestsFromNames([''], unittest) |
| 718 | except AttributeError: |
| 719 | pass |
| 720 | else: |
| 721 | self.fail("Failed to raise ValueError") |
| 722 | |
| 723 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 724 | # a module, a test case class, a TestSuite instance, a test method |
| 725 | # within a test case class, or a callable object which returns a |
| 726 | # TestCase or TestSuite instance." |
| 727 | # ... |
| 728 | # "The method optionally resolves name relative to the given module" |
| 729 | # |
| 730 | # What happens when presented with an impossible attribute name? |
| 731 | def test_loadTestsFromNames__relative_malformed_name(self): |
| 732 | loader = unittest.TestLoader() |
| 733 | |
| 734 | # XXX Should this raise AttributeError or ValueError? |
| 735 | try: |
| 736 | loader.loadTestsFromNames(['abc () //'], unittest) |
| 737 | except AttributeError: |
| 738 | pass |
| 739 | except ValueError: |
| 740 | pass |
| 741 | else: |
| 742 | self.fail("TestLoader.loadTestsFromNames failed to raise ValueError") |
| 743 | |
| 744 | # "The method optionally resolves name relative to the given module" |
| 745 | # |
| 746 | # Does loadTestsFromNames() make sure the provided `module` is in fact |
| 747 | # a module? |
| 748 | # |
| 749 | # XXX This validation is currently not done. This flexibility should |
| 750 | # either be documented or a TypeError should be raised. |
| 751 | def test_loadTestsFromNames__relative_not_a_module(self): |
| 752 | class MyTestCase(unittest.TestCase): |
| 753 | def test(self): |
| 754 | pass |
| 755 | |
| 756 | class NotAModule(object): |
| 757 | test_2 = MyTestCase |
| 758 | |
| 759 | loader = unittest.TestLoader() |
| 760 | suite = loader.loadTestsFromNames(['test_2'], NotAModule) |
| 761 | |
| 762 | reference = [unittest.TestSuite([MyTestCase('test')])] |
| 763 | self.assertEqual(list(suite), reference) |
| 764 | |
| 765 | # "The specifier name is a ``dotted name'' that may resolve either to |
| 766 | # a module, a test case class, a TestSuite instance, a test method |
| 767 | # within a test case class, or a callable object which returns a |
| 768 | # TestCase or TestSuite instance." |
| 769 | # |
| 770 | # Does it raise an exception if the name resolves to an invalid |
| 771 | # object? |
| 772 | def test_loadTestsFromNames__relative_bad_object(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 773 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 774 | m.testcase_1 = object() |
| 775 | |
| 776 | loader = unittest.TestLoader() |
| 777 | try: |
| 778 | loader.loadTestsFromNames(['testcase_1'], m) |
| 779 | except TypeError: |
| 780 | pass |
| 781 | else: |
| 782 | self.fail("Should have raised TypeError") |
| 783 | |
| 784 | # "The specifier name is a ``dotted name'' that may resolve ... to |
| 785 | # ... a test case class" |
| 786 | def test_loadTestsFromNames__relative_TestCase_subclass(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 787 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 788 | class MyTestCase(unittest.TestCase): |
| 789 | def test(self): |
| 790 | pass |
| 791 | m.testcase_1 = MyTestCase |
| 792 | |
| 793 | loader = unittest.TestLoader() |
| 794 | suite = loader.loadTestsFromNames(['testcase_1'], m) |
| 795 | self.failUnless(isinstance(suite, loader.suiteClass)) |
| 796 | |
| 797 | expected = loader.suiteClass([MyTestCase('test')]) |
| 798 | self.assertEqual(list(suite), [expected]) |
| 799 | |
| 800 | # "The specifier name is a ``dotted name'' that may resolve ... to |
| 801 | # ... a TestSuite instance" |
| 802 | def test_loadTestsFromNames__relative_TestSuite(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 803 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 804 | class MyTestCase(unittest.TestCase): |
| 805 | def test(self): |
| 806 | pass |
| 807 | m.testsuite = unittest.TestSuite([MyTestCase('test')]) |
| 808 | |
| 809 | loader = unittest.TestLoader() |
| 810 | suite = loader.loadTestsFromNames(['testsuite'], m) |
| 811 | self.failUnless(isinstance(suite, loader.suiteClass)) |
| 812 | |
| 813 | self.assertEqual(list(suite), [m.testsuite]) |
| 814 | |
| 815 | # "The specifier name is a ``dotted name'' that may resolve ... to ... a |
| 816 | # test method within a test case class" |
| 817 | def test_loadTestsFromNames__relative_testmethod(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 818 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 819 | class MyTestCase(unittest.TestCase): |
| 820 | def test(self): |
| 821 | pass |
| 822 | m.testcase_1 = MyTestCase |
| 823 | |
| 824 | loader = unittest.TestLoader() |
| 825 | suite = loader.loadTestsFromNames(['testcase_1.test'], m) |
| 826 | self.failUnless(isinstance(suite, loader.suiteClass)) |
| 827 | |
| 828 | ref_suite = unittest.TestSuite([MyTestCase('test')]) |
| 829 | self.assertEqual(list(suite), [ref_suite]) |
| 830 | |
| 831 | # "The specifier name is a ``dotted name'' that may resolve ... to ... a |
| 832 | # test method within a test case class" |
| 833 | # |
| 834 | # Does the method gracefully handle names that initially look like they |
| 835 | # resolve to "a test method within a test case class" but don't? |
| 836 | def test_loadTestsFromNames__relative_invalid_testmethod(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 837 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 838 | class MyTestCase(unittest.TestCase): |
| 839 | def test(self): |
| 840 | pass |
| 841 | m.testcase_1 = MyTestCase |
| 842 | |
| 843 | loader = unittest.TestLoader() |
| 844 | try: |
| 845 | loader.loadTestsFromNames(['testcase_1.testfoo'], m) |
| 846 | except AttributeError as e: |
| 847 | self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'") |
| 848 | else: |
| 849 | self.fail("Failed to raise AttributeError") |
| 850 | |
| 851 | # "The specifier name is a ``dotted name'' that may resolve ... to |
| 852 | # ... a callable object which returns a ... TestSuite instance" |
| 853 | def test_loadTestsFromNames__callable__TestSuite(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 854 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 855 | testcase_1 = unittest.FunctionTestCase(lambda: None) |
| 856 | testcase_2 = unittest.FunctionTestCase(lambda: None) |
| 857 | def return_TestSuite(): |
| 858 | return unittest.TestSuite([testcase_1, testcase_2]) |
| 859 | m.return_TestSuite = return_TestSuite |
| 860 | |
| 861 | loader = unittest.TestLoader() |
| 862 | suite = loader.loadTestsFromNames(['return_TestSuite'], m) |
| 863 | self.failUnless(isinstance(suite, loader.suiteClass)) |
| 864 | |
| 865 | expected = unittest.TestSuite([testcase_1, testcase_2]) |
| 866 | self.assertEqual(list(suite), [expected]) |
| 867 | |
| 868 | # "The specifier name is a ``dotted name'' that may resolve ... to |
| 869 | # ... a callable object which returns a TestCase ... instance" |
| 870 | def test_loadTestsFromNames__callable__TestCase_instance(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 871 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 872 | testcase_1 = unittest.FunctionTestCase(lambda: None) |
| 873 | def return_TestCase(): |
| 874 | return testcase_1 |
| 875 | m.return_TestCase = return_TestCase |
| 876 | |
| 877 | loader = unittest.TestLoader() |
| 878 | suite = loader.loadTestsFromNames(['return_TestCase'], m) |
| 879 | self.failUnless(isinstance(suite, loader.suiteClass)) |
| 880 | |
| 881 | ref_suite = unittest.TestSuite([testcase_1]) |
| 882 | self.assertEqual(list(suite), [ref_suite]) |
| 883 | |
| 884 | # "The specifier name is a ``dotted name'' that may resolve ... to |
| 885 | # ... a callable object which returns a TestCase or TestSuite instance" |
| 886 | # |
| 887 | # Are staticmethods handled correctly? |
| 888 | def test_loadTestsFromNames__callable__call_staticmethod(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 889 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 890 | class Test1(unittest.TestCase): |
| 891 | def test(self): |
| 892 | pass |
| 893 | |
| 894 | testcase_1 = Test1('test') |
| 895 | class Foo(unittest.TestCase): |
| 896 | @staticmethod |
| 897 | def foo(): |
| 898 | return testcase_1 |
| 899 | m.Foo = Foo |
| 900 | |
| 901 | loader = unittest.TestLoader() |
| 902 | suite = loader.loadTestsFromNames(['Foo.foo'], m) |
| 903 | self.failUnless(isinstance(suite, loader.suiteClass)) |
| 904 | |
| 905 | ref_suite = unittest.TestSuite([testcase_1]) |
| 906 | self.assertEqual(list(suite), [ref_suite]) |
| 907 | |
| 908 | # "The specifier name is a ``dotted name'' that may resolve ... to |
| 909 | # ... a callable object which returns a TestCase or TestSuite instance" |
| 910 | # |
| 911 | # What happens when the callable returns something else? |
| 912 | def test_loadTestsFromNames__callable__wrong_type(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 913 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 914 | def return_wrong(): |
| 915 | return 6 |
| 916 | m.return_wrong = return_wrong |
| 917 | |
| 918 | loader = unittest.TestLoader() |
| 919 | try: |
| 920 | suite = loader.loadTestsFromNames(['return_wrong'], m) |
| 921 | except TypeError: |
| 922 | pass |
| 923 | else: |
| 924 | self.fail("TestLoader.loadTestsFromNames failed to raise TypeError") |
| 925 | |
| 926 | # "The specifier can refer to modules and packages which have not been |
| 927 | # imported; they will be imported as a side-effect" |
| 928 | def test_loadTestsFromNames__module_not_loaded(self): |
| 929 | # We're going to try to load this module as a side-effect, so it |
| 930 | # better not be loaded before we try. |
| 931 | # |
| 932 | # Why pick audioop? Google shows it isn't used very often, so there's |
| 933 | # a good chance that it won't be imported when this test is run |
| 934 | module_name = 'audioop' |
| 935 | |
| 936 | import sys |
| 937 | if module_name in sys.modules: |
| 938 | del sys.modules[module_name] |
| 939 | |
| 940 | loader = unittest.TestLoader() |
| 941 | try: |
| 942 | suite = loader.loadTestsFromNames([module_name]) |
| 943 | |
| 944 | self.failUnless(isinstance(suite, loader.suiteClass)) |
| 945 | self.assertEqual(list(suite), [unittest.TestSuite()]) |
| 946 | |
| 947 | # audioop should now be loaded, thanks to loadTestsFromName() |
| 948 | self.failUnless(module_name in sys.modules) |
| 949 | finally: |
Guido van Rossum | 360e4b8 | 2007-05-14 22:51:27 +0000 | [diff] [blame] | 950 | if module_name in sys.modules: |
| 951 | del sys.modules[module_name] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 952 | |
| 953 | ################################################################ |
| 954 | ### /Tests for TestLoader.loadTestsFromNames() |
| 955 | |
| 956 | ### Tests for TestLoader.getTestCaseNames() |
| 957 | ################################################################ |
| 958 | |
| 959 | # "Return a sorted sequence of method names found within testCaseClass" |
| 960 | # |
| 961 | # Test.foobar is defined to make sure getTestCaseNames() respects |
| 962 | # loader.testMethodPrefix |
| 963 | def test_getTestCaseNames(self): |
| 964 | class Test(unittest.TestCase): |
| 965 | def test_1(self): pass |
| 966 | def test_2(self): pass |
| 967 | def foobar(self): pass |
| 968 | |
| 969 | loader = unittest.TestLoader() |
| 970 | |
| 971 | self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2']) |
| 972 | |
| 973 | # "Return a sorted sequence of method names found within testCaseClass" |
| 974 | # |
| 975 | # Does getTestCaseNames() behave appropriately if no tests are found? |
| 976 | def test_getTestCaseNames__no_tests(self): |
| 977 | class Test(unittest.TestCase): |
| 978 | def foobar(self): pass |
| 979 | |
| 980 | loader = unittest.TestLoader() |
| 981 | |
| 982 | self.assertEqual(loader.getTestCaseNames(Test), []) |
| 983 | |
| 984 | # "Return a sorted sequence of method names found within testCaseClass" |
| 985 | # |
| 986 | # Are not-TestCases handled gracefully? |
| 987 | # |
| 988 | # XXX This should raise a TypeError, not return a list |
| 989 | # |
| 990 | # XXX It's too late in the 2.5 release cycle to fix this, but it should |
| 991 | # probably be revisited for 2.6 |
| 992 | def test_getTestCaseNames__not_a_TestCase(self): |
| 993 | class BadCase(int): |
| 994 | def test_foo(self): |
| 995 | pass |
| 996 | |
| 997 | loader = unittest.TestLoader() |
| 998 | names = loader.getTestCaseNames(BadCase) |
| 999 | |
| 1000 | self.assertEqual(names, ['test_foo']) |
| 1001 | |
| 1002 | # "Return a sorted sequence of method names found within testCaseClass" |
| 1003 | # |
| 1004 | # Make sure inherited names are handled. |
| 1005 | # |
| 1006 | # TestP.foobar is defined to make sure getTestCaseNames() respects |
| 1007 | # loader.testMethodPrefix |
| 1008 | def test_getTestCaseNames__inheritance(self): |
| 1009 | class TestP(unittest.TestCase): |
| 1010 | def test_1(self): pass |
| 1011 | def test_2(self): pass |
| 1012 | def foobar(self): pass |
| 1013 | |
| 1014 | class TestC(TestP): |
| 1015 | def test_1(self): pass |
| 1016 | def test_3(self): pass |
| 1017 | |
| 1018 | loader = unittest.TestLoader() |
| 1019 | |
| 1020 | names = ['test_1', 'test_2', 'test_3'] |
| 1021 | self.assertEqual(loader.getTestCaseNames(TestC), names) |
| 1022 | |
| 1023 | ################################################################ |
| 1024 | ### /Tests for TestLoader.getTestCaseNames() |
| 1025 | |
| 1026 | ### Tests for TestLoader.testMethodPrefix |
| 1027 | ################################################################ |
| 1028 | |
| 1029 | # "String giving the prefix of method names which will be interpreted as |
| 1030 | # test methods" |
| 1031 | # |
| 1032 | # Implicit in the documentation is that testMethodPrefix is respected by |
| 1033 | # all loadTestsFrom* methods. |
| 1034 | def test_testMethodPrefix__loadTestsFromTestCase(self): |
| 1035 | class Foo(unittest.TestCase): |
| 1036 | def test_1(self): pass |
| 1037 | def test_2(self): pass |
| 1038 | def foo_bar(self): pass |
| 1039 | |
| 1040 | tests_1 = unittest.TestSuite([Foo('foo_bar')]) |
| 1041 | tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')]) |
| 1042 | |
| 1043 | loader = unittest.TestLoader() |
| 1044 | loader.testMethodPrefix = 'foo' |
| 1045 | self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1) |
| 1046 | |
| 1047 | loader.testMethodPrefix = 'test' |
| 1048 | self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2) |
| 1049 | |
| 1050 | # "String giving the prefix of method names which will be interpreted as |
| 1051 | # test methods" |
| 1052 | # |
| 1053 | # Implicit in the documentation is that testMethodPrefix is respected by |
| 1054 | # all loadTestsFrom* methods. |
| 1055 | def test_testMethodPrefix__loadTestsFromModule(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 1056 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1057 | class Foo(unittest.TestCase): |
| 1058 | def test_1(self): pass |
| 1059 | def test_2(self): pass |
| 1060 | def foo_bar(self): pass |
| 1061 | m.Foo = Foo |
| 1062 | |
| 1063 | tests_1 = [unittest.TestSuite([Foo('foo_bar')])] |
| 1064 | tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])] |
| 1065 | |
| 1066 | loader = unittest.TestLoader() |
| 1067 | loader.testMethodPrefix = 'foo' |
| 1068 | self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1) |
| 1069 | |
| 1070 | loader.testMethodPrefix = 'test' |
| 1071 | self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2) |
| 1072 | |
| 1073 | # "String giving the prefix of method names which will be interpreted as |
| 1074 | # test methods" |
| 1075 | # |
| 1076 | # Implicit in the documentation is that testMethodPrefix is respected by |
| 1077 | # all loadTestsFrom* methods. |
| 1078 | def test_testMethodPrefix__loadTestsFromName(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 1079 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1080 | class Foo(unittest.TestCase): |
| 1081 | def test_1(self): pass |
| 1082 | def test_2(self): pass |
| 1083 | def foo_bar(self): pass |
| 1084 | m.Foo = Foo |
| 1085 | |
| 1086 | tests_1 = unittest.TestSuite([Foo('foo_bar')]) |
| 1087 | tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')]) |
| 1088 | |
| 1089 | loader = unittest.TestLoader() |
| 1090 | loader.testMethodPrefix = 'foo' |
| 1091 | self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1) |
| 1092 | |
| 1093 | loader.testMethodPrefix = 'test' |
| 1094 | self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2) |
| 1095 | |
| 1096 | # "String giving the prefix of method names which will be interpreted as |
| 1097 | # test methods" |
| 1098 | # |
| 1099 | # Implicit in the documentation is that testMethodPrefix is respected by |
| 1100 | # all loadTestsFrom* methods. |
| 1101 | def test_testMethodPrefix__loadTestsFromNames(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 1102 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1103 | class Foo(unittest.TestCase): |
| 1104 | def test_1(self): pass |
| 1105 | def test_2(self): pass |
| 1106 | def foo_bar(self): pass |
| 1107 | m.Foo = Foo |
| 1108 | |
| 1109 | tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])]) |
| 1110 | tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')]) |
| 1111 | tests_2 = unittest.TestSuite([tests_2]) |
| 1112 | |
| 1113 | loader = unittest.TestLoader() |
| 1114 | loader.testMethodPrefix = 'foo' |
| 1115 | self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1) |
| 1116 | |
| 1117 | loader.testMethodPrefix = 'test' |
| 1118 | self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2) |
| 1119 | |
| 1120 | # "The default value is 'test'" |
| 1121 | def test_testMethodPrefix__default_value(self): |
| 1122 | loader = unittest.TestLoader() |
Guido van Rossum | e61fd5b | 2007-07-11 12:20:59 +0000 | [diff] [blame] | 1123 | self.assertEqual(loader.testMethodPrefix, 'test') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1124 | |
| 1125 | ################################################################ |
| 1126 | ### /Tests for TestLoader.testMethodPrefix |
| 1127 | |
| 1128 | ### Tests for TestLoader.sortTestMethodsUsing |
| 1129 | ################################################################ |
| 1130 | |
| 1131 | # "Function to be used to compare method names when sorting them in |
| 1132 | # getTestCaseNames() and all the loadTestsFromX() methods" |
| 1133 | def test_sortTestMethodsUsing__loadTestsFromTestCase(self): |
| 1134 | def reversed_cmp(x, y): |
Mark Dickinson | a56c467 | 2009-01-27 18:17:45 +0000 | [diff] [blame] | 1135 | return -((x > y) - (x < y)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1136 | |
| 1137 | class Foo(unittest.TestCase): |
| 1138 | def test_1(self): pass |
| 1139 | def test_2(self): pass |
| 1140 | |
| 1141 | loader = unittest.TestLoader() |
| 1142 | loader.sortTestMethodsUsing = reversed_cmp |
| 1143 | |
| 1144 | tests = loader.suiteClass([Foo('test_2'), Foo('test_1')]) |
| 1145 | self.assertEqual(loader.loadTestsFromTestCase(Foo), tests) |
| 1146 | |
| 1147 | # "Function to be used to compare method names when sorting them in |
| 1148 | # getTestCaseNames() and all the loadTestsFromX() methods" |
| 1149 | def test_sortTestMethodsUsing__loadTestsFromModule(self): |
| 1150 | def reversed_cmp(x, y): |
Mark Dickinson | a56c467 | 2009-01-27 18:17:45 +0000 | [diff] [blame] | 1151 | return -((x > y) - (x < y)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1152 | |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 1153 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1154 | class Foo(unittest.TestCase): |
| 1155 | def test_1(self): pass |
| 1156 | def test_2(self): pass |
| 1157 | m.Foo = Foo |
| 1158 | |
| 1159 | loader = unittest.TestLoader() |
| 1160 | loader.sortTestMethodsUsing = reversed_cmp |
| 1161 | |
| 1162 | tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])] |
| 1163 | self.assertEqual(list(loader.loadTestsFromModule(m)), tests) |
| 1164 | |
| 1165 | # "Function to be used to compare method names when sorting them in |
| 1166 | # getTestCaseNames() and all the loadTestsFromX() methods" |
| 1167 | def test_sortTestMethodsUsing__loadTestsFromName(self): |
| 1168 | def reversed_cmp(x, y): |
Mark Dickinson | a56c467 | 2009-01-27 18:17:45 +0000 | [diff] [blame] | 1169 | return -((x > y) - (x < y)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1170 | |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 1171 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1172 | class Foo(unittest.TestCase): |
| 1173 | def test_1(self): pass |
| 1174 | def test_2(self): pass |
| 1175 | m.Foo = Foo |
| 1176 | |
| 1177 | loader = unittest.TestLoader() |
| 1178 | loader.sortTestMethodsUsing = reversed_cmp |
| 1179 | |
| 1180 | tests = loader.suiteClass([Foo('test_2'), Foo('test_1')]) |
| 1181 | self.assertEqual(loader.loadTestsFromName('Foo', m), tests) |
| 1182 | |
| 1183 | # "Function to be used to compare method names when sorting them in |
| 1184 | # getTestCaseNames() and all the loadTestsFromX() methods" |
| 1185 | def test_sortTestMethodsUsing__loadTestsFromNames(self): |
| 1186 | def reversed_cmp(x, y): |
Mark Dickinson | a56c467 | 2009-01-27 18:17:45 +0000 | [diff] [blame] | 1187 | return -((x > y) - (x < y)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1188 | |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 1189 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1190 | class Foo(unittest.TestCase): |
| 1191 | def test_1(self): pass |
| 1192 | def test_2(self): pass |
| 1193 | m.Foo = Foo |
| 1194 | |
| 1195 | loader = unittest.TestLoader() |
| 1196 | loader.sortTestMethodsUsing = reversed_cmp |
| 1197 | |
| 1198 | tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])] |
| 1199 | self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests) |
| 1200 | |
| 1201 | # "Function to be used to compare method names when sorting them in |
| 1202 | # getTestCaseNames()" |
| 1203 | # |
| 1204 | # Does it actually affect getTestCaseNames()? |
| 1205 | def test_sortTestMethodsUsing__getTestCaseNames(self): |
| 1206 | def reversed_cmp(x, y): |
Mark Dickinson | a56c467 | 2009-01-27 18:17:45 +0000 | [diff] [blame] | 1207 | return -((x > y) - (x < y)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1208 | |
| 1209 | class Foo(unittest.TestCase): |
| 1210 | def test_1(self): pass |
| 1211 | def test_2(self): pass |
| 1212 | |
| 1213 | loader = unittest.TestLoader() |
| 1214 | loader.sortTestMethodsUsing = reversed_cmp |
| 1215 | |
| 1216 | test_names = ['test_2', 'test_1'] |
| 1217 | self.assertEqual(loader.getTestCaseNames(Foo), test_names) |
| 1218 | |
| 1219 | # "The default value is the built-in cmp() function" |
Mark Dickinson | a56c467 | 2009-01-27 18:17:45 +0000 | [diff] [blame] | 1220 | # Since cmp is now defunct, we simply verify that the results |
| 1221 | # 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] | 1222 | def test_sortTestMethodsUsing__default_value(self): |
| 1223 | loader = unittest.TestLoader() |
Mark Dickinson | a56c467 | 2009-01-27 18:17:45 +0000 | [diff] [blame] | 1224 | |
| 1225 | class Foo(unittest.TestCase): |
| 1226 | def test_2(self): pass |
| 1227 | def test_3(self): pass |
| 1228 | def test_1(self): pass |
| 1229 | |
| 1230 | test_names = ['test_2', 'test_3', 'test_1'] |
| 1231 | self.assertEqual(loader.getTestCaseNames(Foo), sorted(test_names)) |
| 1232 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1233 | |
| 1234 | # "it can be set to None to disable the sort." |
| 1235 | # |
| 1236 | # XXX How is this different from reassigning cmp? Are the tests returned |
| 1237 | # in a random order or something? This behaviour should die |
| 1238 | def test_sortTestMethodsUsing__None(self): |
| 1239 | class Foo(unittest.TestCase): |
| 1240 | def test_1(self): pass |
| 1241 | def test_2(self): pass |
| 1242 | |
| 1243 | loader = unittest.TestLoader() |
| 1244 | loader.sortTestMethodsUsing = None |
| 1245 | |
| 1246 | test_names = ['test_2', 'test_1'] |
| 1247 | self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names)) |
| 1248 | |
| 1249 | ################################################################ |
| 1250 | ### /Tests for TestLoader.sortTestMethodsUsing |
| 1251 | |
| 1252 | ### Tests for TestLoader.suiteClass |
| 1253 | ################################################################ |
| 1254 | |
| 1255 | # "Callable object that constructs a test suite from a list of tests." |
| 1256 | def test_suiteClass__loadTestsFromTestCase(self): |
| 1257 | class Foo(unittest.TestCase): |
| 1258 | def test_1(self): pass |
| 1259 | def test_2(self): pass |
| 1260 | def foo_bar(self): pass |
| 1261 | |
| 1262 | tests = [Foo('test_1'), Foo('test_2')] |
| 1263 | |
| 1264 | loader = unittest.TestLoader() |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 1265 | loader.classSuiteClass = MyClassSuite |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1266 | self.assertEqual(loader.loadTestsFromTestCase(Foo), tests) |
| 1267 | |
| 1268 | # It is implicit in the documentation for TestLoader.suiteClass that |
| 1269 | # all TestLoader.loadTestsFrom* methods respect it. Let's make sure |
| 1270 | def test_suiteClass__loadTestsFromModule(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 1271 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1272 | class Foo(unittest.TestCase): |
| 1273 | def test_1(self): pass |
| 1274 | def test_2(self): pass |
| 1275 | def foo_bar(self): pass |
| 1276 | m.Foo = Foo |
| 1277 | |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 1278 | tests = [unittest.ClassTestSuite([Foo('test_1'), Foo('test_2')], Foo)] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1279 | |
| 1280 | loader = unittest.TestLoader() |
| 1281 | loader.suiteClass = list |
| 1282 | self.assertEqual(loader.loadTestsFromModule(m), tests) |
| 1283 | |
| 1284 | # It is implicit in the documentation for TestLoader.suiteClass that |
| 1285 | # all TestLoader.loadTestsFrom* methods respect it. Let's make sure |
| 1286 | def test_suiteClass__loadTestsFromName(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 1287 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1288 | class Foo(unittest.TestCase): |
| 1289 | def test_1(self): pass |
| 1290 | def test_2(self): pass |
| 1291 | def foo_bar(self): pass |
| 1292 | m.Foo = Foo |
| 1293 | |
| 1294 | tests = [Foo('test_1'), Foo('test_2')] |
| 1295 | |
| 1296 | loader = unittest.TestLoader() |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 1297 | loader.classSuiteClass = MyClassSuite |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1298 | self.assertEqual(loader.loadTestsFromName('Foo', m), tests) |
| 1299 | |
| 1300 | # It is implicit in the documentation for TestLoader.suiteClass that |
| 1301 | # all TestLoader.loadTestsFrom* methods respect it. Let's make sure |
| 1302 | def test_suiteClass__loadTestsFromNames(self): |
Christian Heimes | 45f9af3 | 2007-11-27 21:50:00 +0000 | [diff] [blame] | 1303 | m = types.ModuleType('m') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1304 | class Foo(unittest.TestCase): |
| 1305 | def test_1(self): pass |
| 1306 | def test_2(self): pass |
| 1307 | def foo_bar(self): pass |
| 1308 | m.Foo = Foo |
| 1309 | |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 1310 | tests = [unittest.ClassTestSuite([Foo('test_1'), Foo('test_2')], Foo)] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1311 | |
| 1312 | loader = unittest.TestLoader() |
| 1313 | loader.suiteClass = list |
| 1314 | self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests) |
| 1315 | |
| 1316 | # "The default value is the TestSuite class" |
| 1317 | def test_suiteClass__default_value(self): |
| 1318 | loader = unittest.TestLoader() |
| 1319 | self.failUnless(loader.suiteClass is unittest.TestSuite) |
| 1320 | |
| 1321 | ################################################################ |
| 1322 | ### /Tests for TestLoader.suiteClass |
| 1323 | |
| 1324 | ### Support code for Test_TestSuite |
| 1325 | ################################################################ |
| 1326 | |
| 1327 | class Foo(unittest.TestCase): |
| 1328 | def test_1(self): pass |
| 1329 | def test_2(self): pass |
| 1330 | def test_3(self): pass |
| 1331 | def runTest(self): pass |
| 1332 | |
| 1333 | def _mk_TestSuite(*names): |
| 1334 | return unittest.TestSuite(Foo(n) for n in names) |
| 1335 | |
| 1336 | ################################################################ |
| 1337 | ### /Support code for Test_TestSuite |
| 1338 | |
| 1339 | class Test_TestSuite(TestCase, TestEquality): |
| 1340 | |
| 1341 | ### Set up attributes needed by inherited tests |
| 1342 | ################################################################ |
| 1343 | |
| 1344 | # Used by TestEquality.test_eq |
| 1345 | eq_pairs = [(unittest.TestSuite(), unittest.TestSuite()) |
| 1346 | ,(unittest.TestSuite(), unittest.TestSuite([])) |
| 1347 | ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))] |
| 1348 | |
| 1349 | # Used by TestEquality.test_ne |
| 1350 | ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1')) |
| 1351 | ,(unittest.TestSuite([]), _mk_TestSuite('test_1')) |
| 1352 | ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3')) |
| 1353 | ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))] |
| 1354 | |
| 1355 | ################################################################ |
| 1356 | ### /Set up attributes needed by inherited tests |
| 1357 | |
| 1358 | ### Tests for TestSuite.__init__ |
| 1359 | ################################################################ |
| 1360 | |
| 1361 | # "class TestSuite([tests])" |
| 1362 | # |
| 1363 | # The tests iterable should be optional |
| 1364 | def test_init__tests_optional(self): |
| 1365 | suite = unittest.TestSuite() |
| 1366 | |
| 1367 | self.assertEqual(suite.countTestCases(), 0) |
| 1368 | |
| 1369 | # "class TestSuite([tests])" |
| 1370 | # ... |
| 1371 | # "If tests is given, it must be an iterable of individual test cases |
| 1372 | # or other test suites that will be used to build the suite initially" |
| 1373 | # |
| 1374 | # TestSuite should deal with empty tests iterables by allowing the |
| 1375 | # creation of an empty suite |
| 1376 | def test_init__empty_tests(self): |
| 1377 | suite = unittest.TestSuite([]) |
| 1378 | |
| 1379 | self.assertEqual(suite.countTestCases(), 0) |
| 1380 | |
| 1381 | # "class TestSuite([tests])" |
| 1382 | # ... |
| 1383 | # "If tests is given, it must be an iterable of individual test cases |
| 1384 | # or other test suites that will be used to build the suite initially" |
| 1385 | # |
| 1386 | # TestSuite should allow any iterable to provide tests |
| 1387 | def test_init__tests_from_any_iterable(self): |
| 1388 | def tests(): |
| 1389 | yield unittest.FunctionTestCase(lambda: None) |
| 1390 | yield unittest.FunctionTestCase(lambda: None) |
| 1391 | |
| 1392 | suite_1 = unittest.TestSuite(tests()) |
| 1393 | self.assertEqual(suite_1.countTestCases(), 2) |
| 1394 | |
| 1395 | suite_2 = unittest.TestSuite(suite_1) |
| 1396 | self.assertEqual(suite_2.countTestCases(), 2) |
| 1397 | |
| 1398 | suite_3 = unittest.TestSuite(set(suite_1)) |
| 1399 | self.assertEqual(suite_3.countTestCases(), 2) |
| 1400 | |
| 1401 | # "class TestSuite([tests])" |
| 1402 | # ... |
| 1403 | # "If tests is given, it must be an iterable of individual test cases |
| 1404 | # or other test suites that will be used to build the suite initially" |
| 1405 | # |
| 1406 | # Does TestSuite() also allow other TestSuite() instances to be present |
| 1407 | # in the tests iterable? |
| 1408 | def test_init__TestSuite_instances_in_tests(self): |
| 1409 | def tests(): |
| 1410 | ftc = unittest.FunctionTestCase(lambda: None) |
| 1411 | yield unittest.TestSuite([ftc]) |
| 1412 | yield unittest.FunctionTestCase(lambda: None) |
| 1413 | |
| 1414 | suite = unittest.TestSuite(tests()) |
| 1415 | self.assertEqual(suite.countTestCases(), 2) |
| 1416 | |
| 1417 | ################################################################ |
| 1418 | ### /Tests for TestSuite.__init__ |
| 1419 | |
| 1420 | # Container types should support the iter protocol |
| 1421 | def test_iter(self): |
| 1422 | test1 = unittest.FunctionTestCase(lambda: None) |
| 1423 | test2 = unittest.FunctionTestCase(lambda: None) |
| 1424 | suite = unittest.TestSuite((test1, test2)) |
| 1425 | |
| 1426 | self.assertEqual(list(suite), [test1, test2]) |
| 1427 | |
| 1428 | # "Return the number of tests represented by the this test object. |
| 1429 | # ...this method is also implemented by the TestSuite class, which can |
| 1430 | # return larger [greater than 1] values" |
| 1431 | # |
| 1432 | # Presumably an empty TestSuite returns 0? |
| 1433 | def test_countTestCases_zero_simple(self): |
| 1434 | suite = unittest.TestSuite() |
| 1435 | |
| 1436 | self.assertEqual(suite.countTestCases(), 0) |
| 1437 | |
| 1438 | # "Return the number of tests represented by the this test object. |
| 1439 | # ...this method is also implemented by the TestSuite class, which can |
| 1440 | # return larger [greater than 1] values" |
| 1441 | # |
| 1442 | # Presumably an empty TestSuite (even if it contains other empty |
| 1443 | # TestSuite instances) returns 0? |
| 1444 | def test_countTestCases_zero_nested(self): |
| 1445 | class Test1(unittest.TestCase): |
| 1446 | def test(self): |
| 1447 | pass |
| 1448 | |
| 1449 | suite = unittest.TestSuite([unittest.TestSuite()]) |
| 1450 | |
| 1451 | self.assertEqual(suite.countTestCases(), 0) |
| 1452 | |
| 1453 | # "Return the number of tests represented by the this test object. |
| 1454 | # ...this method is also implemented by the TestSuite class, which can |
| 1455 | # return larger [greater than 1] values" |
| 1456 | def test_countTestCases_simple(self): |
| 1457 | test1 = unittest.FunctionTestCase(lambda: None) |
| 1458 | test2 = unittest.FunctionTestCase(lambda: None) |
| 1459 | suite = unittest.TestSuite((test1, test2)) |
| 1460 | |
| 1461 | self.assertEqual(suite.countTestCases(), 2) |
| 1462 | |
| 1463 | # "Return the number of tests represented by the this test object. |
| 1464 | # ...this method is also implemented by the TestSuite class, which can |
| 1465 | # return larger [greater than 1] values" |
| 1466 | # |
| 1467 | # Make sure this holds for nested TestSuite instances, too |
| 1468 | def test_countTestCases_nested(self): |
| 1469 | class Test1(unittest.TestCase): |
| 1470 | def test1(self): pass |
| 1471 | def test2(self): pass |
| 1472 | |
| 1473 | test2 = unittest.FunctionTestCase(lambda: None) |
| 1474 | test3 = unittest.FunctionTestCase(lambda: None) |
| 1475 | child = unittest.TestSuite((Test1('test2'), test2)) |
| 1476 | parent = unittest.TestSuite((test3, child, Test1('test1'))) |
| 1477 | |
| 1478 | self.assertEqual(parent.countTestCases(), 4) |
| 1479 | |
| 1480 | # "Run the tests associated with this suite, collecting the result into |
| 1481 | # the test result object passed as result." |
| 1482 | # |
| 1483 | # And if there are no tests? What then? |
| 1484 | def test_run__empty_suite(self): |
| 1485 | events = [] |
| 1486 | result = LoggingResult(events) |
| 1487 | |
| 1488 | suite = unittest.TestSuite() |
| 1489 | |
| 1490 | suite.run(result) |
| 1491 | |
| 1492 | self.assertEqual(events, []) |
| 1493 | |
| 1494 | # "Note that unlike TestCase.run(), TestSuite.run() requires the |
| 1495 | # "result object to be passed in." |
| 1496 | def test_run__requires_result(self): |
| 1497 | suite = unittest.TestSuite() |
| 1498 | |
| 1499 | try: |
| 1500 | suite.run() |
| 1501 | except TypeError: |
| 1502 | pass |
| 1503 | else: |
| 1504 | self.fail("Failed to raise TypeError") |
| 1505 | |
| 1506 | # "Run the tests associated with this suite, collecting the result into |
| 1507 | # the test result object passed as result." |
| 1508 | def test_run(self): |
| 1509 | events = [] |
| 1510 | result = LoggingResult(events) |
| 1511 | |
| 1512 | class LoggingCase(unittest.TestCase): |
| 1513 | def run(self, result): |
| 1514 | events.append('run %s' % self._testMethodName) |
| 1515 | |
| 1516 | def test1(self): pass |
| 1517 | def test2(self): pass |
| 1518 | |
| 1519 | tests = [LoggingCase('test1'), LoggingCase('test2')] |
| 1520 | |
| 1521 | unittest.TestSuite(tests).run(result) |
| 1522 | |
| 1523 | self.assertEqual(events, ['run test1', 'run test2']) |
| 1524 | |
| 1525 | # "Add a TestCase ... to the suite" |
| 1526 | def test_addTest__TestCase(self): |
| 1527 | class Foo(unittest.TestCase): |
| 1528 | def test(self): pass |
| 1529 | |
| 1530 | test = Foo('test') |
| 1531 | suite = unittest.TestSuite() |
| 1532 | |
| 1533 | suite.addTest(test) |
| 1534 | |
| 1535 | self.assertEqual(suite.countTestCases(), 1) |
| 1536 | self.assertEqual(list(suite), [test]) |
| 1537 | |
| 1538 | # "Add a ... TestSuite to the suite" |
| 1539 | def test_addTest__TestSuite(self): |
| 1540 | class Foo(unittest.TestCase): |
| 1541 | def test(self): pass |
| 1542 | |
| 1543 | suite_2 = unittest.TestSuite([Foo('test')]) |
| 1544 | |
| 1545 | suite = unittest.TestSuite() |
| 1546 | suite.addTest(suite_2) |
| 1547 | |
| 1548 | self.assertEqual(suite.countTestCases(), 1) |
| 1549 | self.assertEqual(list(suite), [suite_2]) |
| 1550 | |
| 1551 | # "Add all the tests from an iterable of TestCase and TestSuite |
| 1552 | # instances to this test suite." |
| 1553 | # |
| 1554 | # "This is equivalent to iterating over tests, calling addTest() for |
| 1555 | # each element" |
| 1556 | def test_addTests(self): |
| 1557 | class Foo(unittest.TestCase): |
| 1558 | def test_1(self): pass |
| 1559 | def test_2(self): pass |
| 1560 | |
| 1561 | test_1 = Foo('test_1') |
| 1562 | test_2 = Foo('test_2') |
| 1563 | inner_suite = unittest.TestSuite([test_2]) |
| 1564 | |
| 1565 | def gen(): |
| 1566 | yield test_1 |
| 1567 | yield test_2 |
| 1568 | yield inner_suite |
| 1569 | |
| 1570 | suite_1 = unittest.TestSuite() |
| 1571 | suite_1.addTests(gen()) |
| 1572 | |
| 1573 | self.assertEqual(list(suite_1), list(gen())) |
| 1574 | |
| 1575 | # "This is equivalent to iterating over tests, calling addTest() for |
| 1576 | # each element" |
| 1577 | suite_2 = unittest.TestSuite() |
| 1578 | for t in gen(): |
| 1579 | suite_2.addTest(t) |
| 1580 | |
| 1581 | self.assertEqual(suite_1, suite_2) |
| 1582 | |
| 1583 | # "Add all the tests from an iterable of TestCase and TestSuite |
| 1584 | # instances to this test suite." |
| 1585 | # |
| 1586 | # What happens if it doesn't get an iterable? |
| 1587 | def test_addTest__noniterable(self): |
| 1588 | suite = unittest.TestSuite() |
| 1589 | |
| 1590 | try: |
| 1591 | suite.addTests(5) |
| 1592 | except TypeError: |
| 1593 | pass |
| 1594 | else: |
| 1595 | self.fail("Failed to raise TypeError") |
| 1596 | |
| 1597 | def test_addTest__noncallable(self): |
| 1598 | suite = unittest.TestSuite() |
| 1599 | self.assertRaises(TypeError, suite.addTest, 5) |
| 1600 | |
| 1601 | def test_addTest__casesuiteclass(self): |
| 1602 | suite = unittest.TestSuite() |
| 1603 | self.assertRaises(TypeError, suite.addTest, Test_TestSuite) |
| 1604 | self.assertRaises(TypeError, suite.addTest, unittest.TestSuite) |
| 1605 | |
| 1606 | def test_addTests__string(self): |
| 1607 | suite = unittest.TestSuite() |
| 1608 | self.assertRaises(TypeError, suite.addTests, "foo") |
| 1609 | |
| 1610 | |
| 1611 | class Test_FunctionTestCase(TestCase): |
| 1612 | |
| 1613 | # "Return the number of tests represented by the this test object. For |
| 1614 | # TestCase instances, this will always be 1" |
| 1615 | def test_countTestCases(self): |
| 1616 | test = unittest.FunctionTestCase(lambda: None) |
| 1617 | |
| 1618 | self.assertEqual(test.countTestCases(), 1) |
| 1619 | |
| 1620 | # "When a setUp() method is defined, the test runner will run that method |
| 1621 | # prior to each test. Likewise, if a tearDown() method is defined, the |
| 1622 | # test runner will invoke that method after each test. In the example, |
| 1623 | # setUp() was used to create a fresh sequence for each test." |
| 1624 | # |
| 1625 | # Make sure the proper call order is maintained, even if setUp() raises |
| 1626 | # an exception. |
| 1627 | def test_run_call_order__error_in_setUp(self): |
| 1628 | events = [] |
| 1629 | result = LoggingResult(events) |
| 1630 | |
| 1631 | def setUp(): |
| 1632 | events.append('setUp') |
| 1633 | raise RuntimeError('raised by setUp') |
| 1634 | |
| 1635 | def test(): |
| 1636 | events.append('test') |
| 1637 | |
| 1638 | def tearDown(): |
| 1639 | events.append('tearDown') |
| 1640 | |
| 1641 | expected = ['startTest', 'setUp', 'addError', 'stopTest'] |
| 1642 | unittest.FunctionTestCase(test, setUp, tearDown).run(result) |
| 1643 | self.assertEqual(events, expected) |
| 1644 | |
| 1645 | # "When a setUp() method is defined, the test runner will run that method |
| 1646 | # prior to each test. Likewise, if a tearDown() method is defined, the |
| 1647 | # test runner will invoke that method after each test. In the example, |
| 1648 | # setUp() was used to create a fresh sequence for each test." |
| 1649 | # |
| 1650 | # Make sure the proper call order is maintained, even if the test raises |
| 1651 | # an error (as opposed to a failure). |
| 1652 | def test_run_call_order__error_in_test(self): |
| 1653 | events = [] |
| 1654 | result = LoggingResult(events) |
| 1655 | |
| 1656 | def setUp(): |
| 1657 | events.append('setUp') |
| 1658 | |
| 1659 | def test(): |
| 1660 | events.append('test') |
| 1661 | raise RuntimeError('raised by test') |
| 1662 | |
| 1663 | def tearDown(): |
| 1664 | events.append('tearDown') |
| 1665 | |
| 1666 | expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown', |
| 1667 | 'stopTest'] |
| 1668 | unittest.FunctionTestCase(test, setUp, tearDown).run(result) |
| 1669 | self.assertEqual(events, expected) |
| 1670 | |
| 1671 | # "When a setUp() method is defined, the test runner will run that method |
| 1672 | # prior to each test. Likewise, if a tearDown() method is defined, the |
| 1673 | # test runner will invoke that method after each test. In the example, |
| 1674 | # setUp() was used to create a fresh sequence for each test." |
| 1675 | # |
| 1676 | # Make sure the proper call order is maintained, even if the test signals |
| 1677 | # a failure (as opposed to an error). |
| 1678 | def test_run_call_order__failure_in_test(self): |
| 1679 | events = [] |
| 1680 | result = LoggingResult(events) |
| 1681 | |
| 1682 | def setUp(): |
| 1683 | events.append('setUp') |
| 1684 | |
| 1685 | def test(): |
| 1686 | events.append('test') |
| 1687 | self.fail('raised by test') |
| 1688 | |
| 1689 | def tearDown(): |
| 1690 | events.append('tearDown') |
| 1691 | |
| 1692 | expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown', |
| 1693 | 'stopTest'] |
| 1694 | unittest.FunctionTestCase(test, setUp, tearDown).run(result) |
| 1695 | self.assertEqual(events, expected) |
| 1696 | |
| 1697 | # "When a setUp() method is defined, the test runner will run that method |
| 1698 | # prior to each test. Likewise, if a tearDown() method is defined, the |
| 1699 | # test runner will invoke that method after each test. In the example, |
| 1700 | # setUp() was used to create a fresh sequence for each test." |
| 1701 | # |
| 1702 | # Make sure the proper call order is maintained, even if tearDown() raises |
| 1703 | # an exception. |
| 1704 | def test_run_call_order__error_in_tearDown(self): |
| 1705 | events = [] |
| 1706 | result = LoggingResult(events) |
| 1707 | |
| 1708 | def setUp(): |
| 1709 | events.append('setUp') |
| 1710 | |
| 1711 | def test(): |
| 1712 | events.append('test') |
| 1713 | |
| 1714 | def tearDown(): |
| 1715 | events.append('tearDown') |
| 1716 | raise RuntimeError('raised by tearDown') |
| 1717 | |
| 1718 | expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError', |
| 1719 | 'stopTest'] |
| 1720 | unittest.FunctionTestCase(test, setUp, tearDown).run(result) |
| 1721 | self.assertEqual(events, expected) |
| 1722 | |
| 1723 | # "Return a string identifying the specific test case." |
| 1724 | # |
| 1725 | # Because of the vague nature of the docs, I'm not going to lock this |
| 1726 | # test down too much. Really all that can be asserted is that the id() |
| 1727 | # will be a string (either 8-byte or unicode -- again, because the docs |
| 1728 | # just say "string") |
| 1729 | def test_id(self): |
| 1730 | test = unittest.FunctionTestCase(lambda: None) |
| 1731 | |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 1732 | self.failUnless(isinstance(test.id(), str)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1733 | |
| 1734 | # "Returns a one-line description of the test, or None if no description |
| 1735 | # has been provided. The default implementation of this method returns |
| 1736 | # the first line of the test method's docstring, if available, or None." |
| 1737 | def test_shortDescription__no_docstring(self): |
| 1738 | test = unittest.FunctionTestCase(lambda: None) |
| 1739 | |
| 1740 | self.assertEqual(test.shortDescription(), None) |
| 1741 | |
| 1742 | # "Returns a one-line description of the test, or None if no description |
| 1743 | # has been provided. The default implementation of this method returns |
| 1744 | # the first line of the test method's docstring, if available, or None." |
| 1745 | def test_shortDescription__singleline_docstring(self): |
| 1746 | desc = "this tests foo" |
| 1747 | test = unittest.FunctionTestCase(lambda: None, description=desc) |
| 1748 | |
| 1749 | self.assertEqual(test.shortDescription(), "this tests foo") |
| 1750 | |
| 1751 | class Test_TestResult(TestCase): |
| 1752 | # Note: there are not separate tests for TestResult.wasSuccessful(), |
| 1753 | # TestResult.errors, TestResult.failures, TestResult.testsRun or |
| 1754 | # TestResult.shouldStop because these only have meaning in terms of |
| 1755 | # other TestResult methods. |
| 1756 | # |
| 1757 | # Accordingly, tests for the aforenamed attributes are incorporated |
| 1758 | # in with the tests for the defining methods. |
| 1759 | ################################################################ |
| 1760 | |
| 1761 | def test_init(self): |
| 1762 | result = unittest.TestResult() |
| 1763 | |
| 1764 | self.failUnless(result.wasSuccessful()) |
| 1765 | self.assertEqual(len(result.errors), 0) |
| 1766 | self.assertEqual(len(result.failures), 0) |
| 1767 | self.assertEqual(result.testsRun, 0) |
| 1768 | self.assertEqual(result.shouldStop, False) |
| 1769 | |
| 1770 | # "This method can be called to signal that the set of tests being |
| 1771 | # run should be aborted by setting the TestResult's shouldStop |
| 1772 | # attribute to True." |
| 1773 | def test_stop(self): |
| 1774 | result = unittest.TestResult() |
| 1775 | |
| 1776 | result.stop() |
| 1777 | |
| 1778 | self.assertEqual(result.shouldStop, True) |
| 1779 | |
| 1780 | # "Called when the test case test is about to be run. The default |
| 1781 | # implementation simply increments the instance's testsRun counter." |
| 1782 | def test_startTest(self): |
| 1783 | class Foo(unittest.TestCase): |
| 1784 | def test_1(self): |
| 1785 | pass |
| 1786 | |
| 1787 | test = Foo('test_1') |
| 1788 | |
| 1789 | result = unittest.TestResult() |
| 1790 | |
| 1791 | result.startTest(test) |
| 1792 | |
| 1793 | self.failUnless(result.wasSuccessful()) |
| 1794 | self.assertEqual(len(result.errors), 0) |
| 1795 | self.assertEqual(len(result.failures), 0) |
| 1796 | self.assertEqual(result.testsRun, 1) |
| 1797 | self.assertEqual(result.shouldStop, False) |
| 1798 | |
| 1799 | result.stopTest(test) |
| 1800 | |
| 1801 | # "Called after the test case test has been executed, regardless of |
| 1802 | # the outcome. The default implementation does nothing." |
| 1803 | def test_stopTest(self): |
| 1804 | class Foo(unittest.TestCase): |
| 1805 | def test_1(self): |
| 1806 | pass |
| 1807 | |
| 1808 | test = Foo('test_1') |
| 1809 | |
| 1810 | result = unittest.TestResult() |
| 1811 | |
| 1812 | result.startTest(test) |
| 1813 | |
| 1814 | self.failUnless(result.wasSuccessful()) |
| 1815 | self.assertEqual(len(result.errors), 0) |
| 1816 | self.assertEqual(len(result.failures), 0) |
| 1817 | self.assertEqual(result.testsRun, 1) |
| 1818 | self.assertEqual(result.shouldStop, False) |
| 1819 | |
| 1820 | result.stopTest(test) |
| 1821 | |
| 1822 | # Same tests as above; make sure nothing has changed |
| 1823 | self.failUnless(result.wasSuccessful()) |
| 1824 | self.assertEqual(len(result.errors), 0) |
| 1825 | self.assertEqual(len(result.failures), 0) |
| 1826 | self.assertEqual(result.testsRun, 1) |
| 1827 | self.assertEqual(result.shouldStop, False) |
| 1828 | |
| 1829 | # "addSuccess(test)" |
| 1830 | # ... |
| 1831 | # "Called when the test case test succeeds" |
| 1832 | # ... |
| 1833 | # "wasSuccessful() - Returns True if all tests run so far have passed, |
| 1834 | # otherwise returns False" |
| 1835 | # ... |
| 1836 | # "testsRun - The total number of tests run so far." |
| 1837 | # ... |
| 1838 | # "errors - A list containing 2-tuples of TestCase instances and |
| 1839 | # formatted tracebacks. Each tuple represents a test which raised an |
| 1840 | # unexpected exception. Contains formatted |
| 1841 | # tracebacks instead of sys.exc_info() results." |
| 1842 | # ... |
| 1843 | # "failures - A list containing 2-tuples of TestCase instances and |
| 1844 | # formatted tracebacks. Each tuple represents a test where a failure was |
| 1845 | # explicitly signalled using the TestCase.fail*() or TestCase.assert*() |
| 1846 | # methods. Contains formatted tracebacks instead |
| 1847 | # of sys.exc_info() results." |
| 1848 | def test_addSuccess(self): |
| 1849 | class Foo(unittest.TestCase): |
| 1850 | def test_1(self): |
| 1851 | pass |
| 1852 | |
| 1853 | test = Foo('test_1') |
| 1854 | |
| 1855 | result = unittest.TestResult() |
| 1856 | |
| 1857 | result.startTest(test) |
| 1858 | result.addSuccess(test) |
| 1859 | result.stopTest(test) |
| 1860 | |
| 1861 | self.failUnless(result.wasSuccessful()) |
| 1862 | self.assertEqual(len(result.errors), 0) |
| 1863 | self.assertEqual(len(result.failures), 0) |
| 1864 | self.assertEqual(result.testsRun, 1) |
| 1865 | self.assertEqual(result.shouldStop, False) |
| 1866 | |
| 1867 | # "addFailure(test, err)" |
| 1868 | # ... |
| 1869 | # "Called when the test case test signals a failure. err is a tuple of |
| 1870 | # the form returned by sys.exc_info(): (type, value, traceback)" |
| 1871 | # ... |
| 1872 | # "wasSuccessful() - Returns True if all tests run so far have passed, |
| 1873 | # otherwise returns False" |
| 1874 | # ... |
| 1875 | # "testsRun - The total number of tests run so far." |
| 1876 | # ... |
| 1877 | # "errors - A list containing 2-tuples of TestCase instances and |
| 1878 | # formatted tracebacks. Each tuple represents a test which raised an |
| 1879 | # unexpected exception. Contains formatted |
| 1880 | # tracebacks instead of sys.exc_info() results." |
| 1881 | # ... |
| 1882 | # "failures - A list containing 2-tuples of TestCase instances and |
| 1883 | # formatted tracebacks. Each tuple represents a test where a failure was |
| 1884 | # explicitly signalled using the TestCase.fail*() or TestCase.assert*() |
| 1885 | # methods. Contains formatted tracebacks instead |
| 1886 | # of sys.exc_info() results." |
| 1887 | def test_addFailure(self): |
| 1888 | import sys |
| 1889 | |
| 1890 | class Foo(unittest.TestCase): |
| 1891 | def test_1(self): |
| 1892 | pass |
| 1893 | |
| 1894 | test = Foo('test_1') |
| 1895 | try: |
| 1896 | test.fail("foo") |
| 1897 | except: |
| 1898 | exc_info_tuple = sys.exc_info() |
| 1899 | |
| 1900 | result = unittest.TestResult() |
| 1901 | |
| 1902 | result.startTest(test) |
| 1903 | result.addFailure(test, exc_info_tuple) |
| 1904 | result.stopTest(test) |
| 1905 | |
| 1906 | self.failIf(result.wasSuccessful()) |
| 1907 | self.assertEqual(len(result.errors), 0) |
| 1908 | self.assertEqual(len(result.failures), 1) |
| 1909 | self.assertEqual(result.testsRun, 1) |
| 1910 | self.assertEqual(result.shouldStop, False) |
| 1911 | |
| 1912 | test_case, formatted_exc = result.failures[0] |
| 1913 | self.failUnless(test_case is test) |
| 1914 | self.failUnless(isinstance(formatted_exc, str)) |
| 1915 | |
| 1916 | # "addError(test, err)" |
| 1917 | # ... |
| 1918 | # "Called when the test case test raises an unexpected exception err |
| 1919 | # is a tuple of the form returned by sys.exc_info(): |
| 1920 | # (type, value, traceback)" |
| 1921 | # ... |
| 1922 | # "wasSuccessful() - Returns True if all tests run so far have passed, |
| 1923 | # otherwise returns False" |
| 1924 | # ... |
| 1925 | # "testsRun - The total number of tests run so far." |
| 1926 | # ... |
| 1927 | # "errors - A list containing 2-tuples of TestCase instances and |
| 1928 | # formatted tracebacks. Each tuple represents a test which raised an |
| 1929 | # unexpected exception. Contains formatted |
| 1930 | # tracebacks instead of sys.exc_info() results." |
| 1931 | # ... |
| 1932 | # "failures - A list containing 2-tuples of TestCase instances and |
| 1933 | # formatted tracebacks. Each tuple represents a test where a failure was |
| 1934 | # explicitly signalled using the TestCase.fail*() or TestCase.assert*() |
| 1935 | # methods. Contains formatted tracebacks instead |
| 1936 | # of sys.exc_info() results." |
| 1937 | def test_addError(self): |
| 1938 | import sys |
| 1939 | |
| 1940 | class Foo(unittest.TestCase): |
| 1941 | def test_1(self): |
| 1942 | pass |
| 1943 | |
| 1944 | test = Foo('test_1') |
| 1945 | try: |
| 1946 | raise TypeError() |
| 1947 | except: |
| 1948 | exc_info_tuple = sys.exc_info() |
| 1949 | |
| 1950 | result = unittest.TestResult() |
| 1951 | |
| 1952 | result.startTest(test) |
| 1953 | result.addError(test, exc_info_tuple) |
| 1954 | result.stopTest(test) |
| 1955 | |
| 1956 | self.failIf(result.wasSuccessful()) |
| 1957 | self.assertEqual(len(result.errors), 1) |
| 1958 | self.assertEqual(len(result.failures), 0) |
| 1959 | self.assertEqual(result.testsRun, 1) |
| 1960 | self.assertEqual(result.shouldStop, False) |
| 1961 | |
| 1962 | test_case, formatted_exc = result.errors[0] |
| 1963 | self.failUnless(test_case is test) |
| 1964 | self.failUnless(isinstance(formatted_exc, str)) |
| 1965 | |
| 1966 | ### Support code for Test_TestCase |
| 1967 | ################################################################ |
| 1968 | |
| 1969 | class Foo(unittest.TestCase): |
| 1970 | def runTest(self): pass |
| 1971 | def test1(self): pass |
| 1972 | |
| 1973 | class Bar(Foo): |
| 1974 | def test2(self): pass |
| 1975 | |
| 1976 | ################################################################ |
| 1977 | ### /Support code for Test_TestCase |
| 1978 | |
| 1979 | class Test_TestCase(TestCase, TestEquality, TestHashing): |
| 1980 | |
| 1981 | ### Set up attributes used by inherited tests |
| 1982 | ################################################################ |
| 1983 | |
| 1984 | # Used by TestHashing.test_hash and TestEquality.test_eq |
| 1985 | eq_pairs = [(Foo('test1'), Foo('test1'))] |
| 1986 | |
| 1987 | # Used by TestEquality.test_ne |
| 1988 | ne_pairs = [(Foo('test1'), Foo('runTest')) |
| 1989 | ,(Foo('test1'), Bar('test1')) |
| 1990 | ,(Foo('test1'), Bar('test2'))] |
| 1991 | |
| 1992 | ################################################################ |
| 1993 | ### /Set up attributes used by inherited tests |
| 1994 | |
| 1995 | |
| 1996 | # "class TestCase([methodName])" |
| 1997 | # ... |
| 1998 | # "Each instance of TestCase will run a single test method: the |
| 1999 | # method named methodName." |
| 2000 | # ... |
| 2001 | # "methodName defaults to "runTest"." |
| 2002 | # |
| 2003 | # Make sure it really is optional, and that it defaults to the proper |
| 2004 | # thing. |
| 2005 | def test_init__no_test_name(self): |
| 2006 | class Test(unittest.TestCase): |
| 2007 | def runTest(self): raise MyException() |
| 2008 | def test(self): pass |
| 2009 | |
| 2010 | self.assertEqual(Test().id()[-13:], '.Test.runTest') |
| 2011 | |
| 2012 | # "class TestCase([methodName])" |
| 2013 | # ... |
| 2014 | # "Each instance of TestCase will run a single test method: the |
| 2015 | # method named methodName." |
| 2016 | def test_init__test_name__valid(self): |
| 2017 | class Test(unittest.TestCase): |
| 2018 | def runTest(self): raise MyException() |
| 2019 | def test(self): pass |
| 2020 | |
| 2021 | self.assertEqual(Test('test').id()[-10:], '.Test.test') |
| 2022 | |
| 2023 | # "class TestCase([methodName])" |
| 2024 | # ... |
| 2025 | # "Each instance of TestCase will run a single test method: the |
| 2026 | # method named methodName." |
| 2027 | def test_init__test_name__invalid(self): |
| 2028 | class Test(unittest.TestCase): |
| 2029 | def runTest(self): raise MyException() |
| 2030 | def test(self): pass |
| 2031 | |
| 2032 | try: |
| 2033 | Test('testfoo') |
| 2034 | except ValueError: |
| 2035 | pass |
| 2036 | else: |
| 2037 | self.fail("Failed to raise ValueError") |
| 2038 | |
| 2039 | # "Return the number of tests represented by the this test object. For |
| 2040 | # TestCase instances, this will always be 1" |
| 2041 | def test_countTestCases(self): |
| 2042 | class Foo(unittest.TestCase): |
| 2043 | def test(self): pass |
| 2044 | |
| 2045 | self.assertEqual(Foo('test').countTestCases(), 1) |
| 2046 | |
| 2047 | # "Return the default type of test result object to be used to run this |
| 2048 | # test. For TestCase instances, this will always be |
| 2049 | # unittest.TestResult; subclasses of TestCase should |
| 2050 | # override this as necessary." |
| 2051 | def test_defaultTestResult(self): |
| 2052 | class Foo(unittest.TestCase): |
| 2053 | def runTest(self): |
| 2054 | pass |
| 2055 | |
| 2056 | result = Foo().defaultTestResult() |
| 2057 | self.assertEqual(type(result), unittest.TestResult) |
| 2058 | |
| 2059 | # "When a setUp() method is defined, the test runner will run that method |
| 2060 | # prior to each test. Likewise, if a tearDown() method is defined, the |
| 2061 | # test runner will invoke that method after each test. In the example, |
| 2062 | # setUp() was used to create a fresh sequence for each test." |
| 2063 | # |
| 2064 | # Make sure the proper call order is maintained, even if setUp() raises |
| 2065 | # an exception. |
| 2066 | def test_run_call_order__error_in_setUp(self): |
| 2067 | events = [] |
| 2068 | result = LoggingResult(events) |
| 2069 | |
| 2070 | class Foo(unittest.TestCase): |
| 2071 | def setUp(self): |
| 2072 | events.append('setUp') |
| 2073 | raise RuntimeError('raised by Foo.setUp') |
| 2074 | |
| 2075 | def test(self): |
| 2076 | events.append('test') |
| 2077 | |
| 2078 | def tearDown(self): |
| 2079 | events.append('tearDown') |
| 2080 | |
| 2081 | Foo('test').run(result) |
| 2082 | expected = ['startTest', 'setUp', 'addError', 'stopTest'] |
| 2083 | self.assertEqual(events, expected) |
| 2084 | |
| 2085 | # "When a setUp() method is defined, the test runner will run that method |
| 2086 | # prior to each test. Likewise, if a tearDown() method is defined, the |
| 2087 | # test runner will invoke that method after each test. In the example, |
| 2088 | # setUp() was used to create a fresh sequence for each test." |
| 2089 | # |
| 2090 | # Make sure the proper call order is maintained, even if the test raises |
| 2091 | # an error (as opposed to a failure). |
| 2092 | def test_run_call_order__error_in_test(self): |
| 2093 | events = [] |
| 2094 | result = LoggingResult(events) |
| 2095 | |
| 2096 | class Foo(unittest.TestCase): |
| 2097 | def setUp(self): |
| 2098 | events.append('setUp') |
| 2099 | |
| 2100 | def test(self): |
| 2101 | events.append('test') |
| 2102 | raise RuntimeError('raised by Foo.test') |
| 2103 | |
| 2104 | def tearDown(self): |
| 2105 | events.append('tearDown') |
| 2106 | |
| 2107 | expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown', |
| 2108 | 'stopTest'] |
| 2109 | Foo('test').run(result) |
| 2110 | self.assertEqual(events, expected) |
| 2111 | |
| 2112 | # "When a setUp() method is defined, the test runner will run that method |
| 2113 | # prior to each test. Likewise, if a tearDown() method is defined, the |
| 2114 | # test runner will invoke that method after each test. In the example, |
| 2115 | # setUp() was used to create a fresh sequence for each test." |
| 2116 | # |
| 2117 | # Make sure the proper call order is maintained, even if the test signals |
| 2118 | # a failure (as opposed to an error). |
| 2119 | def test_run_call_order__failure_in_test(self): |
| 2120 | events = [] |
| 2121 | result = LoggingResult(events) |
| 2122 | |
| 2123 | class Foo(unittest.TestCase): |
| 2124 | def setUp(self): |
| 2125 | events.append('setUp') |
| 2126 | |
| 2127 | def test(self): |
| 2128 | events.append('test') |
| 2129 | self.fail('raised by Foo.test') |
| 2130 | |
| 2131 | def tearDown(self): |
| 2132 | events.append('tearDown') |
| 2133 | |
| 2134 | expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown', |
| 2135 | 'stopTest'] |
| 2136 | Foo('test').run(result) |
| 2137 | self.assertEqual(events, expected) |
| 2138 | |
| 2139 | # "When a setUp() method is defined, the test runner will run that method |
| 2140 | # prior to each test. Likewise, if a tearDown() method is defined, the |
| 2141 | # test runner will invoke that method after each test. In the example, |
| 2142 | # setUp() was used to create a fresh sequence for each test." |
| 2143 | # |
| 2144 | # Make sure the proper call order is maintained, even if tearDown() raises |
| 2145 | # an exception. |
| 2146 | def test_run_call_order__error_in_tearDown(self): |
| 2147 | events = [] |
| 2148 | result = LoggingResult(events) |
| 2149 | |
| 2150 | class Foo(unittest.TestCase): |
| 2151 | def setUp(self): |
| 2152 | events.append('setUp') |
| 2153 | |
| 2154 | def test(self): |
| 2155 | events.append('test') |
| 2156 | |
| 2157 | def tearDown(self): |
| 2158 | events.append('tearDown') |
| 2159 | raise RuntimeError('raised by Foo.tearDown') |
| 2160 | |
| 2161 | Foo('test').run(result) |
| 2162 | expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError', |
| 2163 | 'stopTest'] |
| 2164 | self.assertEqual(events, expected) |
| 2165 | |
| 2166 | # "This class attribute gives the exception raised by the test() method. |
| 2167 | # If a test framework needs to use a specialized exception, possibly to |
| 2168 | # carry additional information, it must subclass this exception in |
| 2169 | # order to ``play fair'' with the framework. The initial value of this |
| 2170 | # attribute is AssertionError" |
| 2171 | def test_failureException__default(self): |
| 2172 | class Foo(unittest.TestCase): |
| 2173 | def test(self): |
| 2174 | pass |
| 2175 | |
| 2176 | self.failUnless(Foo('test').failureException is AssertionError) |
| 2177 | |
| 2178 | # "This class attribute gives the exception raised by the test() method. |
| 2179 | # If a test framework needs to use a specialized exception, possibly to |
| 2180 | # carry additional information, it must subclass this exception in |
| 2181 | # order to ``play fair'' with the framework." |
| 2182 | # |
| 2183 | # Make sure TestCase.run() respects the designated failureException |
| 2184 | def test_failureException__subclassing__explicit_raise(self): |
| 2185 | events = [] |
| 2186 | result = LoggingResult(events) |
| 2187 | |
| 2188 | class Foo(unittest.TestCase): |
| 2189 | def test(self): |
| 2190 | raise RuntimeError() |
| 2191 | |
| 2192 | failureException = RuntimeError |
| 2193 | |
| 2194 | self.failUnless(Foo('test').failureException is RuntimeError) |
| 2195 | |
| 2196 | |
| 2197 | Foo('test').run(result) |
| 2198 | expected = ['startTest', 'addFailure', 'stopTest'] |
| 2199 | self.assertEqual(events, expected) |
| 2200 | |
| 2201 | # "This class attribute gives the exception raised by the test() method. |
| 2202 | # If a test framework needs to use a specialized exception, possibly to |
| 2203 | # carry additional information, it must subclass this exception in |
| 2204 | # order to ``play fair'' with the framework." |
| 2205 | # |
| 2206 | # Make sure TestCase.run() respects the designated failureException |
| 2207 | def test_failureException__subclassing__implicit_raise(self): |
| 2208 | events = [] |
| 2209 | result = LoggingResult(events) |
| 2210 | |
| 2211 | class Foo(unittest.TestCase): |
| 2212 | def test(self): |
| 2213 | self.fail("foo") |
| 2214 | |
| 2215 | failureException = RuntimeError |
| 2216 | |
| 2217 | self.failUnless(Foo('test').failureException is RuntimeError) |
| 2218 | |
| 2219 | |
| 2220 | Foo('test').run(result) |
| 2221 | expected = ['startTest', 'addFailure', 'stopTest'] |
| 2222 | self.assertEqual(events, expected) |
| 2223 | |
| 2224 | # "The default implementation does nothing." |
| 2225 | def test_setUp(self): |
| 2226 | class Foo(unittest.TestCase): |
| 2227 | def runTest(self): |
| 2228 | pass |
| 2229 | |
| 2230 | # ... and nothing should happen |
| 2231 | Foo().setUp() |
| 2232 | |
| 2233 | # "The default implementation does nothing." |
| 2234 | def test_tearDown(self): |
| 2235 | class Foo(unittest.TestCase): |
| 2236 | def runTest(self): |
| 2237 | pass |
| 2238 | |
| 2239 | # ... and nothing should happen |
| 2240 | Foo().tearDown() |
| 2241 | |
| 2242 | # "Return a string identifying the specific test case." |
| 2243 | # |
| 2244 | # Because of the vague nature of the docs, I'm not going to lock this |
| 2245 | # test down too much. Really all that can be asserted is that the id() |
| 2246 | # will be a string (either 8-byte or unicode -- again, because the docs |
| 2247 | # just say "string") |
| 2248 | def test_id(self): |
| 2249 | class Foo(unittest.TestCase): |
| 2250 | def runTest(self): |
| 2251 | pass |
| 2252 | |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 2253 | self.failUnless(isinstance(Foo().id(), str)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2254 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2255 | # "If result is omitted or None, a temporary result object is created |
| 2256 | # and used, but is not made available to the caller" |
| 2257 | def test_run__uses_defaultTestResult(self): |
| 2258 | events = [] |
| 2259 | |
| 2260 | class Foo(unittest.TestCase): |
| 2261 | def test(self): |
| 2262 | events.append('test') |
| 2263 | |
| 2264 | def defaultTestResult(self): |
| 2265 | return LoggingResult(events) |
| 2266 | |
| 2267 | # Make run() find a result object on its own |
| 2268 | Foo('test').run() |
| 2269 | |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 2270 | expected = ['startTest', 'test', 'addSuccess', 'stopTest'] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2271 | self.assertEqual(events, expected) |
Jim Fulton | fafd874 | 2004-08-28 15:22:12 +0000 | [diff] [blame] | 2272 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2273 | def testShortDescriptionWithoutDocstring(self): |
| 2274 | self.assertEqual( |
| 2275 | self.shortDescription(), |
| 2276 | 'testShortDescriptionWithoutDocstring (' + __name__ + |
| 2277 | '.Test_TestCase)') |
| 2278 | |
| 2279 | def testShortDescriptionWithOneLineDocstring(self): |
| 2280 | """Tests shortDescription() for a method with a docstring.""" |
| 2281 | self.assertEqual( |
| 2282 | self.shortDescription(), |
| 2283 | ('testShortDescriptionWithOneLineDocstring ' |
| 2284 | '(' + __name__ + '.Test_TestCase)\n' |
| 2285 | 'Tests shortDescription() for a method with a docstring.')) |
| 2286 | |
| 2287 | def testShortDescriptionWithMultiLineDocstring(self): |
| 2288 | """Tests shortDescription() for a method with a longer docstring. |
| 2289 | |
| 2290 | This method ensures that only the first line of a docstring is |
| 2291 | returned used in the short description, no matter how long the |
| 2292 | whole thing is. |
| 2293 | """ |
| 2294 | self.assertEqual( |
| 2295 | self.shortDescription(), |
| 2296 | ('testShortDescriptionWithMultiLineDocstring ' |
| 2297 | '(' + __name__ + '.Test_TestCase)\n' |
| 2298 | 'Tests shortDescription() for a method with a longer ' |
| 2299 | 'docstring.')) |
| 2300 | |
| 2301 | def testAddTypeEqualityFunc(self): |
| 2302 | class SadSnake(object): |
| 2303 | """Dummy class for test_addTypeEqualityFunc.""" |
| 2304 | s1, s2 = SadSnake(), SadSnake() |
| 2305 | self.assertFalse(s1 == s2) |
| 2306 | def AllSnakesCreatedEqual(a, b, msg=None): |
| 2307 | return type(a) == type(b) == SadSnake |
| 2308 | self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual) |
| 2309 | self.assertEqual(s1, s2) |
| 2310 | # No this doesn't clean up and remove the SadSnake equality func |
| 2311 | # from this TestCase instance but since its a local nothing else |
| 2312 | # will ever notice that. |
| 2313 | |
| 2314 | def testAssertIn(self): |
| 2315 | animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'} |
| 2316 | |
| 2317 | self.assertIn('a', 'abc') |
| 2318 | self.assertIn(2, [1, 2, 3]) |
| 2319 | self.assertIn('monkey', animals) |
| 2320 | |
| 2321 | self.assertNotIn('d', 'abc') |
| 2322 | self.assertNotIn(0, [1, 2, 3]) |
| 2323 | self.assertNotIn('otter', animals) |
| 2324 | |
| 2325 | self.assertRaises(self.failureException, self.assertIn, 'x', 'abc') |
| 2326 | self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3]) |
| 2327 | self.assertRaises(self.failureException, self.assertIn, 'elephant', |
| 2328 | animals) |
| 2329 | |
| 2330 | self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc') |
| 2331 | self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3]) |
| 2332 | self.assertRaises(self.failureException, self.assertNotIn, 'cow', |
| 2333 | animals) |
| 2334 | |
| 2335 | def testAssertDictContainsSubset(self): |
| 2336 | self.assertDictContainsSubset({}, {}) |
| 2337 | self.assertDictContainsSubset({}, {'a': 1}) |
| 2338 | self.assertDictContainsSubset({'a': 1}, {'a': 1}) |
| 2339 | self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2}) |
| 2340 | self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2}) |
| 2341 | |
| 2342 | self.assertRaises(unittest.TestCase.failureException, |
| 2343 | self.assertDictContainsSubset, {'a': 2}, {'a': 1}, |
| 2344 | '.*Mismatched values:.*') |
| 2345 | |
| 2346 | self.assertRaises(unittest.TestCase.failureException, |
| 2347 | self.assertDictContainsSubset, {'c': 1}, {'a': 1}, |
| 2348 | '.*Missing:.*') |
| 2349 | |
| 2350 | self.assertRaises(unittest.TestCase.failureException, |
| 2351 | self.assertDictContainsSubset, {'a': 1, 'c': 1}, |
| 2352 | {'a': 1}, '.*Missing:.*') |
| 2353 | |
| 2354 | self.assertRaises(unittest.TestCase.failureException, |
| 2355 | self.assertDictContainsSubset, {'a': 1, 'c': 1}, |
| 2356 | {'a': 1}, '.*Missing:.*Mismatched values:.*') |
| 2357 | |
| 2358 | def testAssertEqual(self): |
| 2359 | equal_pairs = [ |
| 2360 | ((), ()), |
| 2361 | ({}, {}), |
| 2362 | ([], []), |
| 2363 | (set(), set()), |
| 2364 | (frozenset(), frozenset())] |
| 2365 | for a, b in equal_pairs: |
| 2366 | # This mess of try excepts is to test the assertEqual behavior |
| 2367 | # itself. |
| 2368 | try: |
| 2369 | self.assertEqual(a, b) |
| 2370 | except self.failureException: |
| 2371 | self.fail('assertEqual(%r, %r) failed' % (a, b)) |
| 2372 | try: |
| 2373 | self.assertEqual(a, b, msg='foo') |
| 2374 | except self.failureException: |
| 2375 | self.fail('assertEqual(%r, %r) with msg= failed' % (a, b)) |
| 2376 | try: |
| 2377 | self.assertEqual(a, b, 'foo') |
| 2378 | except self.failureException: |
| 2379 | self.fail('assertEqual(%r, %r) with third parameter failed' % |
| 2380 | (a, b)) |
| 2381 | |
| 2382 | unequal_pairs = [ |
| 2383 | ((), []), |
| 2384 | ({}, set()), |
| 2385 | (set([4,1]), frozenset([4,2])), |
| 2386 | (frozenset([4,5]), set([2,3])), |
| 2387 | (set([3,4]), set([5,4]))] |
| 2388 | for a, b in unequal_pairs: |
| 2389 | self.assertRaises(self.failureException, self.assertEqual, a, b) |
| 2390 | self.assertRaises(self.failureException, self.assertEqual, a, b, |
| 2391 | 'foo') |
| 2392 | self.assertRaises(self.failureException, self.assertEqual, a, b, |
| 2393 | msg='foo') |
| 2394 | |
| 2395 | def testEquality(self): |
| 2396 | self.assertListEqual([], []) |
| 2397 | self.assertTupleEqual((), ()) |
| 2398 | self.assertSequenceEqual([], ()) |
| 2399 | |
| 2400 | a = [0, 'a', []] |
| 2401 | b = [] |
| 2402 | self.assertRaises(unittest.TestCase.failureException, |
| 2403 | self.assertListEqual, a, b) |
| 2404 | self.assertRaises(unittest.TestCase.failureException, |
| 2405 | self.assertListEqual, tuple(a), tuple(b)) |
| 2406 | self.assertRaises(unittest.TestCase.failureException, |
| 2407 | self.assertSequenceEqual, a, tuple(b)) |
| 2408 | |
| 2409 | b.extend(a) |
| 2410 | self.assertListEqual(a, b) |
| 2411 | self.assertTupleEqual(tuple(a), tuple(b)) |
| 2412 | self.assertSequenceEqual(a, tuple(b)) |
| 2413 | self.assertSequenceEqual(tuple(a), b) |
| 2414 | |
| 2415 | self.assertRaises(self.failureException, self.assertListEqual, |
| 2416 | a, tuple(b)) |
| 2417 | self.assertRaises(self.failureException, self.assertTupleEqual, |
| 2418 | tuple(a), b) |
| 2419 | self.assertRaises(self.failureException, self.assertListEqual, None, b) |
| 2420 | self.assertRaises(self.failureException, self.assertTupleEqual, None, |
| 2421 | tuple(b)) |
| 2422 | self.assertRaises(self.failureException, self.assertSequenceEqual, |
| 2423 | None, tuple(b)) |
| 2424 | self.assertRaises(self.failureException, self.assertListEqual, 1, 1) |
| 2425 | self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1) |
| 2426 | self.assertRaises(self.failureException, self.assertSequenceEqual, |
| 2427 | 1, 1) |
| 2428 | |
| 2429 | self.assertDictEqual({}, {}) |
| 2430 | |
| 2431 | c = { 'x': 1 } |
| 2432 | d = {} |
| 2433 | self.assertRaises(unittest.TestCase.failureException, |
| 2434 | self.assertDictEqual, c, d) |
| 2435 | |
| 2436 | d.update(c) |
| 2437 | self.assertDictEqual(c, d) |
| 2438 | |
| 2439 | d['x'] = 0 |
| 2440 | self.assertRaises(unittest.TestCase.failureException, |
| 2441 | self.assertDictEqual, c, d, 'These are unequal') |
| 2442 | |
| 2443 | self.assertRaises(self.failureException, self.assertDictEqual, None, d) |
| 2444 | self.assertRaises(self.failureException, self.assertDictEqual, [], d) |
| 2445 | self.assertRaises(self.failureException, self.assertDictEqual, 1, 1) |
| 2446 | |
| 2447 | self.assertSameElements([1, 2, 3], [3, 2, 1]) |
| 2448 | self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3]) |
| 2449 | self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo']) |
| 2450 | self.assertRaises(self.failureException, self.assertSameElements, |
| 2451 | [10], [10, 11]) |
| 2452 | self.assertRaises(self.failureException, self.assertSameElements, |
| 2453 | [10, 11], [10]) |
| 2454 | |
| 2455 | # Test that sequences of unhashable objects can be tested for sameness: |
| 2456 | self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]]) |
| 2457 | self.assertRaises(self.failureException, self.assertSameElements, |
| 2458 | [[1]], [[2]]) |
| 2459 | |
| 2460 | def testAssertSetEqual(self): |
| 2461 | set1 = set() |
| 2462 | set2 = set() |
| 2463 | self.assertSetEqual(set1, set2) |
| 2464 | |
| 2465 | self.assertRaises(self.failureException, self.assertSetEqual, None, set2) |
| 2466 | self.assertRaises(self.failureException, self.assertSetEqual, [], set2) |
| 2467 | self.assertRaises(self.failureException, self.assertSetEqual, set1, None) |
| 2468 | self.assertRaises(self.failureException, self.assertSetEqual, set1, []) |
| 2469 | |
| 2470 | set1 = set(['a']) |
| 2471 | set2 = set() |
| 2472 | self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) |
| 2473 | |
| 2474 | set1 = set(['a']) |
| 2475 | set2 = set(['a']) |
| 2476 | self.assertSetEqual(set1, set2) |
| 2477 | |
| 2478 | set1 = set(['a']) |
| 2479 | set2 = set(['a', 'b']) |
| 2480 | self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) |
| 2481 | |
| 2482 | set1 = set(['a']) |
| 2483 | set2 = frozenset(['a', 'b']) |
| 2484 | self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) |
| 2485 | |
| 2486 | set1 = set(['a', 'b']) |
| 2487 | set2 = frozenset(['a', 'b']) |
| 2488 | self.assertSetEqual(set1, set2) |
| 2489 | |
| 2490 | set1 = set() |
| 2491 | set2 = "foo" |
| 2492 | self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) |
| 2493 | self.assertRaises(self.failureException, self.assertSetEqual, set2, set1) |
| 2494 | |
| 2495 | # make sure any string formatting is tuple-safe |
| 2496 | set1 = set([(0, 1), (2, 3)]) |
| 2497 | set2 = set([(4, 5)]) |
| 2498 | self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) |
| 2499 | |
| 2500 | def testInequality(self): |
| 2501 | # Try ints |
| 2502 | self.assertGreater(2, 1) |
| 2503 | self.assertGreaterEqual(2, 1) |
| 2504 | self.assertGreaterEqual(1, 1) |
| 2505 | self.assertLess(1, 2) |
| 2506 | self.assertLessEqual(1, 2) |
| 2507 | self.assertLessEqual(1, 1) |
| 2508 | self.assertRaises(self.failureException, self.assertGreater, 1, 2) |
| 2509 | self.assertRaises(self.failureException, self.assertGreater, 1, 1) |
| 2510 | self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2) |
| 2511 | self.assertRaises(self.failureException, self.assertLess, 2, 1) |
| 2512 | self.assertRaises(self.failureException, self.assertLess, 1, 1) |
| 2513 | self.assertRaises(self.failureException, self.assertLessEqual, 2, 1) |
| 2514 | |
| 2515 | # Try Floats |
| 2516 | self.assertGreater(1.1, 1.0) |
| 2517 | self.assertGreaterEqual(1.1, 1.0) |
| 2518 | self.assertGreaterEqual(1.0, 1.0) |
| 2519 | self.assertLess(1.0, 1.1) |
| 2520 | self.assertLessEqual(1.0, 1.1) |
| 2521 | self.assertLessEqual(1.0, 1.0) |
| 2522 | self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1) |
| 2523 | self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0) |
| 2524 | self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1) |
| 2525 | self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0) |
| 2526 | self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0) |
| 2527 | self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0) |
| 2528 | |
| 2529 | # Try Strings |
| 2530 | self.assertGreater('bug', 'ant') |
| 2531 | self.assertGreaterEqual('bug', 'ant') |
| 2532 | self.assertGreaterEqual('ant', 'ant') |
| 2533 | self.assertLess('ant', 'bug') |
| 2534 | self.assertLessEqual('ant', 'bug') |
| 2535 | self.assertLessEqual('ant', 'ant') |
| 2536 | self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug') |
| 2537 | self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant') |
| 2538 | self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug') |
| 2539 | self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant') |
| 2540 | self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant') |
| 2541 | self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant') |
| 2542 | |
| 2543 | # Try bytes |
| 2544 | self.assertGreater(b'bug', b'ant') |
| 2545 | self.assertGreaterEqual(b'bug', b'ant') |
| 2546 | self.assertGreaterEqual(b'ant', b'ant') |
| 2547 | self.assertLess(b'ant', b'bug') |
| 2548 | self.assertLessEqual(b'ant', b'bug') |
| 2549 | self.assertLessEqual(b'ant', b'ant') |
| 2550 | self.assertRaises(self.failureException, self.assertGreater, b'ant', b'bug') |
| 2551 | self.assertRaises(self.failureException, self.assertGreater, b'ant', b'ant') |
| 2552 | self.assertRaises(self.failureException, self.assertGreaterEqual, b'ant', |
| 2553 | b'bug') |
| 2554 | self.assertRaises(self.failureException, self.assertLess, b'bug', b'ant') |
| 2555 | self.assertRaises(self.failureException, self.assertLess, b'ant', b'ant') |
| 2556 | self.assertRaises(self.failureException, self.assertLessEqual, b'bug', b'ant') |
| 2557 | |
| 2558 | def testAssertMultiLineEqual(self): |
| 2559 | sample_text = """\ |
| 2560 | http://www.python.org/doc/2.3/lib/module-unittest.html |
| 2561 | test case |
| 2562 | A test case is the smallest unit of testing. [...] |
| 2563 | """ |
| 2564 | revised_sample_text = """\ |
| 2565 | http://www.python.org/doc/2.4.1/lib/module-unittest.html |
| 2566 | test case |
| 2567 | A test case is the smallest unit of testing. [...] You may provide your |
| 2568 | own implementation that does not subclass from TestCase, of course. |
| 2569 | """ |
| 2570 | sample_text_error = """ |
| 2571 | - http://www.python.org/doc/2.3/lib/module-unittest.html |
| 2572 | ? ^ |
| 2573 | + http://www.python.org/doc/2.4.1/lib/module-unittest.html |
| 2574 | ? ^^^ |
| 2575 | test case |
| 2576 | - A test case is the smallest unit of testing. [...] |
| 2577 | + A test case is the smallest unit of testing. [...] You may provide your |
| 2578 | ? +++++++++++++++++++++ |
| 2579 | + own implementation that does not subclass from TestCase, of course. |
| 2580 | """ |
| 2581 | |
| 2582 | try: |
| 2583 | self.assertMultiLineEqual(sample_text, revised_sample_text) |
| 2584 | except self.failureException as e: |
| 2585 | # no fair testing ourself with ourself, use assertEqual.. |
| 2586 | self.assertEqual(sample_text_error, str(e)) |
| 2587 | |
| 2588 | def testAssertIsNone(self): |
| 2589 | self.assertIsNone(None) |
| 2590 | self.assertRaises(self.failureException, self.assertIsNone, False) |
| 2591 | self.assertIsNotNone('DjZoPloGears on Rails') |
| 2592 | self.assertRaises(self.failureException, self.assertIsNotNone, None) |
| 2593 | |
| 2594 | def testAssertRegexpMatches(self): |
| 2595 | self.assertRegexpMatches('asdfabasdf', r'ab+') |
| 2596 | self.assertRaises(self.failureException, self.assertRegexpMatches, |
| 2597 | 'saaas', r'aaaa') |
| 2598 | |
| 2599 | def testAssertRaisesRegexp(self): |
| 2600 | class ExceptionMock(Exception): |
| 2601 | pass |
| 2602 | |
| 2603 | def Stub(): |
| 2604 | raise ExceptionMock('We expect') |
| 2605 | |
| 2606 | self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub) |
| 2607 | self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub) |
| 2608 | |
| 2609 | def testAssertNotRaisesRegexp(self): |
| 2610 | self.assertRaisesRegexp( |
Benjamin Peterson | 4f75b64 | 2009-04-04 16:39:09 +0000 | [diff] [blame^] | 2611 | self.failureException, '^Exception not raised by <lambda>$', |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2612 | self.assertRaisesRegexp, Exception, re.compile('x'), |
| 2613 | lambda: None) |
| 2614 | self.assertRaisesRegexp( |
Benjamin Peterson | 4f75b64 | 2009-04-04 16:39:09 +0000 | [diff] [blame^] | 2615 | self.failureException, '^Exception not raised by <lambda>$', |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2616 | self.assertRaisesRegexp, Exception, 'x', |
| 2617 | lambda: None) |
| 2618 | |
| 2619 | def testAssertRaisesRegexpMismatch(self): |
| 2620 | def Stub(): |
| 2621 | raise Exception('Unexpected') |
| 2622 | |
| 2623 | self.assertRaisesRegexp( |
| 2624 | self.failureException, |
| 2625 | r'"\^Expected\$" does not match "Unexpected"', |
| 2626 | self.assertRaisesRegexp, Exception, '^Expected$', |
| 2627 | Stub) |
| 2628 | self.assertRaisesRegexp( |
| 2629 | self.failureException, |
| 2630 | r'"\^Expected\$" does not match "Unexpected"', |
| 2631 | self.assertRaisesRegexp, Exception, |
| 2632 | re.compile('^Expected$'), Stub) |
| 2633 | |
| 2634 | def testSynonymAssertMethodNames(self): |
| 2635 | """Test undocumented method name synonyms. |
| 2636 | |
| 2637 | Please do not use these methods names in your own code. |
| 2638 | |
| 2639 | This test confirms their continued existence and functionality |
| 2640 | in order to avoid breaking existing code. |
| 2641 | """ |
| 2642 | self.assertNotEquals(3, 5) |
| 2643 | self.assertEquals(3, 3) |
| 2644 | self.assertAlmostEquals(2.0, 2.0) |
| 2645 | self.assertNotAlmostEquals(3.0, 5.0) |
| 2646 | self.assert_(True) |
| 2647 | |
| 2648 | def testPendingDeprecationMethodNames(self): |
| 2649 | """Test fail* methods pending deprecation, they will warn in 3.2. |
| 2650 | |
| 2651 | Do not use these methods. They will go away in 3.3. |
| 2652 | """ |
| 2653 | self.failIfEqual(3, 5) |
| 2654 | self.failUnlessEqual(3, 3) |
| 2655 | self.failUnlessAlmostEqual(2.0, 2.0) |
| 2656 | self.failIfAlmostEqual(3.0, 5.0) |
| 2657 | self.failUnless(True) |
| 2658 | self.failUnlessRaises(TypeError, lambda _: 3.14 + 'spam') |
| 2659 | self.failIf(False) |
| 2660 | |
| 2661 | def testDeepcopy(self): |
| 2662 | # Issue: 5660 |
| 2663 | class TestableTest(TestCase): |
| 2664 | def testNothing(self): |
| 2665 | pass |
| 2666 | |
| 2667 | test = TestableTest('testNothing') |
| 2668 | |
| 2669 | # This shouldn't blow up |
| 2670 | deepcopy(test) |
| 2671 | |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 2672 | |
| 2673 | class Test_TestSkipping(TestCase): |
| 2674 | |
| 2675 | def test_skipping(self): |
| 2676 | class Foo(unittest.TestCase): |
| 2677 | def test_skip_me(self): |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 2678 | self.skipTest("skip") |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 2679 | events = [] |
| 2680 | result = LoggingResult(events) |
| 2681 | test = Foo("test_skip_me") |
| 2682 | test.run(result) |
| 2683 | self.assertEqual(events, ['startTest', 'addSkip', 'stopTest']) |
| 2684 | self.assertEqual(result.skipped, [(test, "skip")]) |
| 2685 | |
| 2686 | # Try letting setUp skip the test now. |
| 2687 | class Foo(unittest.TestCase): |
| 2688 | def setUp(self): |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 2689 | self.skipTest("testing") |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 2690 | def test_nothing(self): pass |
| 2691 | events = [] |
| 2692 | result = LoggingResult(events) |
| 2693 | test = Foo("test_nothing") |
| 2694 | test.run(result) |
| 2695 | self.assertEqual(events, ['startTest', 'addSkip', 'stopTest']) |
| 2696 | self.assertEqual(result.skipped, [(test, "testing")]) |
| 2697 | self.assertEqual(result.testsRun, 1) |
| 2698 | |
| 2699 | def test_skipping_decorators(self): |
| 2700 | op_table = ((unittest.skipUnless, False, True), |
| 2701 | (unittest.skipIf, True, False)) |
| 2702 | for deco, do_skip, dont_skip in op_table: |
| 2703 | class Foo(unittest.TestCase): |
| 2704 | @deco(do_skip, "testing") |
| 2705 | def test_skip(self): pass |
| 2706 | |
| 2707 | @deco(dont_skip, "testing") |
| 2708 | def test_dont_skip(self): pass |
| 2709 | test_do_skip = Foo("test_skip") |
| 2710 | test_dont_skip = Foo("test_dont_skip") |
| 2711 | suite = unittest.ClassTestSuite([test_do_skip, test_dont_skip], Foo) |
| 2712 | events = [] |
| 2713 | result = LoggingResult(events) |
| 2714 | suite.run(result) |
| 2715 | self.assertEqual(len(result.skipped), 1) |
| 2716 | expected = ['startTest', 'addSkip', 'stopTest', |
| 2717 | 'startTest', 'addSuccess', 'stopTest'] |
| 2718 | self.assertEqual(events, expected) |
| 2719 | self.assertEqual(result.testsRun, 2) |
| 2720 | self.assertEqual(result.skipped, [(test_do_skip, "testing")]) |
| 2721 | self.assertTrue(result.wasSuccessful()) |
| 2722 | |
| 2723 | def test_skip_class(self): |
| 2724 | @unittest.skip("testing") |
| 2725 | class Foo(unittest.TestCase): |
| 2726 | def test_1(self): |
| 2727 | record.append(1) |
| 2728 | record = [] |
| 2729 | result = unittest.TestResult() |
| 2730 | suite = unittest.ClassTestSuite([Foo("test_1")], Foo) |
| 2731 | suite.run(result) |
| 2732 | self.assertEqual(result.skipped, [(suite, "testing")]) |
| 2733 | self.assertEqual(record, []) |
| 2734 | |
| 2735 | def test_expected_failure(self): |
| 2736 | class Foo(unittest.TestCase): |
| 2737 | @unittest.expectedFailure |
| 2738 | def test_die(self): |
| 2739 | self.fail("help me!") |
| 2740 | events = [] |
| 2741 | result = LoggingResult(events) |
| 2742 | test = Foo("test_die") |
| 2743 | test.run(result) |
| 2744 | self.assertEqual(events, |
| 2745 | ['startTest', 'addExpectedFailure', 'stopTest']) |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 2746 | self.assertEqual(result.expectedFailures[0][0], test) |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 2747 | self.assertTrue(result.wasSuccessful()) |
| 2748 | |
| 2749 | def test_unexpected_success(self): |
| 2750 | class Foo(unittest.TestCase): |
| 2751 | @unittest.expectedFailure |
| 2752 | def test_die(self): |
| 2753 | pass |
| 2754 | events = [] |
| 2755 | result = LoggingResult(events) |
| 2756 | test = Foo("test_die") |
| 2757 | test.run(result) |
| 2758 | self.assertEqual(events, |
| 2759 | ['startTest', 'addUnexpectedSuccess', 'stopTest']) |
| 2760 | self.assertFalse(result.failures) |
Benjamin Peterson | 52baa29 | 2009-03-24 00:56:30 +0000 | [diff] [blame] | 2761 | self.assertEqual(result.unexpectedSuccesses, [test]) |
Benjamin Peterson | 5254c04 | 2009-03-23 22:25:03 +0000 | [diff] [blame] | 2762 | self.assertTrue(result.wasSuccessful()) |
| 2763 | |
| 2764 | |
| 2765 | |
Jeffrey Yasskin | aaaef11 | 2007-09-07 15:00:39 +0000 | [diff] [blame] | 2766 | class Test_Assertions(TestCase): |
| 2767 | def test_AlmostEqual(self): |
| 2768 | self.failUnlessAlmostEqual(1.00000001, 1.0) |
| 2769 | self.failIfAlmostEqual(1.0000001, 1.0) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2770 | self.assertRaises(self.failureException, |
Jeffrey Yasskin | aaaef11 | 2007-09-07 15:00:39 +0000 | [diff] [blame] | 2771 | self.failUnlessAlmostEqual, 1.0000001, 1.0) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2772 | self.assertRaises(self.failureException, |
Jeffrey Yasskin | aaaef11 | 2007-09-07 15:00:39 +0000 | [diff] [blame] | 2773 | self.failIfAlmostEqual, 1.00000001, 1.0) |
| 2774 | |
| 2775 | self.failUnlessAlmostEqual(1.1, 1.0, places=0) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2776 | self.assertRaises(self.failureException, |
Jeffrey Yasskin | aaaef11 | 2007-09-07 15:00:39 +0000 | [diff] [blame] | 2777 | self.failUnlessAlmostEqual, 1.1, 1.0, places=1) |
| 2778 | |
| 2779 | self.failUnlessAlmostEqual(0, .1+.1j, places=0) |
| 2780 | self.failIfAlmostEqual(0, .1+.1j, places=1) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2781 | self.assertRaises(self.failureException, |
Jeffrey Yasskin | aaaef11 | 2007-09-07 15:00:39 +0000 | [diff] [blame] | 2782 | self.failUnlessAlmostEqual, 0, .1+.1j, places=1) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2783 | self.assertRaises(self.failureException, |
Jeffrey Yasskin | aaaef11 | 2007-09-07 15:00:39 +0000 | [diff] [blame] | 2784 | self.failIfAlmostEqual, 0, .1+.1j, places=0) |
| 2785 | |
Antoine Pitrou | 5acd41e | 2008-12-28 14:29:00 +0000 | [diff] [blame] | 2786 | def test_assertRaises(self): |
| 2787 | def _raise(e): |
| 2788 | raise e |
| 2789 | self.assertRaises(KeyError, _raise, KeyError) |
| 2790 | self.assertRaises(KeyError, _raise, KeyError("key")) |
| 2791 | try: |
| 2792 | self.assertRaises(KeyError, lambda: None) |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2793 | except self.failureException as e: |
Antoine Pitrou | 5acd41e | 2008-12-28 14:29:00 +0000 | [diff] [blame] | 2794 | self.assert_("KeyError not raised" in str(e), str(e)) |
| 2795 | else: |
| 2796 | self.fail("assertRaises() didn't fail") |
| 2797 | try: |
| 2798 | self.assertRaises(KeyError, _raise, ValueError) |
| 2799 | except ValueError: |
| 2800 | pass |
| 2801 | else: |
| 2802 | self.fail("assertRaises() didn't let exception pass through") |
| 2803 | with self.assertRaises(KeyError): |
| 2804 | raise KeyError |
| 2805 | with self.assertRaises(KeyError): |
| 2806 | raise KeyError("key") |
| 2807 | try: |
| 2808 | with self.assertRaises(KeyError): |
| 2809 | pass |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2810 | except self.failureException as e: |
Antoine Pitrou | 5acd41e | 2008-12-28 14:29:00 +0000 | [diff] [blame] | 2811 | self.assert_("KeyError not raised" in str(e), str(e)) |
| 2812 | else: |
| 2813 | self.fail("assertRaises() didn't fail") |
| 2814 | try: |
| 2815 | with self.assertRaises(KeyError): |
| 2816 | raise ValueError |
| 2817 | except ValueError: |
| 2818 | pass |
| 2819 | else: |
| 2820 | self.fail("assertRaises() didn't let exception pass through") |
| 2821 | |
| 2822 | |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2823 | class TestLongMessage(TestCase): |
| 2824 | """Test that the individual asserts honour longMessage. |
| 2825 | This actually tests all the message behaviour for |
| 2826 | asserts that use longMessage.""" |
| 2827 | |
| 2828 | def setUp(self): |
| 2829 | class TestableTestFalse(TestCase): |
| 2830 | longMessage = False |
| 2831 | failureException = self.failureException |
| 2832 | |
| 2833 | def testTest(self): |
| 2834 | pass |
| 2835 | |
| 2836 | class TestableTestTrue(TestCase): |
| 2837 | longMessage = True |
| 2838 | failureException = self.failureException |
| 2839 | |
| 2840 | def testTest(self): |
| 2841 | pass |
| 2842 | |
| 2843 | self.testableTrue = TestableTestTrue('testTest') |
| 2844 | self.testableFalse = TestableTestFalse('testTest') |
| 2845 | |
| 2846 | def testDefault(self): |
| 2847 | self.assertFalse(TestCase.longMessage) |
| 2848 | |
| 2849 | def test_formatMsg(self): |
| 2850 | self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo") |
| 2851 | self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo") |
| 2852 | |
| 2853 | self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo") |
| 2854 | self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo") |
| 2855 | |
| 2856 | def assertMessages(self, methodName, args, errors): |
| 2857 | def getMethod(i): |
| 2858 | useTestableFalse = i < 2 |
| 2859 | if useTestableFalse: |
| 2860 | test = self.testableFalse |
| 2861 | else: |
| 2862 | test = self.testableTrue |
| 2863 | return getattr(test, methodName) |
| 2864 | |
| 2865 | for i, expected_regexp in enumerate(errors): |
| 2866 | testMethod = getMethod(i) |
| 2867 | kwargs = {} |
| 2868 | withMsg = i % 2 |
| 2869 | if withMsg: |
| 2870 | kwargs = {"msg": "oops"} |
| 2871 | |
| 2872 | with self.assertRaisesRegexp(self.failureException, |
| 2873 | expected_regexp=expected_regexp): |
| 2874 | testMethod(*args, **kwargs) |
| 2875 | |
| 2876 | def testAssertTrue(self): |
| 2877 | self.assertMessages('assertTrue', (False,), |
| 2878 | ["^False is not True$", "^oops$", "^False is not True$", |
| 2879 | "^False is not True : oops$"]) |
| 2880 | |
| 2881 | def testAssertFalse(self): |
| 2882 | self.assertMessages('assertFalse', (True,), |
| 2883 | ["^True is not False$", "^oops$", "^True is not False$", |
| 2884 | "^True is not False : oops$"]) |
| 2885 | |
| 2886 | def testNotEqual(self): |
| 2887 | self.assertMessages('assertNotEqual', (1, 1), |
| 2888 | ["^1 == 1$", "^oops$", "^1 == 1$", |
| 2889 | "^1 == 1 : oops$"]) |
| 2890 | |
| 2891 | def testAlmostEqual(self): |
| 2892 | self.assertMessages('assertAlmostEqual', (1, 2), |
| 2893 | ["^1 != 2 within 7 places$", "^oops$", |
| 2894 | "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"]) |
| 2895 | |
| 2896 | def testNotAlmostEqual(self): |
| 2897 | self.assertMessages('assertNotAlmostEqual', (1, 1), |
| 2898 | ["^1 == 1 within 7 places$", "^oops$", |
| 2899 | "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"]) |
| 2900 | |
| 2901 | def test_baseAssertEqual(self): |
| 2902 | self.assertMessages('_baseAssertEqual', (1, 2), |
| 2903 | ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"]) |
| 2904 | |
| 2905 | def testAssertSequenceEqual(self): |
| 2906 | # Error messages are multiline so not testing on full message |
| 2907 | # assertTupleEqual and assertListEqual delegate to this method |
| 2908 | self.assertMessages('assertSequenceEqual', ([], [None]), |
| 2909 | ["\+ \[None\]$", "^oops$", r"\+ \[None\]$", |
| 2910 | r"\+ \[None\] : oops$"]) |
| 2911 | |
| 2912 | def testAssertSetEqual(self): |
| 2913 | self.assertMessages('assertSetEqual', (set(), set([None])), |
| 2914 | ["None$", "^oops$", "None$", |
| 2915 | "None : oops$"]) |
| 2916 | |
| 2917 | def testAssertIn(self): |
| 2918 | self.assertMessages('assertIn', (None, []), |
| 2919 | ['^None not found in \[\]$', "^oops$", |
| 2920 | '^None not found in \[\]$', |
| 2921 | '^None not found in \[\] : oops$']) |
| 2922 | |
| 2923 | def testAssertNotIn(self): |
| 2924 | self.assertMessages('assertNotIn', (None, [None]), |
| 2925 | ['^None unexpectedly found in \[None\]$', "^oops$", |
| 2926 | '^None unexpectedly found in \[None\]$', |
| 2927 | '^None unexpectedly found in \[None\] : oops$']) |
| 2928 | |
| 2929 | def testAssertDictEqual(self): |
| 2930 | self.assertMessages('assertDictEqual', ({}, {'key': 'value'}), |
| 2931 | [r"\+ \{'key': 'value'\}$", "^oops$", |
| 2932 | "\+ \{'key': 'value'\}$", |
| 2933 | "\+ \{'key': 'value'\} : oops$"]) |
| 2934 | |
| 2935 | def testAssertDictContainsSubset(self): |
| 2936 | self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}), |
| 2937 | ["^Missing: 'key'$", "^oops$", |
| 2938 | "^Missing: 'key'$", |
| 2939 | "^Missing: 'key' : oops$"]) |
| 2940 | |
| 2941 | def testAssertSameElements(self): |
| 2942 | self.assertMessages('assertSameElements', ([], [None]), |
| 2943 | [r"\[None\]$", "^oops$", |
| 2944 | r"\[None\]$", |
| 2945 | r"\[None\] : oops$"]) |
| 2946 | |
| 2947 | def testAssertMultiLineEqual(self): |
| 2948 | self.assertMessages('assertMultiLineEqual', ("", "foo"), |
| 2949 | [r"\+ foo$", "^oops$", |
| 2950 | r"\+ foo$", |
| 2951 | r"\+ foo : oops$"]) |
| 2952 | |
| 2953 | def testAssertLess(self): |
| 2954 | self.assertMessages('assertLess', (2, 1), |
| 2955 | ["^2 not less than 1$", "^oops$", |
| 2956 | "^2 not less than 1$", "^2 not less than 1 : oops$"]) |
| 2957 | |
| 2958 | def testAssertLessEqual(self): |
| 2959 | self.assertMessages('assertLessEqual', (2, 1), |
| 2960 | ["^2 not less than or equal to 1$", "^oops$", |
| 2961 | "^2 not less than or equal to 1$", |
| 2962 | "^2 not less than or equal to 1 : oops$"]) |
| 2963 | |
| 2964 | def testAssertGreater(self): |
| 2965 | self.assertMessages('assertGreater', (1, 2), |
| 2966 | ["^1 not greater than 2$", "^oops$", |
| 2967 | "^1 not greater than 2$", |
| 2968 | "^1 not greater than 2 : oops$"]) |
| 2969 | |
| 2970 | def testAssertGreaterEqual(self): |
| 2971 | self.assertMessages('assertGreaterEqual', (1, 2), |
| 2972 | ["^1 not greater than or equal to 2$", "^oops$", |
| 2973 | "^1 not greater than or equal to 2$", |
| 2974 | "^1 not greater than or equal to 2 : oops$"]) |
| 2975 | |
| 2976 | def testAssertIsNone(self): |
| 2977 | self.assertMessages('assertIsNone', ('not None',), |
| 2978 | ["^'not None' is not None$", "^oops$", |
| 2979 | "^'not None' is not None$", |
| 2980 | "^'not None' is not None : oops$"]) |
| 2981 | |
| 2982 | def testAssertIsNotNone(self): |
| 2983 | self.assertMessages('assertIsNotNone', (None,), |
| 2984 | ["^unexpectedly None$", "^oops$", |
| 2985 | "^unexpectedly None$", |
| 2986 | "^unexpectedly None : oops$"]) |
| 2987 | |
| 2988 | |
Jim Fulton | fafd874 | 2004-08-28 15:22:12 +0000 | [diff] [blame] | 2989 | ###################################################################### |
| 2990 | ## Main |
| 2991 | ###################################################################### |
| 2992 | |
| 2993 | def test_main(): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 2994 | support.run_unittest(Test_TestCase, Test_TestLoader, |
Jeffrey Yasskin | aaaef11 | 2007-09-07 15:00:39 +0000 | [diff] [blame] | 2995 | Test_TestSuite, Test_TestResult, Test_FunctionTestCase, |
Benjamin Peterson | 7fe73a1 | 2009-04-04 16:35:46 +0000 | [diff] [blame] | 2996 | Test_TestSkipping, Test_Assertions, TestLongMessage) |
Jim Fulton | fafd874 | 2004-08-28 15:22:12 +0000 | [diff] [blame] | 2997 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2998 | if __name__ == "__main__": |
Jim Fulton | fafd874 | 2004-08-28 15:22:12 +0000 | [diff] [blame] | 2999 | test_main() |