blob: ce990b78510289762a48acd60b858cb7b92985c9 [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
Benjamin Petersond2397752009-06-27 23:45:02 +000059from fnmatch import fnmatch
60
61
Fred Drake02538202001-03-21 18:09:46 +000062##############################################################################
Steve Purcelld75e7e42003-09-15 11:01:21 +000063# Exported classes and functions
64##############################################################################
Benjamin Peterson14a3dd72009-05-25 00:51:58 +000065__all__ = ['TestResult', 'TestCase', 'TestSuite',
Benjamin Peterson52baa292009-03-24 00:56:30 +000066 'TextTestRunner', 'TestLoader', 'FunctionTestCase', 'main',
Benjamin Peterson4c93dcb2009-03-24 01:33:55 +000067 'defaultTestLoader', 'SkipTest', 'skip', 'skipIf', 'skipUnless',
Benjamin Peterson52baa292009-03-24 00:56:30 +000068 'expectedFailure']
Steve Purcelld75e7e42003-09-15 11:01:21 +000069
Steve Purcell7e743842003-09-22 11:08:12 +000070# Expose obsolete functions for backwards compatibility
Steve Purcelld75e7e42003-09-15 11:01:21 +000071__all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases'])
72
73
74##############################################################################
Fred Drake02538202001-03-21 18:09:46 +000075# Test framework core
76##############################################################################
77
Steve Purcelldc391a62002-08-09 09:46:23 +000078def _strclass(cls):
79 return "%s.%s" % (cls.__module__, cls.__name__)
80
Benjamin Peterson5254c042009-03-23 22:25:03 +000081
82class SkipTest(Exception):
83 """
84 Raise this exception in a test to skip it.
85
86 Usually you can use TestResult.skip() or one of the skipping decorators
87 instead of raising this directly.
88 """
89 pass
90
91class _ExpectedFailure(Exception):
92 """
93 Raise this when a test is expected to fail.
94
95 This is an implementation detail.
96 """
97
98 def __init__(self, exc_info):
99 super(_ExpectedFailure, self).__init__()
100 self.exc_info = exc_info
101
102class _UnexpectedSuccess(Exception):
103 """
104 The test was supposed to fail, but it didn't!
105 """
106 pass
107
108def _id(obj):
109 return obj
110
111def skip(reason):
112 """
113 Unconditionally skip a test.
114 """
115 def decorator(test_item):
116 if isinstance(test_item, type) and issubclass(test_item, TestCase):
117 test_item.__unittest_skip__ = True
118 test_item.__unittest_skip_why__ = reason
119 return test_item
120 @functools.wraps(test_item)
121 def skip_wrapper(*args, **kwargs):
122 raise SkipTest(reason)
123 return skip_wrapper
124 return decorator
125
126def skipIf(condition, reason):
127 """
128 Skip a test if the condition is true.
129 """
130 if condition:
131 return skip(reason)
132 return _id
133
134def skipUnless(condition, reason):
135 """
136 Skip a test unless the condition is true.
137 """
138 if not condition:
139 return skip(reason)
140 return _id
141
142
143def expectedFailure(func):
144 @functools.wraps(func)
145 def wrapper(*args, **kwargs):
146 try:
147 func(*args, **kwargs)
148 except Exception:
149 raise _ExpectedFailure(sys.exc_info())
150 raise _UnexpectedSuccess
151 return wrapper
152
Steve Purcellb8d5f242003-12-06 13:03:13 +0000153__unittest = 1
154
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000155class TestResult(object):
Fred Drake02538202001-03-21 18:09:46 +0000156 """Holder for test result information.
157
158 Test results are automatically managed by the TestCase and TestSuite
159 classes, and do not need to be explicitly manipulated by writers of tests.
160
161 Each instance holds the total number of tests run, and collections of
162 failures and errors that occurred among those test runs. The collections
Steve Purcell7b065702001-09-06 08:24:40 +0000163 contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
Fred Drake656f9ec2001-09-06 19:13:14 +0000164 formatted traceback of the error that occurred.
Fred Drake02538202001-03-21 18:09:46 +0000165 """
166 def __init__(self):
167 self.failures = []
168 self.errors = []
169 self.testsRun = 0
Benjamin Peterson5254c042009-03-23 22:25:03 +0000170 self.skipped = []
Benjamin Peterson52baa292009-03-24 00:56:30 +0000171 self.expectedFailures = []
172 self.unexpectedSuccesses = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000173 self.shouldStop = False
Fred Drake02538202001-03-21 18:09:46 +0000174
175 def startTest(self, test):
176 "Called when the given test is about to be run"
177 self.testsRun = self.testsRun + 1
178
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000179 def startTestRun(self):
180 """Called once before any tests are executed.
181
182 See startTest for a method called before each test.
183 """
184
Fred Drake02538202001-03-21 18:09:46 +0000185 def stopTest(self, test):
186 "Called when the given test has been run"
187 pass
188
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000189 def stopTestRun(self):
190 """Called once after all tests are executed.
191
192 See stopTest for a method called after each test.
193 """
194
Fred Drake02538202001-03-21 18:09:46 +0000195 def addError(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000196 """Called when an error has occurred. 'err' is a tuple of values as
197 returned by sys.exc_info().
198 """
Steve Purcellb8d5f242003-12-06 13:03:13 +0000199 self.errors.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000200
201 def addFailure(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000202 """Called when an error has occurred. 'err' is a tuple of values as
203 returned by sys.exc_info()."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000204 self.failures.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000205
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000206 def addSuccess(self, test):
207 "Called when a test has completed successfully"
208 pass
209
Benjamin Peterson5254c042009-03-23 22:25:03 +0000210 def addSkip(self, test, reason):
211 """Called when a test is skipped."""
212 self.skipped.append((test, reason))
213
214 def addExpectedFailure(self, test, err):
215 """Called when an expected failure/error occured."""
Benjamin Peterson52baa292009-03-24 00:56:30 +0000216 self.expectedFailures.append(
Benjamin Peterson5254c042009-03-23 22:25:03 +0000217 (test, self._exc_info_to_string(err, test)))
218
219 def addUnexpectedSuccess(self, test):
220 """Called when a test was expected to fail, but succeed."""
Benjamin Peterson52baa292009-03-24 00:56:30 +0000221 self.unexpectedSuccesses.append(test)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000222
Fred Drake02538202001-03-21 18:09:46 +0000223 def wasSuccessful(self):
224 "Tells whether or not this result was a success"
225 return len(self.failures) == len(self.errors) == 0
226
227 def stop(self):
228 "Indicates that the tests should be aborted"
Steve Purcell7e743842003-09-22 11:08:12 +0000229 self.shouldStop = True
Tim Petersa19a1682001-03-29 04:36:09 +0000230
Steve Purcellb8d5f242003-12-06 13:03:13 +0000231 def _exc_info_to_string(self, err, test):
Steve Purcell7b065702001-09-06 08:24:40 +0000232 """Converts a sys.exc_info()-style tuple of values into a string."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000233 exctype, value, tb = err
234 # Skip test runner traceback levels
235 while tb and self._is_relevant_tb_level(tb):
236 tb = tb.tb_next
237 if exctype is test.failureException:
238 # Skip assert*() traceback levels
239 length = self._count_relevant_tb_levels(tb)
Collin Winterce36ad82007-08-30 01:19:48 +0000240 return ''.join(traceback.format_exception(exctype, value,
241 tb, length))
Steve Purcellb8d5f242003-12-06 13:03:13 +0000242 return ''.join(traceback.format_exception(exctype, value, tb))
243
244 def _is_relevant_tb_level(self, tb):
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000245 return '__unittest' in tb.tb_frame.f_globals
Steve Purcellb8d5f242003-12-06 13:03:13 +0000246
247 def _count_relevant_tb_levels(self, tb):
248 length = 0
249 while tb and not self._is_relevant_tb_level(tb):
250 length += 1
251 tb = tb.tb_next
252 return length
Steve Purcell7b065702001-09-06 08:24:40 +0000253
Fred Drake02538202001-03-21 18:09:46 +0000254 def __repr__(self):
255 return "<%s run=%i errors=%i failures=%i>" % \
Steve Purcelldc391a62002-08-09 09:46:23 +0000256 (_strclass(self.__class__), self.testsRun, len(self.errors),
Fred Drake02538202001-03-21 18:09:46 +0000257 len(self.failures))
258
Benjamin Peterson52baa292009-03-24 00:56:30 +0000259
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000260class _AssertRaisesContext(object):
261 """A context manager used to implement TestCase.assertRaises* methods."""
Benjamin Peterson52baa292009-03-24 00:56:30 +0000262
263
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000264 def __init__(self, expected, test_case, callable_obj=None,
265 expected_regexp=None):
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000266 self.expected = expected
267 self.failureException = test_case.failureException
268 if callable_obj is not None:
269 try:
270 self.obj_name = callable_obj.__name__
271 except AttributeError:
272 self.obj_name = str(callable_obj)
273 else:
274 self.obj_name = None
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000275 self.expected_regex = expected_regexp
Benjamin Peterson52baa292009-03-24 00:56:30 +0000276
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000277 def __enter__(self):
278 pass
Benjamin Peterson52baa292009-03-24 00:56:30 +0000279
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000280 def __exit__(self, exc_type, exc_value, tb):
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000281 if exc_type is None:
282 try:
283 exc_name = self.expected.__name__
284 except AttributeError:
285 exc_name = str(self.expected)
286 if self.obj_name:
287 raise self.failureException("{0} not raised by {1}"
288 .format(exc_name, self.obj_name))
289 else:
290 raise self.failureException("{0} not raised"
291 .format(exc_name))
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000292 if not issubclass(exc_type, self.expected):
293 # let unexpected exceptions pass through
294 return False
295 if self.expected_regex is None:
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000296 return True
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000297
298 expected_regexp = self.expected_regex
299 if isinstance(expected_regexp, (bytes, str)):
300 expected_regexp = re.compile(expected_regexp)
301 if not expected_regexp.search(str(exc_value)):
302 raise self.failureException('"%s" does not match "%s"' %
303 (expected_regexp.pattern, str(exc_value)))
304 return True
305
306
307class _AssertWrapper(object):
308 """Wrap entries in the _type_equality_funcs registry to make them deep
309 copyable."""
310
311 def __init__(self, function):
312 self.function = function
313
314 def __deepcopy__(self, memo):
315 memo[id(self)] = self
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000316
Benjamin Peterson52baa292009-03-24 00:56:30 +0000317
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000318class TestCase(object):
Fred Drake02538202001-03-21 18:09:46 +0000319 """A class whose instances are single test cases.
320
Fred Drake02538202001-03-21 18:09:46 +0000321 By default, the test code itself should be placed in a method named
322 'runTest'.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000323
Tim Petersa19a1682001-03-29 04:36:09 +0000324 If the fixture may be used for many test cases, create as
Fred Drake02538202001-03-21 18:09:46 +0000325 many test methods as are needed. When instantiating such a TestCase
326 subclass, specify in the constructor arguments the name of the test method
327 that the instance is to execute.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000328
Tim Petersa19a1682001-03-29 04:36:09 +0000329 Test authors should subclass TestCase for their own tests. Construction
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000330 and deconstruction of the test's environment ('fixture') can be
331 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
332
333 If it is necessary to override the __init__ method, the base class
334 __init__ method must always be called. It is important that subclasses
335 should not change the signature of their __init__ method, since instances
336 of the classes are instantiated automatically by parts of the framework
337 in order to be run.
Fred Drake02538202001-03-21 18:09:46 +0000338 """
Steve Purcell15d89272001-04-12 09:05:01 +0000339
340 # This attribute determines which exception will be raised when
341 # the instance's assertion methods fail; test methods raising this
342 # exception will be deemed to have 'failed' rather than 'errored'
343
344 failureException = AssertionError
345
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000346 # This attribute determines whether long messages (including repr of
347 # objects used in assert methods) will be printed on failure in *addition*
348 # to any explicit message passed.
349
350 longMessage = False
351
352
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):
Fred Drake02538202001-03-21 18:09:46 +0000546 "Fail the test if the expression is true."
Benjamin Peterson52baa292009-03-24 00:56:30 +0000547 if expr:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +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):
Steve Purcell15d89272001-04-12 09:05:01 +0000552 """Fail the test unless the expression is true."""
Benjamin Peterson52baa292009-03-24 00:56:30 +0000553 if not expr:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +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
Benjamin Peterson7fe73a12009-04-04 16:35:46 +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
Benjamin Peterson7fe73a12009-04-04 16:35:46 +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
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000698 For the purposes of this function, a valid orderd sequence type is one
699 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):
887 self.assert_(isinstance(d1, dict), 'First argument is not a dictionary')
888 self.assert_(isinstance(d2, dict), 'Second argument is not a dictionary')
889
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."""
955 self.assert_(isinstance(first, str), (
956 'First argument is not a string'))
957 self.assert_(isinstance(second, str), (
958 'Second argument is not a string'))
959
960 if first != second:
961 standardMsg = '\n' + ''.join(difflib.ndiff(first.splitlines(True), second.splitlines(True)))
962 self.fail(self._formatMessage(msg, standardMsg))
963
964 def assertLess(self, a, b, msg=None):
965 """Just like self.assertTrue(a < b), but with a nicer default message."""
966 if not a < b:
967 standardMsg = '%r not less than %r' % (a, b)
968 self.fail(self._formatMessage(msg, standardMsg))
969
970 def assertLessEqual(self, a, b, msg=None):
971 """Just like self.assertTrue(a <= b), but with a nicer default message."""
972 if not a <= b:
973 standardMsg = '%r not less than or equal to %r' % (a, b)
974 self.fail(self._formatMessage(msg, standardMsg))
975
976 def assertGreater(self, a, b, msg=None):
977 """Just like self.assertTrue(a > b), but with a nicer default message."""
978 if not a > b:
979 standardMsg = '%r not greater than %r' % (a, b)
980 self.fail(self._formatMessage(msg, standardMsg))
981
982 def assertGreaterEqual(self, a, b, msg=None):
983 """Just like self.assertTrue(a >= b), but with a nicer default message."""
984 if not a >= b:
985 standardMsg = '%r not greater than or equal to %r' % (a, b)
986 self.fail(self._formatMessage(msg, standardMsg))
987
988 def assertIsNone(self, obj, msg=None):
989 """Same as self.assertTrue(obj is None), with a nicer default message."""
990 if obj is not None:
991 standardMsg = '%r is not None' % obj
992 self.fail(self._formatMessage(msg, standardMsg))
993
994 def assertIsNotNone(self, obj, msg=None):
995 """Included for symmetry with assertIsNone."""
996 if obj is None:
997 standardMsg = 'unexpectedly None'
998 self.fail(self._formatMessage(msg, standardMsg))
999
1000 def assertRaisesRegexp(self, expected_exception, expected_regexp,
1001 callable_obj=None, *args, **kwargs):
1002 """Asserts that the message in a raised exception matches a regexp.
1003
1004 Args:
1005 expected_exception: Exception class expected to be raised.
1006 expected_regexp: Regexp (re pattern object or string) expected
1007 to be found in error message.
1008 callable_obj: Function to be called.
1009 args: Extra args.
1010 kwargs: Extra kwargs.
1011 """
1012 context = _AssertRaisesContext(expected_exception, self, callable_obj,
1013 expected_regexp)
1014 if callable_obj is None:
1015 return context
1016 with context:
1017 callable_obj(*args, **kwargs)
1018
1019 def assertRegexpMatches(self, text, expected_regex, msg=None):
1020 if isinstance(expected_regex, (str, bytes)):
1021 expected_regex = re.compile(expected_regex)
1022 if not expected_regex.search(text):
1023 msg = msg or "Regexp didn't match"
1024 msg = '%s: %r not found in %r' % (msg, expected_regex.pattern, text)
1025 raise self.failureException(msg)
1026
1027
1028def _SortedListDifference(expected, actual):
1029 """Finds elements in only one or the other of two, sorted input lists.
1030
1031 Returns a two-element tuple of lists. The first list contains those
1032 elements in the "expected" list but not in the "actual" list, and the
1033 second contains those elements in the "actual" list but not in the
1034 "expected" list. Duplicate elements in either input list are ignored.
1035 """
1036 i = j = 0
1037 missing = []
1038 unexpected = []
1039 while True:
1040 try:
1041 e = expected[i]
1042 a = actual[j]
1043 if e < a:
1044 missing.append(e)
1045 i += 1
1046 while expected[i] == e:
1047 i += 1
1048 elif e > a:
1049 unexpected.append(a)
1050 j += 1
1051 while actual[j] == a:
1052 j += 1
1053 else:
1054 i += 1
1055 try:
1056 while expected[i] == e:
1057 i += 1
1058 finally:
1059 j += 1
1060 while actual[j] == a:
1061 j += 1
1062 except IndexError:
1063 missing.extend(expected[i:])
1064 unexpected.extend(actual[j:])
1065 break
1066 return missing, unexpected
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001067
Michael Foorda5809c82009-04-04 18:55:09 +00001068def _UnorderableListDifference(expected, actual):
1069 """Same behavior as _SortedListDifference but
1070 for lists of unorderable items (like dicts).
1071
1072 As it does a linear search per item (remove) it
1073 has O(n*n) performance."""
1074 missing = []
1075 while expected:
1076 item = expected.pop()
1077 try:
1078 actual.remove(item)
1079 except ValueError:
1080 missing.append(item)
1081
1082 # anything left in actual is unexpected
1083 return missing, actual
Fred Drake02538202001-03-21 18:09:46 +00001084
Benjamin Peterson1467ac82009-01-09 03:42:38 +00001085class TestSuite(object):
Fred Drake02538202001-03-21 18:09:46 +00001086 """A test suite is a composite test consisting of a number of TestCases.
1087
1088 For use, create an instance of TestSuite, then add test case instances.
1089 When all tests have been added, the suite can be passed to a test
1090 runner, such as TextTestRunner. It will run the individual test cases
1091 in the order in which they were added, aggregating the results. When
1092 subclassing, do not forget to call the base class constructor.
1093 """
1094 def __init__(self, tests=()):
1095 self._tests = []
1096 self.addTests(tests)
1097
1098 def __repr__(self):
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001099 return "<%s tests=%s>" % (_strclass(self.__class__), list(self))
Fred Drake02538202001-03-21 18:09:46 +00001100
Guido van Rossumd8faa362007-04-27 19:54:29 +00001101 def __eq__(self, other):
Benjamin Peterson5254c042009-03-23 22:25:03 +00001102 if not isinstance(other, self.__class__):
1103 return NotImplemented
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001104 return list(self) == list(other)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001105
1106 def __ne__(self, other):
1107 return not self == other
1108
Jim Fultonfafd8742004-08-28 15:22:12 +00001109 def __iter__(self):
1110 return iter(self._tests)
1111
Fred Drake02538202001-03-21 18:09:46 +00001112 def countTestCases(self):
1113 cases = 0
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001114 for test in self:
Steve Purcell7e743842003-09-22 11:08:12 +00001115 cases += test.countTestCases()
Fred Drake02538202001-03-21 18:09:46 +00001116 return cases
1117
1118 def addTest(self, test):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001119 # sanity checks
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001120 if not hasattr(test, '__call__'):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001121 raise TypeError("the test to add must be callable")
Guido van Rossum13257902007-06-07 23:15:56 +00001122 if isinstance(test, type) and issubclass(test, (TestCase, TestSuite)):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001123 raise TypeError("TestCases and TestSuites must be instantiated "
1124 "before passing them to addTest()")
Fred Drake02538202001-03-21 18:09:46 +00001125 self._tests.append(test)
1126
1127 def addTests(self, tests):
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001128 if isinstance(tests, str):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001129 raise TypeError("tests must be an iterable of tests, not a string")
Fred Drake02538202001-03-21 18:09:46 +00001130 for test in tests:
1131 self.addTest(test)
1132
1133 def run(self, result):
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001134 for test in self:
Fred Drake02538202001-03-21 18:09:46 +00001135 if result.shouldStop:
1136 break
1137 test(result)
1138 return result
1139
Raymond Hettinger664347b2004-12-04 21:21:53 +00001140 def __call__(self, *args, **kwds):
1141 return self.run(*args, **kwds)
1142
Fred Drake02538202001-03-21 18:09:46 +00001143 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001144 """Run the tests without collecting errors in a TestResult"""
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001145 for test in self:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001146 test.debug()
Fred Drake02538202001-03-21 18:09:46 +00001147
1148
1149class FunctionTestCase(TestCase):
1150 """A test case that wraps a test function.
1151
1152 This is useful for slipping pre-existing test functions into the
Guido van Rossumd8faa362007-04-27 19:54:29 +00001153 unittest framework. Optionally, set-up and tidy-up functions can be
Fred Drake02538202001-03-21 18:09:46 +00001154 supplied. As with TestCase, the tidy-up ('tearDown') function will
1155 always be called if the set-up ('setUp') function ran successfully.
1156 """
1157
Benjamin Peterson52baa292009-03-24 00:56:30 +00001158 def __init__(self, testFunc, setUp=None, tearDown=None, description=None):
1159 super(FunctionTestCase, self).__init__()
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001160 self._setUpFunc = setUp
1161 self._tearDownFunc = tearDown
1162 self._testFunc = testFunc
1163 self._description = description
Fred Drake02538202001-03-21 18:09:46 +00001164
1165 def setUp(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001166 if self._setUpFunc is not None:
1167 self._setUpFunc()
Fred Drake02538202001-03-21 18:09:46 +00001168
1169 def tearDown(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001170 if self._tearDownFunc is not None:
1171 self._tearDownFunc()
Fred Drake02538202001-03-21 18:09:46 +00001172
1173 def runTest(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001174 self._testFunc()
Fred Drake02538202001-03-21 18:09:46 +00001175
1176 def id(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001177 return self._testFunc.__name__
Fred Drake02538202001-03-21 18:09:46 +00001178
Guido van Rossumd8faa362007-04-27 19:54:29 +00001179 def __eq__(self, other):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001180 if not isinstance(other, self.__class__):
1181 return NotImplemented
Guido van Rossumd8faa362007-04-27 19:54:29 +00001182
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001183 return self._setUpFunc == other._setUpFunc and \
1184 self._tearDownFunc == other._tearDownFunc and \
1185 self._testFunc == other._testFunc and \
1186 self._description == other._description
Guido van Rossumd8faa362007-04-27 19:54:29 +00001187
1188 def __ne__(self, other):
1189 return not self == other
1190
1191 def __hash__(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001192 return hash((type(self), self._setUpFunc, self._tearDownFunc,
1193 self._testFunc, self._description))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001194
Fred Drake02538202001-03-21 18:09:46 +00001195 def __str__(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001196 return "%s (%s)" % (_strclass(self.__class__), self._testFunc.__name__)
Fred Drake02538202001-03-21 18:09:46 +00001197
1198 def __repr__(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001199 return "<%s testFunc=%s>" % (_strclass(self.__class__), self._testFunc)
Fred Drake02538202001-03-21 18:09:46 +00001200
1201 def shortDescription(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001202 if self._description is not None:
1203 return self._description
1204 doc = self._testFunc.__doc__
Steve Purcell7e743842003-09-22 11:08:12 +00001205 return doc and doc.split("\n")[0].strip() or None
Fred Drake02538202001-03-21 18:09:46 +00001206
1207
1208
1209##############################################################################
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001210# Locating and loading tests
Fred Drake02538202001-03-21 18:09:46 +00001211##############################################################################
1212
Raymond Hettingerd4cb56d2008-01-30 02:55:10 +00001213def CmpToKey(mycmp):
1214 'Convert a cmp= function into a key= function'
1215 class K(object):
1216 def __init__(self, obj, *args):
1217 self.obj = obj
1218 def __lt__(self, other):
1219 return mycmp(self.obj, other.obj) == -1
1220 return K
1221
Mark Dickinsona56c4672009-01-27 18:17:45 +00001222def three_way_cmp(x, y):
1223 """Return -1 if x < y, 0 if x == y and 1 if x > y"""
1224 return (x > y) - (x < y)
1225
Benjamin Peterson1467ac82009-01-09 03:42:38 +00001226class TestLoader(object):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001227 """
1228 This class is responsible for loading tests according to various criteria
1229 and returning them wrapped in a TestSuite
Fred Drake02538202001-03-21 18:09:46 +00001230 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001231 testMethodPrefix = 'test'
Mark Dickinsona56c4672009-01-27 18:17:45 +00001232 sortTestMethodsUsing = staticmethod(three_way_cmp)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001233 suiteClass = TestSuite
Benjamin Petersond2397752009-06-27 23:45:02 +00001234 _top_level_dir = None
Fred Drake02538202001-03-21 18:09:46 +00001235
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001236 def loadTestsFromTestCase(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +00001237 """Return a suite of all tests cases contained in testCaseClass"""
Johannes Gijsbersd7b6ad42004-11-07 15:46:25 +00001238 if issubclass(testCaseClass, TestSuite):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001239 raise TypeError("Test cases should not be derived from TestSuite." \
1240 " Maybe you meant to derive from TestCase?")
Steve Purcell7e743842003-09-22 11:08:12 +00001241 testCaseNames = self.getTestCaseNames(testCaseClass)
1242 if not testCaseNames and hasattr(testCaseClass, 'runTest'):
1243 testCaseNames = ['runTest']
Benjamin Peterson14a3dd72009-05-25 00:51:58 +00001244 suite = self.suiteClass(map(testCaseClass, testCaseNames))
Benjamin Peterson5254c042009-03-23 22:25:03 +00001245 return suite
Fred Drake02538202001-03-21 18:09:46 +00001246
Benjamin Petersond2397752009-06-27 23:45:02 +00001247 def loadTestsFromModule(self, module, use_load_tests=True):
Steve Purcell15d89272001-04-12 09:05:01 +00001248 """Return a suite of all tests cases contained in the given module"""
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001249 tests = []
1250 for name in dir(module):
1251 obj = getattr(module, name)
Guido van Rossum13257902007-06-07 23:15:56 +00001252 if isinstance(obj, type) and issubclass(obj, TestCase):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001253 tests.append(self.loadTestsFromTestCase(obj))
Benjamin Petersond2397752009-06-27 23:45:02 +00001254
1255 load_tests = getattr(module, 'load_tests', None)
1256 if use_load_tests and load_tests is not None:
1257 return load_tests(self, tests, None)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001258 return self.suiteClass(tests)
Fred Drake02538202001-03-21 18:09:46 +00001259
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001260 def loadTestsFromName(self, name, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +00001261 """Return a suite of all tests cases given a string specifier.
1262
1263 The name may resolve either to a module, a test case class, a
1264 test method within a test case class, or a callable object which
1265 returns a TestCase or TestSuite instance.
Tim Peters613b2222001-04-13 05:37:27 +00001266
Steve Purcell15d89272001-04-12 09:05:01 +00001267 The method optionally resolves the names relative to a given module.
1268 """
Steve Purcell7e743842003-09-22 11:08:12 +00001269 parts = name.split('.')
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001270 if module is None:
Steve Purcell7e743842003-09-22 11:08:12 +00001271 parts_copy = parts[:]
1272 while parts_copy:
1273 try:
1274 module = __import__('.'.join(parts_copy))
1275 break
1276 except ImportError:
1277 del parts_copy[-1]
Benjamin Peterson52baa292009-03-24 00:56:30 +00001278 if not parts_copy:
1279 raise
Armin Rigo1b3c04b2003-10-24 17:15:29 +00001280 parts = parts[1:]
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001281 obj = module
1282 for part in parts:
Steve Purcell7e743842003-09-22 11:08:12 +00001283 parent, obj = obj, getattr(obj, part)
Fred Drake02538202001-03-21 18:09:46 +00001284
Benjamin Peterson1467ac82009-01-09 03:42:38 +00001285 if isinstance(obj, types.ModuleType):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001286 return self.loadTestsFromModule(obj)
Guido van Rossum13257902007-06-07 23:15:56 +00001287 elif isinstance(obj, type) and issubclass(obj, TestCase):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001288 return self.loadTestsFromTestCase(obj)
Christian Heimes4a22b5d2007-11-25 09:39:14 +00001289 elif (isinstance(obj, types.FunctionType) and
Guido van Rossum13257902007-06-07 23:15:56 +00001290 isinstance(parent, type) and
Guido van Rossumd8faa362007-04-27 19:54:29 +00001291 issubclass(parent, TestCase)):
Christian Heimes4a22b5d2007-11-25 09:39:14 +00001292 name = obj.__name__
1293 inst = parent(name)
1294 # static methods follow a different path
Christian Heimes4975a1f2007-11-26 10:14:51 +00001295 if not isinstance(getattr(inst, name), types.FunctionType):
Christian Heimes4a22b5d2007-11-25 09:39:14 +00001296 return TestSuite([inst])
Steve Purcell397b45d2003-10-26 10:41:03 +00001297 elif isinstance(obj, TestSuite):
Steve Purcell7e743842003-09-22 11:08:12 +00001298 return obj
Christian Heimes4a22b5d2007-11-25 09:39:14 +00001299
1300 if hasattr(obj, '__call__'):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001301 test = obj()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001302 if isinstance(test, TestSuite):
1303 return test
1304 elif isinstance(test, TestCase):
1305 return TestSuite([test])
1306 else:
1307 raise TypeError("calling %s returned %s, not a test" %
1308 (obj, test))
Fred Drake02538202001-03-21 18:09:46 +00001309 else:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001310 raise TypeError("don't know how to make test from: %s" % obj)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001311
1312 def loadTestsFromNames(self, names, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +00001313 """Return a suite of all tests cases found using the given sequence
1314 of string specifiers. See 'loadTestsFromName()'.
1315 """
Steve Purcell7e743842003-09-22 11:08:12 +00001316 suites = [self.loadTestsFromName(name, module) for name in names]
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001317 return self.suiteClass(suites)
1318
1319 def getTestCaseNames(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +00001320 """Return a sorted sequence of method names found within testCaseClass
1321 """
Collin Winterce36ad82007-08-30 01:19:48 +00001322 def isTestMethod(attrname, testCaseClass=testCaseClass,
1323 prefix=self.testMethodPrefix):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001324 return attrname.startswith(prefix) and \
1325 hasattr(getattr(testCaseClass, attrname), '__call__')
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001326 testFnNames = list(filter(isTestMethod, dir(testCaseClass)))
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001327 if self.sortTestMethodsUsing:
Raymond Hettingerd4cb56d2008-01-30 02:55:10 +00001328 testFnNames.sort(key=CmpToKey(self.sortTestMethodsUsing))
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001329 return testFnNames
1330
Benjamin Petersond2397752009-06-27 23:45:02 +00001331 def discover(self, start_dir, pattern='test*.py', top_level_dir=None):
1332 """Find and return all test modules from the specified start
1333 directory, recursing into subdirectories to find them. Only test files
1334 that match the pattern will be loaded. (Using shell style pattern
1335 matching.)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001336
Benjamin Petersond2397752009-06-27 23:45:02 +00001337 All test modules must be importable from the top level of the project.
1338 If the start directory is not the top level directory then the top
1339 level directory must be specified separately.
1340
1341 If a test package name (directory with '__init__.py') matches the
1342 pattern then the package will be checked for a 'load_tests' function. If
1343 this exists then it will be called with loader, tests, pattern.
1344
1345 If load_tests exists then discovery does *not* recurse into the package,
1346 load_tests is responsible for loading all tests in the package.
1347
1348 The pattern is deliberately not stored as a loader attribute so that
1349 packages can continue discovery themselves. top_level_dir is stored so
1350 load_tests does not need to pass this argument in to loader.discover().
1351 """
1352 if top_level_dir is None and self._top_level_dir is not None:
1353 # make top_level_dir optional if called from load_tests in a package
1354 top_level_dir = self._top_level_dir
1355 elif top_level_dir is None:
1356 top_level_dir = start_dir
1357
1358 top_level_dir = os.path.abspath(os.path.normpath(top_level_dir))
1359 start_dir = os.path.abspath(os.path.normpath(start_dir))
1360
1361 if not top_level_dir in sys.path:
1362 # all test modules must be importable from the top level directory
1363 sys.path.append(top_level_dir)
1364 self._top_level_dir = top_level_dir
1365
1366 if start_dir != top_level_dir and not os.path.isfile(os.path.join(start_dir, '__init__.py')):
1367 # what about __init__.pyc or pyo (etc)
1368 raise ImportError('Start directory is not importable: %r' % start_dir)
1369
1370 tests = list(self._find_tests(start_dir, pattern))
1371 return self.suiteClass(tests)
1372
1373
1374 def _get_module_from_path(self, path):
1375 """Load a module from a path relative to the top-level directory
1376 of a project. Used by discovery."""
1377 path = os.path.splitext(os.path.normpath(path))[0]
1378
1379 relpath = os.path.relpath(path, self._top_level_dir)
1380 assert not os.path.isabs(relpath), "Path must be within the project"
1381 assert not relpath.startswith('..'), "Path must be within the project"
1382
1383 name = relpath.replace(os.path.sep, '.')
1384 __import__(name)
1385 return sys.modules[name]
1386
1387 def _find_tests(self, start_dir, pattern):
1388 """Used by discovery. Yields test suites it loads."""
1389 paths = os.listdir(start_dir)
1390
1391 for path in paths:
1392 full_path = os.path.join(start_dir, path)
1393 # what about __init__.pyc or pyo (etc)
1394 # we would need to avoid loading the same tests multiple times
1395 # from '.py', '.pyc' *and* '.pyo'
1396 if os.path.isfile(full_path) and path.lower().endswith('.py'):
1397 if fnmatch(path, pattern):
1398 # if the test file matches, load it
1399 module = self._get_module_from_path(full_path)
1400 yield self.loadTestsFromModule(module)
1401 elif os.path.isdir(full_path):
1402 if not os.path.isfile(os.path.join(full_path, '__init__.py')):
1403 continue
1404
1405 load_tests = None
1406 tests = None
1407 if fnmatch(path, pattern):
1408 # only check load_tests if the package directory itself matches the filter
1409 package = self._get_module_from_path(full_path)
1410 load_tests = getattr(package, 'load_tests', None)
1411 tests = self.loadTestsFromModule(package, use_load_tests=False)
1412
1413 if load_tests is None:
1414 if tests is not None:
1415 # tests loaded from package file
1416 yield tests
1417 # recurse into the package
1418 for test in self._find_tests(full_path, pattern):
1419 yield test
1420 else:
1421 yield load_tests(self, tests, pattern)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001422
1423defaultTestLoader = TestLoader()
1424
1425
1426##############################################################################
1427# Patches for old functions: these functions should be considered obsolete
1428##############################################################################
1429
1430def _makeLoader(prefix, sortUsing, suiteClass=None):
1431 loader = TestLoader()
1432 loader.sortTestMethodsUsing = sortUsing
1433 loader.testMethodPrefix = prefix
1434 if suiteClass: loader.suiteClass = suiteClass
1435 return loader
1436
Mark Dickinsonc429a832009-01-27 20:27:05 +00001437def getTestCaseNames(testCaseClass, prefix, sortUsing=three_way_cmp):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001438 return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
1439
Mark Dickinsonc429a832009-01-27 20:27:05 +00001440def makeSuite(testCaseClass, prefix='test', sortUsing=three_way_cmp,
1441 suiteClass=TestSuite):
1442 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(
1443 testCaseClass)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001444
Mark Dickinsonc429a832009-01-27 20:27:05 +00001445def findTestCases(module, prefix='test', sortUsing=three_way_cmp,
1446 suiteClass=TestSuite):
1447 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(
1448 module)
Fred Drake02538202001-03-21 18:09:46 +00001449
1450
1451##############################################################################
1452# Text UI
1453##############################################################################
1454
Benjamin Peterson1467ac82009-01-09 03:42:38 +00001455class _WritelnDecorator(object):
Fred Drake02538202001-03-21 18:09:46 +00001456 """Used to decorate file-like objects with a handy 'writeln' method"""
1457 def __init__(self,stream):
1458 self.stream = stream
Fred Drake02538202001-03-21 18:09:46 +00001459
1460 def __getattr__(self, attr):
1461 return getattr(self.stream,attr)
1462
Raymond Hettinger91dd19d2003-09-13 02:58:00 +00001463 def writeln(self, arg=None):
Benjamin Petersone549ead2009-03-28 21:42:05 +00001464 if arg:
1465 self.write(arg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001466 self.write('\n') # text-mode streams translate to \r\n if needed
Tim Petersa19a1682001-03-29 04:36:09 +00001467
Fred Drake02538202001-03-21 18:09:46 +00001468
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001469class _TextTestResult(TestResult):
Fred Drake02538202001-03-21 18:09:46 +00001470 """A test result class that can print formatted text results to a stream.
1471
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001472 Used by TextTestRunner.
Fred Drake02538202001-03-21 18:09:46 +00001473 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001474 separator1 = '=' * 70
1475 separator2 = '-' * 70
Fred Drake02538202001-03-21 18:09:46 +00001476
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001477 def __init__(self, stream, descriptions, verbosity):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001478 super(_TextTestResult, self).__init__()
Fred Drake02538202001-03-21 18:09:46 +00001479 self.stream = stream
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001480 self.showAll = verbosity > 1
1481 self.dots = verbosity == 1
Fred Drake02538202001-03-21 18:09:46 +00001482 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001483
1484 def getDescription(self, test):
1485 if self.descriptions:
1486 return test.shortDescription() or str(test)
1487 else:
1488 return str(test)
1489
Fred Drake02538202001-03-21 18:09:46 +00001490 def startTest(self, test):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001491 super(_TextTestResult, self).startTest(test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001492 if self.showAll:
1493 self.stream.write(self.getDescription(test))
1494 self.stream.write(" ... ")
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001495 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001496
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001497 def addSuccess(self, test):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001498 super(_TextTestResult, self).addSuccess(test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001499 if self.showAll:
Fred Drake02538202001-03-21 18:09:46 +00001500 self.stream.writeln("ok")
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001501 elif self.dots:
1502 self.stream.write('.')
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001503 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001504
1505 def addError(self, test, err):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001506 super(_TextTestResult, self).addError(test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001507 if self.showAll:
1508 self.stream.writeln("ERROR")
1509 elif self.dots:
1510 self.stream.write('E')
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001511 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001512
1513 def addFailure(self, test, err):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001514 super(_TextTestResult, self).addFailure(test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001515 if self.showAll:
1516 self.stream.writeln("FAIL")
1517 elif self.dots:
1518 self.stream.write('F')
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001519 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001520
Benjamin Peterson5254c042009-03-23 22:25:03 +00001521 def addSkip(self, test, reason):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001522 super(_TextTestResult, self).addSkip(test, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +00001523 if self.showAll:
1524 self.stream.writeln("skipped {0!r}".format(reason))
1525 elif self.dots:
1526 self.stream.write("s")
1527 self.stream.flush()
1528
1529 def addExpectedFailure(self, test, err):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001530 super(_TextTestResult, self).addExpectedFailure(test, err)
Benjamin Peterson5254c042009-03-23 22:25:03 +00001531 if self.showAll:
1532 self.stream.writeln("expected failure")
1533 elif self.dots:
Benjamin Petersone549ead2009-03-28 21:42:05 +00001534 self.stream.write("x")
Benjamin Peterson5254c042009-03-23 22:25:03 +00001535 self.stream.flush()
1536
1537 def addUnexpectedSuccess(self, test):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001538 super(_TextTestResult, self).addUnexpectedSuccess(test)
Benjamin Peterson5254c042009-03-23 22:25:03 +00001539 if self.showAll:
1540 self.stream.writeln("unexpected success")
1541 elif self.dots:
Benjamin Petersone549ead2009-03-28 21:42:05 +00001542 self.stream.write("u")
Benjamin Peterson5254c042009-03-23 22:25:03 +00001543 self.stream.flush()
1544
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001545 def printErrors(self):
1546 if self.dots or self.showAll:
Fred Drake02538202001-03-21 18:09:46 +00001547 self.stream.writeln()
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001548 self.printErrorList('ERROR', self.errors)
1549 self.printErrorList('FAIL', self.failures)
1550
1551 def printErrorList(self, flavour, errors):
1552 for test, err in errors:
1553 self.stream.writeln(self.separator1)
1554 self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
1555 self.stream.writeln(self.separator2)
Steve Purcell7b065702001-09-06 08:24:40 +00001556 self.stream.writeln("%s" % err)
Fred Drake02538202001-03-21 18:09:46 +00001557
1558
Benjamin Peterson1467ac82009-01-09 03:42:38 +00001559class TextTestRunner(object):
Fred Drake02538202001-03-21 18:09:46 +00001560 """A test runner class that displays results in textual form.
Tim Petersa19a1682001-03-29 04:36:09 +00001561
Fred Drake02538202001-03-21 18:09:46 +00001562 It prints out the names of tests as they are run, errors as they
1563 occur, and a summary of the results at the end of the test run.
1564 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001565 def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
Fred Drake02538202001-03-21 18:09:46 +00001566 self.stream = _WritelnDecorator(stream)
1567 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001568 self.verbosity = verbosity
1569
1570 def _makeResult(self):
1571 return _TextTestResult(self.stream, self.descriptions, self.verbosity)
Fred Drake02538202001-03-21 18:09:46 +00001572
1573 def run(self, test):
1574 "Run the given test case or test suite."
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001575 result = self._makeResult()
Fred Drake02538202001-03-21 18:09:46 +00001576 startTime = time.time()
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001577 startTestRun = getattr(result, 'startTestRun', None)
1578 if startTestRun is not None:
1579 startTestRun()
1580 try:
1581 test(result)
1582 finally:
1583 stopTestRun = getattr(result, 'stopTestRun', None)
1584 if stopTestRun is not None:
1585 stopTestRun()
Fred Drake02538202001-03-21 18:09:46 +00001586 stopTime = time.time()
Steve Purcell397b45d2003-10-26 10:41:03 +00001587 timeTaken = stopTime - startTime
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001588 result.printErrors()
1589 self.stream.writeln(result.separator2)
Fred Drake02538202001-03-21 18:09:46 +00001590 run = result.testsRun
1591 self.stream.writeln("Ran %d test%s in %.3fs" %
Neal Norwitz76165042002-05-31 14:15:11 +00001592 (run, run != 1 and "s" or "", timeTaken))
Fred Drake02538202001-03-21 18:09:46 +00001593 self.stream.writeln()
Benjamin Peterson52baa292009-03-24 00:56:30 +00001594 results = map(len, (result.expectedFailures,
1595 result.unexpectedSuccesses,
Benjamin Peterson5254c042009-03-23 22:25:03 +00001596 result.skipped))
Benjamin Peterson52baa292009-03-24 00:56:30 +00001597 expectedFails, unexpectedSuccesses, skipped = results
Benjamin Peterson5254c042009-03-23 22:25:03 +00001598 infos = []
Fred Drake02538202001-03-21 18:09:46 +00001599 if not result.wasSuccessful():
Benjamin Peterson5254c042009-03-23 22:25:03 +00001600 self.stream.write("FAILED")
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001601 failed, errored = len(result.failures), len(result.errors)
Fred Drake02538202001-03-21 18:09:46 +00001602 if failed:
Benjamin Peterson5254c042009-03-23 22:25:03 +00001603 infos.append("failures=%d" % failed)
Fred Drake02538202001-03-21 18:09:46 +00001604 if errored:
Benjamin Peterson5254c042009-03-23 22:25:03 +00001605 infos.append("errors=%d" % errored)
Fred Drake02538202001-03-21 18:09:46 +00001606 else:
Benjamin Petersone549ead2009-03-28 21:42:05 +00001607 self.stream.write("OK")
Benjamin Peterson5254c042009-03-23 22:25:03 +00001608 if skipped:
1609 infos.append("skipped=%d" % skipped)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001610 if expectedFails:
1611 infos.append("expected failures=%d" % expectedFails)
1612 if unexpectedSuccesses:
1613 infos.append("unexpected successes=%d" % unexpectedSuccesses)
Benjamin Peterson5254c042009-03-23 22:25:03 +00001614 if infos:
1615 self.stream.writeln(" (%s)" % (", ".join(infos),))
Benjamin Petersone549ead2009-03-28 21:42:05 +00001616 else:
1617 self.stream.write("\n")
Fred Drake02538202001-03-21 18:09:46 +00001618 return result
Tim Petersa19a1682001-03-29 04:36:09 +00001619
Fred Drake02538202001-03-21 18:09:46 +00001620
Fred Drake02538202001-03-21 18:09:46 +00001621
1622##############################################################################
1623# Facilities for running tests from the command line
1624##############################################################################
1625
Benjamin Petersond2397752009-06-27 23:45:02 +00001626USAGE_AS_MAIN = """\
1627Usage: %(progName)s [options] [tests]
1628
1629Options:
1630 -h, --help Show this message
1631 -v, --verbose Verbose output
1632 -q, --quiet Minimal output
1633
1634Examples:
1635 %(progName)s test_module - run tests from test_module
1636 %(progName)s test_module.TestClass - run tests from
1637 test_module.TestClass
1638 %(progName)s test_module.TestClass.test_method - run specified test method
1639
1640[tests] can be a list of any number of test modules, classes and test
1641methods.
1642
1643Alternative Usage: %(progName)s discover [options]
1644
1645Options:
1646 -v, --verbose Verbose output
1647 -s directory Directory to start discovery ('.' default)
1648 -p pattern Pattern to match test files ('test*.py' default)
1649 -t directory Top level directory of project (default to
1650 start directory)
1651
1652For test discovery all test modules must be importable from the top
1653level directory of the project.
1654"""
1655
1656USAGE_FROM_MODULE = """\
Steve Purcell17a781b2001-04-09 15:37:31 +00001657Usage: %(progName)s [options] [test] [...]
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001658
1659Options:
1660 -h, --help Show this message
1661 -v, --verbose Verbose output
1662 -q, --quiet Minimal output
Fred Drake02538202001-03-21 18:09:46 +00001663
1664Examples:
1665 %(progName)s - run default set of tests
1666 %(progName)s MyTestSuite - run suite 'MyTestSuite'
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001667 %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
1668 %(progName)s MyTestCase - run all 'test*' test methods
Fred Drake02538202001-03-21 18:09:46 +00001669 in MyTestCase
1670"""
Benjamin Petersond2397752009-06-27 23:45:02 +00001671
1672if __name__ == '__main__':
1673 USAGE = USAGE_AS_MAIN
1674else:
1675 USAGE = USAGE_FROM_MODULE
1676
1677
1678class TestProgram(object):
1679 """A command-line program that runs a set of tests; this is primarily
1680 for making test modules conveniently executable.
1681 """
1682 USAGE = USAGE
Fred Drake02538202001-03-21 18:09:46 +00001683 def __init__(self, module='__main__', defaultTest=None,
Benjamin Petersond2397752009-06-27 23:45:02 +00001684 argv=None, testRunner=None,
1685 testLoader=defaultTestLoader, exit=True,
1686 verbosity=1):
1687 if testRunner is None:
1688 testRunner = TextTestRunner
Antoine Pitroue7bd8682009-01-09 19:29:16 +00001689 if isinstance(module, str):
Fred Drake02538202001-03-21 18:09:46 +00001690 self.module = __import__(module)
Steve Purcell7e743842003-09-22 11:08:12 +00001691 for part in module.split('.')[1:]:
Fred Drake02538202001-03-21 18:09:46 +00001692 self.module = getattr(self.module, part)
1693 else:
1694 self.module = module
1695 if argv is None:
1696 argv = sys.argv
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001697
1698 self.exit = exit
Benjamin Petersond2397752009-06-27 23:45:02 +00001699 self.verbosity = verbosity
Fred Drake02538202001-03-21 18:09:46 +00001700 self.defaultTest = defaultTest
1701 self.testRunner = testRunner
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001702 self.testLoader = testLoader
Fred Drake02538202001-03-21 18:09:46 +00001703 self.progName = os.path.basename(argv[0])
1704 self.parseArgs(argv)
Fred Drake02538202001-03-21 18:09:46 +00001705 self.runTests()
1706
1707 def usageExit(self, msg=None):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001708 if msg:
1709 print(msg)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001710 print(self.USAGE % self.__dict__)
Fred Drake02538202001-03-21 18:09:46 +00001711 sys.exit(2)
1712
1713 def parseArgs(self, argv):
Benjamin Petersond2397752009-06-27 23:45:02 +00001714 if len(argv) > 1 and argv[1].lower() == 'discover':
1715 self._do_discovery(argv[2:])
1716 return
1717
Fred Drake02538202001-03-21 18:09:46 +00001718 import getopt
Benjamin Peterson5254c042009-03-23 22:25:03 +00001719 long_opts = ['help','verbose','quiet']
Fred Drake02538202001-03-21 18:09:46 +00001720 try:
Benjamin Peterson5254c042009-03-23 22:25:03 +00001721 options, args = getopt.getopt(argv[1:], 'hHvq', long_opts)
Fred Drake02538202001-03-21 18:09:46 +00001722 for opt, value in options:
1723 if opt in ('-h','-H','--help'):
1724 self.usageExit()
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001725 if opt in ('-q','--quiet'):
1726 self.verbosity = 0
1727 if opt in ('-v','--verbose'):
1728 self.verbosity = 2
Fred Drake02538202001-03-21 18:09:46 +00001729 if len(args) == 0 and self.defaultTest is None:
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001730 self.test = self.testLoader.loadTestsFromModule(self.module)
1731 return
Fred Drake02538202001-03-21 18:09:46 +00001732 if len(args) > 0:
1733 self.testNames = args
Benjamin Petersond2397752009-06-27 23:45:02 +00001734 if __name__ == '__main__':
1735 # to support python -m unittest ...
1736 self.module = None
Fred Drake02538202001-03-21 18:09:46 +00001737 else:
1738 self.testNames = (self.defaultTest,)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001739 self.createTests()
Guido van Rossumb940e112007-01-10 16:19:56 +00001740 except getopt.error as msg:
Fred Drake02538202001-03-21 18:09:46 +00001741 self.usageExit(msg)
1742
1743 def createTests(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001744 self.test = self.testLoader.loadTestsFromNames(self.testNames,
1745 self.module)
Fred Drake02538202001-03-21 18:09:46 +00001746
Benjamin Petersond2397752009-06-27 23:45:02 +00001747 def _do_discovery(self, argv, Loader=TestLoader):
1748 # handle command line args for test discovery
1749 import optparse
1750 parser = optparse.OptionParser()
1751 parser.add_option('-v', '--verbose', dest='verbose', default=False,
1752 help='Verbose output', action='store_true')
1753 parser.add_option('-s', '--start-directory', dest='start', default='.',
1754 help="Directory to start discovery ('.' default)")
1755 parser.add_option('-p', '--pattern', dest='pattern', default='test*.py',
1756 help="Pattern to match tests ('test*.py' default)")
1757 parser.add_option('-t', '--top-level-directory', dest='top', default=None,
1758 help='Top level directory of project (defaults to start directory)')
1759
1760 options, args = parser.parse_args(argv)
1761 if len(args) > 3:
1762 self.usageExit()
1763
1764 for name, value in zip(('start', 'pattern', 'top'), args):
1765 setattr(options, name, value)
1766
1767 if options.verbose:
1768 self.verbosity = 2
1769
1770 start_dir = options.start
1771 pattern = options.pattern
1772 top_level_dir = options.top
1773
1774 loader = Loader()
1775 self.test = loader.discover(start_dir, pattern, top_level_dir)
1776
Fred Drake02538202001-03-21 18:09:46 +00001777 def runTests(self):
Guido van Rossum13257902007-06-07 23:15:56 +00001778 if isinstance(self.testRunner, type):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001779 try:
1780 testRunner = self.testRunner(verbosity=self.verbosity)
1781 except TypeError:
1782 # didn't accept the verbosity argument
1783 testRunner = self.testRunner()
1784 else:
1785 # it is assumed to be a TestRunner instance
1786 testRunner = self.testRunner
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001787 self.result = testRunner.run(self.test)
1788 if self.exit:
1789 sys.exit(not self.result.wasSuccessful())
Fred Drake02538202001-03-21 18:09:46 +00001790
1791main = TestProgram
1792
1793
1794##############################################################################
1795# Executing this module from the command line
1796##############################################################################
1797
1798if __name__ == "__main__":
Benjamin Petersond2397752009-06-27 23:45:02 +00001799 sys.modules['unittest'] = sys.modules['__main__']
Fred Drake02538202001-03-21 18:09:46 +00001800 main(module=None)