blob: 064429c4478ed20fc3c9e34705b9ac3531b3d3f1 [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*'
Gregory P. Smith28399852009-03-31 16:54:10 +000017 self.assertEqual((1 + 2), 3)
18 self.assertEqual(0 + 1, 1)
Steve Purcell7b065702001-09-06 08:24:40 +000019 def testMultiply(self):
Gregory P. Smith28399852009-03-31 16:54:10 +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 Peterson4e4de332009-03-24 00:37:12 +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 Peterson4e4de332009-03-24 00:37:12 +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
Gregory P. Smith28399852009-03-31 16:54:10 +000048import difflib
Benjamin Peterson692428e2009-03-23 21:50:21 +000049import functools
Gregory P. Smith28399852009-03-31 16:54:10 +000050import os
51import pprint
52import re
53import sys
54import time
55import traceback
56import types
Gregory P. Smith65ff0052009-03-31 19:59:14 +000057import warnings
Fred Drake02538202001-03-21 18:09:46 +000058
Michael Foordb4a81c82009-05-29 20:33:46 +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 Peterson176a56c2009-05-25 00:48:58 +000065__all__ = ['TestResult', 'TestCase', 'TestSuite',
Benjamin Petersonc750d4d2009-03-24 00:39:24 +000066 'TextTestRunner', 'TestLoader', 'FunctionTestCase', 'main',
Benjamin Peterson03715482009-03-24 01:11:37 +000067 'defaultTestLoader', 'SkipTest', 'skip', 'skipIf', 'skipUnless',
Benjamin Petersonc750d4d2009-03-24 00:39:24 +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##############################################################################
Steve Purcell7e743842003-09-22 11:08:12 +000075# Backward compatibility
76##############################################################################
Steve Purcell7e743842003-09-22 11:08:12 +000077
Raymond Hettinger5930d8f2008-07-10 16:06:41 +000078def _CmpToKey(mycmp):
79 'Convert a cmp= function into a key= function'
80 class K(object):
81 def __init__(self, obj):
82 self.obj = obj
83 def __lt__(self, other):
84 return mycmp(self.obj, other.obj) == -1
85 return K
Steve Purcell7e743842003-09-22 11:08:12 +000086
87##############################################################################
Fred Drake02538202001-03-21 18:09:46 +000088# Test framework core
89##############################################################################
90
Steve Purcelldc391a62002-08-09 09:46:23 +000091def _strclass(cls):
92 return "%s.%s" % (cls.__module__, cls.__name__)
93
Benjamin Peterson692428e2009-03-23 21:50:21 +000094
95class SkipTest(Exception):
96 """
97 Raise this exception in a test to skip it.
98
99 Usually you can use TestResult.skip() or one of the skipping decorators
100 instead of raising this directly.
101 """
102 pass
103
104class _ExpectedFailure(Exception):
105 """
106 Raise this when a test is expected to fail.
107
108 This is an implementation detail.
109 """
110
111 def __init__(self, exc_info):
112 super(_ExpectedFailure, self).__init__()
113 self.exc_info = exc_info
114
115class _UnexpectedSuccess(Exception):
116 """
117 The test was supposed to fail, but it didn't!
118 """
119 pass
120
121def _id(obj):
122 return obj
123
124def skip(reason):
125 """
126 Unconditionally skip a test.
127 """
128 def decorator(test_item):
129 if isinstance(test_item, type) and issubclass(test_item, TestCase):
130 test_item.__unittest_skip__ = True
131 test_item.__unittest_skip_why__ = reason
132 return test_item
133 @functools.wraps(test_item)
134 def skip_wrapper(*args, **kwargs):
135 raise SkipTest(reason)
136 return skip_wrapper
137 return decorator
138
139def skipIf(condition, reason):
140 """
141 Skip a test if the condition is true.
142 """
143 if condition:
144 return skip(reason)
145 return _id
146
147def skipUnless(condition, reason):
148 """
149 Skip a test unless the condition is true.
150 """
151 if not condition:
152 return skip(reason)
153 return _id
154
155
156def expectedFailure(func):
157 @functools.wraps(func)
158 def wrapper(*args, **kwargs):
159 try:
160 func(*args, **kwargs)
161 except Exception:
162 raise _ExpectedFailure(sys.exc_info())
163 raise _UnexpectedSuccess
164 return wrapper
165
Steve Purcellb8d5f242003-12-06 13:03:13 +0000166__unittest = 1
167
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000168class TestResult(object):
Fred Drake02538202001-03-21 18:09:46 +0000169 """Holder for test result information.
170
171 Test results are automatically managed by the TestCase and TestSuite
172 classes, and do not need to be explicitly manipulated by writers of tests.
173
174 Each instance holds the total number of tests run, and collections of
175 failures and errors that occurred among those test runs. The collections
Steve Purcell7b065702001-09-06 08:24:40 +0000176 contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
Fred Drake656f9ec2001-09-06 19:13:14 +0000177 formatted traceback of the error that occurred.
Fred Drake02538202001-03-21 18:09:46 +0000178 """
179 def __init__(self):
180 self.failures = []
181 self.errors = []
182 self.testsRun = 0
Benjamin Peterson692428e2009-03-23 21:50:21 +0000183 self.skipped = []
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +0000184 self.expectedFailures = []
185 self.unexpectedSuccesses = []
Georg Brandl15c5ce92007-03-07 09:09:40 +0000186 self.shouldStop = False
Fred Drake02538202001-03-21 18:09:46 +0000187
188 def startTest(self, test):
189 "Called when the given test is about to be run"
190 self.testsRun = self.testsRun + 1
191
Michael Foord07ef4872009-05-02 22:43:34 +0000192 def startTestRun(self):
193 """Called once before any tests are executed.
194
195 See startTest for a method called before each test.
196 """
197
Fred Drake02538202001-03-21 18:09:46 +0000198 def stopTest(self, test):
199 "Called when the given test has been run"
200 pass
201
Michael Foord07ef4872009-05-02 22:43:34 +0000202 def stopTestRun(self):
203 """Called once after all tests are executed.
204
205 See stopTest for a method called after each test.
206 """
207
Fred Drake02538202001-03-21 18:09:46 +0000208 def addError(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000209 """Called when an error has occurred. 'err' is a tuple of values as
210 returned by sys.exc_info().
211 """
Steve Purcellb8d5f242003-12-06 13:03:13 +0000212 self.errors.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000213
214 def addFailure(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000215 """Called when an error has occurred. 'err' is a tuple of values as
216 returned by sys.exc_info()."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000217 self.failures.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000218
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000219 def addSuccess(self, test):
220 "Called when a test has completed successfully"
221 pass
222
Benjamin Peterson692428e2009-03-23 21:50:21 +0000223 def addSkip(self, test, reason):
224 """Called when a test is skipped."""
225 self.skipped.append((test, reason))
226
227 def addExpectedFailure(self, test, err):
228 """Called when an expected failure/error occured."""
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +0000229 self.expectedFailures.append(
Benjamin Peterson692428e2009-03-23 21:50:21 +0000230 (test, self._exc_info_to_string(err, test)))
231
232 def addUnexpectedSuccess(self, test):
233 """Called when a test was expected to fail, but succeed."""
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +0000234 self.unexpectedSuccesses.append(test)
Benjamin Peterson692428e2009-03-23 21:50:21 +0000235
Fred Drake02538202001-03-21 18:09:46 +0000236 def wasSuccessful(self):
237 "Tells whether or not this result was a success"
238 return len(self.failures) == len(self.errors) == 0
239
240 def stop(self):
241 "Indicates that the tests should be aborted"
Steve Purcell7e743842003-09-22 11:08:12 +0000242 self.shouldStop = True
Tim Petersa19a1682001-03-29 04:36:09 +0000243
Steve Purcellb8d5f242003-12-06 13:03:13 +0000244 def _exc_info_to_string(self, err, test):
Steve Purcell7b065702001-09-06 08:24:40 +0000245 """Converts a sys.exc_info()-style tuple of values into a string."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000246 exctype, value, tb = err
247 # Skip test runner traceback levels
248 while tb and self._is_relevant_tb_level(tb):
249 tb = tb.tb_next
250 if exctype is test.failureException:
251 # Skip assert*() traceback levels
252 length = self._count_relevant_tb_levels(tb)
253 return ''.join(traceback.format_exception(exctype, value, tb, length))
254 return ''.join(traceback.format_exception(exctype, value, tb))
255
256 def _is_relevant_tb_level(self, tb):
Georg Brandl56af5fc2008-07-18 19:30:10 +0000257 return '__unittest' in tb.tb_frame.f_globals
Steve Purcellb8d5f242003-12-06 13:03:13 +0000258
259 def _count_relevant_tb_levels(self, tb):
260 length = 0
261 while tb and not self._is_relevant_tb_level(tb):
262 length += 1
263 tb = tb.tb_next
264 return length
Steve Purcell7b065702001-09-06 08:24:40 +0000265
Fred Drake02538202001-03-21 18:09:46 +0000266 def __repr__(self):
267 return "<%s run=%i errors=%i failures=%i>" % \
Steve Purcelldc391a62002-08-09 09:46:23 +0000268 (_strclass(self.__class__), self.testsRun, len(self.errors),
Fred Drake02538202001-03-21 18:09:46 +0000269 len(self.failures))
270
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000271
Gregory P. Smith28399852009-03-31 16:54:10 +0000272class _AssertRaisesContext(object):
273 """A context manager used to implement TestCase.assertRaises* methods."""
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000274
Gregory P. Smith28399852009-03-31 16:54:10 +0000275 def __init__(self, expected, test_case, expected_regexp=None):
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000276 self.expected = expected
277 self.failureException = test_case.failureException
Gregory P. Smith28399852009-03-31 16:54:10 +0000278 self.expected_regex = expected_regexp
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000279
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000280 def __enter__(self):
281 pass
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000282
Benjamin Petersonbaba1952009-04-18 19:26:19 +0000283 def __exit__(self, exc_type, exc_value, tb):
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000284 if exc_type is None:
285 try:
286 exc_name = self.expected.__name__
287 except AttributeError:
288 exc_name = str(self.expected)
289 raise self.failureException(
290 "{0} not raised".format(exc_name))
Gregory P. Smith28399852009-03-31 16:54:10 +0000291 if not issubclass(exc_type, self.expected):
Michael Foord345b2fe2009-04-02 03:20:38 +0000292 # let unexpected exceptions pass through
Gregory P. Smith28399852009-03-31 16:54:10 +0000293 return False
294 if self.expected_regex is None:
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000295 return True
Gregory P. Smith28399852009-03-31 16:54:10 +0000296
297 expected_regexp = self.expected_regex
298 if isinstance(expected_regexp, basestring):
299 expected_regexp = re.compile(expected_regexp)
300 if not expected_regexp.search(str(exc_value)):
301 raise self.failureException('"%s" does not match "%s"' %
302 (expected_regexp.pattern, str(exc_value)))
303 return True
304
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000305
Michael Foorde2942d02009-04-02 05:51:54 +0000306class _AssertWrapper(object):
307 """Wrap entries in the _type_equality_funcs registry to make them deep
308 copyable."""
309
310 def __init__(self, function):
311 self.function = function
312
313 def __deepcopy__(self, memo):
314 memo[id(self)] = self
315
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000316
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000317class TestCase(object):
Fred Drake02538202001-03-21 18:09:46 +0000318 """A class whose instances are single test cases.
319
Fred Drake02538202001-03-21 18:09:46 +0000320 By default, the test code itself should be placed in a method named
321 'runTest'.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000322
Tim Petersa19a1682001-03-29 04:36:09 +0000323 If the fixture may be used for many test cases, create as
Fred Drake02538202001-03-21 18:09:46 +0000324 many test methods as are needed. When instantiating such a TestCase
325 subclass, specify in the constructor arguments the name of the test method
326 that the instance is to execute.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000327
Tim Petersa19a1682001-03-29 04:36:09 +0000328 Test authors should subclass TestCase for their own tests. Construction
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000329 and deconstruction of the test's environment ('fixture') can be
330 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
331
332 If it is necessary to override the __init__ method, the base class
333 __init__ method must always be called. It is important that subclasses
334 should not change the signature of their __init__ method, since instances
335 of the classes are instantiated automatically by parts of the framework
336 in order to be run.
Fred Drake02538202001-03-21 18:09:46 +0000337 """
Steve Purcell15d89272001-04-12 09:05:01 +0000338
339 # This attribute determines which exception will be raised when
340 # the instance's assertion methods fail; test methods raising this
341 # exception will be deemed to have 'failed' rather than 'errored'
342
343 failureException = AssertionError
344
Michael Foord345b2fe2009-04-02 03:20:38 +0000345 # This attribute determines whether long messages (including repr of
346 # objects used in assert methods) will be printed on failure in *addition*
347 # to any explicit message passed.
348
349 longMessage = False
350
351
Fred Drake02538202001-03-21 18:09:46 +0000352 def __init__(self, methodName='runTest'):
353 """Create an instance of the class that will use the named test
354 method when executed. Raises a ValueError if the instance does
355 not have a method with the specified name.
356 """
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000357 self._testMethodName = methodName
Michael Foorda50af062009-05-21 22:57:02 +0000358 self._resultForDoCleanups = None
Fred Drake02538202001-03-21 18:09:46 +0000359 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000360 testMethod = getattr(self, methodName)
Fred Drake02538202001-03-21 18:09:46 +0000361 except AttributeError:
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000362 raise ValueError("no such test method in %s: %s" % \
363 (self.__class__, methodName))
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000364 self._testMethodDoc = testMethod.__doc__
Michael Foorde2fb98f2009-05-02 20:15:05 +0000365 self._cleanups = []
Fred Drake02538202001-03-21 18:09:46 +0000366
Gregory P. Smith28399852009-03-31 16:54:10 +0000367 # Map types to custom assertEqual functions that will compare
368 # instances of said type in more detail to generate a more useful
369 # error message.
Benjamin Peterson71095ae2009-04-01 23:15:49 +0000370 self._type_equality_funcs = {}
Gregory P. Smith28399852009-03-31 16:54:10 +0000371 self.addTypeEqualityFunc(dict, self.assertDictEqual)
372 self.addTypeEqualityFunc(list, self.assertListEqual)
373 self.addTypeEqualityFunc(tuple, self.assertTupleEqual)
374 self.addTypeEqualityFunc(set, self.assertSetEqual)
375 self.addTypeEqualityFunc(frozenset, self.assertSetEqual)
376
377 def addTypeEqualityFunc(self, typeobj, function):
378 """Add a type specific assertEqual style function to compare a type.
379
380 This method is for use by TestCase subclasses that need to register
381 their own type equality functions to provide nicer error messages.
382
383 Args:
384 typeobj: The data type to call this function on when both values
385 are of the same type in assertEqual().
386 function: The callable taking two arguments and an optional
387 msg= argument that raises self.failureException with a
388 useful error message when the two arguments are not equal.
389 """
Michael Foorde2942d02009-04-02 05:51:54 +0000390 self._type_equality_funcs[typeobj] = _AssertWrapper(function)
Gregory P. Smith28399852009-03-31 16:54:10 +0000391
Michael Foorde2fb98f2009-05-02 20:15:05 +0000392 def addCleanup(self, function, *args, **kwargs):
393 """Add a function, with arguments, to be called when the test is
394 completed. Functions added are called on a LIFO basis and are
395 called after tearDown on test failure or success.
396
397 Cleanup items are called even if setUp fails (unlike tearDown)."""
398 self._cleanups.append((function, args, kwargs))
399
Fred Drake02538202001-03-21 18:09:46 +0000400 def setUp(self):
401 "Hook method for setting up the test fixture before exercising it."
402 pass
403
404 def tearDown(self):
405 "Hook method for deconstructing the test fixture after testing it."
406 pass
407
408 def countTestCases(self):
409 return 1
410
411 def defaultTestResult(self):
412 return TestResult()
413
414 def shortDescription(self):
Gregory P. Smith28399852009-03-31 16:54:10 +0000415 """Returns both the test method name and first line of its docstring.
Fred Drake02538202001-03-21 18:09:46 +0000416
Gregory P. Smith28399852009-03-31 16:54:10 +0000417 If no docstring is given, only returns the method name.
418
419 This method overrides unittest.TestCase.shortDescription(), which
420 only returns the first line of the docstring, obscuring the name
421 of the test upon failure.
Fred Drake02538202001-03-21 18:09:46 +0000422 """
Gregory P. Smith28399852009-03-31 16:54:10 +0000423 desc = str(self)
424 doc_first_line = None
425
426 if self._testMethodDoc:
427 doc_first_line = self._testMethodDoc.split("\n")[0].strip()
428 if doc_first_line:
429 desc = '\n'.join((desc, doc_first_line))
430 return desc
Fred Drake02538202001-03-21 18:09:46 +0000431
432 def id(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000433 return "%s.%s" % (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000434
Georg Brandl15c5ce92007-03-07 09:09:40 +0000435 def __eq__(self, other):
436 if type(self) is not type(other):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000437 return NotImplemented
Georg Brandl15c5ce92007-03-07 09:09:40 +0000438
439 return self._testMethodName == other._testMethodName
440
441 def __ne__(self, other):
442 return not self == other
443
444 def __hash__(self):
Collin Winter9453e5d2007-03-09 23:30:39 +0000445 return hash((type(self), self._testMethodName))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000446
Fred Drake02538202001-03-21 18:09:46 +0000447 def __str__(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000448 return "%s (%s)" % (self._testMethodName, _strclass(self.__class__))
Fred Drake02538202001-03-21 18:09:46 +0000449
450 def __repr__(self):
451 return "<%s testMethod=%s>" % \
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000452 (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000453
454 def run(self, result=None):
Michael Foord07ef4872009-05-02 22:43:34 +0000455 orig_result = result
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000456 if result is None:
457 result = self.defaultTestResult()
Michael Foord07ef4872009-05-02 22:43:34 +0000458 startTestRun = getattr(result, 'startTestRun', None)
459 if startTestRun is not None:
460 startTestRun()
461
Michael Foorda50af062009-05-21 22:57:02 +0000462 self._resultForDoCleanups = result
Fred Drake02538202001-03-21 18:09:46 +0000463 result.startTest(self)
Benjamin Peterson176a56c2009-05-25 00:48:58 +0000464 if getattr(self.__class__, "__unittest_skip__", False):
465 # If the whole class was skipped.
466 try:
467 result.addSkip(self, self.__class__.__unittest_skip_why__)
468 finally:
469 result.stopTest(self)
470 return
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000471 testMethod = getattr(self, self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000472 try:
Benjamin Peterson692428e2009-03-23 21:50:21 +0000473 success = False
Fred Drake02538202001-03-21 18:09:46 +0000474 try:
Michael Foorde2fb98f2009-05-02 20:15:05 +0000475 self.setUp()
Benjamin Peterson692428e2009-03-23 21:50:21 +0000476 except SkipTest as e:
477 result.addSkip(self, str(e))
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000478 except Exception:
Benjamin Petersonc9301352009-03-26 16:32:23 +0000479 result.addError(self, sys.exc_info())
Benjamin Peterson692428e2009-03-23 21:50:21 +0000480 else:
Michael Foorde2fb98f2009-05-02 20:15:05 +0000481 try:
482 testMethod()
483 except self.failureException:
484 result.addFailure(self, sys.exc_info())
485 except _ExpectedFailure as e:
486 result.addExpectedFailure(self, e.exc_info)
487 except _UnexpectedSuccess:
488 result.addUnexpectedSuccess(self)
489 except SkipTest as e:
490 result.addSkip(self, str(e))
491 except Exception:
492 result.addError(self, sys.exc_info())
493 else:
494 success = True
Fred Drake02538202001-03-21 18:09:46 +0000495
Michael Foorde2fb98f2009-05-02 20:15:05 +0000496 try:
497 self.tearDown()
498 except Exception:
499 result.addError(self, sys.exc_info())
500 success = False
501
502 cleanUpSuccess = self.doCleanups()
503 success = success and cleanUpSuccess
Benjamin Peterson692428e2009-03-23 21:50:21 +0000504 if success:
505 result.addSuccess(self)
Fred Drake02538202001-03-21 18:09:46 +0000506 finally:
507 result.stopTest(self)
Michael Foord07ef4872009-05-02 22:43:34 +0000508 if orig_result is None:
509 stopTestRun = getattr(result, 'stopTestRun', None)
510 if stopTestRun is not None:
511 stopTestRun()
Fred Drake02538202001-03-21 18:09:46 +0000512
Michael Foorde2fb98f2009-05-02 20:15:05 +0000513 def doCleanups(self):
514 """Execute all cleanup functions. Normally called for you after
515 tearDown."""
Michael Foorda50af062009-05-21 22:57:02 +0000516 result = self._resultForDoCleanups
Michael Foorde2fb98f2009-05-02 20:15:05 +0000517 ok = True
518 while self._cleanups:
519 function, args, kwargs = self._cleanups.pop(-1)
520 try:
521 function(*args, **kwargs)
522 except Exception:
523 ok = False
524 result.addError(self, sys.exc_info())
525 return ok
526
Raymond Hettinger664347b2004-12-04 21:21:53 +0000527 def __call__(self, *args, **kwds):
528 return self.run(*args, **kwds)
Steve Purcell7e743842003-09-22 11:08:12 +0000529
Fred Drake02538202001-03-21 18:09:46 +0000530 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000531 """Run the test without collecting errors in a TestResult"""
Fred Drake02538202001-03-21 18:09:46 +0000532 self.setUp()
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000533 getattr(self, self._testMethodName)()
Fred Drake02538202001-03-21 18:09:46 +0000534 self.tearDown()
535
Benjamin Peterson47d97382009-03-26 20:05:50 +0000536 def skipTest(self, reason):
Benjamin Peterson692428e2009-03-23 21:50:21 +0000537 """Skip this test."""
538 raise SkipTest(reason)
539
Steve Purcell15d89272001-04-12 09:05:01 +0000540 def fail(self, msg=None):
541 """Fail immediately, with the given message."""
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000542 raise self.failureException(msg)
Fred Drake02538202001-03-21 18:09:46 +0000543
Gregory P. Smith7558d572009-03-31 19:03:28 +0000544 def assertFalse(self, expr, msg=None):
Fred Drake02538202001-03-21 18:09:46 +0000545 "Fail the test if the expression is true."
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000546 if expr:
Michael Foord345b2fe2009-04-02 03:20:38 +0000547 msg = self._formatMessage(msg, "%r is not False" % expr)
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000548 raise self.failureException(msg)
Fred Drake02538202001-03-21 18:09:46 +0000549
Gregory P. Smith7558d572009-03-31 19:03:28 +0000550 def assertTrue(self, expr, msg=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000551 """Fail the test unless the expression is true."""
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000552 if not expr:
Michael Foord345b2fe2009-04-02 03:20:38 +0000553 msg = self._formatMessage(msg, "%r is not True" % expr)
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000554 raise self.failureException(msg)
Steve Purcell15d89272001-04-12 09:05:01 +0000555
Michael Foord345b2fe2009-04-02 03:20:38 +0000556 def _formatMessage(self, msg, standardMsg):
557 """Honour the longMessage attribute when generating failure messages.
558 If longMessage is False this means:
559 * Use only an explicit message if it is provided
560 * Otherwise use the standard message for the assert
561
562 If longMessage is True:
563 * Use the standard message
564 * If an explicit message is provided, plus ' : ' and the explicit message
565 """
566 if not self.longMessage:
567 return msg or standardMsg
568 if msg is None:
569 return standardMsg
570 return standardMsg + ' : ' + msg
571
572
Gregory P. Smith7558d572009-03-31 19:03:28 +0000573 def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
Steve Purcell15d89272001-04-12 09:05:01 +0000574 """Fail unless an exception of class excClass is thrown
Fred Drake02538202001-03-21 18:09:46 +0000575 by callableObj when invoked with arguments args and keyword
576 arguments kwargs. If a different type of exception is
577 thrown, it will not be caught, and the test case will be
578 deemed to have suffered an error, exactly as for an
579 unexpected exception.
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000580
581 If called with callableObj omitted or None, will return a
582 context object used like this::
583
Gregory P. Smith7558d572009-03-31 19:03:28 +0000584 with self.assertRaises(some_error_class):
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000585 do_something()
Fred Drake02538202001-03-21 18:09:46 +0000586 """
Gregory P. Smith28399852009-03-31 16:54:10 +0000587 context = _AssertRaisesContext(excClass, self)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000588 if callableObj is None:
589 return context
590 with context:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000591 callableObj(*args, **kwargs)
Fred Drake02538202001-03-21 18:09:46 +0000592
Gregory P. Smith28399852009-03-31 16:54:10 +0000593 def _getAssertEqualityFunc(self, first, second):
594 """Get a detailed comparison function for the types of the two args.
595
596 Returns: A callable accepting (first, second, msg=None) that will
597 raise a failure exception if first != second with a useful human
598 readable error message for those types.
599 """
600 #
601 # NOTE(gregory.p.smith): I considered isinstance(first, type(second))
602 # and vice versa. I opted for the conservative approach in case
603 # subclasses are not intended to be compared in detail to their super
604 # class instances using a type equality func. This means testing
605 # subtypes won't automagically use the detailed comparison. Callers
606 # should use their type specific assertSpamEqual method to compare
607 # subclasses if the detailed comparison is desired and appropriate.
608 # See the discussion in http://bugs.python.org/issue2578.
609 #
610 if type(first) is type(second):
Michael Foorde2942d02009-04-02 05:51:54 +0000611 asserter = self._type_equality_funcs.get(type(first))
612 if asserter is not None:
613 return asserter.function
614
Gregory P. Smith28399852009-03-31 16:54:10 +0000615 return self._baseAssertEqual
616
617 def _baseAssertEqual(self, first, second, msg=None):
618 """The default assertEqual implementation, not type specific."""
619 if not first == second:
Michael Foord345b2fe2009-04-02 03:20:38 +0000620 standardMsg = '%r != %r' % (first, second)
621 msg = self._formatMessage(msg, standardMsg)
622 raise self.failureException(msg)
Gregory P. Smith28399852009-03-31 16:54:10 +0000623
Gregory P. Smith7558d572009-03-31 19:03:28 +0000624 def assertEqual(self, first, second, msg=None):
Raymond Hettingerc377cbf2003-04-04 22:56:42 +0000625 """Fail if the two objects are unequal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000626 operator.
627 """
Gregory P. Smith28399852009-03-31 16:54:10 +0000628 assertion_func = self._getAssertEqualityFunc(first, second)
629 assertion_func(first, second, msg=msg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000630
Gregory P. Smith7558d572009-03-31 19:03:28 +0000631 def assertNotEqual(self, first, second, msg=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000632 """Fail if the two objects are equal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000633 operator.
634 """
Michael Foord345b2fe2009-04-02 03:20:38 +0000635 if not first != second:
636 msg = self._formatMessage(msg, '%r == %r' % (first, second))
637 raise self.failureException(msg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000638
Gregory P. Smith7558d572009-03-31 19:03:28 +0000639 def assertAlmostEqual(self, first, second, places=7, msg=None):
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000640 """Fail if the two objects are unequal as determined by their
641 difference rounded to the given number of decimal places
642 (default 7) and comparing to zero.
643
Steve Purcell397b45d2003-10-26 10:41:03 +0000644 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000645 as significant digits (measured from the most signficant digit).
646 """
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000647 if round(abs(second-first), places) != 0:
Michael Foord345b2fe2009-04-02 03:20:38 +0000648 standardMsg = '%r != %r within %r places' % (first, second, places)
649 msg = self._formatMessage(msg, standardMsg)
650 raise self.failureException(msg)
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000651
Gregory P. Smith7558d572009-03-31 19:03:28 +0000652 def assertNotAlmostEqual(self, first, second, places=7, msg=None):
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000653 """Fail if the two objects are equal as determined by their
654 difference rounded to the given number of decimal places
655 (default 7) and comparing to zero.
656
Steve Purcellcca34912003-10-26 16:38:16 +0000657 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000658 as significant digits (measured from the most signficant digit).
659 """
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000660 if round(abs(second-first), places) == 0:
Michael Foord345b2fe2009-04-02 03:20:38 +0000661 standardMsg = '%r == %r within %r places' % (first, second, places)
662 msg = self._formatMessage(msg, standardMsg)
663 raise self.failureException(msg)
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000664
Steve Purcell7e743842003-09-22 11:08:12 +0000665 # Synonyms for assertion methods
666
Gregory P. Smith7558d572009-03-31 19:03:28 +0000667 # The plurals are undocumented. Keep them that way to discourage use.
668 # Do not add more. Do not remove.
669 # Going through a deprecation cycle on these would annoy many people.
670 assertEquals = assertEqual
671 assertNotEquals = assertNotEqual
672 assertAlmostEquals = assertAlmostEqual
673 assertNotAlmostEquals = assertNotAlmostEqual
674 assert_ = assertTrue
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000675
Gregory P. Smith7558d572009-03-31 19:03:28 +0000676 # These fail* assertion method names are pending deprecation and will
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000677 # be a DeprecationWarning in 3.2; http://bugs.python.org/issue2578
Benjamin Peterson71095ae2009-04-01 23:15:49 +0000678 def _deprecate(original_func):
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000679 def deprecated_func(*args, **kwargs):
680 warnings.warn(
681 'Please use {0} instead.'.format(original_func.__name__),
682 PendingDeprecationWarning, 2)
683 return original_func(*args, **kwargs)
684 return deprecated_func
Steve Purcell15d89272001-04-12 09:05:01 +0000685
Benjamin Peterson71095ae2009-04-01 23:15:49 +0000686 failUnlessEqual = _deprecate(assertEqual)
687 failIfEqual = _deprecate(assertNotEqual)
688 failUnlessAlmostEqual = _deprecate(assertAlmostEqual)
689 failIfAlmostEqual = _deprecate(assertNotAlmostEqual)
690 failUnless = _deprecate(assertTrue)
691 failUnlessRaises = _deprecate(assertRaises)
692 failIf = _deprecate(assertFalse)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000693
Gregory P. Smith28399852009-03-31 16:54:10 +0000694 def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
695 """An equality assertion for ordered sequences (like lists and tuples).
696
697 For the purposes of this function, a valid orderd sequence type is one
698 which can be indexed, has a length, and has an equality operator.
699
700 Args:
701 seq1: The first sequence to compare.
702 seq2: The second sequence to compare.
703 seq_type: The expected datatype of the sequences, or None if no
704 datatype should be enforced.
705 msg: Optional message to use on failure instead of a list of
706 differences.
707 """
708 if seq_type != None:
709 seq_type_name = seq_type.__name__
710 if not isinstance(seq1, seq_type):
711 raise self.failureException('First sequence is not a %s: %r'
712 % (seq_type_name, seq1))
713 if not isinstance(seq2, seq_type):
714 raise self.failureException('Second sequence is not a %s: %r'
715 % (seq_type_name, seq2))
716 else:
717 seq_type_name = "sequence"
718
719 differing = None
720 try:
721 len1 = len(seq1)
722 except (TypeError, NotImplementedError):
723 differing = 'First %s has no length. Non-sequence?' % (
724 seq_type_name)
725
726 if differing is None:
727 try:
728 len2 = len(seq2)
729 except (TypeError, NotImplementedError):
730 differing = 'Second %s has no length. Non-sequence?' % (
731 seq_type_name)
732
733 if differing is None:
734 if seq1 == seq2:
735 return
736
Michael Foord04516612009-05-25 20:36:56 +0000737 seq1_repr = repr(seq1)
738 seq2_repr = repr(seq2)
739 if len(seq1_repr) > 30:
740 seq1_repr = seq1_repr[:30] + '...'
741 if len(seq2_repr) > 30:
742 seq2_repr = seq2_repr[:30] + '...'
743 elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr)
744 differing = '%ss differ: %s != %s\n' % elements
745
Gregory P. Smith28399852009-03-31 16:54:10 +0000746 for i in xrange(min(len1, len2)):
747 try:
748 item1 = seq1[i]
749 except (TypeError, IndexError, NotImplementedError):
Michael Foord04516612009-05-25 20:36:56 +0000750 differing += ('\nUnable to index element %d of first %s\n' %
Gregory P. Smith28399852009-03-31 16:54:10 +0000751 (i, seq_type_name))
752 break
753
754 try:
755 item2 = seq2[i]
756 except (TypeError, IndexError, NotImplementedError):
Michael Foord04516612009-05-25 20:36:56 +0000757 differing += ('\nUnable to index element %d of second %s\n' %
Gregory P. Smith28399852009-03-31 16:54:10 +0000758 (i, seq_type_name))
759 break
760
761 if item1 != item2:
Michael Foord04516612009-05-25 20:36:56 +0000762 differing += ('\nFirst differing element %d:\n%s\n%s\n' %
Gregory P. Smith28399852009-03-31 16:54:10 +0000763 (i, item1, item2))
764 break
765 else:
766 if (len1 == len2 and seq_type is None and
767 type(seq1) != type(seq2)):
768 # The sequences are the same, but have differing types.
769 return
Michael Foord04516612009-05-25 20:36:56 +0000770
771 if len1 > len2:
772 differing += ('\nFirst %s contains %d additional '
773 'elements.\n' % (seq_type_name, len1 - len2))
774 try:
775 differing += ('First extra element %d:\n%s\n' %
776 (len2, seq1[len2]))
777 except (TypeError, IndexError, NotImplementedError):
778 differing += ('Unable to index element %d '
779 'of first %s\n' % (len2, seq_type_name))
780 elif len1 < len2:
781 differing += ('\nSecond %s contains %d additional '
782 'elements.\n' % (seq_type_name, len2 - len1))
783 try:
784 differing += ('First extra element %d:\n%s\n' %
785 (len1, seq2[len1]))
786 except (TypeError, IndexError, NotImplementedError):
787 differing += ('Unable to index element %d '
788 'of second %s\n' % (len1, seq_type_name))
789 standardMsg = differing + '\n' + '\n'.join(difflib.ndiff(pprint.pformat(seq1).splitlines(),
Michael Foord345b2fe2009-04-02 03:20:38 +0000790 pprint.pformat(seq2).splitlines()))
791 msg = self._formatMessage(msg, standardMsg)
792 self.fail(msg)
Gregory P. Smith28399852009-03-31 16:54:10 +0000793
794 def assertListEqual(self, list1, list2, msg=None):
795 """A list-specific equality assertion.
796
797 Args:
798 list1: The first list to compare.
799 list2: The second list to compare.
800 msg: Optional message to use on failure instead of a list of
801 differences.
802
803 """
804 self.assertSequenceEqual(list1, list2, msg, seq_type=list)
805
806 def assertTupleEqual(self, tuple1, tuple2, msg=None):
807 """A tuple-specific equality assertion.
808
809 Args:
810 tuple1: The first tuple to compare.
811 tuple2: The second tuple to compare.
812 msg: Optional message to use on failure instead of a list of
813 differences.
814 """
815 self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
816
817 def assertSetEqual(self, set1, set2, msg=None):
818 """A set-specific equality assertion.
819
820 Args:
821 set1: The first set to compare.
822 set2: The second set to compare.
823 msg: Optional message to use on failure instead of a list of
824 differences.
825
826 For more general containership equality, assertSameElements will work
827 with things other than sets. This uses ducktyping to support
828 different types of sets, and is optimized for sets specifically
829 (parameters must support a difference method).
830 """
831 try:
832 difference1 = set1.difference(set2)
833 except TypeError, e:
834 self.fail('invalid type when attempting set difference: %s' % e)
835 except AttributeError, e:
836 self.fail('first argument does not support set difference: %s' % e)
837
838 try:
839 difference2 = set2.difference(set1)
840 except TypeError, e:
841 self.fail('invalid type when attempting set difference: %s' % e)
842 except AttributeError, e:
843 self.fail('second argument does not support set difference: %s' % e)
844
845 if not (difference1 or difference2):
846 return
847
Gregory P. Smith28399852009-03-31 16:54:10 +0000848 lines = []
849 if difference1:
850 lines.append('Items in the first set but not the second:')
851 for item in difference1:
852 lines.append(repr(item))
853 if difference2:
854 lines.append('Items in the second set but not the first:')
855 for item in difference2:
856 lines.append(repr(item))
Gregory P. Smith28399852009-03-31 16:54:10 +0000857
Michael Foord345b2fe2009-04-02 03:20:38 +0000858 standardMsg = '\n'.join(lines)
859 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000860
Michael Foord345b2fe2009-04-02 03:20:38 +0000861 def assertIn(self, member, container, msg=None):
862 """Just like self.assertTrue(a in b), but with a nicer default message."""
863 if member not in container:
864 standardMsg = '%r not found in %r' % (member, container)
865 self.fail(self._formatMessage(msg, standardMsg))
866
867 def assertNotIn(self, member, container, msg=None):
868 """Just like self.assertTrue(a not in b), but with a nicer default message."""
869 if member in container:
870 standardMsg = '%r unexpectedly found in %r' % (member, container)
871 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000872
Michael Foordf2dfef12009-04-05 19:19:28 +0000873 def assertIs(self, expr1, expr2, msg=None):
874 """Just like self.assertTrue(a is b), but with a nicer default message."""
875 if expr1 is not expr2:
876 standardMsg = '%r is not %r' % (expr1, expr2)
877 self.fail(self._formatMessage(msg, standardMsg))
878
879 def assertIsNot(self, expr1, expr2, msg=None):
880 """Just like self.assertTrue(a is not b), but with a nicer default message."""
881 if expr1 is expr2:
882 standardMsg = 'unexpectedly identical: %r' % (expr1,)
883 self.fail(self._formatMessage(msg, standardMsg))
884
Gregory P. Smith28399852009-03-31 16:54:10 +0000885 def assertDictEqual(self, d1, d2, msg=None):
886 self.assert_(isinstance(d1, dict), 'First argument is not a dictionary')
887 self.assert_(isinstance(d2, dict), 'Second argument is not a dictionary')
888
889 if d1 != d2:
Michael Foord345b2fe2009-04-02 03:20:38 +0000890 standardMsg = ('\n' + '\n'.join(difflib.ndiff(
891 pprint.pformat(d1).splitlines(),
892 pprint.pformat(d2).splitlines())))
893 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000894
895 def assertDictContainsSubset(self, expected, actual, msg=None):
896 """Checks whether actual is a superset of expected."""
897 missing = []
898 mismatched = []
899 for key, value in expected.iteritems():
900 if key not in actual:
901 missing.append(key)
902 elif value != actual[key]:
Michael Foord345b2fe2009-04-02 03:20:38 +0000903 mismatched.append('%s, expected: %s, actual: %s' % (key, value, actual[key]))
Gregory P. Smith28399852009-03-31 16:54:10 +0000904
905 if not (missing or mismatched):
906 return
907
Michael Foord345b2fe2009-04-02 03:20:38 +0000908 standardMsg = ''
Gregory P. Smith28399852009-03-31 16:54:10 +0000909 if missing:
Michael Foord345b2fe2009-04-02 03:20:38 +0000910 standardMsg = 'Missing: %r' % ','.join(missing)
Gregory P. Smith28399852009-03-31 16:54:10 +0000911 if mismatched:
Michael Foord345b2fe2009-04-02 03:20:38 +0000912 if standardMsg:
913 standardMsg += '; '
914 standardMsg += 'Mismatched values: %s' % ','.join(mismatched)
Gregory P. Smith28399852009-03-31 16:54:10 +0000915
Michael Foord345b2fe2009-04-02 03:20:38 +0000916 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000917
918 def assertSameElements(self, expected_seq, actual_seq, msg=None):
919 """An unordered sequence specific comparison.
920
921 Raises with an error message listing which elements of expected_seq
922 are missing from actual_seq and vice versa if any.
923 """
924 try:
925 expected = set(expected_seq)
926 actual = set(actual_seq)
927 missing = list(expected.difference(actual))
928 unexpected = list(actual.difference(expected))
929 missing.sort()
930 unexpected.sort()
931 except TypeError:
932 # Fall back to slower list-compare if any of the objects are
933 # not hashable.
934 expected = list(expected_seq)
935 actual = list(actual_seq)
936 expected.sort()
937 actual.sort()
938 missing, unexpected = _SortedListDifference(expected, actual)
939 errors = []
940 if missing:
Michael Foord345b2fe2009-04-02 03:20:38 +0000941 errors.append('Expected, but missing:\n %r' % missing)
Gregory P. Smith28399852009-03-31 16:54:10 +0000942 if unexpected:
Michael Foord345b2fe2009-04-02 03:20:38 +0000943 errors.append('Unexpected, but present:\n %r' % unexpected)
Gregory P. Smith28399852009-03-31 16:54:10 +0000944 if errors:
Michael Foord345b2fe2009-04-02 03:20:38 +0000945 standardMsg = '\n'.join(errors)
946 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000947
948 def assertMultiLineEqual(self, first, second, msg=None):
949 """Assert that two multi-line strings are equal."""
Michael Foord345b2fe2009-04-02 03:20:38 +0000950 self.assert_(isinstance(first, basestring), (
Gregory P. Smith28399852009-03-31 16:54:10 +0000951 'First argument is not a string'))
Michael Foord345b2fe2009-04-02 03:20:38 +0000952 self.assert_(isinstance(second, basestring), (
Gregory P. Smith28399852009-03-31 16:54:10 +0000953 'Second argument is not a string'))
954
955 if first != second:
Michael Foord345b2fe2009-04-02 03:20:38 +0000956 standardMsg = '\n' + ''.join(difflib.ndiff(first.splitlines(True), second.splitlines(True)))
957 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000958
959 def assertLess(self, a, b, msg=None):
Michael Foord345b2fe2009-04-02 03:20:38 +0000960 """Just like self.assertTrue(a < b), but with a nicer default message."""
961 if not a < b:
962 standardMsg = '%r not less than %r' % (a, b)
963 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000964
965 def assertLessEqual(self, a, b, msg=None):
Michael Foord345b2fe2009-04-02 03:20:38 +0000966 """Just like self.assertTrue(a <= b), but with a nicer default message."""
967 if not a <= b:
968 standardMsg = '%r not less than or equal to %r' % (a, b)
969 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000970
971 def assertGreater(self, a, b, msg=None):
Michael Foord345b2fe2009-04-02 03:20:38 +0000972 """Just like self.assertTrue(a > b), but with a nicer default message."""
973 if not a > b:
974 standardMsg = '%r not greater than %r' % (a, b)
975 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000976
977 def assertGreaterEqual(self, a, b, msg=None):
Michael Foord345b2fe2009-04-02 03:20:38 +0000978 """Just like self.assertTrue(a >= b), but with a nicer default message."""
979 if not a >= b:
980 standardMsg = '%r not greater than or equal to %r' % (a, b)
981 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000982
983 def assertIsNone(self, obj, msg=None):
Michael Foord345b2fe2009-04-02 03:20:38 +0000984 """Same as self.assertTrue(obj is None), with a nicer default message."""
985 if obj is not None:
986 standardMsg = '%r is not None' % obj
987 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000988
Michael Foord345b2fe2009-04-02 03:20:38 +0000989 def assertIsNotNone(self, obj, msg=None):
Gregory P. Smith28399852009-03-31 16:54:10 +0000990 """Included for symmetry with assertIsNone."""
Michael Foord345b2fe2009-04-02 03:20:38 +0000991 if obj is None:
992 standardMsg = 'unexpectedly None'
993 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000994
995 def assertRaisesRegexp(self, expected_exception, expected_regexp,
996 callable_obj=None, *args, **kwargs):
997 """Asserts that the message in a raised exception matches a regexp.
998
999 Args:
1000 expected_exception: Exception class expected to be raised.
1001 expected_regexp: Regexp (re pattern object or string) expected
1002 to be found in error message.
1003 callable_obj: Function to be called.
1004 args: Extra args.
1005 kwargs: Extra kwargs.
1006 """
1007 context = _AssertRaisesContext(expected_exception, self, expected_regexp)
1008 if callable_obj is None:
1009 return context
1010 with context:
1011 callable_obj(*args, **kwargs)
1012
1013 def assertRegexpMatches(self, text, expected_regex, msg=None):
1014 if isinstance(expected_regex, basestring):
1015 expected_regex = re.compile(expected_regex)
1016 if not expected_regex.search(text):
1017 msg = msg or "Regexp didn't match"
1018 msg = '%s: %r not found in %r' % (msg, expected_regex.pattern, text)
1019 raise self.failureException(msg)
1020
1021
1022def _SortedListDifference(expected, actual):
1023 """Finds elements in only one or the other of two, sorted input lists.
1024
1025 Returns a two-element tuple of lists. The first list contains those
1026 elements in the "expected" list but not in the "actual" list, and the
1027 second contains those elements in the "actual" list but not in the
1028 "expected" list. Duplicate elements in either input list are ignored.
1029 """
1030 i = j = 0
1031 missing = []
1032 unexpected = []
1033 while True:
1034 try:
1035 e = expected[i]
1036 a = actual[j]
1037 if e < a:
1038 missing.append(e)
1039 i += 1
1040 while expected[i] == e:
1041 i += 1
1042 elif e > a:
1043 unexpected.append(a)
1044 j += 1
1045 while actual[j] == a:
1046 j += 1
1047 else:
1048 i += 1
1049 try:
1050 while expected[i] == e:
1051 i += 1
1052 finally:
1053 j += 1
1054 while actual[j] == a:
1055 j += 1
1056 except IndexError:
1057 missing.extend(expected[i:])
1058 unexpected.extend(actual[j:])
1059 break
1060 return missing, unexpected
1061
Fred Drake02538202001-03-21 18:09:46 +00001062
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001063class TestSuite(object):
Fred Drake02538202001-03-21 18:09:46 +00001064 """A test suite is a composite test consisting of a number of TestCases.
1065
1066 For use, create an instance of TestSuite, then add test case instances.
1067 When all tests have been added, the suite can be passed to a test
1068 runner, such as TextTestRunner. It will run the individual test cases
1069 in the order in which they were added, aggregating the results. When
1070 subclassing, do not forget to call the base class constructor.
1071 """
1072 def __init__(self, tests=()):
1073 self._tests = []
1074 self.addTests(tests)
1075
1076 def __repr__(self):
Michael Foord37d89a22009-04-05 01:15:01 +00001077 return "<%s tests=%s>" % (_strclass(self.__class__), list(self))
Fred Drake02538202001-03-21 18:09:46 +00001078
Georg Brandl15c5ce92007-03-07 09:09:40 +00001079 def __eq__(self, other):
Benjamin Peterson692428e2009-03-23 21:50:21 +00001080 if not isinstance(other, self.__class__):
1081 return NotImplemented
Michael Foord829f6b82009-05-02 11:43:06 +00001082 return list(self) == list(other)
Georg Brandl15c5ce92007-03-07 09:09:40 +00001083
1084 def __ne__(self, other):
1085 return not self == other
1086
Nick Coghlan48361f52008-08-11 15:45:58 +00001087 # Can't guarantee hash invariant, so flag as unhashable
1088 __hash__ = None
1089
Jim Fultonfafd8742004-08-28 15:22:12 +00001090 def __iter__(self):
1091 return iter(self._tests)
1092
Fred Drake02538202001-03-21 18:09:46 +00001093 def countTestCases(self):
1094 cases = 0
Michael Foord37d89a22009-04-05 01:15:01 +00001095 for test in self:
Steve Purcell7e743842003-09-22 11:08:12 +00001096 cases += test.countTestCases()
Fred Drake02538202001-03-21 18:09:46 +00001097 return cases
1098
1099 def addTest(self, test):
Georg Brandld9e50262007-03-07 11:54:49 +00001100 # sanity checks
Raymond Hettinger5930d8f2008-07-10 16:06:41 +00001101 if not hasattr(test, '__call__'):
Georg Brandld9e50262007-03-07 11:54:49 +00001102 raise TypeError("the test to add must be callable")
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001103 if isinstance(test, type) and issubclass(test, (TestCase, TestSuite)):
Georg Brandld9e50262007-03-07 11:54:49 +00001104 raise TypeError("TestCases and TestSuites must be instantiated "
1105 "before passing them to addTest()")
Fred Drake02538202001-03-21 18:09:46 +00001106 self._tests.append(test)
1107
1108 def addTests(self, tests):
Georg Brandld9e50262007-03-07 11:54:49 +00001109 if isinstance(tests, basestring):
1110 raise TypeError("tests must be an iterable of tests, not a string")
Fred Drake02538202001-03-21 18:09:46 +00001111 for test in tests:
1112 self.addTest(test)
1113
1114 def run(self, result):
Michael Foord37d89a22009-04-05 01:15:01 +00001115 for test in self:
Fred Drake02538202001-03-21 18:09:46 +00001116 if result.shouldStop:
1117 break
1118 test(result)
1119 return result
1120
Raymond Hettinger664347b2004-12-04 21:21:53 +00001121 def __call__(self, *args, **kwds):
1122 return self.run(*args, **kwds)
1123
Fred Drake02538202001-03-21 18:09:46 +00001124 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001125 """Run the tests without collecting errors in a TestResult"""
Michael Foord37d89a22009-04-05 01:15:01 +00001126 for test in self:
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001127 test.debug()
Fred Drake02538202001-03-21 18:09:46 +00001128
1129
1130class FunctionTestCase(TestCase):
1131 """A test case that wraps a test function.
1132
1133 This is useful for slipping pre-existing test functions into the
Georg Brandl15c5ce92007-03-07 09:09:40 +00001134 unittest framework. Optionally, set-up and tidy-up functions can be
Fred Drake02538202001-03-21 18:09:46 +00001135 supplied. As with TestCase, the tidy-up ('tearDown') function will
1136 always be called if the set-up ('setUp') function ran successfully.
1137 """
1138
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001139 def __init__(self, testFunc, setUp=None, tearDown=None, description=None):
1140 super(FunctionTestCase, self).__init__()
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001141 self._setUpFunc = setUp
1142 self._tearDownFunc = tearDown
1143 self._testFunc = testFunc
1144 self._description = description
Fred Drake02538202001-03-21 18:09:46 +00001145
1146 def setUp(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001147 if self._setUpFunc is not None:
1148 self._setUpFunc()
Fred Drake02538202001-03-21 18:09:46 +00001149
1150 def tearDown(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001151 if self._tearDownFunc is not None:
1152 self._tearDownFunc()
Fred Drake02538202001-03-21 18:09:46 +00001153
1154 def runTest(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001155 self._testFunc()
Fred Drake02538202001-03-21 18:09:46 +00001156
1157 def id(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001158 return self._testFunc.__name__
Fred Drake02538202001-03-21 18:09:46 +00001159
Georg Brandl15c5ce92007-03-07 09:09:40 +00001160 def __eq__(self, other):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001161 if not isinstance(other, self.__class__):
1162 return NotImplemented
Georg Brandl15c5ce92007-03-07 09:09:40 +00001163
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001164 return self._setUpFunc == other._setUpFunc and \
1165 self._tearDownFunc == other._tearDownFunc and \
1166 self._testFunc == other._testFunc and \
1167 self._description == other._description
Georg Brandl15c5ce92007-03-07 09:09:40 +00001168
1169 def __ne__(self, other):
1170 return not self == other
1171
1172 def __hash__(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001173 return hash((type(self), self._setUpFunc, self._tearDownFunc,
1174 self._testFunc, self._description))
Georg Brandl15c5ce92007-03-07 09:09:40 +00001175
Fred Drake02538202001-03-21 18:09:46 +00001176 def __str__(self):
Benjamin Petersonbaba1952009-04-18 19:26:19 +00001177 return "%s (%s)" % (_strclass(self.__class__), self._testFunc.__name__)
Fred Drake02538202001-03-21 18:09:46 +00001178
1179 def __repr__(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001180 return "<%s testFunc=%s>" % (_strclass(self.__class__), self._testFunc)
Fred Drake02538202001-03-21 18:09:46 +00001181
1182 def shortDescription(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001183 if self._description is not None:
1184 return self._description
1185 doc = self._testFunc.__doc__
Steve Purcell7e743842003-09-22 11:08:12 +00001186 return doc and doc.split("\n")[0].strip() or None
Fred Drake02538202001-03-21 18:09:46 +00001187
1188
1189
1190##############################################################################
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001191# Locating and loading tests
Fred Drake02538202001-03-21 18:09:46 +00001192##############################################################################
1193
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001194class TestLoader(object):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001195 """
1196 This class is responsible for loading tests according to various criteria
1197 and returning them wrapped in a TestSuite
Fred Drake02538202001-03-21 18:09:46 +00001198 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001199 testMethodPrefix = 'test'
1200 sortTestMethodsUsing = cmp
1201 suiteClass = TestSuite
Michael Foordb4a81c82009-05-29 20:33:46 +00001202 _top_level_dir = None
Fred Drake02538202001-03-21 18:09:46 +00001203
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001204 def loadTestsFromTestCase(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +00001205 """Return a suite of all tests cases contained in testCaseClass"""
Johannes Gijsbersd7b6ad42004-11-07 15:46:25 +00001206 if issubclass(testCaseClass, TestSuite):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001207 raise TypeError("Test cases should not be derived from TestSuite." \
1208 " Maybe you meant to derive from TestCase?")
Steve Purcell7e743842003-09-22 11:08:12 +00001209 testCaseNames = self.getTestCaseNames(testCaseClass)
1210 if not testCaseNames and hasattr(testCaseClass, 'runTest'):
1211 testCaseNames = ['runTest']
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001212 suite = self.suiteClass(map(testCaseClass, testCaseNames))
Benjamin Peterson692428e2009-03-23 21:50:21 +00001213 return suite
Fred Drake02538202001-03-21 18:09:46 +00001214
Michael Foordb4a81c82009-05-29 20:33:46 +00001215 def loadTestsFromModule(self, module, use_load_tests=True):
Steve Purcell15d89272001-04-12 09:05:01 +00001216 """Return a suite of all tests cases contained in the given module"""
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001217 tests = []
1218 for name in dir(module):
1219 obj = getattr(module, name)
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001220 if isinstance(obj, type) and issubclass(obj, TestCase):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001221 tests.append(self.loadTestsFromTestCase(obj))
Michael Foordb4a81c82009-05-29 20:33:46 +00001222
1223 load_tests = getattr(module, 'load_tests', None)
1224 if use_load_tests and load_tests is not None:
1225 return load_tests(self, tests, None)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001226 return self.suiteClass(tests)
Fred Drake02538202001-03-21 18:09:46 +00001227
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001228 def loadTestsFromName(self, name, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +00001229 """Return a suite of all tests cases given a string specifier.
1230
1231 The name may resolve either to a module, a test case class, a
1232 test method within a test case class, or a callable object which
1233 returns a TestCase or TestSuite instance.
Tim Peters613b2222001-04-13 05:37:27 +00001234
Steve Purcell15d89272001-04-12 09:05:01 +00001235 The method optionally resolves the names relative to a given module.
1236 """
Steve Purcell7e743842003-09-22 11:08:12 +00001237 parts = name.split('.')
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001238 if module is None:
Steve Purcell7e743842003-09-22 11:08:12 +00001239 parts_copy = parts[:]
1240 while parts_copy:
1241 try:
1242 module = __import__('.'.join(parts_copy))
1243 break
1244 except ImportError:
1245 del parts_copy[-1]
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001246 if not parts_copy:
1247 raise
Armin Rigo1b3c04b2003-10-24 17:15:29 +00001248 parts = parts[1:]
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001249 obj = module
1250 for part in parts:
Steve Purcell7e743842003-09-22 11:08:12 +00001251 parent, obj = obj, getattr(obj, part)
Fred Drake02538202001-03-21 18:09:46 +00001252
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001253 if isinstance(obj, types.ModuleType):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001254 return self.loadTestsFromModule(obj)
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001255 elif isinstance(obj, type) and issubclass(obj, TestCase):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001256 return self.loadTestsFromTestCase(obj)
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001257 elif (isinstance(obj, types.UnboundMethodType) and
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001258 isinstance(parent, type) and
Georg Brandl15c5ce92007-03-07 09:09:40 +00001259 issubclass(parent, TestCase)):
1260 return TestSuite([parent(obj.__name__)])
Steve Purcell397b45d2003-10-26 10:41:03 +00001261 elif isinstance(obj, TestSuite):
Steve Purcell7e743842003-09-22 11:08:12 +00001262 return obj
Raymond Hettinger5930d8f2008-07-10 16:06:41 +00001263 elif hasattr(obj, '__call__'):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001264 test = obj()
Georg Brandl15c5ce92007-03-07 09:09:40 +00001265 if isinstance(test, TestSuite):
1266 return test
1267 elif isinstance(test, TestCase):
1268 return TestSuite([test])
1269 else:
1270 raise TypeError("calling %s returned %s, not a test" %
1271 (obj, test))
Fred Drake02538202001-03-21 18:09:46 +00001272 else:
Georg Brandl15c5ce92007-03-07 09:09:40 +00001273 raise TypeError("don't know how to make test from: %s" % obj)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001274
1275 def loadTestsFromNames(self, names, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +00001276 """Return a suite of all tests cases found using the given sequence
1277 of string specifiers. See 'loadTestsFromName()'.
1278 """
Steve Purcell7e743842003-09-22 11:08:12 +00001279 suites = [self.loadTestsFromName(name, module) for name in names]
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001280 return self.suiteClass(suites)
1281
1282 def getTestCaseNames(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +00001283 """Return a sorted sequence of method names found within testCaseClass
1284 """
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001285 def isTestMethod(attrname, testCaseClass=testCaseClass,
1286 prefix=self.testMethodPrefix):
1287 return attrname.startswith(prefix) and \
1288 hasattr(getattr(testCaseClass, attrname), '__call__')
Steve Purcell7e743842003-09-22 11:08:12 +00001289 testFnNames = filter(isTestMethod, dir(testCaseClass))
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001290 if self.sortTestMethodsUsing:
Raymond Hettinger5930d8f2008-07-10 16:06:41 +00001291 testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing))
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001292 return testFnNames
1293
Michael Foordb4a81c82009-05-29 20:33:46 +00001294 def discover(self, start_dir, pattern='test*.py', top_level_dir=None):
1295 """Find and return all test modules from the specified start
1296 directory, recursing into subdirectories to find them. Only test files
1297 that match the pattern will be loaded. (Using shell style pattern
1298 matching.)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001299
Michael Foordb4a81c82009-05-29 20:33:46 +00001300 All test modules must be importable from the top level of the project.
1301 If the start directory is not the top level directory then the top
1302 level directory must be specified separately.
1303
1304 If a test package name (directory with '__init__.py') matches the
1305 pattern then the package will be checked for a 'load_tests' function. If
1306 this exists then it will be called with loader, tests, pattern.
1307
1308 If load_tests exists then discovery does *not* recurse into the package,
1309 load_tests is responsible for loading all tests in the package.
1310
1311 The pattern is deliberately not stored as a loader attribute so that
1312 packages can continue discovery themselves. top_level_dir is stored so
1313 load_tests does not need to pass this argument in to loader.discover().
1314 """
1315 if top_level_dir is None and self._top_level_dir is not None:
1316 # make top_level_dir optional if called from load_tests in a package
1317 top_level_dir = self._top_level_dir
1318 elif top_level_dir is None:
1319 top_level_dir = start_dir
1320
1321 top_level_dir = os.path.abspath(os.path.normpath(top_level_dir))
1322 start_dir = os.path.abspath(os.path.normpath(start_dir))
1323
1324 if not top_level_dir in sys.path:
1325 # all test modules must be importable from the top level directory
1326 sys.path.append(top_level_dir)
1327 self._top_level_dir = top_level_dir
1328
1329 if start_dir != top_level_dir and not os.path.isfile(os.path.join(start_dir, '__init__.py')):
1330 # what about __init__.pyc or pyo (etc)
1331 raise ImportError('Start directory is not importable: %r' % start_dir)
1332
1333 tests = list(self._find_tests(start_dir, pattern))
1334 return self.suiteClass(tests)
1335
1336
1337 def _get_module_from_path(self, path):
1338 """Load a module from a path relative to the top-level directory
1339 of a project. Used by discovery."""
1340 path = os.path.splitext(os.path.normpath(path))[0]
1341
1342 relpath = os.path.relpath(path, self._top_level_dir)
1343 assert not os.path.isabs(relpath), "Path must be within the project"
1344 assert not relpath.startswith('..'), "Path must be within the project"
1345
1346 name = relpath.replace(os.path.sep, '.')
1347 __import__(name)
1348 return sys.modules[name]
1349
1350 def _find_tests(self, start_dir, pattern):
1351 """Used by discovery. Yields test suites it loads."""
1352 paths = os.listdir(start_dir)
1353
1354 for path in paths:
1355 full_path = os.path.join(start_dir, path)
1356 # what about __init__.pyc or pyo (etc)
1357 # we would need to avoid loading the same tests multiple times
1358 # from '.py', '.pyc' *and* '.pyo'
1359 if os.path.isfile(full_path) and path.lower().endswith('.py'):
1360 if fnmatch(path, pattern):
1361 # if the test file matches, load it
1362 module = self._get_module_from_path(full_path)
1363 yield self.loadTestsFromModule(module)
1364 elif os.path.isdir(full_path):
1365 if not os.path.isfile(os.path.join(full_path, '__init__.py')):
1366 continue
1367
1368 load_tests = None
1369 tests = None
1370 if fnmatch(path, pattern):
1371 # only check load_tests if the package directory itself matches the filter
1372 package = self._get_module_from_path(full_path)
1373 load_tests = getattr(package, 'load_tests', None)
1374 tests = self.loadTestsFromModule(package, use_load_tests=False)
1375
1376 if load_tests is None:
1377 if tests is not None:
1378 # tests loaded from package file
1379 yield tests
1380 # recurse into the package
1381 for test in self._find_tests(full_path, pattern):
1382 yield test
1383 else:
1384 yield load_tests(self, tests, pattern)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001385
1386defaultTestLoader = TestLoader()
1387
1388
1389##############################################################################
1390# Patches for old functions: these functions should be considered obsolete
1391##############################################################################
1392
1393def _makeLoader(prefix, sortUsing, suiteClass=None):
1394 loader = TestLoader()
1395 loader.sortTestMethodsUsing = sortUsing
1396 loader.testMethodPrefix = prefix
1397 if suiteClass: loader.suiteClass = suiteClass
1398 return loader
1399
1400def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp):
1401 return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
1402
1403def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
1404 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
1405
1406def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
1407 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
Fred Drake02538202001-03-21 18:09:46 +00001408
1409
1410##############################################################################
1411# Text UI
1412##############################################################################
1413
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001414class _WritelnDecorator(object):
Fred Drake02538202001-03-21 18:09:46 +00001415 """Used to decorate file-like objects with a handy 'writeln' method"""
1416 def __init__(self,stream):
1417 self.stream = stream
Fred Drake02538202001-03-21 18:09:46 +00001418
1419 def __getattr__(self, attr):
1420 return getattr(self.stream,attr)
1421
Raymond Hettinger91dd19d2003-09-13 02:58:00 +00001422 def writeln(self, arg=None):
Benjamin Petersond0cdb2d2009-03-24 23:07:07 +00001423 if arg:
1424 self.write(arg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001425 self.write('\n') # text-mode streams translate to \r\n if needed
Tim Petersa19a1682001-03-29 04:36:09 +00001426
Fred Drake02538202001-03-21 18:09:46 +00001427
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001428class _TextTestResult(TestResult):
Fred Drake02538202001-03-21 18:09:46 +00001429 """A test result class that can print formatted text results to a stream.
1430
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001431 Used by TextTestRunner.
Fred Drake02538202001-03-21 18:09:46 +00001432 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001433 separator1 = '=' * 70
1434 separator2 = '-' * 70
Fred Drake02538202001-03-21 18:09:46 +00001435
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001436 def __init__(self, stream, descriptions, verbosity):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001437 super(_TextTestResult, self).__init__()
Fred Drake02538202001-03-21 18:09:46 +00001438 self.stream = stream
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001439 self.showAll = verbosity > 1
1440 self.dots = verbosity == 1
Fred Drake02538202001-03-21 18:09:46 +00001441 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001442
1443 def getDescription(self, test):
1444 if self.descriptions:
1445 return test.shortDescription() or str(test)
1446 else:
1447 return str(test)
1448
Fred Drake02538202001-03-21 18:09:46 +00001449 def startTest(self, test):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001450 super(_TextTestResult, self).startTest(test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001451 if self.showAll:
1452 self.stream.write(self.getDescription(test))
1453 self.stream.write(" ... ")
Georg Brandld0632402008-05-11 15:17:41 +00001454 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001455
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001456 def addSuccess(self, test):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001457 super(_TextTestResult, self).addSuccess(test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001458 if self.showAll:
Fred Drake02538202001-03-21 18:09:46 +00001459 self.stream.writeln("ok")
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001460 elif self.dots:
1461 self.stream.write('.')
Georg Brandld0632402008-05-11 15:17:41 +00001462 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001463
1464 def addError(self, test, err):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001465 super(_TextTestResult, self).addError(test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001466 if self.showAll:
1467 self.stream.writeln("ERROR")
1468 elif self.dots:
1469 self.stream.write('E')
Georg Brandld0632402008-05-11 15:17:41 +00001470 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001471
1472 def addFailure(self, test, err):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001473 super(_TextTestResult, self).addFailure(test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001474 if self.showAll:
1475 self.stream.writeln("FAIL")
1476 elif self.dots:
1477 self.stream.write('F')
Georg Brandld0632402008-05-11 15:17:41 +00001478 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001479
Benjamin Peterson692428e2009-03-23 21:50:21 +00001480 def addSkip(self, test, reason):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001481 super(_TextTestResult, self).addSkip(test, reason)
Benjamin Peterson692428e2009-03-23 21:50:21 +00001482 if self.showAll:
1483 self.stream.writeln("skipped {0!r}".format(reason))
1484 elif self.dots:
1485 self.stream.write("s")
1486 self.stream.flush()
1487
1488 def addExpectedFailure(self, test, err):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001489 super(_TextTestResult, self).addExpectedFailure(test, err)
Benjamin Peterson692428e2009-03-23 21:50:21 +00001490 if self.showAll:
1491 self.stream.writeln("expected failure")
1492 elif self.dots:
Benjamin Petersona8adceb2009-03-25 21:24:04 +00001493 self.stream.write("x")
Benjamin Peterson692428e2009-03-23 21:50:21 +00001494 self.stream.flush()
1495
1496 def addUnexpectedSuccess(self, test):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001497 super(_TextTestResult, self).addUnexpectedSuccess(test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00001498 if self.showAll:
1499 self.stream.writeln("unexpected success")
1500 elif self.dots:
Benjamin Petersona8adceb2009-03-25 21:24:04 +00001501 self.stream.write("u")
Benjamin Peterson692428e2009-03-23 21:50:21 +00001502 self.stream.flush()
1503
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001504 def printErrors(self):
1505 if self.dots or self.showAll:
Fred Drake02538202001-03-21 18:09:46 +00001506 self.stream.writeln()
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001507 self.printErrorList('ERROR', self.errors)
1508 self.printErrorList('FAIL', self.failures)
1509
1510 def printErrorList(self, flavour, errors):
1511 for test, err in errors:
1512 self.stream.writeln(self.separator1)
1513 self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
1514 self.stream.writeln(self.separator2)
Steve Purcell7b065702001-09-06 08:24:40 +00001515 self.stream.writeln("%s" % err)
Fred Drake02538202001-03-21 18:09:46 +00001516
1517
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001518class TextTestRunner(object):
Fred Drake02538202001-03-21 18:09:46 +00001519 """A test runner class that displays results in textual form.
Tim Petersa19a1682001-03-29 04:36:09 +00001520
Fred Drake02538202001-03-21 18:09:46 +00001521 It prints out the names of tests as they are run, errors as they
1522 occur, and a summary of the results at the end of the test run.
1523 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001524 def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
Fred Drake02538202001-03-21 18:09:46 +00001525 self.stream = _WritelnDecorator(stream)
1526 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001527 self.verbosity = verbosity
1528
1529 def _makeResult(self):
1530 return _TextTestResult(self.stream, self.descriptions, self.verbosity)
Fred Drake02538202001-03-21 18:09:46 +00001531
1532 def run(self, test):
1533 "Run the given test case or test suite."
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001534 result = self._makeResult()
Fred Drake02538202001-03-21 18:09:46 +00001535 startTime = time.time()
Michael Foord07ef4872009-05-02 22:43:34 +00001536 startTestRun = getattr(result, 'startTestRun', None)
1537 if startTestRun is not None:
1538 startTestRun()
1539 try:
1540 test(result)
1541 finally:
1542 stopTestRun = getattr(result, 'stopTestRun', None)
1543 if stopTestRun is not None:
1544 stopTestRun()
Fred Drake02538202001-03-21 18:09:46 +00001545 stopTime = time.time()
Steve Purcell397b45d2003-10-26 10:41:03 +00001546 timeTaken = stopTime - startTime
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001547 result.printErrors()
1548 self.stream.writeln(result.separator2)
Fred Drake02538202001-03-21 18:09:46 +00001549 run = result.testsRun
1550 self.stream.writeln("Ran %d test%s in %.3fs" %
Neal Norwitz76165042002-05-31 14:15:11 +00001551 (run, run != 1 and "s" or "", timeTaken))
Fred Drake02538202001-03-21 18:09:46 +00001552 self.stream.writeln()
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00001553 results = map(len, (result.expectedFailures,
1554 result.unexpectedSuccesses,
Benjamin Peterson692428e2009-03-23 21:50:21 +00001555 result.skipped))
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00001556 expectedFails, unexpectedSuccesses, skipped = results
Benjamin Peterson692428e2009-03-23 21:50:21 +00001557 infos = []
Fred Drake02538202001-03-21 18:09:46 +00001558 if not result.wasSuccessful():
Benjamin Peterson692428e2009-03-23 21:50:21 +00001559 self.stream.write("FAILED")
Fred Drake02538202001-03-21 18:09:46 +00001560 failed, errored = map(len, (result.failures, result.errors))
1561 if failed:
Benjamin Peterson692428e2009-03-23 21:50:21 +00001562 infos.append("failures=%d" % failed)
Fred Drake02538202001-03-21 18:09:46 +00001563 if errored:
Benjamin Peterson692428e2009-03-23 21:50:21 +00001564 infos.append("errors=%d" % errored)
Fred Drake02538202001-03-21 18:09:46 +00001565 else:
Benjamin Petersona473f002009-03-24 22:56:32 +00001566 self.stream.write("OK")
Benjamin Peterson692428e2009-03-23 21:50:21 +00001567 if skipped:
1568 infos.append("skipped=%d" % skipped)
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001569 if expectedFails:
1570 infos.append("expected failures=%d" % expectedFails)
1571 if unexpectedSuccesses:
1572 infos.append("unexpected successes=%d" % unexpectedSuccesses)
Benjamin Peterson692428e2009-03-23 21:50:21 +00001573 if infos:
1574 self.stream.writeln(" (%s)" % (", ".join(infos),))
Benjamin Petersona473f002009-03-24 22:56:32 +00001575 else:
1576 self.stream.write("\n")
Fred Drake02538202001-03-21 18:09:46 +00001577 return result
Tim Petersa19a1682001-03-29 04:36:09 +00001578
Fred Drake02538202001-03-21 18:09:46 +00001579
Fred Drake02538202001-03-21 18:09:46 +00001580
1581##############################################################################
1582# Facilities for running tests from the command line
1583##############################################################################
1584
Michael Foordb4a81c82009-05-29 20:33:46 +00001585USAGE_AS_MAIN = """\
1586Usage: %(progName)s [options] [tests]
1587
1588Options:
1589 -h, --help Show this message
1590 -v, --verbose Verbose output
1591 -q, --quiet Minimal output
1592
1593Examples:
1594 %(progName)s test_module - run tests from test_module
1595 %(progName)s test_module.TestClass - run tests from
1596 test_module.TestClass
1597 %(progName)s test_module.TestClass.test_method - run specified test method
1598
1599[tests] can be a list of any number of test modules, classes and test
1600methods.
1601
1602Alternative Usage: %(progName)s discover [options]
1603
1604Options:
1605 -v, --verbose Verbose output
1606 -s directory Directory to start discovery ('.' default)
1607 -p pattern Pattern to match test files ('test*.py' default)
1608 -t directory Top level directory of project (default to
1609 start directory)
1610
1611For test discovery all test modules must be importable from the top
1612level directory of the project.
1613"""
1614
1615USAGE_FROM_MODULE = """\
Steve Purcell17a781b2001-04-09 15:37:31 +00001616Usage: %(progName)s [options] [test] [...]
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001617
1618Options:
1619 -h, --help Show this message
1620 -v, --verbose Verbose output
1621 -q, --quiet Minimal output
Fred Drake02538202001-03-21 18:09:46 +00001622
1623Examples:
1624 %(progName)s - run default set of tests
1625 %(progName)s MyTestSuite - run suite 'MyTestSuite'
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001626 %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
1627 %(progName)s MyTestCase - run all 'test*' test methods
Fred Drake02538202001-03-21 18:09:46 +00001628 in MyTestCase
1629"""
Michael Foordb4a81c82009-05-29 20:33:46 +00001630
1631if __name__ == '__main__':
1632 USAGE = USAGE_AS_MAIN
1633else:
1634 USAGE = USAGE_FROM_MODULE
1635
1636
1637class TestProgram(object):
1638 """A command-line program that runs a set of tests; this is primarily
1639 for making test modules conveniently executable.
1640 """
1641 USAGE = USAGE
Fred Drake02538202001-03-21 18:09:46 +00001642 def __init__(self, module='__main__', defaultTest=None,
Michael Foorddad7b7b2009-06-02 18:08:27 +00001643 argv=None, testRunner=None,
Michael Foord5d31e052009-05-11 17:59:43 +00001644 testLoader=defaultTestLoader, exit=True,
1645 verbosity=1):
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001646 if isinstance(module, basestring):
Fred Drake02538202001-03-21 18:09:46 +00001647 self.module = __import__(module)
Steve Purcell7e743842003-09-22 11:08:12 +00001648 for part in module.split('.')[1:]:
Fred Drake02538202001-03-21 18:09:46 +00001649 self.module = getattr(self.module, part)
1650 else:
1651 self.module = module
1652 if argv is None:
1653 argv = sys.argv
Michael Foord829f6b82009-05-02 11:43:06 +00001654
1655 self.exit = exit
Michael Foord5d31e052009-05-11 17:59:43 +00001656 self.verbosity = verbosity
Fred Drake02538202001-03-21 18:09:46 +00001657 self.defaultTest = defaultTest
1658 self.testRunner = testRunner
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001659 self.testLoader = testLoader
Fred Drake02538202001-03-21 18:09:46 +00001660 self.progName = os.path.basename(argv[0])
1661 self.parseArgs(argv)
Fred Drake02538202001-03-21 18:09:46 +00001662 self.runTests()
1663
1664 def usageExit(self, msg=None):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001665 if msg:
1666 print msg
Fred Drake02538202001-03-21 18:09:46 +00001667 print self.USAGE % self.__dict__
1668 sys.exit(2)
1669
1670 def parseArgs(self, argv):
Michael Foordb4a81c82009-05-29 20:33:46 +00001671 if len(argv) > 1 and argv[1].lower() == 'discover':
1672 self._do_discovery(argv[2:])
1673 return
1674
Fred Drake02538202001-03-21 18:09:46 +00001675 import getopt
Benjamin Peterson692428e2009-03-23 21:50:21 +00001676 long_opts = ['help','verbose','quiet']
Fred Drake02538202001-03-21 18:09:46 +00001677 try:
Benjamin Peterson692428e2009-03-23 21:50:21 +00001678 options, args = getopt.getopt(argv[1:], 'hHvq', long_opts)
Fred Drake02538202001-03-21 18:09:46 +00001679 for opt, value in options:
1680 if opt in ('-h','-H','--help'):
1681 self.usageExit()
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001682 if opt in ('-q','--quiet'):
1683 self.verbosity = 0
1684 if opt in ('-v','--verbose'):
1685 self.verbosity = 2
Fred Drake02538202001-03-21 18:09:46 +00001686 if len(args) == 0 and self.defaultTest is None:
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001687 self.test = self.testLoader.loadTestsFromModule(self.module)
1688 return
Fred Drake02538202001-03-21 18:09:46 +00001689 if len(args) > 0:
1690 self.testNames = args
Michael Foordb4a81c82009-05-29 20:33:46 +00001691 if __name__ == '__main__':
1692 # to support python -m unittest ...
Michael Foord7df82c92009-05-12 10:46:23 +00001693 self.module = None
Fred Drake02538202001-03-21 18:09:46 +00001694 else:
1695 self.testNames = (self.defaultTest,)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001696 self.createTests()
Fred Drake02538202001-03-21 18:09:46 +00001697 except getopt.error, msg:
1698 self.usageExit(msg)
1699
1700 def createTests(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001701 self.test = self.testLoader.loadTestsFromNames(self.testNames,
1702 self.module)
Fred Drake02538202001-03-21 18:09:46 +00001703
Michael Foordb4a81c82009-05-29 20:33:46 +00001704 def _do_discovery(self, argv, Loader=TestLoader):
1705 # handle command line args for test discovery
1706 import optparse
1707 parser = optparse.OptionParser()
1708 parser.add_option('-v', '--verbose', dest='verbose', default=False,
1709 help='Verbose output', action='store_true')
1710 parser.add_option('-s', '--start-directory', dest='start', default='.',
1711 help="Directory to start discovery ('.' default)")
1712 parser.add_option('-p', '--pattern', dest='pattern', default='test*.py',
1713 help="Pattern to match tests ('test*.py' default)")
1714 parser.add_option('-t', '--top-level-directory', dest='top', default=None,
1715 help='Top level directory of project (defaults to start directory)')
1716
1717 options, args = parser.parse_args(argv)
1718 if len(args) > 3:
1719 self.usageExit()
1720
1721 for name, value in zip(('start', 'pattern', 'top'), args):
1722 setattr(options, name, value)
1723
1724 if options.verbose:
1725 self.verbosity = 2
1726
1727 start_dir = options.start
1728 pattern = options.pattern
1729 top_level_dir = options.top
1730
1731 loader = Loader()
1732 self.test = loader.discover(start_dir, pattern, top_level_dir)
1733
Fred Drake02538202001-03-21 18:09:46 +00001734 def runTests(self):
Michael Foord91dcd932009-07-14 17:58:12 +00001735 if self.testRunner is None:
1736 self.testRunner = TextTestRunner
Georg Brandld0a96252007-03-07 09:21:06 +00001737 if isinstance(self.testRunner, (type, types.ClassType)):
1738 try:
1739 testRunner = self.testRunner(verbosity=self.verbosity)
1740 except TypeError:
1741 # didn't accept the verbosity argument
1742 testRunner = self.testRunner()
1743 else:
1744 # it is assumed to be a TestRunner instance
1745 testRunner = self.testRunner
Michael Foord829f6b82009-05-02 11:43:06 +00001746 self.result = testRunner.run(self.test)
1747 if self.exit:
1748 sys.exit(not self.result.wasSuccessful())
Fred Drake02538202001-03-21 18:09:46 +00001749
1750main = TestProgram
1751
1752
Michael Foorde2fb98f2009-05-02 20:15:05 +00001753##############################################################################
1754# Executing this module from the command line
1755##############################################################################
1756
Fred Drake02538202001-03-21 18:09:46 +00001757if __name__ == "__main__":
Michael Foord5d31e052009-05-11 17:59:43 +00001758 sys.modules['unittest'] = sys.modules['__main__']
Fred Drake02538202001-03-21 18:09:46 +00001759 main(module=None)