blob: cabd857a0e8e898f6ca95fec1654d5297714bb7b [file] [log] [blame]
Fred Drake02538202001-03-21 18:09:46 +00001#!/usr/bin/env python
Steve Purcell5ddd1a82001-03-22 08:45:36 +00002'''
Fred Drake02538202001-03-21 18:09:46 +00003Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's
4Smalltalk testing framework.
5
Fred Drake02538202001-03-21 18:09:46 +00006This module contains the core framework classes that form the basis of
7specific test cases and suites (TestCase, TestSuite etc.), and also a
8text-based utility class for running the tests and reporting the results
Jeremy Hyltonefef5da2001-10-22 18:14:15 +00009 (TextTestRunner).
Fred Drake02538202001-03-21 18:09:46 +000010
Steve Purcell5ddd1a82001-03-22 08:45:36 +000011Simple usage:
12
13 import unittest
14
15 class IntegerArithmenticTestCase(unittest.TestCase):
16 def testAdd(self): ## test method names begin 'test*'
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000017 self.assertEqual((1 + 2), 3)
18 self.assertEqual(0 + 1, 1)
Steve Purcell7b065702001-09-06 08:24:40 +000019 def testMultiply(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000020 self.assertEqual((0 * 10), 0)
21 self.assertEqual((5 * 8), 40)
Steve Purcell5ddd1a82001-03-22 08:45:36 +000022
23 if __name__ == '__main__':
24 unittest.main()
25
26Further information is available in the bundled documentation, and from
27
Benjamin Peterson52baa292009-03-24 00:56:30 +000028 http://docs.python.org/library/unittest.html
Steve Purcell5ddd1a82001-03-22 08:45:36 +000029
Steve Purcell7e743842003-09-22 11:08:12 +000030Copyright (c) 1999-2003 Steve Purcell
Benjamin Peterson52baa292009-03-24 00:56:30 +000031Copyright (c) 2003-2009 Python Software Foundation
Fred Drake02538202001-03-21 18:09:46 +000032This module is free software, and you may redistribute it and/or modify
33it under the same terms as Python itself, so long as this copyright message
34and disclaimer are retained in their original form.
35
36IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
37SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
38THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
39DAMAGE.
40
41THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
42LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
43PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
44AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
45SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
Steve Purcell5ddd1a82001-03-22 08:45:36 +000046'''
Fred Drake02538202001-03-21 18:09:46 +000047
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000048import difflib
Benjamin Peterson5254c042009-03-23 22:25:03 +000049import functools
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000050import os
51import pprint
52import re
53import sys
54import time
55import traceback
56import types
57import warnings
Fred Drake02538202001-03-21 18:09:46 +000058
59##############################################################################
Steve Purcelld75e7e42003-09-15 11:01:21 +000060# Exported classes and functions
61##############################################################################
Benjamin Peterson14a3dd72009-05-25 00:51:58 +000062__all__ = ['TestResult', 'TestCase', 'TestSuite',
Benjamin Peterson52baa292009-03-24 00:56:30 +000063 'TextTestRunner', 'TestLoader', 'FunctionTestCase', 'main',
Benjamin Peterson4c93dcb2009-03-24 01:33:55 +000064 'defaultTestLoader', 'SkipTest', 'skip', 'skipIf', 'skipUnless',
Benjamin Peterson52baa292009-03-24 00:56:30 +000065 'expectedFailure']
Steve Purcelld75e7e42003-09-15 11:01:21 +000066
Steve Purcell7e743842003-09-22 11:08:12 +000067# Expose obsolete functions for backwards compatibility
Steve Purcelld75e7e42003-09-15 11:01:21 +000068__all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases'])
69
70
71##############################################################################
Fred Drake02538202001-03-21 18:09:46 +000072# Test framework core
73##############################################################################
74
Steve Purcelldc391a62002-08-09 09:46:23 +000075def _strclass(cls):
76 return "%s.%s" % (cls.__module__, cls.__name__)
77
Benjamin Peterson5254c042009-03-23 22:25:03 +000078
79class SkipTest(Exception):
80 """
81 Raise this exception in a test to skip it.
82
83 Usually you can use TestResult.skip() or one of the skipping decorators
84 instead of raising this directly.
85 """
86 pass
87
88class _ExpectedFailure(Exception):
89 """
90 Raise this when a test is expected to fail.
91
92 This is an implementation detail.
93 """
94
95 def __init__(self, exc_info):
96 super(_ExpectedFailure, self).__init__()
97 self.exc_info = exc_info
98
99class _UnexpectedSuccess(Exception):
100 """
101 The test was supposed to fail, but it didn't!
102 """
103 pass
104
105def _id(obj):
106 return obj
107
108def skip(reason):
109 """
110 Unconditionally skip a test.
111 """
112 def decorator(test_item):
113 if isinstance(test_item, type) and issubclass(test_item, TestCase):
114 test_item.__unittest_skip__ = True
115 test_item.__unittest_skip_why__ = reason
116 return test_item
117 @functools.wraps(test_item)
118 def skip_wrapper(*args, **kwargs):
119 raise SkipTest(reason)
120 return skip_wrapper
121 return decorator
122
123def skipIf(condition, reason):
124 """
125 Skip a test if the condition is true.
126 """
127 if condition:
128 return skip(reason)
129 return _id
130
131def skipUnless(condition, reason):
132 """
133 Skip a test unless the condition is true.
134 """
135 if not condition:
136 return skip(reason)
137 return _id
138
139
140def expectedFailure(func):
141 @functools.wraps(func)
142 def wrapper(*args, **kwargs):
143 try:
144 func(*args, **kwargs)
145 except Exception:
146 raise _ExpectedFailure(sys.exc_info())
147 raise _UnexpectedSuccess
148 return wrapper
149
Steve Purcellb8d5f242003-12-06 13:03:13 +0000150__unittest = 1
151
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000152class TestResult(object):
Fred Drake02538202001-03-21 18:09:46 +0000153 """Holder for test result information.
154
155 Test results are automatically managed by the TestCase and TestSuite
156 classes, and do not need to be explicitly manipulated by writers of tests.
157
158 Each instance holds the total number of tests run, and collections of
159 failures and errors that occurred among those test runs. The collections
Steve Purcell7b065702001-09-06 08:24:40 +0000160 contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
Fred Drake656f9ec2001-09-06 19:13:14 +0000161 formatted traceback of the error that occurred.
Fred Drake02538202001-03-21 18:09:46 +0000162 """
163 def __init__(self):
164 self.failures = []
165 self.errors = []
166 self.testsRun = 0
Benjamin Peterson5254c042009-03-23 22:25:03 +0000167 self.skipped = []
Benjamin Peterson52baa292009-03-24 00:56:30 +0000168 self.expectedFailures = []
169 self.unexpectedSuccesses = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000170 self.shouldStop = False
Fred Drake02538202001-03-21 18:09:46 +0000171
172 def startTest(self, test):
173 "Called when the given test is about to be run"
174 self.testsRun = self.testsRun + 1
175
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000176 def startTestRun(self):
177 """Called once before any tests are executed.
178
179 See startTest for a method called before each test.
180 """
181
Fred Drake02538202001-03-21 18:09:46 +0000182 def stopTest(self, test):
183 "Called when the given test has been run"
184 pass
185
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000186 def stopTestRun(self):
187 """Called once after all tests are executed.
188
189 See stopTest for a method called after each test.
190 """
191
Fred Drake02538202001-03-21 18:09:46 +0000192 def addError(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000193 """Called when an error has occurred. 'err' is a tuple of values as
194 returned by sys.exc_info().
195 """
Steve Purcellb8d5f242003-12-06 13:03:13 +0000196 self.errors.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000197
198 def addFailure(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000199 """Called when an error has occurred. 'err' is a tuple of values as
200 returned by sys.exc_info()."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000201 self.failures.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000202
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000203 def addSuccess(self, test):
204 "Called when a test has completed successfully"
205 pass
206
Benjamin Peterson5254c042009-03-23 22:25:03 +0000207 def addSkip(self, test, reason):
208 """Called when a test is skipped."""
209 self.skipped.append((test, reason))
210
211 def addExpectedFailure(self, test, err):
212 """Called when an expected failure/error occured."""
Benjamin Peterson52baa292009-03-24 00:56:30 +0000213 self.expectedFailures.append(
Benjamin Peterson5254c042009-03-23 22:25:03 +0000214 (test, self._exc_info_to_string(err, test)))
215
216 def addUnexpectedSuccess(self, test):
217 """Called when a test was expected to fail, but succeed."""
Benjamin Peterson52baa292009-03-24 00:56:30 +0000218 self.unexpectedSuccesses.append(test)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000219
Fred Drake02538202001-03-21 18:09:46 +0000220 def wasSuccessful(self):
221 "Tells whether or not this result was a success"
222 return len(self.failures) == len(self.errors) == 0
223
224 def stop(self):
225 "Indicates that the tests should be aborted"
Steve Purcell7e743842003-09-22 11:08:12 +0000226 self.shouldStop = True
Tim Petersa19a1682001-03-29 04:36:09 +0000227
Steve Purcellb8d5f242003-12-06 13:03:13 +0000228 def _exc_info_to_string(self, err, test):
Steve Purcell7b065702001-09-06 08:24:40 +0000229 """Converts a sys.exc_info()-style tuple of values into a string."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000230 exctype, value, tb = err
231 # Skip test runner traceback levels
232 while tb and self._is_relevant_tb_level(tb):
233 tb = tb.tb_next
234 if exctype is test.failureException:
235 # Skip assert*() traceback levels
236 length = self._count_relevant_tb_levels(tb)
Collin Winterce36ad82007-08-30 01:19:48 +0000237 return ''.join(traceback.format_exception(exctype, value,
238 tb, length))
Steve Purcellb8d5f242003-12-06 13:03:13 +0000239 return ''.join(traceback.format_exception(exctype, value, tb))
240
241 def _is_relevant_tb_level(self, tb):
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000242 return '__unittest' in tb.tb_frame.f_globals
Steve Purcellb8d5f242003-12-06 13:03:13 +0000243
244 def _count_relevant_tb_levels(self, tb):
245 length = 0
246 while tb and not self._is_relevant_tb_level(tb):
247 length += 1
248 tb = tb.tb_next
249 return length
Steve Purcell7b065702001-09-06 08:24:40 +0000250
Fred Drake02538202001-03-21 18:09:46 +0000251 def __repr__(self):
252 return "<%s run=%i errors=%i failures=%i>" % \
Steve Purcelldc391a62002-08-09 09:46:23 +0000253 (_strclass(self.__class__), self.testsRun, len(self.errors),
Fred Drake02538202001-03-21 18:09:46 +0000254 len(self.failures))
255
Benjamin Peterson52baa292009-03-24 00:56:30 +0000256
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000257class _AssertRaisesContext(object):
258 """A context manager used to implement TestCase.assertRaises* methods."""
Benjamin Peterson52baa292009-03-24 00:56:30 +0000259
260
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000261 def __init__(self, expected, test_case, callable_obj=None,
262 expected_regexp=None):
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000263 self.expected = expected
264 self.failureException = test_case.failureException
265 if callable_obj is not None:
266 try:
267 self.obj_name = callable_obj.__name__
268 except AttributeError:
269 self.obj_name = str(callable_obj)
270 else:
271 self.obj_name = None
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000272 self.expected_regex = expected_regexp
Benjamin Peterson52baa292009-03-24 00:56:30 +0000273
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000274 def __enter__(self):
275 pass
Benjamin Peterson52baa292009-03-24 00:56:30 +0000276
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000277 def __exit__(self, exc_type, exc_value, tb):
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000278 if exc_type is None:
279 try:
280 exc_name = self.expected.__name__
281 except AttributeError:
282 exc_name = str(self.expected)
283 if self.obj_name:
284 raise self.failureException("{0} not raised by {1}"
285 .format(exc_name, self.obj_name))
286 else:
287 raise self.failureException("{0} not raised"
288 .format(exc_name))
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000289 if not issubclass(exc_type, self.expected):
290 # let unexpected exceptions pass through
291 return False
292 if self.expected_regex is None:
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000293 return True
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000294
295 expected_regexp = self.expected_regex
296 if isinstance(expected_regexp, (bytes, str)):
297 expected_regexp = re.compile(expected_regexp)
298 if not expected_regexp.search(str(exc_value)):
299 raise self.failureException('"%s" does not match "%s"' %
300 (expected_regexp.pattern, str(exc_value)))
301 return True
302
303
304class _AssertWrapper(object):
305 """Wrap entries in the _type_equality_funcs registry to make them deep
306 copyable."""
307
308 def __init__(self, function):
309 self.function = function
310
311 def __deepcopy__(self, memo):
312 memo[id(self)] = self
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000313
Benjamin Peterson52baa292009-03-24 00:56:30 +0000314
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000315class TestCase(object):
Fred Drake02538202001-03-21 18:09:46 +0000316 """A class whose instances are single test cases.
317
Fred Drake02538202001-03-21 18:09:46 +0000318 By default, the test code itself should be placed in a method named
319 'runTest'.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000320
Tim Petersa19a1682001-03-29 04:36:09 +0000321 If the fixture may be used for many test cases, create as
Fred Drake02538202001-03-21 18:09:46 +0000322 many test methods as are needed. When instantiating such a TestCase
323 subclass, specify in the constructor arguments the name of the test method
324 that the instance is to execute.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000325
Tim Petersa19a1682001-03-29 04:36:09 +0000326 Test authors should subclass TestCase for their own tests. Construction
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000327 and deconstruction of the test's environment ('fixture') can be
328 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
329
330 If it is necessary to override the __init__ method, the base class
331 __init__ method must always be called. It is important that subclasses
332 should not change the signature of their __init__ method, since instances
333 of the classes are instantiated automatically by parts of the framework
334 in order to be run.
Fred Drake02538202001-03-21 18:09:46 +0000335 """
Steve Purcell15d89272001-04-12 09:05:01 +0000336
337 # This attribute determines which exception will be raised when
338 # the instance's assertion methods fail; test methods raising this
339 # exception will be deemed to have 'failed' rather than 'errored'
340
341 failureException = AssertionError
342
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000343 # This attribute determines whether long messages (including repr of
344 # objects used in assert methods) will be printed on failure in *addition*
345 # to any explicit message passed.
346
347 longMessage = False
348
Ezio Melotti935a5882011-04-27 10:17:34 +0300349 # If a string is longer than _diffThreshold, use normal comparison instead
350 # of difflib. See #11763.
351 _diffThreshold = 2**16
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000352
Fred Drake02538202001-03-21 18:09:46 +0000353 def __init__(self, methodName='runTest'):
354 """Create an instance of the class that will use the named test
355 method when executed. Raises a ValueError if the instance does
356 not have a method with the specified name.
357 """
Benjamin Peterson52baa292009-03-24 00:56:30 +0000358 self._testMethodName = methodName
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000359 self._resultForDoCleanups = None
Fred Drake02538202001-03-21 18:09:46 +0000360 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000361 testMethod = getattr(self, methodName)
Fred Drake02538202001-03-21 18:09:46 +0000362 except AttributeError:
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000363 raise ValueError("no such test method in %s: %s" % \
364 (self.__class__, methodName))
Benjamin Peterson52baa292009-03-24 00:56:30 +0000365 self._testMethodDoc = testMethod.__doc__
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000366 self._cleanups = []
Fred Drake02538202001-03-21 18:09:46 +0000367
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000368 # Map types to custom assertEqual functions that will compare
369 # instances of said type in more detail to generate a more useful
370 # error message.
371 self._type_equality_funcs = {}
372 self.addTypeEqualityFunc(dict, self.assertDictEqual)
373 self.addTypeEqualityFunc(list, self.assertListEqual)
374 self.addTypeEqualityFunc(tuple, self.assertTupleEqual)
375 self.addTypeEqualityFunc(set, self.assertSetEqual)
376 self.addTypeEqualityFunc(frozenset, self.assertSetEqual)
377
378 def addTypeEqualityFunc(self, typeobj, function):
379 """Add a type specific assertEqual style function to compare a type.
380
381 This method is for use by TestCase subclasses that need to register
382 their own type equality functions to provide nicer error messages.
383
384 Args:
385 typeobj: The data type to call this function on when both values
386 are of the same type in assertEqual().
387 function: The callable taking two arguments and an optional
388 msg= argument that raises self.failureException with a
389 useful error message when the two arguments are not equal.
390 """
391 self._type_equality_funcs[typeobj] = _AssertWrapper(function)
392
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000393 def addCleanup(self, function, *args, **kwargs):
394 """Add a function, with arguments, to be called when the test is
395 completed. Functions added are called on a LIFO basis and are
396 called after tearDown on test failure or success.
397
398 Cleanup items are called even if setUp fails (unlike tearDown)."""
399 self._cleanups.append((function, args, kwargs))
400
Fred Drake02538202001-03-21 18:09:46 +0000401 def setUp(self):
402 "Hook method for setting up the test fixture before exercising it."
403 pass
404
405 def tearDown(self):
406 "Hook method for deconstructing the test fixture after testing it."
407 pass
408
409 def countTestCases(self):
410 return 1
411
412 def defaultTestResult(self):
413 return TestResult()
414
415 def shortDescription(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000416 """Returns both the test method name and first line of its docstring.
Fred Drake02538202001-03-21 18:09:46 +0000417
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000418 If no docstring is given, only returns the method name.
419
420 This method overrides unittest.TestCase.shortDescription(), which
421 only returns the first line of the docstring, obscuring the name
422 of the test upon failure.
Fred Drake02538202001-03-21 18:09:46 +0000423 """
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000424 desc = str(self)
425 doc_first_line = None
426
427 if self._testMethodDoc:
428 doc_first_line = self._testMethodDoc.split("\n")[0].strip()
429 if doc_first_line:
430 desc = '\n'.join((desc, doc_first_line))
431 return desc
Fred Drake02538202001-03-21 18:09:46 +0000432
433 def id(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000434 return "%s.%s" % (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000435
Guido van Rossumd8faa362007-04-27 19:54:29 +0000436 def __eq__(self, other):
437 if type(self) is not type(other):
Benjamin Peterson52baa292009-03-24 00:56:30 +0000438 return NotImplemented
Guido van Rossumd8faa362007-04-27 19:54:29 +0000439
440 return self._testMethodName == other._testMethodName
441
442 def __ne__(self, other):
443 return not self == other
444
445 def __hash__(self):
446 return hash((type(self), self._testMethodName))
447
Fred Drake02538202001-03-21 18:09:46 +0000448 def __str__(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000449 return "%s (%s)" % (self._testMethodName, _strclass(self.__class__))
Fred Drake02538202001-03-21 18:09:46 +0000450
451 def __repr__(self):
452 return "<%s testMethod=%s>" % \
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000453 (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000454
455 def run(self, result=None):
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000456 orig_result = result
Benjamin Peterson52baa292009-03-24 00:56:30 +0000457 if result is None:
458 result = self.defaultTestResult()
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000459 startTestRun = getattr(result, 'startTestRun', None)
460 if startTestRun is not None:
461 startTestRun()
462
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000463 self._resultForDoCleanups = result
Fred Drake02538202001-03-21 18:09:46 +0000464 result.startTest(self)
Benjamin Peterson14a3dd72009-05-25 00:51:58 +0000465 if getattr(self.__class__, "__unittest_skip__", False):
466 # If the whole class was skipped.
467 try:
468 result.addSkip(self, self.__class__.__unittest_skip_why__)
469 finally:
470 result.stopTest(self)
471 return
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000472 testMethod = getattr(self, self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000473 try:
Benjamin Peterson5254c042009-03-23 22:25:03 +0000474 success = False
Fred Drake02538202001-03-21 18:09:46 +0000475 try:
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000476 self.setUp()
Benjamin Peterson5254c042009-03-23 22:25:03 +0000477 except SkipTest as e:
478 result.addSkip(self, str(e))
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000479 except Exception:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000480 result.addError(self, sys.exc_info())
Benjamin Peterson5254c042009-03-23 22:25:03 +0000481 else:
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000482 try:
483 testMethod()
484 except self.failureException:
485 result.addFailure(self, sys.exc_info())
486 except _ExpectedFailure as e:
487 result.addExpectedFailure(self, e.exc_info)
488 except _UnexpectedSuccess:
489 result.addUnexpectedSuccess(self)
490 except SkipTest as e:
491 result.addSkip(self, str(e))
492 except Exception:
493 result.addError(self, sys.exc_info())
494 else:
495 success = True
Fred Drake02538202001-03-21 18:09:46 +0000496
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000497 try:
498 self.tearDown()
499 except Exception:
500 result.addError(self, sys.exc_info())
501 success = False
502
503 cleanUpSuccess = self.doCleanups()
504 success = success and cleanUpSuccess
Benjamin Peterson5254c042009-03-23 22:25:03 +0000505 if success:
506 result.addSuccess(self)
Fred Drake02538202001-03-21 18:09:46 +0000507 finally:
508 result.stopTest(self)
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000509 if orig_result is None:
510 stopTestRun = getattr(result, 'stopTestRun', None)
511 if stopTestRun is not None:
512 stopTestRun()
513
514 def doCleanups(self):
515 """Execute all cleanup functions. Normally called for you after
516 tearDown."""
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000517 result = self._resultForDoCleanups
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000518 ok = True
519 while self._cleanups:
520 function, args, kwargs = self._cleanups.pop(-1)
521 try:
522 function(*args, **kwargs)
523 except Exception:
524 ok = False
525 result.addError(self, sys.exc_info())
526 return ok
Fred Drake02538202001-03-21 18:09:46 +0000527
Raymond Hettinger664347b2004-12-04 21:21:53 +0000528 def __call__(self, *args, **kwds):
529 return self.run(*args, **kwds)
Steve Purcell7e743842003-09-22 11:08:12 +0000530
Fred Drake02538202001-03-21 18:09:46 +0000531 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000532 """Run the test without collecting errors in a TestResult"""
Fred Drake02538202001-03-21 18:09:46 +0000533 self.setUp()
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000534 getattr(self, self._testMethodName)()
Fred Drake02538202001-03-21 18:09:46 +0000535 self.tearDown()
536
Benjamin Petersone549ead2009-03-28 21:42:05 +0000537 def skipTest(self, reason):
Benjamin Peterson5254c042009-03-23 22:25:03 +0000538 """Skip this test."""
539 raise SkipTest(reason)
540
Steve Purcell15d89272001-04-12 09:05:01 +0000541 def fail(self, msg=None):
542 """Fail immediately, with the given message."""
Collin Winterce36ad82007-08-30 01:19:48 +0000543 raise self.failureException(msg)
Fred Drake02538202001-03-21 18:09:46 +0000544
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000545 def assertFalse(self, expr, msg=None):
Ezio Melottia2eb94b2010-12-18 17:55:43 +0000546 """Check that the expression is false."""
Benjamin Peterson52baa292009-03-24 00:56:30 +0000547 if expr:
Ezio Melottia2eb94b2010-12-18 17:55:43 +0000548 msg = self._formatMessage(msg, "%r is not false" % expr)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000549 raise self.failureException(msg)
Fred Drake02538202001-03-21 18:09:46 +0000550
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000551 def assertTrue(self, expr, msg=None):
Ezio Melottia2eb94b2010-12-18 17:55:43 +0000552 """Check that the expression is true."""
Benjamin Peterson52baa292009-03-24 00:56:30 +0000553 if not expr:
Ezio Melottia2eb94b2010-12-18 17:55:43 +0000554 msg = self._formatMessage(msg, "%r is not true" % expr)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000555 raise self.failureException(msg)
Steve Purcell15d89272001-04-12 09:05:01 +0000556
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000557 def _formatMessage(self, msg, standardMsg):
558 """Honour the longMessage attribute when generating failure messages.
559 If longMessage is False this means:
560 * Use only an explicit message if it is provided
561 * Otherwise use the standard message for the assert
562
563 If longMessage is True:
564 * Use the standard message
565 * If an explicit message is provided, plus ' : ' and the explicit message
566 """
567 if not self.longMessage:
568 return msg or standardMsg
569 if msg is None:
570 return standardMsg
571 return standardMsg + ' : ' + msg
572
573
574 def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
Steve Purcell15d89272001-04-12 09:05:01 +0000575 """Fail unless an exception of class excClass is thrown
Fred Drake02538202001-03-21 18:09:46 +0000576 by callableObj when invoked with arguments args and keyword
577 arguments kwargs. If a different type of exception is
578 thrown, it will not be caught, and the test case will be
579 deemed to have suffered an error, exactly as for an
580 unexpected exception.
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000581
582 If called with callableObj omitted or None, will return a
583 context object used like this::
584
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000585 with self.assertRaises(some_error_class):
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000586 do_something()
Fred Drake02538202001-03-21 18:09:46 +0000587 """
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000588 context = _AssertRaisesContext(excClass, self, callableObj)
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000589 if callableObj is None:
590 return context
591 with context:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000592 callableObj(*args, **kwargs)
Fred Drake02538202001-03-21 18:09:46 +0000593
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000594 def _getAssertEqualityFunc(self, first, second):
595 """Get a detailed comparison function for the types of the two args.
596
597 Returns: A callable accepting (first, second, msg=None) that will
598 raise a failure exception if first != second with a useful human
599 readable error message for those types.
600 """
601 #
602 # NOTE(gregory.p.smith): I considered isinstance(first, type(second))
603 # and vice versa. I opted for the conservative approach in case
604 # subclasses are not intended to be compared in detail to their super
605 # class instances using a type equality func. This means testing
606 # subtypes won't automagically use the detailed comparison. Callers
607 # should use their type specific assertSpamEqual method to compare
608 # subclasses if the detailed comparison is desired and appropriate.
609 # See the discussion in http://bugs.python.org/issue2578.
610 #
611 if type(first) is type(second):
612 asserter = self._type_equality_funcs.get(type(first))
613 if asserter is not None:
614 return asserter.function
615
616 return self._baseAssertEqual
617
618 def _baseAssertEqual(self, first, second, msg=None):
619 """The default assertEqual implementation, not type specific."""
620 if not first == second:
621 standardMsg = '%r != %r' % (first, second)
622 msg = self._formatMessage(msg, standardMsg)
623 raise self.failureException(msg)
624
625 def assertEqual(self, first, second, msg=None):
Raymond Hettingerc377cbf2003-04-04 22:56:42 +0000626 """Fail if the two objects are unequal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000627 operator.
628 """
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000629 assertion_func = self._getAssertEqualityFunc(first, second)
630 assertion_func(first, second, msg=msg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000631
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000632 def assertNotEqual(self, first, second, msg=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000633 """Fail if the two objects are equal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000634 operator.
635 """
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000636 if not first != second:
637 msg = self._formatMessage(msg, '%r == %r' % (first, second))
638 raise self.failureException(msg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000639
Michael Foordb36f8322010-11-02 14:46:41 +0000640 def assertAlmostEqual(self, first, second, places=7, msg=None):
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000641 """Fail if the two objects are unequal as determined by their
642 difference rounded to the given number of decimal places
643 (default 7) and comparing to zero.
644
Steve Purcell397b45d2003-10-26 10:41:03 +0000645 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000646 as significant digits (measured from the most signficant digit).
647 """
Jeffrey Yasskin1cc55442007-09-06 18:55:17 +0000648 if round(abs(second-first), places) != 0:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000649 standardMsg = '%r != %r within %r places' % (first, second, places)
650 msg = self._formatMessage(msg, standardMsg)
651 raise self.failureException(msg)
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000652
Michael Foordb36f8322010-11-02 14:46:41 +0000653 def assertNotAlmostEqual(self, first, second, places=7, msg=None):
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000654 """Fail if the two objects are equal as determined by their
655 difference rounded to the given number of decimal places
656 (default 7) and comparing to zero.
657
Steve Purcellcca34912003-10-26 16:38:16 +0000658 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000659 as significant digits (measured from the most signficant digit).
660 """
Jeffrey Yasskin1cc55442007-09-06 18:55:17 +0000661 if round(abs(second-first), places) == 0:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000662 standardMsg = '%r == %r within %r places' % (first, second, places)
663 msg = self._formatMessage(msg, standardMsg)
664 raise self.failureException(msg)
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000665
Steve Purcell7e743842003-09-22 11:08:12 +0000666 # Synonyms for assertion methods
667
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000668 # The plurals are undocumented. Keep them that way to discourage use.
669 # Do not add more. Do not remove.
670 # Going through a deprecation cycle on these would annoy many people.
671 assertEquals = assertEqual
672 assertNotEquals = assertNotEqual
673 assertAlmostEquals = assertAlmostEqual
674 assertNotAlmostEquals = assertNotAlmostEqual
675 assert_ = assertTrue
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000676
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000677 # These fail* assertion method names are pending deprecation and will
678 # be a DeprecationWarning in 3.2; http://bugs.python.org/issue2578
679 def _deprecate(original_func):
680 def deprecated_func(*args, **kwargs):
681 warnings.warn(
682 'Please use {0} instead.'.format(original_func.__name__),
683 PendingDeprecationWarning, 2)
684 return original_func(*args, **kwargs)
685 return deprecated_func
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000686
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000687 failUnlessEqual = _deprecate(assertEqual)
688 failIfEqual = _deprecate(assertNotEqual)
689 failUnlessAlmostEqual = _deprecate(assertAlmostEqual)
690 failIfAlmostEqual = _deprecate(assertNotAlmostEqual)
691 failUnless = _deprecate(assertTrue)
692 failUnlessRaises = _deprecate(assertRaises)
693 failIf = _deprecate(assertFalse)
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000694
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000695 def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
696 """An equality assertion for ordered sequences (like lists and tuples).
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000697
R. David Murrayd1a90582010-01-29 22:26:45 +0000698 For the purposes of this function, a valid ordered sequence type is one
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000699 which can be indexed, has a length, and has an equality operator.
Steve Purcell15d89272001-04-12 09:05:01 +0000700
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000701 Args:
702 seq1: The first sequence to compare.
703 seq2: The second sequence to compare.
704 seq_type: The expected datatype of the sequences, or None if no
705 datatype should be enforced.
706 msg: Optional message to use on failure instead of a list of
707 differences.
708 """
709 if seq_type != None:
710 seq_type_name = seq_type.__name__
711 if not isinstance(seq1, seq_type):
712 raise self.failureException('First sequence is not a %s: %r'
713 % (seq_type_name, seq1))
714 if not isinstance(seq2, seq_type):
715 raise self.failureException('Second sequence is not a %s: %r'
716 % (seq_type_name, seq2))
717 else:
718 seq_type_name = "sequence"
Steve Purcell7e743842003-09-22 11:08:12 +0000719
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000720 differing = None
721 try:
722 len1 = len(seq1)
723 except (TypeError, NotImplementedError):
724 differing = 'First %s has no length. Non-sequence?' % (
725 seq_type_name)
Steve Purcell15d89272001-04-12 09:05:01 +0000726
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000727 if differing is None:
728 try:
729 len2 = len(seq2)
730 except (TypeError, NotImplementedError):
731 differing = 'Second %s has no length. Non-sequence?' % (
732 seq_type_name)
733
734 if differing is None:
735 if seq1 == seq2:
736 return
737
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000738 seq1_repr = repr(seq1)
739 seq2_repr = repr(seq2)
740 if len(seq1_repr) > 30:
741 seq1_repr = seq1_repr[:30] + '...'
742 if len(seq2_repr) > 30:
743 seq2_repr = seq2_repr[:30] + '...'
744 elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr)
745 differing = '%ss differ: %s != %s\n' % elements
746
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000747 for i in range(min(len1, len2)):
748 try:
749 item1 = seq1[i]
750 except (TypeError, IndexError, NotImplementedError):
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000751 differing += ('\nUnable to index element %d of first %s\n' %
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000752 (i, seq_type_name))
753 break
754
755 try:
756 item2 = seq2[i]
757 except (TypeError, IndexError, NotImplementedError):
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000758 differing += ('\nUnable to index element %d of second %s\n' %
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000759 (i, seq_type_name))
760 break
761
762 if item1 != item2:
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000763 differing += ('\nFirst differing element %d:\n%s\n%s\n' %
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000764 (i, item1, item2))
765 break
766 else:
767 if (len1 == len2 and seq_type is None and
768 type(seq1) != type(seq2)):
769 # The sequences are the same, but have differing types.
770 return
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000771
772 if len1 > len2:
773 differing += ('\nFirst %s contains %d additional '
774 'elements.\n' % (seq_type_name, len1 - len2))
775 try:
776 differing += ('First extra element %d:\n%s\n' %
777 (len2, seq1[len2]))
778 except (TypeError, IndexError, NotImplementedError):
779 differing += ('Unable to index element %d '
780 'of first %s\n' % (len2, seq_type_name))
781 elif len1 < len2:
782 differing += ('\nSecond %s contains %d additional '
783 'elements.\n' % (seq_type_name, len2 - len1))
784 try:
785 differing += ('First extra element %d:\n%s\n' %
786 (len1, seq2[len1]))
787 except (TypeError, IndexError, NotImplementedError):
788 differing += ('Unable to index element %d '
789 'of second %s\n' % (len1, seq_type_name))
790 standardMsg = differing + '\n' + '\n'.join(difflib.ndiff(pprint.pformat(seq1).splitlines(),
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000791 pprint.pformat(seq2).splitlines()))
792 msg = self._formatMessage(msg, standardMsg)
793 self.fail(msg)
794
795 def assertListEqual(self, list1, list2, msg=None):
796 """A list-specific equality assertion.
797
798 Args:
799 list1: The first list to compare.
800 list2: The second list to compare.
801 msg: Optional message to use on failure instead of a list of
802 differences.
803
804 """
805 self.assertSequenceEqual(list1, list2, msg, seq_type=list)
806
807 def assertTupleEqual(self, tuple1, tuple2, msg=None):
808 """A tuple-specific equality assertion.
809
810 Args:
811 tuple1: The first tuple to compare.
812 tuple2: The second tuple to compare.
813 msg: Optional message to use on failure instead of a list of
814 differences.
815 """
816 self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
817
818 def assertSetEqual(self, set1, set2, msg=None):
819 """A set-specific equality assertion.
820
821 Args:
822 set1: The first set to compare.
823 set2: The second set to compare.
824 msg: Optional message to use on failure instead of a list of
825 differences.
826
827 For more general containership equality, assertSameElements will work
828 with things other than sets. This uses ducktyping to support
829 different types of sets, and is optimized for sets specifically
830 (parameters must support a difference method).
831 """
832 try:
833 difference1 = set1.difference(set2)
834 except TypeError as e:
835 self.fail('invalid type when attempting set difference: %s' % e)
836 except AttributeError as e:
837 self.fail('first argument does not support set difference: %s' % e)
838
839 try:
840 difference2 = set2.difference(set1)
841 except TypeError as e:
842 self.fail('invalid type when attempting set difference: %s' % e)
843 except AttributeError as e:
844 self.fail('second argument does not support set difference: %s' % e)
845
846 if not (difference1 or difference2):
847 return
848
849 lines = []
850 if difference1:
851 lines.append('Items in the first set but not the second:')
852 for item in difference1:
853 lines.append(repr(item))
854 if difference2:
855 lines.append('Items in the second set but not the first:')
856 for item in difference2:
857 lines.append(repr(item))
858
859 standardMsg = '\n'.join(lines)
860 self.fail(self._formatMessage(msg, standardMsg))
861
862 def assertIn(self, member, container, msg=None):
863 """Just like self.assertTrue(a in b), but with a nicer default message."""
864 if member not in container:
865 standardMsg = '%r not found in %r' % (member, container)
866 self.fail(self._formatMessage(msg, standardMsg))
867
868 def assertNotIn(self, member, container, msg=None):
869 """Just like self.assertTrue(a not in b), but with a nicer default message."""
870 if member in container:
871 standardMsg = '%r unexpectedly found in %r' % (member, container)
872 self.fail(self._formatMessage(msg, standardMsg))
873
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000874 def assertIs(self, expr1, expr2, msg=None):
875 """Just like self.assertTrue(a is b), but with a nicer default message."""
876 if expr1 is not expr2:
877 standardMsg = '%r is not %r' % (expr1, expr2)
878 self.fail(self._formatMessage(msg, standardMsg))
879
880 def assertIsNot(self, expr1, expr2, msg=None):
881 """Just like self.assertTrue(a is not b), but with a nicer default message."""
882 if expr1 is expr2:
883 standardMsg = 'unexpectedly identical: %r' % (expr1,)
884 self.fail(self._formatMessage(msg, standardMsg))
885
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000886 def assertDictEqual(self, d1, d2, msg=None):
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000887 self.assertTrue(isinstance(d1, dict), 'First argument is not a dictionary')
888 self.assertTrue(isinstance(d2, dict), 'Second argument is not a dictionary')
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000889
890 if d1 != d2:
891 standardMsg = ('\n' + '\n'.join(difflib.ndiff(
892 pprint.pformat(d1).splitlines(),
893 pprint.pformat(d2).splitlines())))
894 self.fail(self._formatMessage(msg, standardMsg))
895
896 def assertDictContainsSubset(self, expected, actual, msg=None):
897 """Checks whether actual is a superset of expected."""
898 missing = []
899 mismatched = []
900 for key, value in expected.items():
901 if key not in actual:
902 missing.append(key)
903 elif value != actual[key]:
904 mismatched.append('%s, expected: %s, actual: %s' % (key, value, actual[key]))
905
906 if not (missing or mismatched):
907 return
908
909 standardMsg = ''
910 if missing:
911 standardMsg = 'Missing: %r' % ','.join(missing)
912 if mismatched:
913 if standardMsg:
914 standardMsg += '; '
915 standardMsg += 'Mismatched values: %s' % ','.join(mismatched)
916
917 self.fail(self._formatMessage(msg, standardMsg))
918
919 def assertSameElements(self, expected_seq, actual_seq, msg=None):
920 """An unordered sequence specific comparison.
921
922 Raises with an error message listing which elements of expected_seq
923 are missing from actual_seq and vice versa if any.
924 """
925 try:
926 expected = set(expected_seq)
927 actual = set(actual_seq)
928 missing = list(expected.difference(actual))
929 unexpected = list(actual.difference(expected))
930 missing.sort()
931 unexpected.sort()
932 except TypeError:
933 # Fall back to slower list-compare if any of the objects are
934 # not hashable.
935 expected = list(expected_seq)
936 actual = list(actual_seq)
Michael Foorda5809c82009-04-04 18:55:09 +0000937 try:
938 expected.sort()
939 actual.sort()
940 except TypeError:
941 missing, unexpected = _UnorderableListDifference(expected, actual)
942 else:
943 missing, unexpected = _SortedListDifference(expected, actual)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000944 errors = []
945 if missing:
946 errors.append('Expected, but missing:\n %r' % missing)
947 if unexpected:
948 errors.append('Unexpected, but present:\n %r' % unexpected)
949 if errors:
950 standardMsg = '\n'.join(errors)
951 self.fail(self._formatMessage(msg, standardMsg))
952
953 def assertMultiLineEqual(self, first, second, msg=None):
954 """Assert that two multi-line strings are equal."""
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000955 self.assertTrue(isinstance(first, str), (
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000956 'First argument is not a string'))
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000957 self.assertTrue(isinstance(second, str), (
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000958 'Second argument is not a string'))
959
960 if first != second:
Ezio Melotti935a5882011-04-27 10:17:34 +0300961 # don't use difflib if the strings are too long
962 if (len(first) > self._diffThreshold or
963 len(second) > self._diffThreshold):
964 self._baseAssertEqual(first, second, msg)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000965 standardMsg = '\n' + ''.join(difflib.ndiff(first.splitlines(True), second.splitlines(True)))
966 self.fail(self._formatMessage(msg, standardMsg))
967
968 def assertLess(self, a, b, msg=None):
969 """Just like self.assertTrue(a < b), but with a nicer default message."""
970 if not a < b:
971 standardMsg = '%r not less than %r' % (a, b)
972 self.fail(self._formatMessage(msg, standardMsg))
973
974 def assertLessEqual(self, a, b, msg=None):
975 """Just like self.assertTrue(a <= b), but with a nicer default message."""
976 if not a <= b:
977 standardMsg = '%r not less than or equal to %r' % (a, b)
978 self.fail(self._formatMessage(msg, standardMsg))
979
980 def assertGreater(self, a, b, msg=None):
981 """Just like self.assertTrue(a > b), but with a nicer default message."""
982 if not a > b:
983 standardMsg = '%r not greater than %r' % (a, b)
984 self.fail(self._formatMessage(msg, standardMsg))
985
986 def assertGreaterEqual(self, a, b, msg=None):
987 """Just like self.assertTrue(a >= b), but with a nicer default message."""
988 if not a >= b:
989 standardMsg = '%r not greater than or equal to %r' % (a, b)
990 self.fail(self._formatMessage(msg, standardMsg))
991
992 def assertIsNone(self, obj, msg=None):
993 """Same as self.assertTrue(obj is None), with a nicer default message."""
994 if obj is not None:
995 standardMsg = '%r is not None' % obj
996 self.fail(self._formatMessage(msg, standardMsg))
997
998 def assertIsNotNone(self, obj, msg=None):
999 """Included for symmetry with assertIsNone."""
1000 if obj is None:
1001 standardMsg = 'unexpectedly None'
1002 self.fail(self._formatMessage(msg, standardMsg))
1003
1004 def assertRaisesRegexp(self, expected_exception, expected_regexp,
1005 callable_obj=None, *args, **kwargs):
1006 """Asserts that the message in a raised exception matches a regexp.
1007
1008 Args:
1009 expected_exception: Exception class expected to be raised.
1010 expected_regexp: Regexp (re pattern object or string) expected
1011 to be found in error message.
1012 callable_obj: Function to be called.
1013 args: Extra args.
1014 kwargs: Extra kwargs.
1015 """
1016 context = _AssertRaisesContext(expected_exception, self, callable_obj,
1017 expected_regexp)
1018 if callable_obj is None:
1019 return context
1020 with context:
1021 callable_obj(*args, **kwargs)
1022
1023 def assertRegexpMatches(self, text, expected_regex, msg=None):
1024 if isinstance(expected_regex, (str, bytes)):
1025 expected_regex = re.compile(expected_regex)
1026 if not expected_regex.search(text):
1027 msg = msg or "Regexp didn't match"
1028 msg = '%s: %r not found in %r' % (msg, expected_regex.pattern, text)
1029 raise self.failureException(msg)
1030
1031
1032def _SortedListDifference(expected, actual):
1033 """Finds elements in only one or the other of two, sorted input lists.
1034
1035 Returns a two-element tuple of lists. The first list contains those
1036 elements in the "expected" list but not in the "actual" list, and the
1037 second contains those elements in the "actual" list but not in the
1038 "expected" list. Duplicate elements in either input list are ignored.
1039 """
1040 i = j = 0
1041 missing = []
1042 unexpected = []
1043 while True:
1044 try:
1045 e = expected[i]
1046 a = actual[j]
1047 if e < a:
1048 missing.append(e)
1049 i += 1
1050 while expected[i] == e:
1051 i += 1
1052 elif e > a:
1053 unexpected.append(a)
1054 j += 1
1055 while actual[j] == a:
1056 j += 1
1057 else:
1058 i += 1
1059 try:
1060 while expected[i] == e:
1061 i += 1
1062 finally:
1063 j += 1
1064 while actual[j] == a:
1065 j += 1
1066 except IndexError:
1067 missing.extend(expected[i:])
1068 unexpected.extend(actual[j:])
1069 break
1070 return missing, unexpected
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001071
Michael Foorda5809c82009-04-04 18:55:09 +00001072def _UnorderableListDifference(expected, actual):
1073 """Same behavior as _SortedListDifference but
1074 for lists of unorderable items (like dicts).
1075
1076 As it does a linear search per item (remove) it
1077 has O(n*n) performance."""
1078 missing = []
1079 while expected:
1080 item = expected.pop()
1081 try:
1082 actual.remove(item)
1083 except ValueError:
1084 missing.append(item)
1085
1086 # anything left in actual is unexpected
1087 return missing, actual
Fred Drake02538202001-03-21 18:09:46 +00001088
Benjamin Peterson1467ac82009-01-09 03:42:38 +00001089class TestSuite(object):
Fred Drake02538202001-03-21 18:09:46 +00001090 """A test suite is a composite test consisting of a number of TestCases.
1091
1092 For use, create an instance of TestSuite, then add test case instances.
1093 When all tests have been added, the suite can be passed to a test
1094 runner, such as TextTestRunner. It will run the individual test cases
1095 in the order in which they were added, aggregating the results. When
1096 subclassing, do not forget to call the base class constructor.
1097 """
1098 def __init__(self, tests=()):
1099 self._tests = []
1100 self.addTests(tests)
1101
1102 def __repr__(self):
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001103 return "<%s tests=%s>" % (_strclass(self.__class__), list(self))
Fred Drake02538202001-03-21 18:09:46 +00001104
Guido van Rossumd8faa362007-04-27 19:54:29 +00001105 def __eq__(self, other):
Benjamin Peterson5254c042009-03-23 22:25:03 +00001106 if not isinstance(other, self.__class__):
1107 return NotImplemented
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001108 return list(self) == list(other)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001109
1110 def __ne__(self, other):
1111 return not self == other
1112
Jim Fultonfafd8742004-08-28 15:22:12 +00001113 def __iter__(self):
1114 return iter(self._tests)
1115
Fred Drake02538202001-03-21 18:09:46 +00001116 def countTestCases(self):
1117 cases = 0
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001118 for test in self:
Steve Purcell7e743842003-09-22 11:08:12 +00001119 cases += test.countTestCases()
Fred Drake02538202001-03-21 18:09:46 +00001120 return cases
1121
1122 def addTest(self, test):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001123 # sanity checks
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001124 if not hasattr(test, '__call__'):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001125 raise TypeError("the test to add must be callable")
Guido van Rossum13257902007-06-07 23:15:56 +00001126 if isinstance(test, type) and issubclass(test, (TestCase, TestSuite)):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001127 raise TypeError("TestCases and TestSuites must be instantiated "
1128 "before passing them to addTest()")
Fred Drake02538202001-03-21 18:09:46 +00001129 self._tests.append(test)
1130
1131 def addTests(self, tests):
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001132 if isinstance(tests, str):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001133 raise TypeError("tests must be an iterable of tests, not a string")
Fred Drake02538202001-03-21 18:09:46 +00001134 for test in tests:
1135 self.addTest(test)
1136
1137 def run(self, result):
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001138 for test in self:
Fred Drake02538202001-03-21 18:09:46 +00001139 if result.shouldStop:
1140 break
1141 test(result)
1142 return result
1143
Raymond Hettinger664347b2004-12-04 21:21:53 +00001144 def __call__(self, *args, **kwds):
1145 return self.run(*args, **kwds)
1146
Fred Drake02538202001-03-21 18:09:46 +00001147 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001148 """Run the tests without collecting errors in a TestResult"""
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001149 for test in self:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001150 test.debug()
Fred Drake02538202001-03-21 18:09:46 +00001151
1152
1153class FunctionTestCase(TestCase):
1154 """A test case that wraps a test function.
1155
1156 This is useful for slipping pre-existing test functions into the
Guido van Rossumd8faa362007-04-27 19:54:29 +00001157 unittest framework. Optionally, set-up and tidy-up functions can be
Fred Drake02538202001-03-21 18:09:46 +00001158 supplied. As with TestCase, the tidy-up ('tearDown') function will
1159 always be called if the set-up ('setUp') function ran successfully.
1160 """
1161
Benjamin Peterson52baa292009-03-24 00:56:30 +00001162 def __init__(self, testFunc, setUp=None, tearDown=None, description=None):
1163 super(FunctionTestCase, self).__init__()
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001164 self._setUpFunc = setUp
1165 self._tearDownFunc = tearDown
1166 self._testFunc = testFunc
1167 self._description = description
Fred Drake02538202001-03-21 18:09:46 +00001168
1169 def setUp(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001170 if self._setUpFunc is not None:
1171 self._setUpFunc()
Fred Drake02538202001-03-21 18:09:46 +00001172
1173 def tearDown(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001174 if self._tearDownFunc is not None:
1175 self._tearDownFunc()
Fred Drake02538202001-03-21 18:09:46 +00001176
1177 def runTest(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001178 self._testFunc()
Fred Drake02538202001-03-21 18:09:46 +00001179
1180 def id(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001181 return self._testFunc.__name__
Fred Drake02538202001-03-21 18:09:46 +00001182
Guido van Rossumd8faa362007-04-27 19:54:29 +00001183 def __eq__(self, other):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001184 if not isinstance(other, self.__class__):
1185 return NotImplemented
Guido van Rossumd8faa362007-04-27 19:54:29 +00001186
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001187 return self._setUpFunc == other._setUpFunc and \
1188 self._tearDownFunc == other._tearDownFunc and \
1189 self._testFunc == other._testFunc and \
1190 self._description == other._description
Guido van Rossumd8faa362007-04-27 19:54:29 +00001191
1192 def __ne__(self, other):
1193 return not self == other
1194
1195 def __hash__(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001196 return hash((type(self), self._setUpFunc, self._tearDownFunc,
1197 self._testFunc, self._description))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001198
Fred Drake02538202001-03-21 18:09:46 +00001199 def __str__(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001200 return "%s (%s)" % (_strclass(self.__class__), self._testFunc.__name__)
Fred Drake02538202001-03-21 18:09:46 +00001201
1202 def __repr__(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001203 return "<%s testFunc=%s>" % (_strclass(self.__class__), self._testFunc)
Fred Drake02538202001-03-21 18:09:46 +00001204
1205 def shortDescription(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001206 if self._description is not None:
1207 return self._description
1208 doc = self._testFunc.__doc__
Steve Purcell7e743842003-09-22 11:08:12 +00001209 return doc and doc.split("\n")[0].strip() or None
Fred Drake02538202001-03-21 18:09:46 +00001210
1211
1212
1213##############################################################################
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001214# Locating and loading tests
Fred Drake02538202001-03-21 18:09:46 +00001215##############################################################################
1216
Raymond Hettingerd4cb56d2008-01-30 02:55:10 +00001217def CmpToKey(mycmp):
1218 'Convert a cmp= function into a key= function'
1219 class K(object):
1220 def __init__(self, obj, *args):
1221 self.obj = obj
1222 def __lt__(self, other):
1223 return mycmp(self.obj, other.obj) == -1
1224 return K
1225
Mark Dickinsona56c4672009-01-27 18:17:45 +00001226def three_way_cmp(x, y):
1227 """Return -1 if x < y, 0 if x == y and 1 if x > y"""
1228 return (x > y) - (x < y)
1229
Benjamin Peterson1467ac82009-01-09 03:42:38 +00001230class TestLoader(object):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001231 """
1232 This class is responsible for loading tests according to various criteria
1233 and returning them wrapped in a TestSuite
Fred Drake02538202001-03-21 18:09:46 +00001234 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001235 testMethodPrefix = 'test'
Mark Dickinsona56c4672009-01-27 18:17:45 +00001236 sortTestMethodsUsing = staticmethod(three_way_cmp)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001237 suiteClass = TestSuite
Fred Drake02538202001-03-21 18:09:46 +00001238
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001239 def loadTestsFromTestCase(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +00001240 """Return a suite of all tests cases contained in testCaseClass"""
Johannes Gijsbersd7b6ad42004-11-07 15:46:25 +00001241 if issubclass(testCaseClass, TestSuite):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001242 raise TypeError("Test cases should not be derived from TestSuite." \
1243 " Maybe you meant to derive from TestCase?")
Steve Purcell7e743842003-09-22 11:08:12 +00001244 testCaseNames = self.getTestCaseNames(testCaseClass)
1245 if not testCaseNames and hasattr(testCaseClass, 'runTest'):
1246 testCaseNames = ['runTest']
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001247 suite = self.suiteClass(map(testCaseClass, testCaseNames))
Benjamin Peterson5254c042009-03-23 22:25:03 +00001248 return suite
Fred Drake02538202001-03-21 18:09:46 +00001249
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001250 def loadTestsFromModule(self, module):
Steve Purcell15d89272001-04-12 09:05:01 +00001251 """Return a suite of all tests cases contained in the given module"""
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001252 tests = []
1253 for name in dir(module):
1254 obj = getattr(module, name)
Guido van Rossum13257902007-06-07 23:15:56 +00001255 if isinstance(obj, type) and issubclass(obj, TestCase):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001256 tests.append(self.loadTestsFromTestCase(obj))
1257 return self.suiteClass(tests)
Fred Drake02538202001-03-21 18:09:46 +00001258
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001259 def loadTestsFromName(self, name, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +00001260 """Return a suite of all tests cases given a string specifier.
1261
1262 The name may resolve either to a module, a test case class, a
1263 test method within a test case class, or a callable object which
1264 returns a TestCase or TestSuite instance.
Tim Peters613b2222001-04-13 05:37:27 +00001265
Steve Purcell15d89272001-04-12 09:05:01 +00001266 The method optionally resolves the names relative to a given module.
1267 """
Steve Purcell7e743842003-09-22 11:08:12 +00001268 parts = name.split('.')
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001269 if module is None:
Steve Purcell7e743842003-09-22 11:08:12 +00001270 parts_copy = parts[:]
1271 while parts_copy:
1272 try:
1273 module = __import__('.'.join(parts_copy))
1274 break
1275 except ImportError:
1276 del parts_copy[-1]
Benjamin Peterson52baa292009-03-24 00:56:30 +00001277 if not parts_copy:
1278 raise
Armin Rigo1b3c04b2003-10-24 17:15:29 +00001279 parts = parts[1:]
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001280 obj = module
1281 for part in parts:
Steve Purcell7e743842003-09-22 11:08:12 +00001282 parent, obj = obj, getattr(obj, part)
Fred Drake02538202001-03-21 18:09:46 +00001283
Benjamin Peterson1467ac82009-01-09 03:42:38 +00001284 if isinstance(obj, types.ModuleType):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001285 return self.loadTestsFromModule(obj)
Guido van Rossum13257902007-06-07 23:15:56 +00001286 elif isinstance(obj, type) and issubclass(obj, TestCase):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001287 return self.loadTestsFromTestCase(obj)
Christian Heimes4a22b5d2007-11-25 09:39:14 +00001288 elif (isinstance(obj, types.FunctionType) and
Guido van Rossum13257902007-06-07 23:15:56 +00001289 isinstance(parent, type) and
Guido van Rossumd8faa362007-04-27 19:54:29 +00001290 issubclass(parent, TestCase)):
Christian Heimes4a22b5d2007-11-25 09:39:14 +00001291 name = obj.__name__
1292 inst = parent(name)
1293 # static methods follow a different path
Christian Heimes4975a1f2007-11-26 10:14:51 +00001294 if not isinstance(getattr(inst, name), types.FunctionType):
Christian Heimes4a22b5d2007-11-25 09:39:14 +00001295 return TestSuite([inst])
Steve Purcell397b45d2003-10-26 10:41:03 +00001296 elif isinstance(obj, TestSuite):
Steve Purcell7e743842003-09-22 11:08:12 +00001297 return obj
Christian Heimes4a22b5d2007-11-25 09:39:14 +00001298
1299 if hasattr(obj, '__call__'):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001300 test = obj()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001301 if isinstance(test, TestSuite):
1302 return test
1303 elif isinstance(test, TestCase):
1304 return TestSuite([test])
1305 else:
1306 raise TypeError("calling %s returned %s, not a test" %
1307 (obj, test))
Fred Drake02538202001-03-21 18:09:46 +00001308 else:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001309 raise TypeError("don't know how to make test from: %s" % obj)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001310
1311 def loadTestsFromNames(self, names, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +00001312 """Return a suite of all tests cases found using the given sequence
1313 of string specifiers. See 'loadTestsFromName()'.
1314 """
Steve Purcell7e743842003-09-22 11:08:12 +00001315 suites = [self.loadTestsFromName(name, module) for name in names]
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001316 return self.suiteClass(suites)
1317
1318 def getTestCaseNames(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +00001319 """Return a sorted sequence of method names found within testCaseClass
1320 """
Collin Winterce36ad82007-08-30 01:19:48 +00001321 def isTestMethod(attrname, testCaseClass=testCaseClass,
1322 prefix=self.testMethodPrefix):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001323 return attrname.startswith(prefix) and \
1324 hasattr(getattr(testCaseClass, attrname), '__call__')
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001325 testFnNames = list(filter(isTestMethod, dir(testCaseClass)))
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001326 if self.sortTestMethodsUsing:
Raymond Hettingerd4cb56d2008-01-30 02:55:10 +00001327 testFnNames.sort(key=CmpToKey(self.sortTestMethodsUsing))
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001328 return testFnNames
1329
1330
1331
1332defaultTestLoader = TestLoader()
1333
1334
1335##############################################################################
1336# Patches for old functions: these functions should be considered obsolete
1337##############################################################################
1338
1339def _makeLoader(prefix, sortUsing, suiteClass=None):
1340 loader = TestLoader()
1341 loader.sortTestMethodsUsing = sortUsing
1342 loader.testMethodPrefix = prefix
1343 if suiteClass: loader.suiteClass = suiteClass
1344 return loader
1345
Mark Dickinsonc429a832009-01-27 20:27:05 +00001346def getTestCaseNames(testCaseClass, prefix, sortUsing=three_way_cmp):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001347 return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
1348
Mark Dickinsonc429a832009-01-27 20:27:05 +00001349def makeSuite(testCaseClass, prefix='test', sortUsing=three_way_cmp,
1350 suiteClass=TestSuite):
1351 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(
1352 testCaseClass)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001353
Mark Dickinsonc429a832009-01-27 20:27:05 +00001354def findTestCases(module, prefix='test', sortUsing=three_way_cmp,
1355 suiteClass=TestSuite):
1356 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(
1357 module)
Fred Drake02538202001-03-21 18:09:46 +00001358
1359
1360##############################################################################
1361# Text UI
1362##############################################################################
1363
Benjamin Peterson1467ac82009-01-09 03:42:38 +00001364class _WritelnDecorator(object):
Fred Drake02538202001-03-21 18:09:46 +00001365 """Used to decorate file-like objects with a handy 'writeln' method"""
1366 def __init__(self,stream):
1367 self.stream = stream
Fred Drake02538202001-03-21 18:09:46 +00001368
1369 def __getattr__(self, attr):
1370 return getattr(self.stream,attr)
1371
Raymond Hettinger91dd19d2003-09-13 02:58:00 +00001372 def writeln(self, arg=None):
Benjamin Petersone549ead2009-03-28 21:42:05 +00001373 if arg:
1374 self.write(arg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001375 self.write('\n') # text-mode streams translate to \r\n if needed
Tim Petersa19a1682001-03-29 04:36:09 +00001376
Fred Drake02538202001-03-21 18:09:46 +00001377
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001378class _TextTestResult(TestResult):
Fred Drake02538202001-03-21 18:09:46 +00001379 """A test result class that can print formatted text results to a stream.
1380
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001381 Used by TextTestRunner.
Fred Drake02538202001-03-21 18:09:46 +00001382 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001383 separator1 = '=' * 70
1384 separator2 = '-' * 70
Fred Drake02538202001-03-21 18:09:46 +00001385
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001386 def __init__(self, stream, descriptions, verbosity):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001387 super(_TextTestResult, self).__init__()
Fred Drake02538202001-03-21 18:09:46 +00001388 self.stream = stream
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001389 self.showAll = verbosity > 1
1390 self.dots = verbosity == 1
Fred Drake02538202001-03-21 18:09:46 +00001391 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001392
1393 def getDescription(self, test):
1394 if self.descriptions:
1395 return test.shortDescription() or str(test)
1396 else:
1397 return str(test)
1398
Fred Drake02538202001-03-21 18:09:46 +00001399 def startTest(self, test):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001400 super(_TextTestResult, self).startTest(test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001401 if self.showAll:
1402 self.stream.write(self.getDescription(test))
1403 self.stream.write(" ... ")
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001404 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001405
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001406 def addSuccess(self, test):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001407 super(_TextTestResult, self).addSuccess(test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001408 if self.showAll:
Fred Drake02538202001-03-21 18:09:46 +00001409 self.stream.writeln("ok")
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001410 elif self.dots:
1411 self.stream.write('.')
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001412 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001413
1414 def addError(self, test, err):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001415 super(_TextTestResult, self).addError(test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001416 if self.showAll:
1417 self.stream.writeln("ERROR")
1418 elif self.dots:
1419 self.stream.write('E')
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001420 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001421
1422 def addFailure(self, test, err):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001423 super(_TextTestResult, self).addFailure(test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001424 if self.showAll:
1425 self.stream.writeln("FAIL")
1426 elif self.dots:
1427 self.stream.write('F')
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001428 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001429
Benjamin Peterson5254c042009-03-23 22:25:03 +00001430 def addSkip(self, test, reason):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001431 super(_TextTestResult, self).addSkip(test, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +00001432 if self.showAll:
1433 self.stream.writeln("skipped {0!r}".format(reason))
1434 elif self.dots:
1435 self.stream.write("s")
1436 self.stream.flush()
1437
1438 def addExpectedFailure(self, test, err):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001439 super(_TextTestResult, self).addExpectedFailure(test, err)
Benjamin Peterson5254c042009-03-23 22:25:03 +00001440 if self.showAll:
1441 self.stream.writeln("expected failure")
1442 elif self.dots:
Benjamin Petersone549ead2009-03-28 21:42:05 +00001443 self.stream.write("x")
Benjamin Peterson5254c042009-03-23 22:25:03 +00001444 self.stream.flush()
1445
1446 def addUnexpectedSuccess(self, test):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001447 super(_TextTestResult, self).addUnexpectedSuccess(test)
Benjamin Peterson5254c042009-03-23 22:25:03 +00001448 if self.showAll:
1449 self.stream.writeln("unexpected success")
1450 elif self.dots:
Benjamin Petersone549ead2009-03-28 21:42:05 +00001451 self.stream.write("u")
Benjamin Peterson5254c042009-03-23 22:25:03 +00001452 self.stream.flush()
1453
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001454 def printErrors(self):
1455 if self.dots or self.showAll:
Fred Drake02538202001-03-21 18:09:46 +00001456 self.stream.writeln()
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001457 self.printErrorList('ERROR', self.errors)
1458 self.printErrorList('FAIL', self.failures)
1459
1460 def printErrorList(self, flavour, errors):
1461 for test, err in errors:
1462 self.stream.writeln(self.separator1)
1463 self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
1464 self.stream.writeln(self.separator2)
Steve Purcell7b065702001-09-06 08:24:40 +00001465 self.stream.writeln("%s" % err)
Fred Drake02538202001-03-21 18:09:46 +00001466
1467
Benjamin Peterson1467ac82009-01-09 03:42:38 +00001468class TextTestRunner(object):
Fred Drake02538202001-03-21 18:09:46 +00001469 """A test runner class that displays results in textual form.
Tim Petersa19a1682001-03-29 04:36:09 +00001470
Fred Drake02538202001-03-21 18:09:46 +00001471 It prints out the names of tests as they are run, errors as they
1472 occur, and a summary of the results at the end of the test run.
1473 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001474 def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
Fred Drake02538202001-03-21 18:09:46 +00001475 self.stream = _WritelnDecorator(stream)
1476 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001477 self.verbosity = verbosity
1478
1479 def _makeResult(self):
1480 return _TextTestResult(self.stream, self.descriptions, self.verbosity)
Fred Drake02538202001-03-21 18:09:46 +00001481
1482 def run(self, test):
1483 "Run the given test case or test suite."
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001484 result = self._makeResult()
Fred Drake02538202001-03-21 18:09:46 +00001485 startTime = time.time()
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001486 startTestRun = getattr(result, 'startTestRun', None)
1487 if startTestRun is not None:
1488 startTestRun()
1489 try:
1490 test(result)
1491 finally:
1492 stopTestRun = getattr(result, 'stopTestRun', None)
1493 if stopTestRun is not None:
1494 stopTestRun()
Fred Drake02538202001-03-21 18:09:46 +00001495 stopTime = time.time()
Steve Purcell397b45d2003-10-26 10:41:03 +00001496 timeTaken = stopTime - startTime
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001497 result.printErrors()
1498 self.stream.writeln(result.separator2)
Fred Drake02538202001-03-21 18:09:46 +00001499 run = result.testsRun
1500 self.stream.writeln("Ran %d test%s in %.3fs" %
Neal Norwitz76165042002-05-31 14:15:11 +00001501 (run, run != 1 and "s" or "", timeTaken))
Fred Drake02538202001-03-21 18:09:46 +00001502 self.stream.writeln()
Benjamin Peterson52baa292009-03-24 00:56:30 +00001503 results = map(len, (result.expectedFailures,
1504 result.unexpectedSuccesses,
Benjamin Peterson5254c042009-03-23 22:25:03 +00001505 result.skipped))
Benjamin Peterson52baa292009-03-24 00:56:30 +00001506 expectedFails, unexpectedSuccesses, skipped = results
Benjamin Peterson5254c042009-03-23 22:25:03 +00001507 infos = []
Fred Drake02538202001-03-21 18:09:46 +00001508 if not result.wasSuccessful():
Benjamin Peterson5254c042009-03-23 22:25:03 +00001509 self.stream.write("FAILED")
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001510 failed, errored = len(result.failures), len(result.errors)
Fred Drake02538202001-03-21 18:09:46 +00001511 if failed:
Benjamin Peterson5254c042009-03-23 22:25:03 +00001512 infos.append("failures=%d" % failed)
Fred Drake02538202001-03-21 18:09:46 +00001513 if errored:
Benjamin Peterson5254c042009-03-23 22:25:03 +00001514 infos.append("errors=%d" % errored)
Fred Drake02538202001-03-21 18:09:46 +00001515 else:
Benjamin Petersone549ead2009-03-28 21:42:05 +00001516 self.stream.write("OK")
Benjamin Peterson5254c042009-03-23 22:25:03 +00001517 if skipped:
1518 infos.append("skipped=%d" % skipped)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001519 if expectedFails:
1520 infos.append("expected failures=%d" % expectedFails)
1521 if unexpectedSuccesses:
1522 infos.append("unexpected successes=%d" % unexpectedSuccesses)
Benjamin Peterson5254c042009-03-23 22:25:03 +00001523 if infos:
1524 self.stream.writeln(" (%s)" % (", ".join(infos),))
Benjamin Petersone549ead2009-03-28 21:42:05 +00001525 else:
1526 self.stream.write("\n")
Fred Drake02538202001-03-21 18:09:46 +00001527 return result
Tim Petersa19a1682001-03-29 04:36:09 +00001528
Fred Drake02538202001-03-21 18:09:46 +00001529
Fred Drake02538202001-03-21 18:09:46 +00001530
1531##############################################################################
1532# Facilities for running tests from the command line
1533##############################################################################
1534
Benjamin Peterson1467ac82009-01-09 03:42:38 +00001535class TestProgram(object):
Fred Drake02538202001-03-21 18:09:46 +00001536 """A command-line program that runs a set of tests; this is primarily
1537 for making test modules conveniently executable.
1538 """
1539 USAGE = """\
Steve Purcell17a781b2001-04-09 15:37:31 +00001540Usage: %(progName)s [options] [test] [...]
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001541
1542Options:
1543 -h, --help Show this message
1544 -v, --verbose Verbose output
1545 -q, --quiet Minimal output
Fred Drake02538202001-03-21 18:09:46 +00001546
1547Examples:
1548 %(progName)s - run default set of tests
1549 %(progName)s MyTestSuite - run suite 'MyTestSuite'
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001550 %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
1551 %(progName)s MyTestCase - run all 'test*' test methods
Fred Drake02538202001-03-21 18:09:46 +00001552 in MyTestCase
1553"""
1554 def __init__(self, module='__main__', defaultTest=None,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001555 argv=None, testRunner=TextTestRunner,
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001556 testLoader=defaultTestLoader, exit=True):
Antoine Pitroue7bd8682009-01-09 19:29:16 +00001557 if isinstance(module, str):
Fred Drake02538202001-03-21 18:09:46 +00001558 self.module = __import__(module)
Steve Purcell7e743842003-09-22 11:08:12 +00001559 for part in module.split('.')[1:]:
Fred Drake02538202001-03-21 18:09:46 +00001560 self.module = getattr(self.module, part)
1561 else:
1562 self.module = module
1563 if argv is None:
1564 argv = sys.argv
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001565
1566 self.exit = exit
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001567 self.verbosity = 1
Fred Drake02538202001-03-21 18:09:46 +00001568 self.defaultTest = defaultTest
1569 self.testRunner = testRunner
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001570 self.testLoader = testLoader
Fred Drake02538202001-03-21 18:09:46 +00001571 self.progName = os.path.basename(argv[0])
1572 self.parseArgs(argv)
Fred Drake02538202001-03-21 18:09:46 +00001573 self.runTests()
1574
1575 def usageExit(self, msg=None):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001576 if msg:
1577 print(msg)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001578 print(self.USAGE % self.__dict__)
Fred Drake02538202001-03-21 18:09:46 +00001579 sys.exit(2)
1580
1581 def parseArgs(self, argv):
1582 import getopt
Benjamin Peterson5254c042009-03-23 22:25:03 +00001583 long_opts = ['help','verbose','quiet']
Fred Drake02538202001-03-21 18:09:46 +00001584 try:
Benjamin Peterson5254c042009-03-23 22:25:03 +00001585 options, args = getopt.getopt(argv[1:], 'hHvq', long_opts)
Fred Drake02538202001-03-21 18:09:46 +00001586 for opt, value in options:
1587 if opt in ('-h','-H','--help'):
1588 self.usageExit()
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001589 if opt in ('-q','--quiet'):
1590 self.verbosity = 0
1591 if opt in ('-v','--verbose'):
1592 self.verbosity = 2
Fred Drake02538202001-03-21 18:09:46 +00001593 if len(args) == 0 and self.defaultTest is None:
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001594 self.test = self.testLoader.loadTestsFromModule(self.module)
1595 return
Fred Drake02538202001-03-21 18:09:46 +00001596 if len(args) > 0:
1597 self.testNames = args
1598 else:
1599 self.testNames = (self.defaultTest,)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001600 self.createTests()
Guido van Rossumb940e112007-01-10 16:19:56 +00001601 except getopt.error as msg:
Fred Drake02538202001-03-21 18:09:46 +00001602 self.usageExit(msg)
1603
1604 def createTests(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001605 self.test = self.testLoader.loadTestsFromNames(self.testNames,
1606 self.module)
Fred Drake02538202001-03-21 18:09:46 +00001607
1608 def runTests(self):
Guido van Rossum13257902007-06-07 23:15:56 +00001609 if isinstance(self.testRunner, type):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001610 try:
1611 testRunner = self.testRunner(verbosity=self.verbosity)
1612 except TypeError:
1613 # didn't accept the verbosity argument
1614 testRunner = self.testRunner()
1615 else:
1616 # it is assumed to be a TestRunner instance
1617 testRunner = self.testRunner
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001618 self.result = testRunner.run(self.test)
1619 if self.exit:
1620 sys.exit(not self.result.wasSuccessful())
Fred Drake02538202001-03-21 18:09:46 +00001621
1622main = TestProgram
1623
1624
1625##############################################################################
1626# Executing this module from the command line
1627##############################################################################
1628
1629if __name__ == "__main__":
1630 main(module=None)