Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 2 | ''' |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 3 | Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's |
| 4 | Smalltalk testing framework. |
| 5 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 6 | This module contains the core framework classes that form the basis of |
| 7 | specific test cases and suites (TestCase, TestSuite etc.), and also a |
| 8 | text-based utility class for running the tests and reporting the results |
Jeremy Hylton | efef5da | 2001-10-22 18:14:15 +0000 | [diff] [blame] | 9 | (TextTestRunner). |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 10 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 11 | Simple usage: |
| 12 | |
| 13 | import unittest |
| 14 | |
| 15 | class IntegerArithmenticTestCase(unittest.TestCase): |
| 16 | def testAdd(self): ## test method names begin 'test*' |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 17 | self.assertEqual((1 + 2), 3) |
| 18 | self.assertEqual(0 + 1, 1) |
Steve Purcell | 7b06570 | 2001-09-06 08:24:40 +0000 | [diff] [blame] | 19 | def testMultiply(self): |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 20 | self.assertEqual((0 * 10), 0) |
| 21 | self.assertEqual((5 * 8), 40) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 22 | |
| 23 | if __name__ == '__main__': |
| 24 | unittest.main() |
| 25 | |
| 26 | Further information is available in the bundled documentation, and from |
| 27 | |
Benjamin Peterson | 4e4de33 | 2009-03-24 00:37:12 +0000 | [diff] [blame] | 28 | http://docs.python.org/library/unittest.html |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 29 | |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 30 | Copyright (c) 1999-2003 Steve Purcell |
Benjamin Peterson | 4e4de33 | 2009-03-24 00:37:12 +0000 | [diff] [blame] | 31 | Copyright (c) 2003-2009 Python Software Foundation |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 32 | This module is free software, and you may redistribute it and/or modify |
| 33 | it under the same terms as Python itself, so long as this copyright message |
| 34 | and disclaimer are retained in their original form. |
| 35 | |
| 36 | IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, |
| 37 | SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF |
| 38 | THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH |
| 39 | DAMAGE. |
| 40 | |
| 41 | THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT |
| 42 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A |
| 43 | PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, |
| 44 | AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE, |
| 45 | SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 46 | ''' |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 47 | |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 48 | import difflib |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 49 | import functools |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 50 | import os |
| 51 | import pprint |
| 52 | import re |
| 53 | import sys |
| 54 | import time |
| 55 | import traceback |
| 56 | import types |
Gregory P. Smith | 65ff005 | 2009-03-31 19:59:14 +0000 | [diff] [blame] | 57 | import warnings |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 58 | |
| 59 | ############################################################################## |
Steve Purcell | d75e7e4 | 2003-09-15 11:01:21 +0000 | [diff] [blame] | 60 | # Exported classes and functions |
| 61 | ############################################################################## |
Benjamin Peterson | 176a56c | 2009-05-25 00:48:58 +0000 | [diff] [blame] | 62 | __all__ = ['TestResult', 'TestCase', 'TestSuite', |
Benjamin Peterson | c750d4d | 2009-03-24 00:39:24 +0000 | [diff] [blame] | 63 | 'TextTestRunner', 'TestLoader', 'FunctionTestCase', 'main', |
Benjamin Peterson | 0371548 | 2009-03-24 01:11:37 +0000 | [diff] [blame] | 64 | 'defaultTestLoader', 'SkipTest', 'skip', 'skipIf', 'skipUnless', |
Benjamin Peterson | c750d4d | 2009-03-24 00:39:24 +0000 | [diff] [blame] | 65 | 'expectedFailure'] |
Steve Purcell | d75e7e4 | 2003-09-15 11:01:21 +0000 | [diff] [blame] | 66 | |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 67 | # Expose obsolete functions for backwards compatibility |
Steve Purcell | d75e7e4 | 2003-09-15 11:01:21 +0000 | [diff] [blame] | 68 | __all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases']) |
| 69 | |
| 70 | |
| 71 | ############################################################################## |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 72 | # Backward compatibility |
| 73 | ############################################################################## |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 74 | |
Raymond Hettinger | 5930d8f | 2008-07-10 16:06:41 +0000 | [diff] [blame] | 75 | def _CmpToKey(mycmp): |
| 76 | 'Convert a cmp= function into a key= function' |
| 77 | class K(object): |
| 78 | def __init__(self, obj): |
| 79 | self.obj = obj |
| 80 | def __lt__(self, other): |
| 81 | return mycmp(self.obj, other.obj) == -1 |
| 82 | return K |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 83 | |
| 84 | ############################################################################## |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 85 | # Test framework core |
| 86 | ############################################################################## |
| 87 | |
Steve Purcell | dc391a6 | 2002-08-09 09:46:23 +0000 | [diff] [blame] | 88 | def _strclass(cls): |
| 89 | return "%s.%s" % (cls.__module__, cls.__name__) |
| 90 | |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 91 | |
| 92 | class SkipTest(Exception): |
| 93 | """ |
| 94 | Raise this exception in a test to skip it. |
| 95 | |
| 96 | Usually you can use TestResult.skip() or one of the skipping decorators |
| 97 | instead of raising this directly. |
| 98 | """ |
| 99 | pass |
| 100 | |
| 101 | class _ExpectedFailure(Exception): |
| 102 | """ |
| 103 | Raise this when a test is expected to fail. |
| 104 | |
| 105 | This is an implementation detail. |
| 106 | """ |
| 107 | |
| 108 | def __init__(self, exc_info): |
| 109 | super(_ExpectedFailure, self).__init__() |
| 110 | self.exc_info = exc_info |
| 111 | |
| 112 | class _UnexpectedSuccess(Exception): |
| 113 | """ |
| 114 | The test was supposed to fail, but it didn't! |
| 115 | """ |
| 116 | pass |
| 117 | |
| 118 | def _id(obj): |
| 119 | return obj |
| 120 | |
| 121 | def skip(reason): |
| 122 | """ |
| 123 | Unconditionally skip a test. |
| 124 | """ |
| 125 | def decorator(test_item): |
| 126 | if isinstance(test_item, type) and issubclass(test_item, TestCase): |
| 127 | test_item.__unittest_skip__ = True |
| 128 | test_item.__unittest_skip_why__ = reason |
| 129 | return test_item |
| 130 | @functools.wraps(test_item) |
| 131 | def skip_wrapper(*args, **kwargs): |
| 132 | raise SkipTest(reason) |
| 133 | return skip_wrapper |
| 134 | return decorator |
| 135 | |
| 136 | def skipIf(condition, reason): |
| 137 | """ |
| 138 | Skip a test if the condition is true. |
| 139 | """ |
| 140 | if condition: |
| 141 | return skip(reason) |
| 142 | return _id |
| 143 | |
| 144 | def skipUnless(condition, reason): |
| 145 | """ |
| 146 | Skip a test unless the condition is true. |
| 147 | """ |
| 148 | if not condition: |
| 149 | return skip(reason) |
| 150 | return _id |
| 151 | |
| 152 | |
| 153 | def expectedFailure(func): |
| 154 | @functools.wraps(func) |
| 155 | def wrapper(*args, **kwargs): |
| 156 | try: |
| 157 | func(*args, **kwargs) |
| 158 | except Exception: |
| 159 | raise _ExpectedFailure(sys.exc_info()) |
| 160 | raise _UnexpectedSuccess |
| 161 | return wrapper |
| 162 | |
Steve Purcell | b8d5f24 | 2003-12-06 13:03:13 +0000 | [diff] [blame] | 163 | __unittest = 1 |
| 164 | |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 165 | class TestResult(object): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 166 | """Holder for test result information. |
| 167 | |
| 168 | Test results are automatically managed by the TestCase and TestSuite |
| 169 | classes, and do not need to be explicitly manipulated by writers of tests. |
| 170 | |
| 171 | Each instance holds the total number of tests run, and collections of |
| 172 | failures and errors that occurred among those test runs. The collections |
Steve Purcell | 7b06570 | 2001-09-06 08:24:40 +0000 | [diff] [blame] | 173 | contain tuples of (testcase, exceptioninfo), where exceptioninfo is the |
Fred Drake | 656f9ec | 2001-09-06 19:13:14 +0000 | [diff] [blame] | 174 | formatted traceback of the error that occurred. |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 175 | """ |
| 176 | def __init__(self): |
| 177 | self.failures = [] |
| 178 | self.errors = [] |
| 179 | self.testsRun = 0 |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 180 | self.skipped = [] |
Benjamin Peterson | cb2b0e4 | 2009-03-23 22:29:45 +0000 | [diff] [blame] | 181 | self.expectedFailures = [] |
| 182 | self.unexpectedSuccesses = [] |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 183 | self.shouldStop = False |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 184 | |
| 185 | def startTest(self, test): |
| 186 | "Called when the given test is about to be run" |
| 187 | self.testsRun = self.testsRun + 1 |
| 188 | |
Michael Foord | 07ef487 | 2009-05-02 22:43:34 +0000 | [diff] [blame] | 189 | def startTestRun(self): |
| 190 | """Called once before any tests are executed. |
| 191 | |
| 192 | See startTest for a method called before each test. |
| 193 | """ |
| 194 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 195 | def stopTest(self, test): |
| 196 | "Called when the given test has been run" |
| 197 | pass |
| 198 | |
Michael Foord | 07ef487 | 2009-05-02 22:43:34 +0000 | [diff] [blame] | 199 | def stopTestRun(self): |
| 200 | """Called once after all tests are executed. |
| 201 | |
| 202 | See stopTest for a method called after each test. |
| 203 | """ |
| 204 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 205 | def addError(self, test, err): |
Steve Purcell | 7b06570 | 2001-09-06 08:24:40 +0000 | [diff] [blame] | 206 | """Called when an error has occurred. 'err' is a tuple of values as |
| 207 | returned by sys.exc_info(). |
| 208 | """ |
Steve Purcell | b8d5f24 | 2003-12-06 13:03:13 +0000 | [diff] [blame] | 209 | self.errors.append((test, self._exc_info_to_string(err, test))) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 210 | |
| 211 | def addFailure(self, test, err): |
Steve Purcell | 7b06570 | 2001-09-06 08:24:40 +0000 | [diff] [blame] | 212 | """Called when an error has occurred. 'err' is a tuple of values as |
| 213 | returned by sys.exc_info().""" |
Steve Purcell | b8d5f24 | 2003-12-06 13:03:13 +0000 | [diff] [blame] | 214 | self.failures.append((test, self._exc_info_to_string(err, test))) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 215 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 216 | def addSuccess(self, test): |
| 217 | "Called when a test has completed successfully" |
| 218 | pass |
| 219 | |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 220 | def addSkip(self, test, reason): |
| 221 | """Called when a test is skipped.""" |
| 222 | self.skipped.append((test, reason)) |
| 223 | |
| 224 | def addExpectedFailure(self, test, err): |
| 225 | """Called when an expected failure/error occured.""" |
Benjamin Peterson | cb2b0e4 | 2009-03-23 22:29:45 +0000 | [diff] [blame] | 226 | self.expectedFailures.append( |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 227 | (test, self._exc_info_to_string(err, test))) |
| 228 | |
| 229 | def addUnexpectedSuccess(self, test): |
| 230 | """Called when a test was expected to fail, but succeed.""" |
Benjamin Peterson | cb2b0e4 | 2009-03-23 22:29:45 +0000 | [diff] [blame] | 231 | self.unexpectedSuccesses.append(test) |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 232 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 233 | def wasSuccessful(self): |
| 234 | "Tells whether or not this result was a success" |
| 235 | return len(self.failures) == len(self.errors) == 0 |
| 236 | |
| 237 | def stop(self): |
| 238 | "Indicates that the tests should be aborted" |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 239 | self.shouldStop = True |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 240 | |
Steve Purcell | b8d5f24 | 2003-12-06 13:03:13 +0000 | [diff] [blame] | 241 | def _exc_info_to_string(self, err, test): |
Steve Purcell | 7b06570 | 2001-09-06 08:24:40 +0000 | [diff] [blame] | 242 | """Converts a sys.exc_info()-style tuple of values into a string.""" |
Steve Purcell | b8d5f24 | 2003-12-06 13:03:13 +0000 | [diff] [blame] | 243 | exctype, value, tb = err |
| 244 | # Skip test runner traceback levels |
| 245 | while tb and self._is_relevant_tb_level(tb): |
| 246 | tb = tb.tb_next |
| 247 | if exctype is test.failureException: |
| 248 | # Skip assert*() traceback levels |
| 249 | length = self._count_relevant_tb_levels(tb) |
| 250 | return ''.join(traceback.format_exception(exctype, value, tb, length)) |
| 251 | return ''.join(traceback.format_exception(exctype, value, tb)) |
| 252 | |
| 253 | def _is_relevant_tb_level(self, tb): |
Georg Brandl | 56af5fc | 2008-07-18 19:30:10 +0000 | [diff] [blame] | 254 | return '__unittest' in tb.tb_frame.f_globals |
Steve Purcell | b8d5f24 | 2003-12-06 13:03:13 +0000 | [diff] [blame] | 255 | |
| 256 | def _count_relevant_tb_levels(self, tb): |
| 257 | length = 0 |
| 258 | while tb and not self._is_relevant_tb_level(tb): |
| 259 | length += 1 |
| 260 | tb = tb.tb_next |
| 261 | return length |
Steve Purcell | 7b06570 | 2001-09-06 08:24:40 +0000 | [diff] [blame] | 262 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 263 | def __repr__(self): |
| 264 | return "<%s run=%i errors=%i failures=%i>" % \ |
Steve Purcell | dc391a6 | 2002-08-09 09:46:23 +0000 | [diff] [blame] | 265 | (_strclass(self.__class__), self.testsRun, len(self.errors), |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 266 | len(self.failures)) |
| 267 | |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 268 | |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 269 | class _AssertRaisesContext(object): |
| 270 | """A context manager used to implement TestCase.assertRaises* methods.""" |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 271 | |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 272 | def __init__(self, expected, test_case, expected_regexp=None): |
Antoine Pitrou | 697ca3d | 2008-12-28 14:09:36 +0000 | [diff] [blame] | 273 | self.expected = expected |
| 274 | self.failureException = test_case.failureException |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 275 | self.expected_regex = expected_regexp |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 276 | |
Antoine Pitrou | 697ca3d | 2008-12-28 14:09:36 +0000 | [diff] [blame] | 277 | def __enter__(self): |
| 278 | pass |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 279 | |
Benjamin Peterson | baba195 | 2009-04-18 19:26:19 +0000 | [diff] [blame] | 280 | def __exit__(self, exc_type, exc_value, tb): |
Antoine Pitrou | 697ca3d | 2008-12-28 14:09:36 +0000 | [diff] [blame] | 281 | if exc_type is None: |
| 282 | try: |
| 283 | exc_name = self.expected.__name__ |
| 284 | except AttributeError: |
| 285 | exc_name = str(self.expected) |
| 286 | raise self.failureException( |
| 287 | "{0} not raised".format(exc_name)) |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 288 | if not issubclass(exc_type, self.expected): |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 289 | # let unexpected exceptions pass through |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 290 | return False |
| 291 | if self.expected_regex is None: |
Antoine Pitrou | 697ca3d | 2008-12-28 14:09:36 +0000 | [diff] [blame] | 292 | return True |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 293 | |
| 294 | expected_regexp = self.expected_regex |
| 295 | if isinstance(expected_regexp, basestring): |
| 296 | expected_regexp = re.compile(expected_regexp) |
| 297 | if not expected_regexp.search(str(exc_value)): |
| 298 | raise self.failureException('"%s" does not match "%s"' % |
| 299 | (expected_regexp.pattern, str(exc_value))) |
| 300 | return True |
| 301 | |
Antoine Pitrou | 697ca3d | 2008-12-28 14:09:36 +0000 | [diff] [blame] | 302 | |
Michael Foord | e2942d0 | 2009-04-02 05:51:54 +0000 | [diff] [blame] | 303 | class _AssertWrapper(object): |
| 304 | """Wrap entries in the _type_equality_funcs registry to make them deep |
| 305 | copyable.""" |
| 306 | |
| 307 | def __init__(self, function): |
| 308 | self.function = function |
| 309 | |
| 310 | def __deepcopy__(self, memo): |
| 311 | memo[id(self)] = self |
| 312 | |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 313 | |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 314 | class TestCase(object): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 315 | """A class whose instances are single test cases. |
| 316 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 317 | By default, the test code itself should be placed in a method named |
| 318 | 'runTest'. |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 319 | |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 320 | If the fixture may be used for many test cases, create as |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 321 | many test methods as are needed. When instantiating such a TestCase |
| 322 | subclass, specify in the constructor arguments the name of the test method |
| 323 | that the instance is to execute. |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 324 | |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 325 | Test authors should subclass TestCase for their own tests. Construction |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 326 | and deconstruction of the test's environment ('fixture') can be |
| 327 | implemented by overriding the 'setUp' and 'tearDown' methods respectively. |
| 328 | |
| 329 | If it is necessary to override the __init__ method, the base class |
| 330 | __init__ method must always be called. It is important that subclasses |
| 331 | should not change the signature of their __init__ method, since instances |
| 332 | of the classes are instantiated automatically by parts of the framework |
| 333 | in order to be run. |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 334 | """ |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 335 | |
| 336 | # This attribute determines which exception will be raised when |
| 337 | # the instance's assertion methods fail; test methods raising this |
| 338 | # exception will be deemed to have 'failed' rather than 'errored' |
| 339 | |
| 340 | failureException = AssertionError |
| 341 | |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 342 | # This attribute determines whether long messages (including repr of |
| 343 | # objects used in assert methods) will be printed on failure in *addition* |
| 344 | # to any explicit message passed. |
| 345 | |
| 346 | longMessage = False |
| 347 | |
| 348 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 349 | def __init__(self, methodName='runTest'): |
| 350 | """Create an instance of the class that will use the named test |
| 351 | method when executed. Raises a ValueError if the instance does |
| 352 | not have a method with the specified name. |
| 353 | """ |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 354 | self._testMethodName = methodName |
Michael Foord | a50af06 | 2009-05-21 22:57:02 +0000 | [diff] [blame] | 355 | self._resultForDoCleanups = None |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 356 | try: |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 357 | testMethod = getattr(self, methodName) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 358 | except AttributeError: |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 359 | raise ValueError("no such test method in %s: %s" % \ |
| 360 | (self.__class__, methodName)) |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 361 | self._testMethodDoc = testMethod.__doc__ |
Michael Foord | e2fb98f | 2009-05-02 20:15:05 +0000 | [diff] [blame] | 362 | self._cleanups = [] |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 363 | |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 364 | # Map types to custom assertEqual functions that will compare |
| 365 | # instances of said type in more detail to generate a more useful |
| 366 | # error message. |
Benjamin Peterson | 71095ae | 2009-04-01 23:15:49 +0000 | [diff] [blame] | 367 | self._type_equality_funcs = {} |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 368 | self.addTypeEqualityFunc(dict, self.assertDictEqual) |
| 369 | self.addTypeEqualityFunc(list, self.assertListEqual) |
| 370 | self.addTypeEqualityFunc(tuple, self.assertTupleEqual) |
| 371 | self.addTypeEqualityFunc(set, self.assertSetEqual) |
| 372 | self.addTypeEqualityFunc(frozenset, self.assertSetEqual) |
| 373 | |
| 374 | def addTypeEqualityFunc(self, typeobj, function): |
| 375 | """Add a type specific assertEqual style function to compare a type. |
| 376 | |
| 377 | This method is for use by TestCase subclasses that need to register |
| 378 | their own type equality functions to provide nicer error messages. |
| 379 | |
| 380 | Args: |
| 381 | typeobj: The data type to call this function on when both values |
| 382 | are of the same type in assertEqual(). |
| 383 | function: The callable taking two arguments and an optional |
| 384 | msg= argument that raises self.failureException with a |
| 385 | useful error message when the two arguments are not equal. |
| 386 | """ |
Michael Foord | e2942d0 | 2009-04-02 05:51:54 +0000 | [diff] [blame] | 387 | self._type_equality_funcs[typeobj] = _AssertWrapper(function) |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 388 | |
Michael Foord | e2fb98f | 2009-05-02 20:15:05 +0000 | [diff] [blame] | 389 | def addCleanup(self, function, *args, **kwargs): |
| 390 | """Add a function, with arguments, to be called when the test is |
| 391 | completed. Functions added are called on a LIFO basis and are |
| 392 | called after tearDown on test failure or success. |
| 393 | |
| 394 | Cleanup items are called even if setUp fails (unlike tearDown).""" |
| 395 | self._cleanups.append((function, args, kwargs)) |
| 396 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 397 | def setUp(self): |
| 398 | "Hook method for setting up the test fixture before exercising it." |
| 399 | pass |
| 400 | |
| 401 | def tearDown(self): |
| 402 | "Hook method for deconstructing the test fixture after testing it." |
| 403 | pass |
| 404 | |
| 405 | def countTestCases(self): |
| 406 | return 1 |
| 407 | |
| 408 | def defaultTestResult(self): |
| 409 | return TestResult() |
| 410 | |
| 411 | def shortDescription(self): |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 412 | """Returns both the test method name and first line of its docstring. |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 413 | |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 414 | If no docstring is given, only returns the method name. |
| 415 | |
| 416 | This method overrides unittest.TestCase.shortDescription(), which |
| 417 | only returns the first line of the docstring, obscuring the name |
| 418 | of the test upon failure. |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 419 | """ |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 420 | desc = str(self) |
| 421 | doc_first_line = None |
| 422 | |
| 423 | if self._testMethodDoc: |
| 424 | doc_first_line = self._testMethodDoc.split("\n")[0].strip() |
| 425 | if doc_first_line: |
| 426 | desc = '\n'.join((desc, doc_first_line)) |
| 427 | return desc |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 428 | |
| 429 | def id(self): |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 430 | return "%s.%s" % (_strclass(self.__class__), self._testMethodName) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 431 | |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 432 | def __eq__(self, other): |
| 433 | if type(self) is not type(other): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 434 | return NotImplemented |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 435 | |
| 436 | return self._testMethodName == other._testMethodName |
| 437 | |
| 438 | def __ne__(self, other): |
| 439 | return not self == other |
| 440 | |
| 441 | def __hash__(self): |
Collin Winter | 9453e5d | 2007-03-09 23:30:39 +0000 | [diff] [blame] | 442 | return hash((type(self), self._testMethodName)) |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 443 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 444 | def __str__(self): |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 445 | return "%s (%s)" % (self._testMethodName, _strclass(self.__class__)) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 446 | |
| 447 | def __repr__(self): |
| 448 | return "<%s testMethod=%s>" % \ |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 449 | (_strclass(self.__class__), self._testMethodName) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 450 | |
| 451 | def run(self, result=None): |
Michael Foord | 07ef487 | 2009-05-02 22:43:34 +0000 | [diff] [blame] | 452 | orig_result = result |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 453 | if result is None: |
| 454 | result = self.defaultTestResult() |
Michael Foord | 07ef487 | 2009-05-02 22:43:34 +0000 | [diff] [blame] | 455 | startTestRun = getattr(result, 'startTestRun', None) |
| 456 | if startTestRun is not None: |
| 457 | startTestRun() |
| 458 | |
Michael Foord | a50af06 | 2009-05-21 22:57:02 +0000 | [diff] [blame] | 459 | self._resultForDoCleanups = result |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 460 | result.startTest(self) |
Benjamin Peterson | 176a56c | 2009-05-25 00:48:58 +0000 | [diff] [blame] | 461 | if getattr(self.__class__, "__unittest_skip__", False): |
| 462 | # If the whole class was skipped. |
| 463 | try: |
| 464 | result.addSkip(self, self.__class__.__unittest_skip_why__) |
| 465 | finally: |
| 466 | result.stopTest(self) |
| 467 | return |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 468 | testMethod = getattr(self, self._testMethodName) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 469 | try: |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 470 | success = False |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 471 | try: |
Michael Foord | e2fb98f | 2009-05-02 20:15:05 +0000 | [diff] [blame] | 472 | self.setUp() |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 473 | except SkipTest as e: |
| 474 | result.addSkip(self, str(e)) |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 475 | except Exception: |
Benjamin Peterson | c930135 | 2009-03-26 16:32:23 +0000 | [diff] [blame] | 476 | result.addError(self, sys.exc_info()) |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 477 | else: |
Michael Foord | e2fb98f | 2009-05-02 20:15:05 +0000 | [diff] [blame] | 478 | try: |
| 479 | testMethod() |
| 480 | except self.failureException: |
| 481 | result.addFailure(self, sys.exc_info()) |
| 482 | except _ExpectedFailure as e: |
| 483 | result.addExpectedFailure(self, e.exc_info) |
| 484 | except _UnexpectedSuccess: |
| 485 | result.addUnexpectedSuccess(self) |
| 486 | except SkipTest as e: |
| 487 | result.addSkip(self, str(e)) |
| 488 | except Exception: |
| 489 | result.addError(self, sys.exc_info()) |
| 490 | else: |
| 491 | success = True |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 492 | |
Michael Foord | e2fb98f | 2009-05-02 20:15:05 +0000 | [diff] [blame] | 493 | try: |
| 494 | self.tearDown() |
| 495 | except Exception: |
| 496 | result.addError(self, sys.exc_info()) |
| 497 | success = False |
| 498 | |
| 499 | cleanUpSuccess = self.doCleanups() |
| 500 | success = success and cleanUpSuccess |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 501 | if success: |
| 502 | result.addSuccess(self) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 503 | finally: |
| 504 | result.stopTest(self) |
Michael Foord | 07ef487 | 2009-05-02 22:43:34 +0000 | [diff] [blame] | 505 | if orig_result is None: |
| 506 | stopTestRun = getattr(result, 'stopTestRun', None) |
| 507 | if stopTestRun is not None: |
| 508 | stopTestRun() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 509 | |
Michael Foord | e2fb98f | 2009-05-02 20:15:05 +0000 | [diff] [blame] | 510 | def doCleanups(self): |
| 511 | """Execute all cleanup functions. Normally called for you after |
| 512 | tearDown.""" |
Michael Foord | a50af06 | 2009-05-21 22:57:02 +0000 | [diff] [blame] | 513 | result = self._resultForDoCleanups |
Michael Foord | e2fb98f | 2009-05-02 20:15:05 +0000 | [diff] [blame] | 514 | ok = True |
| 515 | while self._cleanups: |
| 516 | function, args, kwargs = self._cleanups.pop(-1) |
| 517 | try: |
| 518 | function(*args, **kwargs) |
| 519 | except Exception: |
| 520 | ok = False |
| 521 | result.addError(self, sys.exc_info()) |
| 522 | return ok |
| 523 | |
Raymond Hettinger | 664347b | 2004-12-04 21:21:53 +0000 | [diff] [blame] | 524 | def __call__(self, *args, **kwds): |
| 525 | return self.run(*args, **kwds) |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 526 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 527 | def debug(self): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 528 | """Run the test without collecting errors in a TestResult""" |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 529 | self.setUp() |
Georg Brandl | 81cdb4e | 2006-01-20 17:55:00 +0000 | [diff] [blame] | 530 | getattr(self, self._testMethodName)() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 531 | self.tearDown() |
| 532 | |
Benjamin Peterson | 47d9738 | 2009-03-26 20:05:50 +0000 | [diff] [blame] | 533 | def skipTest(self, reason): |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 534 | """Skip this test.""" |
| 535 | raise SkipTest(reason) |
| 536 | |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 537 | def fail(self, msg=None): |
| 538 | """Fail immediately, with the given message.""" |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 539 | raise self.failureException(msg) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 540 | |
Gregory P. Smith | 7558d57 | 2009-03-31 19:03:28 +0000 | [diff] [blame] | 541 | def assertFalse(self, expr, msg=None): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 542 | "Fail the test if the expression is true." |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 543 | if expr: |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 544 | msg = self._formatMessage(msg, "%r is not False" % expr) |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 545 | raise self.failureException(msg) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 546 | |
Gregory P. Smith | 7558d57 | 2009-03-31 19:03:28 +0000 | [diff] [blame] | 547 | def assertTrue(self, expr, msg=None): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 548 | """Fail the test unless the expression is true.""" |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 549 | if not expr: |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 550 | msg = self._formatMessage(msg, "%r is not True" % expr) |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 551 | raise self.failureException(msg) |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 552 | |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 553 | def _formatMessage(self, msg, standardMsg): |
| 554 | """Honour the longMessage attribute when generating failure messages. |
| 555 | If longMessage is False this means: |
| 556 | * Use only an explicit message if it is provided |
| 557 | * Otherwise use the standard message for the assert |
| 558 | |
| 559 | If longMessage is True: |
| 560 | * Use the standard message |
| 561 | * If an explicit message is provided, plus ' : ' and the explicit message |
| 562 | """ |
| 563 | if not self.longMessage: |
| 564 | return msg or standardMsg |
| 565 | if msg is None: |
| 566 | return standardMsg |
| 567 | return standardMsg + ' : ' + msg |
| 568 | |
| 569 | |
Gregory P. Smith | 7558d57 | 2009-03-31 19:03:28 +0000 | [diff] [blame] | 570 | def assertRaises(self, excClass, callableObj=None, *args, **kwargs): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 571 | """Fail unless an exception of class excClass is thrown |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 572 | by callableObj when invoked with arguments args and keyword |
| 573 | arguments kwargs. If a different type of exception is |
| 574 | thrown, it will not be caught, and the test case will be |
| 575 | deemed to have suffered an error, exactly as for an |
| 576 | unexpected exception. |
Antoine Pitrou | 697ca3d | 2008-12-28 14:09:36 +0000 | [diff] [blame] | 577 | |
| 578 | If called with callableObj omitted or None, will return a |
| 579 | context object used like this:: |
| 580 | |
Gregory P. Smith | 7558d57 | 2009-03-31 19:03:28 +0000 | [diff] [blame] | 581 | with self.assertRaises(some_error_class): |
Antoine Pitrou | 697ca3d | 2008-12-28 14:09:36 +0000 | [diff] [blame] | 582 | do_something() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 583 | """ |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 584 | context = _AssertRaisesContext(excClass, self) |
Antoine Pitrou | 697ca3d | 2008-12-28 14:09:36 +0000 | [diff] [blame] | 585 | if callableObj is None: |
| 586 | return context |
| 587 | with context: |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 588 | callableObj(*args, **kwargs) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 589 | |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 590 | def _getAssertEqualityFunc(self, first, second): |
| 591 | """Get a detailed comparison function for the types of the two args. |
| 592 | |
| 593 | Returns: A callable accepting (first, second, msg=None) that will |
| 594 | raise a failure exception if first != second with a useful human |
| 595 | readable error message for those types. |
| 596 | """ |
| 597 | # |
| 598 | # NOTE(gregory.p.smith): I considered isinstance(first, type(second)) |
| 599 | # and vice versa. I opted for the conservative approach in case |
| 600 | # subclasses are not intended to be compared in detail to their super |
| 601 | # class instances using a type equality func. This means testing |
| 602 | # subtypes won't automagically use the detailed comparison. Callers |
| 603 | # should use their type specific assertSpamEqual method to compare |
| 604 | # subclasses if the detailed comparison is desired and appropriate. |
| 605 | # See the discussion in http://bugs.python.org/issue2578. |
| 606 | # |
| 607 | if type(first) is type(second): |
Michael Foord | e2942d0 | 2009-04-02 05:51:54 +0000 | [diff] [blame] | 608 | asserter = self._type_equality_funcs.get(type(first)) |
| 609 | if asserter is not None: |
| 610 | return asserter.function |
| 611 | |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 612 | return self._baseAssertEqual |
| 613 | |
| 614 | def _baseAssertEqual(self, first, second, msg=None): |
| 615 | """The default assertEqual implementation, not type specific.""" |
| 616 | if not first == second: |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 617 | standardMsg = '%r != %r' % (first, second) |
| 618 | msg = self._formatMessage(msg, standardMsg) |
| 619 | raise self.failureException(msg) |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 620 | |
Gregory P. Smith | 7558d57 | 2009-03-31 19:03:28 +0000 | [diff] [blame] | 621 | def assertEqual(self, first, second, msg=None): |
Raymond Hettinger | c377cbf | 2003-04-04 22:56:42 +0000 | [diff] [blame] | 622 | """Fail if the two objects are unequal as determined by the '==' |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 623 | operator. |
| 624 | """ |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 625 | assertion_func = self._getAssertEqualityFunc(first, second) |
| 626 | assertion_func(first, second, msg=msg) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 627 | |
Gregory P. Smith | 7558d57 | 2009-03-31 19:03:28 +0000 | [diff] [blame] | 628 | def assertNotEqual(self, first, second, msg=None): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 629 | """Fail if the two objects are equal as determined by the '==' |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 630 | operator. |
| 631 | """ |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 632 | if not first != second: |
| 633 | msg = self._formatMessage(msg, '%r == %r' % (first, second)) |
| 634 | raise self.failureException(msg) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 635 | |
Gregory P. Smith | 7558d57 | 2009-03-31 19:03:28 +0000 | [diff] [blame] | 636 | def assertAlmostEqual(self, first, second, places=7, msg=None): |
Raymond Hettinger | c7b0769 | 2002-12-29 17:59:24 +0000 | [diff] [blame] | 637 | """Fail if the two objects are unequal as determined by their |
| 638 | difference rounded to the given number of decimal places |
| 639 | (default 7) and comparing to zero. |
| 640 | |
Steve Purcell | 397b45d | 2003-10-26 10:41:03 +0000 | [diff] [blame] | 641 | Note that decimal places (from zero) are usually not the same |
Raymond Hettinger | c7b0769 | 2002-12-29 17:59:24 +0000 | [diff] [blame] | 642 | as significant digits (measured from the most signficant digit). |
| 643 | """ |
Jeffrey Yasskin | 2f3c16b | 2008-01-03 02:21:52 +0000 | [diff] [blame] | 644 | if round(abs(second-first), places) != 0: |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 645 | standardMsg = '%r != %r within %r places' % (first, second, places) |
| 646 | msg = self._formatMessage(msg, standardMsg) |
| 647 | raise self.failureException(msg) |
Raymond Hettinger | c7b0769 | 2002-12-29 17:59:24 +0000 | [diff] [blame] | 648 | |
Gregory P. Smith | 7558d57 | 2009-03-31 19:03:28 +0000 | [diff] [blame] | 649 | def assertNotAlmostEqual(self, first, second, places=7, msg=None): |
Raymond Hettinger | c7b0769 | 2002-12-29 17:59:24 +0000 | [diff] [blame] | 650 | """Fail if the two objects are equal as determined by their |
| 651 | difference rounded to the given number of decimal places |
| 652 | (default 7) and comparing to zero. |
| 653 | |
Steve Purcell | cca3491 | 2003-10-26 16:38:16 +0000 | [diff] [blame] | 654 | Note that decimal places (from zero) are usually not the same |
Raymond Hettinger | c7b0769 | 2002-12-29 17:59:24 +0000 | [diff] [blame] | 655 | as significant digits (measured from the most signficant digit). |
| 656 | """ |
Jeffrey Yasskin | 2f3c16b | 2008-01-03 02:21:52 +0000 | [diff] [blame] | 657 | if round(abs(second-first), places) == 0: |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 658 | standardMsg = '%r == %r within %r places' % (first, second, places) |
| 659 | msg = self._formatMessage(msg, standardMsg) |
| 660 | raise self.failureException(msg) |
Raymond Hettinger | c7b0769 | 2002-12-29 17:59:24 +0000 | [diff] [blame] | 661 | |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 662 | # Synonyms for assertion methods |
| 663 | |
Gregory P. Smith | 7558d57 | 2009-03-31 19:03:28 +0000 | [diff] [blame] | 664 | # The plurals are undocumented. Keep them that way to discourage use. |
| 665 | # Do not add more. Do not remove. |
| 666 | # Going through a deprecation cycle on these would annoy many people. |
| 667 | assertEquals = assertEqual |
| 668 | assertNotEquals = assertNotEqual |
| 669 | assertAlmostEquals = assertAlmostEqual |
| 670 | assertNotAlmostEquals = assertNotAlmostEqual |
| 671 | assert_ = assertTrue |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 672 | |
Gregory P. Smith | 7558d57 | 2009-03-31 19:03:28 +0000 | [diff] [blame] | 673 | # These fail* assertion method names are pending deprecation and will |
Gregory P. Smith | 65ff005 | 2009-03-31 19:59:14 +0000 | [diff] [blame] | 674 | # be a DeprecationWarning in 3.2; http://bugs.python.org/issue2578 |
Benjamin Peterson | 71095ae | 2009-04-01 23:15:49 +0000 | [diff] [blame] | 675 | def _deprecate(original_func): |
Gregory P. Smith | 65ff005 | 2009-03-31 19:59:14 +0000 | [diff] [blame] | 676 | def deprecated_func(*args, **kwargs): |
| 677 | warnings.warn( |
| 678 | 'Please use {0} instead.'.format(original_func.__name__), |
| 679 | PendingDeprecationWarning, 2) |
| 680 | return original_func(*args, **kwargs) |
| 681 | return deprecated_func |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 682 | |
Benjamin Peterson | 71095ae | 2009-04-01 23:15:49 +0000 | [diff] [blame] | 683 | failUnlessEqual = _deprecate(assertEqual) |
| 684 | failIfEqual = _deprecate(assertNotEqual) |
| 685 | failUnlessAlmostEqual = _deprecate(assertAlmostEqual) |
| 686 | failIfAlmostEqual = _deprecate(assertNotAlmostEqual) |
| 687 | failUnless = _deprecate(assertTrue) |
| 688 | failUnlessRaises = _deprecate(assertRaises) |
| 689 | failIf = _deprecate(assertFalse) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 690 | |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 691 | def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None): |
| 692 | """An equality assertion for ordered sequences (like lists and tuples). |
| 693 | |
| 694 | For the purposes of this function, a valid orderd sequence type is one |
| 695 | which can be indexed, has a length, and has an equality operator. |
| 696 | |
| 697 | Args: |
| 698 | seq1: The first sequence to compare. |
| 699 | seq2: The second sequence to compare. |
| 700 | seq_type: The expected datatype of the sequences, or None if no |
| 701 | datatype should be enforced. |
| 702 | msg: Optional message to use on failure instead of a list of |
| 703 | differences. |
| 704 | """ |
| 705 | if seq_type != None: |
| 706 | seq_type_name = seq_type.__name__ |
| 707 | if not isinstance(seq1, seq_type): |
| 708 | raise self.failureException('First sequence is not a %s: %r' |
| 709 | % (seq_type_name, seq1)) |
| 710 | if not isinstance(seq2, seq_type): |
| 711 | raise self.failureException('Second sequence is not a %s: %r' |
| 712 | % (seq_type_name, seq2)) |
| 713 | else: |
| 714 | seq_type_name = "sequence" |
| 715 | |
| 716 | differing = None |
| 717 | try: |
| 718 | len1 = len(seq1) |
| 719 | except (TypeError, NotImplementedError): |
| 720 | differing = 'First %s has no length. Non-sequence?' % ( |
| 721 | seq_type_name) |
| 722 | |
| 723 | if differing is None: |
| 724 | try: |
| 725 | len2 = len(seq2) |
| 726 | except (TypeError, NotImplementedError): |
| 727 | differing = 'Second %s has no length. Non-sequence?' % ( |
| 728 | seq_type_name) |
| 729 | |
| 730 | if differing is None: |
| 731 | if seq1 == seq2: |
| 732 | return |
| 733 | |
Michael Foord | 0451661 | 2009-05-25 20:36:56 +0000 | [diff] [blame^] | 734 | seq1_repr = repr(seq1) |
| 735 | seq2_repr = repr(seq2) |
| 736 | if len(seq1_repr) > 30: |
| 737 | seq1_repr = seq1_repr[:30] + '...' |
| 738 | if len(seq2_repr) > 30: |
| 739 | seq2_repr = seq2_repr[:30] + '...' |
| 740 | elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr) |
| 741 | differing = '%ss differ: %s != %s\n' % elements |
| 742 | |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 743 | for i in xrange(min(len1, len2)): |
| 744 | try: |
| 745 | item1 = seq1[i] |
| 746 | except (TypeError, IndexError, NotImplementedError): |
Michael Foord | 0451661 | 2009-05-25 20:36:56 +0000 | [diff] [blame^] | 747 | differing += ('\nUnable to index element %d of first %s\n' % |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 748 | (i, seq_type_name)) |
| 749 | break |
| 750 | |
| 751 | try: |
| 752 | item2 = seq2[i] |
| 753 | except (TypeError, IndexError, NotImplementedError): |
Michael Foord | 0451661 | 2009-05-25 20:36:56 +0000 | [diff] [blame^] | 754 | differing += ('\nUnable to index element %d of second %s\n' % |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 755 | (i, seq_type_name)) |
| 756 | break |
| 757 | |
| 758 | if item1 != item2: |
Michael Foord | 0451661 | 2009-05-25 20:36:56 +0000 | [diff] [blame^] | 759 | differing += ('\nFirst differing element %d:\n%s\n%s\n' % |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 760 | (i, item1, item2)) |
| 761 | break |
| 762 | else: |
| 763 | if (len1 == len2 and seq_type is None and |
| 764 | type(seq1) != type(seq2)): |
| 765 | # The sequences are the same, but have differing types. |
| 766 | return |
Michael Foord | 0451661 | 2009-05-25 20:36:56 +0000 | [diff] [blame^] | 767 | |
| 768 | if len1 > len2: |
| 769 | differing += ('\nFirst %s contains %d additional ' |
| 770 | 'elements.\n' % (seq_type_name, len1 - len2)) |
| 771 | try: |
| 772 | differing += ('First extra element %d:\n%s\n' % |
| 773 | (len2, seq1[len2])) |
| 774 | except (TypeError, IndexError, NotImplementedError): |
| 775 | differing += ('Unable to index element %d ' |
| 776 | 'of first %s\n' % (len2, seq_type_name)) |
| 777 | elif len1 < len2: |
| 778 | differing += ('\nSecond %s contains %d additional ' |
| 779 | 'elements.\n' % (seq_type_name, len2 - len1)) |
| 780 | try: |
| 781 | differing += ('First extra element %d:\n%s\n' % |
| 782 | (len1, seq2[len1])) |
| 783 | except (TypeError, IndexError, NotImplementedError): |
| 784 | differing += ('Unable to index element %d ' |
| 785 | 'of second %s\n' % (len1, seq_type_name)) |
| 786 | standardMsg = differing + '\n' + '\n'.join(difflib.ndiff(pprint.pformat(seq1).splitlines(), |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 787 | pprint.pformat(seq2).splitlines())) |
| 788 | msg = self._formatMessage(msg, standardMsg) |
| 789 | self.fail(msg) |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 790 | |
| 791 | def assertListEqual(self, list1, list2, msg=None): |
| 792 | """A list-specific equality assertion. |
| 793 | |
| 794 | Args: |
| 795 | list1: The first list to compare. |
| 796 | list2: The second list to compare. |
| 797 | msg: Optional message to use on failure instead of a list of |
| 798 | differences. |
| 799 | |
| 800 | """ |
| 801 | self.assertSequenceEqual(list1, list2, msg, seq_type=list) |
| 802 | |
| 803 | def assertTupleEqual(self, tuple1, tuple2, msg=None): |
| 804 | """A tuple-specific equality assertion. |
| 805 | |
| 806 | Args: |
| 807 | tuple1: The first tuple to compare. |
| 808 | tuple2: The second tuple to compare. |
| 809 | msg: Optional message to use on failure instead of a list of |
| 810 | differences. |
| 811 | """ |
| 812 | self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple) |
| 813 | |
| 814 | def assertSetEqual(self, set1, set2, msg=None): |
| 815 | """A set-specific equality assertion. |
| 816 | |
| 817 | Args: |
| 818 | set1: The first set to compare. |
| 819 | set2: The second set to compare. |
| 820 | msg: Optional message to use on failure instead of a list of |
| 821 | differences. |
| 822 | |
| 823 | For more general containership equality, assertSameElements will work |
| 824 | with things other than sets. This uses ducktyping to support |
| 825 | different types of sets, and is optimized for sets specifically |
| 826 | (parameters must support a difference method). |
| 827 | """ |
| 828 | try: |
| 829 | difference1 = set1.difference(set2) |
| 830 | except TypeError, e: |
| 831 | self.fail('invalid type when attempting set difference: %s' % e) |
| 832 | except AttributeError, e: |
| 833 | self.fail('first argument does not support set difference: %s' % e) |
| 834 | |
| 835 | try: |
| 836 | difference2 = set2.difference(set1) |
| 837 | except TypeError, e: |
| 838 | self.fail('invalid type when attempting set difference: %s' % e) |
| 839 | except AttributeError, e: |
| 840 | self.fail('second argument does not support set difference: %s' % e) |
| 841 | |
| 842 | if not (difference1 or difference2): |
| 843 | return |
| 844 | |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 845 | lines = [] |
| 846 | if difference1: |
| 847 | lines.append('Items in the first set but not the second:') |
| 848 | for item in difference1: |
| 849 | lines.append(repr(item)) |
| 850 | if difference2: |
| 851 | lines.append('Items in the second set but not the first:') |
| 852 | for item in difference2: |
| 853 | lines.append(repr(item)) |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 854 | |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 855 | standardMsg = '\n'.join(lines) |
| 856 | self.fail(self._formatMessage(msg, standardMsg)) |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 857 | |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 858 | def assertIn(self, member, container, msg=None): |
| 859 | """Just like self.assertTrue(a in b), but with a nicer default message.""" |
| 860 | if member not in container: |
| 861 | standardMsg = '%r not found in %r' % (member, container) |
| 862 | self.fail(self._formatMessage(msg, standardMsg)) |
| 863 | |
| 864 | def assertNotIn(self, member, container, msg=None): |
| 865 | """Just like self.assertTrue(a not in b), but with a nicer default message.""" |
| 866 | if member in container: |
| 867 | standardMsg = '%r unexpectedly found in %r' % (member, container) |
| 868 | self.fail(self._formatMessage(msg, standardMsg)) |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 869 | |
Michael Foord | f2dfef1 | 2009-04-05 19:19:28 +0000 | [diff] [blame] | 870 | def assertIs(self, expr1, expr2, msg=None): |
| 871 | """Just like self.assertTrue(a is b), but with a nicer default message.""" |
| 872 | if expr1 is not expr2: |
| 873 | standardMsg = '%r is not %r' % (expr1, expr2) |
| 874 | self.fail(self._formatMessage(msg, standardMsg)) |
| 875 | |
| 876 | def assertIsNot(self, expr1, expr2, msg=None): |
| 877 | """Just like self.assertTrue(a is not b), but with a nicer default message.""" |
| 878 | if expr1 is expr2: |
| 879 | standardMsg = 'unexpectedly identical: %r' % (expr1,) |
| 880 | self.fail(self._formatMessage(msg, standardMsg)) |
| 881 | |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 882 | def assertDictEqual(self, d1, d2, msg=None): |
| 883 | self.assert_(isinstance(d1, dict), 'First argument is not a dictionary') |
| 884 | self.assert_(isinstance(d2, dict), 'Second argument is not a dictionary') |
| 885 | |
| 886 | if d1 != d2: |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 887 | standardMsg = ('\n' + '\n'.join(difflib.ndiff( |
| 888 | pprint.pformat(d1).splitlines(), |
| 889 | pprint.pformat(d2).splitlines()))) |
| 890 | self.fail(self._formatMessage(msg, standardMsg)) |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 891 | |
| 892 | def assertDictContainsSubset(self, expected, actual, msg=None): |
| 893 | """Checks whether actual is a superset of expected.""" |
| 894 | missing = [] |
| 895 | mismatched = [] |
| 896 | for key, value in expected.iteritems(): |
| 897 | if key not in actual: |
| 898 | missing.append(key) |
| 899 | elif value != actual[key]: |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 900 | mismatched.append('%s, expected: %s, actual: %s' % (key, value, actual[key])) |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 901 | |
| 902 | if not (missing or mismatched): |
| 903 | return |
| 904 | |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 905 | standardMsg = '' |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 906 | if missing: |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 907 | standardMsg = 'Missing: %r' % ','.join(missing) |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 908 | if mismatched: |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 909 | if standardMsg: |
| 910 | standardMsg += '; ' |
| 911 | standardMsg += 'Mismatched values: %s' % ','.join(mismatched) |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 912 | |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 913 | self.fail(self._formatMessage(msg, standardMsg)) |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 914 | |
| 915 | def assertSameElements(self, expected_seq, actual_seq, msg=None): |
| 916 | """An unordered sequence specific comparison. |
| 917 | |
| 918 | Raises with an error message listing which elements of expected_seq |
| 919 | are missing from actual_seq and vice versa if any. |
| 920 | """ |
| 921 | try: |
| 922 | expected = set(expected_seq) |
| 923 | actual = set(actual_seq) |
| 924 | missing = list(expected.difference(actual)) |
| 925 | unexpected = list(actual.difference(expected)) |
| 926 | missing.sort() |
| 927 | unexpected.sort() |
| 928 | except TypeError: |
| 929 | # Fall back to slower list-compare if any of the objects are |
| 930 | # not hashable. |
| 931 | expected = list(expected_seq) |
| 932 | actual = list(actual_seq) |
| 933 | expected.sort() |
| 934 | actual.sort() |
| 935 | missing, unexpected = _SortedListDifference(expected, actual) |
| 936 | errors = [] |
| 937 | if missing: |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 938 | errors.append('Expected, but missing:\n %r' % missing) |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 939 | if unexpected: |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 940 | errors.append('Unexpected, but present:\n %r' % unexpected) |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 941 | if errors: |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 942 | standardMsg = '\n'.join(errors) |
| 943 | self.fail(self._formatMessage(msg, standardMsg)) |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 944 | |
| 945 | def assertMultiLineEqual(self, first, second, msg=None): |
| 946 | """Assert that two multi-line strings are equal.""" |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 947 | self.assert_(isinstance(first, basestring), ( |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 948 | 'First argument is not a string')) |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 949 | self.assert_(isinstance(second, basestring), ( |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 950 | 'Second argument is not a string')) |
| 951 | |
| 952 | if first != second: |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 953 | standardMsg = '\n' + ''.join(difflib.ndiff(first.splitlines(True), second.splitlines(True))) |
| 954 | self.fail(self._formatMessage(msg, standardMsg)) |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 955 | |
| 956 | def assertLess(self, a, b, msg=None): |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 957 | """Just like self.assertTrue(a < b), but with a nicer default message.""" |
| 958 | if not a < b: |
| 959 | standardMsg = '%r not less than %r' % (a, b) |
| 960 | self.fail(self._formatMessage(msg, standardMsg)) |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 961 | |
| 962 | def assertLessEqual(self, a, b, msg=None): |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 963 | """Just like self.assertTrue(a <= b), but with a nicer default message.""" |
| 964 | if not a <= b: |
| 965 | standardMsg = '%r not less than or equal to %r' % (a, b) |
| 966 | self.fail(self._formatMessage(msg, standardMsg)) |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 967 | |
| 968 | def assertGreater(self, a, b, msg=None): |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 969 | """Just like self.assertTrue(a > b), but with a nicer default message.""" |
| 970 | if not a > b: |
| 971 | standardMsg = '%r not greater than %r' % (a, b) |
| 972 | self.fail(self._formatMessage(msg, standardMsg)) |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 973 | |
| 974 | def assertGreaterEqual(self, a, b, msg=None): |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 975 | """Just like self.assertTrue(a >= b), but with a nicer default message.""" |
| 976 | if not a >= b: |
| 977 | standardMsg = '%r not greater than or equal to %r' % (a, b) |
| 978 | self.fail(self._formatMessage(msg, standardMsg)) |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 979 | |
| 980 | def assertIsNone(self, obj, msg=None): |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 981 | """Same as self.assertTrue(obj is None), with a nicer default message.""" |
| 982 | if obj is not None: |
| 983 | standardMsg = '%r is not None' % obj |
| 984 | self.fail(self._formatMessage(msg, standardMsg)) |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 985 | |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 986 | def assertIsNotNone(self, obj, msg=None): |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 987 | """Included for symmetry with assertIsNone.""" |
Michael Foord | 345b2fe | 2009-04-02 03:20:38 +0000 | [diff] [blame] | 988 | if obj is None: |
| 989 | standardMsg = 'unexpectedly None' |
| 990 | self.fail(self._formatMessage(msg, standardMsg)) |
Gregory P. Smith | 2839985 | 2009-03-31 16:54:10 +0000 | [diff] [blame] | 991 | |
| 992 | def assertRaisesRegexp(self, expected_exception, expected_regexp, |
| 993 | callable_obj=None, *args, **kwargs): |
| 994 | """Asserts that the message in a raised exception matches a regexp. |
| 995 | |
| 996 | Args: |
| 997 | expected_exception: Exception class expected to be raised. |
| 998 | expected_regexp: Regexp (re pattern object or string) expected |
| 999 | to be found in error message. |
| 1000 | callable_obj: Function to be called. |
| 1001 | args: Extra args. |
| 1002 | kwargs: Extra kwargs. |
| 1003 | """ |
| 1004 | context = _AssertRaisesContext(expected_exception, self, expected_regexp) |
| 1005 | if callable_obj is None: |
| 1006 | return context |
| 1007 | with context: |
| 1008 | callable_obj(*args, **kwargs) |
| 1009 | |
| 1010 | def assertRegexpMatches(self, text, expected_regex, msg=None): |
| 1011 | if isinstance(expected_regex, basestring): |
| 1012 | expected_regex = re.compile(expected_regex) |
| 1013 | if not expected_regex.search(text): |
| 1014 | msg = msg or "Regexp didn't match" |
| 1015 | msg = '%s: %r not found in %r' % (msg, expected_regex.pattern, text) |
| 1016 | raise self.failureException(msg) |
| 1017 | |
| 1018 | |
| 1019 | def _SortedListDifference(expected, actual): |
| 1020 | """Finds elements in only one or the other of two, sorted input lists. |
| 1021 | |
| 1022 | Returns a two-element tuple of lists. The first list contains those |
| 1023 | elements in the "expected" list but not in the "actual" list, and the |
| 1024 | second contains those elements in the "actual" list but not in the |
| 1025 | "expected" list. Duplicate elements in either input list are ignored. |
| 1026 | """ |
| 1027 | i = j = 0 |
| 1028 | missing = [] |
| 1029 | unexpected = [] |
| 1030 | while True: |
| 1031 | try: |
| 1032 | e = expected[i] |
| 1033 | a = actual[j] |
| 1034 | if e < a: |
| 1035 | missing.append(e) |
| 1036 | i += 1 |
| 1037 | while expected[i] == e: |
| 1038 | i += 1 |
| 1039 | elif e > a: |
| 1040 | unexpected.append(a) |
| 1041 | j += 1 |
| 1042 | while actual[j] == a: |
| 1043 | j += 1 |
| 1044 | else: |
| 1045 | i += 1 |
| 1046 | try: |
| 1047 | while expected[i] == e: |
| 1048 | i += 1 |
| 1049 | finally: |
| 1050 | j += 1 |
| 1051 | while actual[j] == a: |
| 1052 | j += 1 |
| 1053 | except IndexError: |
| 1054 | missing.extend(expected[i:]) |
| 1055 | unexpected.extend(actual[j:]) |
| 1056 | break |
| 1057 | return missing, unexpected |
| 1058 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1059 | |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 1060 | class TestSuite(object): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1061 | """A test suite is a composite test consisting of a number of TestCases. |
| 1062 | |
| 1063 | For use, create an instance of TestSuite, then add test case instances. |
| 1064 | When all tests have been added, the suite can be passed to a test |
| 1065 | runner, such as TextTestRunner. It will run the individual test cases |
| 1066 | in the order in which they were added, aggregating the results. When |
| 1067 | subclassing, do not forget to call the base class constructor. |
| 1068 | """ |
| 1069 | def __init__(self, tests=()): |
| 1070 | self._tests = [] |
| 1071 | self.addTests(tests) |
| 1072 | |
| 1073 | def __repr__(self): |
Michael Foord | 37d89a2 | 2009-04-05 01:15:01 +0000 | [diff] [blame] | 1074 | return "<%s tests=%s>" % (_strclass(self.__class__), list(self)) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1075 | |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 1076 | def __eq__(self, other): |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 1077 | if not isinstance(other, self.__class__): |
| 1078 | return NotImplemented |
Michael Foord | 829f6b8 | 2009-05-02 11:43:06 +0000 | [diff] [blame] | 1079 | return list(self) == list(other) |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 1080 | |
| 1081 | def __ne__(self, other): |
| 1082 | return not self == other |
| 1083 | |
Nick Coghlan | 48361f5 | 2008-08-11 15:45:58 +0000 | [diff] [blame] | 1084 | # Can't guarantee hash invariant, so flag as unhashable |
| 1085 | __hash__ = None |
| 1086 | |
Jim Fulton | fafd874 | 2004-08-28 15:22:12 +0000 | [diff] [blame] | 1087 | def __iter__(self): |
| 1088 | return iter(self._tests) |
| 1089 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1090 | def countTestCases(self): |
| 1091 | cases = 0 |
Michael Foord | 37d89a2 | 2009-04-05 01:15:01 +0000 | [diff] [blame] | 1092 | for test in self: |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 1093 | cases += test.countTestCases() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1094 | return cases |
| 1095 | |
| 1096 | def addTest(self, test): |
Georg Brandl | d9e5026 | 2007-03-07 11:54:49 +0000 | [diff] [blame] | 1097 | # sanity checks |
Raymond Hettinger | 5930d8f | 2008-07-10 16:06:41 +0000 | [diff] [blame] | 1098 | if not hasattr(test, '__call__'): |
Georg Brandl | d9e5026 | 2007-03-07 11:54:49 +0000 | [diff] [blame] | 1099 | raise TypeError("the test to add must be callable") |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 1100 | if isinstance(test, type) and issubclass(test, (TestCase, TestSuite)): |
Georg Brandl | d9e5026 | 2007-03-07 11:54:49 +0000 | [diff] [blame] | 1101 | raise TypeError("TestCases and TestSuites must be instantiated " |
| 1102 | "before passing them to addTest()") |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1103 | self._tests.append(test) |
| 1104 | |
| 1105 | def addTests(self, tests): |
Georg Brandl | d9e5026 | 2007-03-07 11:54:49 +0000 | [diff] [blame] | 1106 | if isinstance(tests, basestring): |
| 1107 | raise TypeError("tests must be an iterable of tests, not a string") |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1108 | for test in tests: |
| 1109 | self.addTest(test) |
| 1110 | |
| 1111 | def run(self, result): |
Michael Foord | 37d89a2 | 2009-04-05 01:15:01 +0000 | [diff] [blame] | 1112 | for test in self: |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1113 | if result.shouldStop: |
| 1114 | break |
| 1115 | test(result) |
| 1116 | return result |
| 1117 | |
Raymond Hettinger | 664347b | 2004-12-04 21:21:53 +0000 | [diff] [blame] | 1118 | def __call__(self, *args, **kwds): |
| 1119 | return self.run(*args, **kwds) |
| 1120 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1121 | def debug(self): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1122 | """Run the tests without collecting errors in a TestResult""" |
Michael Foord | 37d89a2 | 2009-04-05 01:15:01 +0000 | [diff] [blame] | 1123 | for test in self: |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 1124 | test.debug() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1125 | |
| 1126 | |
| 1127 | class FunctionTestCase(TestCase): |
| 1128 | """A test case that wraps a test function. |
| 1129 | |
| 1130 | This is useful for slipping pre-existing test functions into the |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 1131 | unittest framework. Optionally, set-up and tidy-up functions can be |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1132 | supplied. As with TestCase, the tidy-up ('tearDown') function will |
| 1133 | always be called if the set-up ('setUp') function ran successfully. |
| 1134 | """ |
| 1135 | |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 1136 | def __init__(self, testFunc, setUp=None, tearDown=None, description=None): |
| 1137 | super(FunctionTestCase, self).__init__() |
Benjamin Peterson | 71095ae | 2009-04-01 23:15:49 +0000 | [diff] [blame] | 1138 | self._setUpFunc = setUp |
| 1139 | self._tearDownFunc = tearDown |
| 1140 | self._testFunc = testFunc |
| 1141 | self._description = description |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1142 | |
| 1143 | def setUp(self): |
Benjamin Peterson | 71095ae | 2009-04-01 23:15:49 +0000 | [diff] [blame] | 1144 | if self._setUpFunc is not None: |
| 1145 | self._setUpFunc() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1146 | |
| 1147 | def tearDown(self): |
Benjamin Peterson | 71095ae | 2009-04-01 23:15:49 +0000 | [diff] [blame] | 1148 | if self._tearDownFunc is not None: |
| 1149 | self._tearDownFunc() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1150 | |
| 1151 | def runTest(self): |
Benjamin Peterson | 71095ae | 2009-04-01 23:15:49 +0000 | [diff] [blame] | 1152 | self._testFunc() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1153 | |
| 1154 | def id(self): |
Benjamin Peterson | 71095ae | 2009-04-01 23:15:49 +0000 | [diff] [blame] | 1155 | return self._testFunc.__name__ |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1156 | |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 1157 | def __eq__(self, other): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 1158 | if not isinstance(other, self.__class__): |
| 1159 | return NotImplemented |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 1160 | |
Benjamin Peterson | 71095ae | 2009-04-01 23:15:49 +0000 | [diff] [blame] | 1161 | return self._setUpFunc == other._setUpFunc and \ |
| 1162 | self._tearDownFunc == other._tearDownFunc and \ |
| 1163 | self._testFunc == other._testFunc and \ |
| 1164 | self._description == other._description |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 1165 | |
| 1166 | def __ne__(self, other): |
| 1167 | return not self == other |
| 1168 | |
| 1169 | def __hash__(self): |
Benjamin Peterson | 71095ae | 2009-04-01 23:15:49 +0000 | [diff] [blame] | 1170 | return hash((type(self), self._setUpFunc, self._tearDownFunc, |
| 1171 | self._testFunc, self._description)) |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 1172 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1173 | def __str__(self): |
Benjamin Peterson | baba195 | 2009-04-18 19:26:19 +0000 | [diff] [blame] | 1174 | return "%s (%s)" % (_strclass(self.__class__), self._testFunc.__name__) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1175 | |
| 1176 | def __repr__(self): |
Benjamin Peterson | 71095ae | 2009-04-01 23:15:49 +0000 | [diff] [blame] | 1177 | return "<%s testFunc=%s>" % (_strclass(self.__class__), self._testFunc) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1178 | |
| 1179 | def shortDescription(self): |
Benjamin Peterson | 71095ae | 2009-04-01 23:15:49 +0000 | [diff] [blame] | 1180 | if self._description is not None: |
| 1181 | return self._description |
| 1182 | doc = self._testFunc.__doc__ |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 1183 | return doc and doc.split("\n")[0].strip() or None |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1184 | |
| 1185 | |
| 1186 | |
| 1187 | ############################################################################## |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1188 | # Locating and loading tests |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1189 | ############################################################################## |
| 1190 | |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 1191 | class TestLoader(object): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 1192 | """ |
| 1193 | This class is responsible for loading tests according to various criteria |
| 1194 | and returning them wrapped in a TestSuite |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1195 | """ |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1196 | testMethodPrefix = 'test' |
| 1197 | sortTestMethodsUsing = cmp |
| 1198 | suiteClass = TestSuite |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1199 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1200 | def loadTestsFromTestCase(self, testCaseClass): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 1201 | """Return a suite of all tests cases contained in testCaseClass""" |
Johannes Gijsbers | d7b6ad4 | 2004-11-07 15:46:25 +0000 | [diff] [blame] | 1202 | if issubclass(testCaseClass, TestSuite): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 1203 | raise TypeError("Test cases should not be derived from TestSuite." \ |
| 1204 | " Maybe you meant to derive from TestCase?") |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 1205 | testCaseNames = self.getTestCaseNames(testCaseClass) |
| 1206 | if not testCaseNames and hasattr(testCaseClass, 'runTest'): |
| 1207 | testCaseNames = ['runTest'] |
Benjamin Peterson | 176a56c | 2009-05-25 00:48:58 +0000 | [diff] [blame] | 1208 | suite = self.suiteClass(map(testCaseClass, testCaseNames)) |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 1209 | return suite |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1210 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1211 | def loadTestsFromModule(self, module): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 1212 | """Return a suite of all tests cases contained in the given module""" |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1213 | tests = [] |
| 1214 | for name in dir(module): |
| 1215 | obj = getattr(module, name) |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 1216 | if isinstance(obj, type) and issubclass(obj, TestCase): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1217 | tests.append(self.loadTestsFromTestCase(obj)) |
| 1218 | return self.suiteClass(tests) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1219 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1220 | def loadTestsFromName(self, name, module=None): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 1221 | """Return a suite of all tests cases given a string specifier. |
| 1222 | |
| 1223 | The name may resolve either to a module, a test case class, a |
| 1224 | test method within a test case class, or a callable object which |
| 1225 | returns a TestCase or TestSuite instance. |
Tim Peters | 613b222 | 2001-04-13 05:37:27 +0000 | [diff] [blame] | 1226 | |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 1227 | The method optionally resolves the names relative to a given module. |
| 1228 | """ |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 1229 | parts = name.split('.') |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1230 | if module is None: |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 1231 | parts_copy = parts[:] |
| 1232 | while parts_copy: |
| 1233 | try: |
| 1234 | module = __import__('.'.join(parts_copy)) |
| 1235 | break |
| 1236 | except ImportError: |
| 1237 | del parts_copy[-1] |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 1238 | if not parts_copy: |
| 1239 | raise |
Armin Rigo | 1b3c04b | 2003-10-24 17:15:29 +0000 | [diff] [blame] | 1240 | parts = parts[1:] |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1241 | obj = module |
| 1242 | for part in parts: |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 1243 | parent, obj = obj, getattr(obj, part) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1244 | |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 1245 | if isinstance(obj, types.ModuleType): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1246 | return self.loadTestsFromModule(obj) |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 1247 | elif isinstance(obj, type) and issubclass(obj, TestCase): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1248 | return self.loadTestsFromTestCase(obj) |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 1249 | elif (isinstance(obj, types.UnboundMethodType) and |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 1250 | isinstance(parent, type) and |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 1251 | issubclass(parent, TestCase)): |
| 1252 | return TestSuite([parent(obj.__name__)]) |
Steve Purcell | 397b45d | 2003-10-26 10:41:03 +0000 | [diff] [blame] | 1253 | elif isinstance(obj, TestSuite): |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 1254 | return obj |
Raymond Hettinger | 5930d8f | 2008-07-10 16:06:41 +0000 | [diff] [blame] | 1255 | elif hasattr(obj, '__call__'): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1256 | test = obj() |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 1257 | if isinstance(test, TestSuite): |
| 1258 | return test |
| 1259 | elif isinstance(test, TestCase): |
| 1260 | return TestSuite([test]) |
| 1261 | else: |
| 1262 | raise TypeError("calling %s returned %s, not a test" % |
| 1263 | (obj, test)) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1264 | else: |
Georg Brandl | 15c5ce9 | 2007-03-07 09:09:40 +0000 | [diff] [blame] | 1265 | raise TypeError("don't know how to make test from: %s" % obj) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1266 | |
| 1267 | def loadTestsFromNames(self, names, module=None): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 1268 | """Return a suite of all tests cases found using the given sequence |
| 1269 | of string specifiers. See 'loadTestsFromName()'. |
| 1270 | """ |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 1271 | suites = [self.loadTestsFromName(name, module) for name in names] |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1272 | return self.suiteClass(suites) |
| 1273 | |
| 1274 | def getTestCaseNames(self, testCaseClass): |
Steve Purcell | 15d8927 | 2001-04-12 09:05:01 +0000 | [diff] [blame] | 1275 | """Return a sorted sequence of method names found within testCaseClass |
| 1276 | """ |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 1277 | def isTestMethod(attrname, testCaseClass=testCaseClass, |
| 1278 | prefix=self.testMethodPrefix): |
| 1279 | return attrname.startswith(prefix) and \ |
| 1280 | hasattr(getattr(testCaseClass, attrname), '__call__') |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 1281 | testFnNames = filter(isTestMethod, dir(testCaseClass)) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1282 | if self.sortTestMethodsUsing: |
Raymond Hettinger | 5930d8f | 2008-07-10 16:06:41 +0000 | [diff] [blame] | 1283 | testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing)) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1284 | return testFnNames |
| 1285 | |
| 1286 | |
| 1287 | |
| 1288 | defaultTestLoader = TestLoader() |
| 1289 | |
| 1290 | |
| 1291 | ############################################################################## |
| 1292 | # Patches for old functions: these functions should be considered obsolete |
| 1293 | ############################################################################## |
| 1294 | |
| 1295 | def _makeLoader(prefix, sortUsing, suiteClass=None): |
| 1296 | loader = TestLoader() |
| 1297 | loader.sortTestMethodsUsing = sortUsing |
| 1298 | loader.testMethodPrefix = prefix |
| 1299 | if suiteClass: loader.suiteClass = suiteClass |
| 1300 | return loader |
| 1301 | |
| 1302 | def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp): |
| 1303 | return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass) |
| 1304 | |
| 1305 | def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite): |
| 1306 | return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass) |
| 1307 | |
| 1308 | def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite): |
| 1309 | return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1310 | |
| 1311 | |
| 1312 | ############################################################################## |
| 1313 | # Text UI |
| 1314 | ############################################################################## |
| 1315 | |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 1316 | class _WritelnDecorator(object): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1317 | """Used to decorate file-like objects with a handy 'writeln' method""" |
| 1318 | def __init__(self,stream): |
| 1319 | self.stream = stream |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1320 | |
| 1321 | def __getattr__(self, attr): |
| 1322 | return getattr(self.stream,attr) |
| 1323 | |
Raymond Hettinger | 91dd19d | 2003-09-13 02:58:00 +0000 | [diff] [blame] | 1324 | def writeln(self, arg=None): |
Benjamin Peterson | d0cdb2d | 2009-03-24 23:07:07 +0000 | [diff] [blame] | 1325 | if arg: |
| 1326 | self.write(arg) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1327 | self.write('\n') # text-mode streams translate to \r\n if needed |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 1328 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1329 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1330 | class _TextTestResult(TestResult): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1331 | """A test result class that can print formatted text results to a stream. |
| 1332 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1333 | Used by TextTestRunner. |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1334 | """ |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1335 | separator1 = '=' * 70 |
| 1336 | separator2 = '-' * 70 |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1337 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1338 | def __init__(self, stream, descriptions, verbosity): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 1339 | super(_TextTestResult, self).__init__() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1340 | self.stream = stream |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1341 | self.showAll = verbosity > 1 |
| 1342 | self.dots = verbosity == 1 |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1343 | self.descriptions = descriptions |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1344 | |
| 1345 | def getDescription(self, test): |
| 1346 | if self.descriptions: |
| 1347 | return test.shortDescription() or str(test) |
| 1348 | else: |
| 1349 | return str(test) |
| 1350 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1351 | def startTest(self, test): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 1352 | super(_TextTestResult, self).startTest(test) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1353 | if self.showAll: |
| 1354 | self.stream.write(self.getDescription(test)) |
| 1355 | self.stream.write(" ... ") |
Georg Brandl | d063240 | 2008-05-11 15:17:41 +0000 | [diff] [blame] | 1356 | self.stream.flush() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1357 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1358 | def addSuccess(self, test): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 1359 | super(_TextTestResult, self).addSuccess(test) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1360 | if self.showAll: |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1361 | self.stream.writeln("ok") |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1362 | elif self.dots: |
| 1363 | self.stream.write('.') |
Georg Brandl | d063240 | 2008-05-11 15:17:41 +0000 | [diff] [blame] | 1364 | self.stream.flush() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1365 | |
| 1366 | def addError(self, test, err): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 1367 | super(_TextTestResult, self).addError(test, err) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1368 | if self.showAll: |
| 1369 | self.stream.writeln("ERROR") |
| 1370 | elif self.dots: |
| 1371 | self.stream.write('E') |
Georg Brandl | d063240 | 2008-05-11 15:17:41 +0000 | [diff] [blame] | 1372 | self.stream.flush() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1373 | |
| 1374 | def addFailure(self, test, err): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 1375 | super(_TextTestResult, self).addFailure(test, err) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1376 | if self.showAll: |
| 1377 | self.stream.writeln("FAIL") |
| 1378 | elif self.dots: |
| 1379 | self.stream.write('F') |
Georg Brandl | d063240 | 2008-05-11 15:17:41 +0000 | [diff] [blame] | 1380 | self.stream.flush() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1381 | |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 1382 | def addSkip(self, test, reason): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 1383 | super(_TextTestResult, self).addSkip(test, reason) |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 1384 | if self.showAll: |
| 1385 | self.stream.writeln("skipped {0!r}".format(reason)) |
| 1386 | elif self.dots: |
| 1387 | self.stream.write("s") |
| 1388 | self.stream.flush() |
| 1389 | |
| 1390 | def addExpectedFailure(self, test, err): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 1391 | super(_TextTestResult, self).addExpectedFailure(test, err) |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 1392 | if self.showAll: |
| 1393 | self.stream.writeln("expected failure") |
| 1394 | elif self.dots: |
Benjamin Peterson | a8adceb | 2009-03-25 21:24:04 +0000 | [diff] [blame] | 1395 | self.stream.write("x") |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 1396 | self.stream.flush() |
| 1397 | |
| 1398 | def addUnexpectedSuccess(self, test): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 1399 | super(_TextTestResult, self).addUnexpectedSuccess(test) |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 1400 | if self.showAll: |
| 1401 | self.stream.writeln("unexpected success") |
| 1402 | elif self.dots: |
Benjamin Peterson | a8adceb | 2009-03-25 21:24:04 +0000 | [diff] [blame] | 1403 | self.stream.write("u") |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 1404 | self.stream.flush() |
| 1405 | |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1406 | def printErrors(self): |
| 1407 | if self.dots or self.showAll: |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1408 | self.stream.writeln() |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1409 | self.printErrorList('ERROR', self.errors) |
| 1410 | self.printErrorList('FAIL', self.failures) |
| 1411 | |
| 1412 | def printErrorList(self, flavour, errors): |
| 1413 | for test, err in errors: |
| 1414 | self.stream.writeln(self.separator1) |
| 1415 | self.stream.writeln("%s: %s" % (flavour,self.getDescription(test))) |
| 1416 | self.stream.writeln(self.separator2) |
Steve Purcell | 7b06570 | 2001-09-06 08:24:40 +0000 | [diff] [blame] | 1417 | self.stream.writeln("%s" % err) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1418 | |
| 1419 | |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 1420 | class TextTestRunner(object): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1421 | """A test runner class that displays results in textual form. |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 1422 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1423 | It prints out the names of tests as they are run, errors as they |
| 1424 | occur, and a summary of the results at the end of the test run. |
| 1425 | """ |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1426 | def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1427 | self.stream = _WritelnDecorator(stream) |
| 1428 | self.descriptions = descriptions |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1429 | self.verbosity = verbosity |
| 1430 | |
| 1431 | def _makeResult(self): |
| 1432 | return _TextTestResult(self.stream, self.descriptions, self.verbosity) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1433 | |
| 1434 | def run(self, test): |
| 1435 | "Run the given test case or test suite." |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1436 | result = self._makeResult() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1437 | startTime = time.time() |
Michael Foord | 07ef487 | 2009-05-02 22:43:34 +0000 | [diff] [blame] | 1438 | startTestRun = getattr(result, 'startTestRun', None) |
| 1439 | if startTestRun is not None: |
| 1440 | startTestRun() |
| 1441 | try: |
| 1442 | test(result) |
| 1443 | finally: |
| 1444 | stopTestRun = getattr(result, 'stopTestRun', None) |
| 1445 | if stopTestRun is not None: |
| 1446 | stopTestRun() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1447 | stopTime = time.time() |
Steve Purcell | 397b45d | 2003-10-26 10:41:03 +0000 | [diff] [blame] | 1448 | timeTaken = stopTime - startTime |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1449 | result.printErrors() |
| 1450 | self.stream.writeln(result.separator2) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1451 | run = result.testsRun |
| 1452 | self.stream.writeln("Ran %d test%s in %.3fs" % |
Neal Norwitz | 7616504 | 2002-05-31 14:15:11 +0000 | [diff] [blame] | 1453 | (run, run != 1 and "s" or "", timeTaken)) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1454 | self.stream.writeln() |
Benjamin Peterson | cb2b0e4 | 2009-03-23 22:29:45 +0000 | [diff] [blame] | 1455 | results = map(len, (result.expectedFailures, |
| 1456 | result.unexpectedSuccesses, |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 1457 | result.skipped)) |
Benjamin Peterson | cb2b0e4 | 2009-03-23 22:29:45 +0000 | [diff] [blame] | 1458 | expectedFails, unexpectedSuccesses, skipped = results |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 1459 | infos = [] |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1460 | if not result.wasSuccessful(): |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 1461 | self.stream.write("FAILED") |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1462 | failed, errored = map(len, (result.failures, result.errors)) |
| 1463 | if failed: |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 1464 | infos.append("failures=%d" % failed) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1465 | if errored: |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 1466 | infos.append("errors=%d" % errored) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1467 | else: |
Benjamin Peterson | a473f00 | 2009-03-24 22:56:32 +0000 | [diff] [blame] | 1468 | self.stream.write("OK") |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 1469 | if skipped: |
| 1470 | infos.append("skipped=%d" % skipped) |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 1471 | if expectedFails: |
| 1472 | infos.append("expected failures=%d" % expectedFails) |
| 1473 | if unexpectedSuccesses: |
| 1474 | infos.append("unexpected successes=%d" % unexpectedSuccesses) |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 1475 | if infos: |
| 1476 | self.stream.writeln(" (%s)" % (", ".join(infos),)) |
Benjamin Peterson | a473f00 | 2009-03-24 22:56:32 +0000 | [diff] [blame] | 1477 | else: |
| 1478 | self.stream.write("\n") |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1479 | return result |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 1480 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1481 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1482 | |
| 1483 | ############################################################################## |
| 1484 | # Facilities for running tests from the command line |
| 1485 | ############################################################################## |
| 1486 | |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 1487 | class TestProgram(object): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1488 | """A command-line program that runs a set of tests; this is primarily |
| 1489 | for making test modules conveniently executable. |
| 1490 | """ |
| 1491 | USAGE = """\ |
Steve Purcell | 17a781b | 2001-04-09 15:37:31 +0000 | [diff] [blame] | 1492 | Usage: %(progName)s [options] [test] [...] |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1493 | |
| 1494 | Options: |
| 1495 | -h, --help Show this message |
| 1496 | -v, --verbose Verbose output |
| 1497 | -q, --quiet Minimal output |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1498 | |
| 1499 | Examples: |
| 1500 | %(progName)s - run default set of tests |
| 1501 | %(progName)s MyTestSuite - run suite 'MyTestSuite' |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1502 | %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething |
| 1503 | %(progName)s MyTestCase - run all 'test*' test methods |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1504 | in MyTestCase |
| 1505 | """ |
| 1506 | def __init__(self, module='__main__', defaultTest=None, |
Georg Brandl | d0a9625 | 2007-03-07 09:21:06 +0000 | [diff] [blame] | 1507 | argv=None, testRunner=TextTestRunner, |
Michael Foord | 5d31e05 | 2009-05-11 17:59:43 +0000 | [diff] [blame] | 1508 | testLoader=defaultTestLoader, exit=True, |
| 1509 | verbosity=1): |
Antoine Pitrou | dae1a6a | 2008-12-28 16:01:11 +0000 | [diff] [blame] | 1510 | if isinstance(module, basestring): |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1511 | self.module = __import__(module) |
Steve Purcell | 7e74384 | 2003-09-22 11:08:12 +0000 | [diff] [blame] | 1512 | for part in module.split('.')[1:]: |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1513 | self.module = getattr(self.module, part) |
| 1514 | else: |
| 1515 | self.module = module |
| 1516 | if argv is None: |
| 1517 | argv = sys.argv |
Michael Foord | 829f6b8 | 2009-05-02 11:43:06 +0000 | [diff] [blame] | 1518 | |
| 1519 | self.exit = exit |
Michael Foord | 5d31e05 | 2009-05-11 17:59:43 +0000 | [diff] [blame] | 1520 | self.verbosity = verbosity |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1521 | self.defaultTest = defaultTest |
| 1522 | self.testRunner = testRunner |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1523 | self.testLoader = testLoader |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1524 | self.progName = os.path.basename(argv[0]) |
| 1525 | self.parseArgs(argv) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1526 | self.runTests() |
| 1527 | |
| 1528 | def usageExit(self, msg=None): |
Benjamin Peterson | a7d441d | 2009-03-24 00:35:20 +0000 | [diff] [blame] | 1529 | if msg: |
| 1530 | print msg |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1531 | print self.USAGE % self.__dict__ |
| 1532 | sys.exit(2) |
| 1533 | |
| 1534 | def parseArgs(self, argv): |
| 1535 | import getopt |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 1536 | long_opts = ['help','verbose','quiet'] |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1537 | try: |
Benjamin Peterson | 692428e | 2009-03-23 21:50:21 +0000 | [diff] [blame] | 1538 | options, args = getopt.getopt(argv[1:], 'hHvq', long_opts) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1539 | for opt, value in options: |
| 1540 | if opt in ('-h','-H','--help'): |
| 1541 | self.usageExit() |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1542 | if opt in ('-q','--quiet'): |
| 1543 | self.verbosity = 0 |
| 1544 | if opt in ('-v','--verbose'): |
| 1545 | self.verbosity = 2 |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1546 | if len(args) == 0 and self.defaultTest is None: |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1547 | self.test = self.testLoader.loadTestsFromModule(self.module) |
| 1548 | return |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1549 | if len(args) > 0: |
| 1550 | self.testNames = args |
Michael Foord | f596a51 | 2009-05-12 10:49:13 +0000 | [diff] [blame] | 1551 | if sys.modules['unittest'] is sys.modules['__main__']: |
Michael Foord | 7df82c9 | 2009-05-12 10:46:23 +0000 | [diff] [blame] | 1552 | self.module = None |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1553 | else: |
| 1554 | self.testNames = (self.defaultTest,) |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1555 | self.createTests() |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1556 | except getopt.error, msg: |
| 1557 | self.usageExit(msg) |
| 1558 | |
| 1559 | def createTests(self): |
Steve Purcell | 5ddd1a8 | 2001-03-22 08:45:36 +0000 | [diff] [blame] | 1560 | self.test = self.testLoader.loadTestsFromNames(self.testNames, |
| 1561 | self.module) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1562 | |
| 1563 | def runTests(self): |
Georg Brandl | d0a9625 | 2007-03-07 09:21:06 +0000 | [diff] [blame] | 1564 | if isinstance(self.testRunner, (type, types.ClassType)): |
| 1565 | try: |
| 1566 | testRunner = self.testRunner(verbosity=self.verbosity) |
| 1567 | except TypeError: |
| 1568 | # didn't accept the verbosity argument |
| 1569 | testRunner = self.testRunner() |
| 1570 | else: |
| 1571 | # it is assumed to be a TestRunner instance |
| 1572 | testRunner = self.testRunner |
Michael Foord | 829f6b8 | 2009-05-02 11:43:06 +0000 | [diff] [blame] | 1573 | self.result = testRunner.run(self.test) |
| 1574 | if self.exit: |
| 1575 | sys.exit(not self.result.wasSuccessful()) |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1576 | |
| 1577 | main = TestProgram |
| 1578 | |
| 1579 | |
Michael Foord | e2fb98f | 2009-05-02 20:15:05 +0000 | [diff] [blame] | 1580 | ############################################################################## |
| 1581 | # Executing this module from the command line |
| 1582 | ############################################################################## |
| 1583 | |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1584 | if __name__ == "__main__": |
Michael Foord | 5d31e05 | 2009-05-11 17:59:43 +0000 | [diff] [blame] | 1585 | sys.modules['unittest'] = sys.modules['__main__'] |
Fred Drake | 0253820 | 2001-03-21 18:09:46 +0000 | [diff] [blame] | 1586 | main(module=None) |