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