blob: b9ef3d7fc24bac404204af280f164ff9d7942525 [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*'
17 self.assertEquals((1 + 2), 3)
18 self.assertEquals(0 + 1, 1)
Steve Purcell7b065702001-09-06 08:24:40 +000019 def testMultiply(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +000020 self.assertEquals((0 * 10), 0)
21 self.assertEquals((5 * 8), 40)
22
23 if __name__ == '__main__':
24 unittest.main()
25
26Further information is available in the bundled documentation, and from
27
Georg Brandl15c5ce92007-03-07 09:09:40 +000028 http://docs.python.org/lib/module-unittest.html
Steve Purcell5ddd1a82001-03-22 08:45:36 +000029
Steve Purcell7e743842003-09-22 11:08:12 +000030Copyright (c) 1999-2003 Steve Purcell
Fred Drake02538202001-03-21 18:09:46 +000031This module is free software, and you may redistribute it and/or modify
32it under the same terms as Python itself, so long as this copyright message
33and disclaimer are retained in their original form.
34
35IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
36SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
37THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
38DAMAGE.
39
40THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
41LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
42PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
43AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
44SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
Steve Purcell5ddd1a82001-03-22 08:45:36 +000045'''
Fred Drake02538202001-03-21 18:09:46 +000046
Steve Purcell5ddd1a82001-03-22 08:45:36 +000047__author__ = "Steve Purcell"
48__email__ = "stephen_purcell at yahoo dot com"
Benjamin Petersonbca248e2009-03-23 23:19:03 +000049__version__ = "$Id$"
Fred Drake02538202001-03-21 18:09:46 +000050
51import time
52import sys
53import traceback
Fred Drake02538202001-03-21 18:09:46 +000054import os
Steve Purcell5ddd1a82001-03-22 08:45:36 +000055import types
Benjamin Peterson692428e2009-03-23 21:50:21 +000056import functools
Fred Drake02538202001-03-21 18:09:46 +000057
58##############################################################################
Steve Purcelld75e7e42003-09-15 11:01:21 +000059# Exported classes and functions
60##############################################################################
61__all__ = ['TestResult', 'TestCase', 'TestSuite', 'TextTestRunner',
62 'TestLoader', 'FunctionTestCase', 'main', 'defaultTestLoader']
63
Steve Purcell7e743842003-09-22 11:08:12 +000064# Expose obsolete functions for backwards compatibility
Steve Purcelld75e7e42003-09-15 11:01:21 +000065__all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases'])
66
67
68##############################################################################
Steve Purcell7e743842003-09-22 11:08:12 +000069# Backward compatibility
70##############################################################################
Steve Purcell7e743842003-09-22 11:08:12 +000071
Raymond Hettinger5930d8f2008-07-10 16:06:41 +000072def _CmpToKey(mycmp):
73 'Convert a cmp= function into a key= function'
74 class K(object):
75 def __init__(self, obj):
76 self.obj = obj
77 def __lt__(self, other):
78 return mycmp(self.obj, other.obj) == -1
79 return K
Steve Purcell7e743842003-09-22 11:08:12 +000080
81##############################################################################
Fred Drake02538202001-03-21 18:09:46 +000082# Test framework core
83##############################################################################
84
Steve Purcelldc391a62002-08-09 09:46:23 +000085def _strclass(cls):
86 return "%s.%s" % (cls.__module__, cls.__name__)
87
Benjamin Peterson692428e2009-03-23 21:50:21 +000088
89class SkipTest(Exception):
90 """
91 Raise this exception in a test to skip it.
92
93 Usually you can use TestResult.skip() or one of the skipping decorators
94 instead of raising this directly.
95 """
96 pass
97
98class _ExpectedFailure(Exception):
99 """
100 Raise this when a test is expected to fail.
101
102 This is an implementation detail.
103 """
104
105 def __init__(self, exc_info):
106 super(_ExpectedFailure, self).__init__()
107 self.exc_info = exc_info
108
109class _UnexpectedSuccess(Exception):
110 """
111 The test was supposed to fail, but it didn't!
112 """
113 pass
114
115def _id(obj):
116 return obj
117
118def skip(reason):
119 """
120 Unconditionally skip a test.
121 """
122 def decorator(test_item):
123 if isinstance(test_item, type) and issubclass(test_item, TestCase):
124 test_item.__unittest_skip__ = True
125 test_item.__unittest_skip_why__ = reason
126 return test_item
127 @functools.wraps(test_item)
128 def skip_wrapper(*args, **kwargs):
129 raise SkipTest(reason)
130 return skip_wrapper
131 return decorator
132
133def skipIf(condition, reason):
134 """
135 Skip a test if the condition is true.
136 """
137 if condition:
138 return skip(reason)
139 return _id
140
141def skipUnless(condition, reason):
142 """
143 Skip a test unless the condition is true.
144 """
145 if not condition:
146 return skip(reason)
147 return _id
148
149
150def expectedFailure(func):
151 @functools.wraps(func)
152 def wrapper(*args, **kwargs):
153 try:
154 func(*args, **kwargs)
155 except Exception:
156 raise _ExpectedFailure(sys.exc_info())
157 raise _UnexpectedSuccess
158 return wrapper
159
160
Steve Purcellb8d5f242003-12-06 13:03:13 +0000161__unittest = 1
162
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000163class TestResult(object):
Fred Drake02538202001-03-21 18:09:46 +0000164 """Holder for test result information.
165
166 Test results are automatically managed by the TestCase and TestSuite
167 classes, and do not need to be explicitly manipulated by writers of tests.
168
169 Each instance holds the total number of tests run, and collections of
170 failures and errors that occurred among those test runs. The collections
Steve Purcell7b065702001-09-06 08:24:40 +0000171 contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
Fred Drake656f9ec2001-09-06 19:13:14 +0000172 formatted traceback of the error that occurred.
Fred Drake02538202001-03-21 18:09:46 +0000173 """
174 def __init__(self):
175 self.failures = []
176 self.errors = []
177 self.testsRun = 0
Benjamin Peterson692428e2009-03-23 21:50:21 +0000178 self.skipped = []
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +0000179 self.expectedFailures = []
180 self.unexpectedSuccesses = []
Georg Brandl15c5ce92007-03-07 09:09:40 +0000181 self.shouldStop = False
Fred Drake02538202001-03-21 18:09:46 +0000182
183 def startTest(self, test):
184 "Called when the given test is about to be run"
185 self.testsRun = self.testsRun + 1
186
187 def stopTest(self, test):
188 "Called when the given test has been run"
189 pass
190
191 def addError(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000192 """Called when an error has occurred. 'err' is a tuple of values as
193 returned by sys.exc_info().
194 """
Steve Purcellb8d5f242003-12-06 13:03:13 +0000195 self.errors.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000196
197 def addFailure(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000198 """Called when an error has occurred. 'err' is a tuple of values as
199 returned by sys.exc_info()."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000200 self.failures.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000201
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000202 def addSuccess(self, test):
203 "Called when a test has completed successfully"
204 pass
205
Benjamin Peterson692428e2009-03-23 21:50:21 +0000206 def addSkip(self, test, reason):
207 """Called when a test is skipped."""
208 self.skipped.append((test, reason))
209
210 def addExpectedFailure(self, test, err):
211 """Called when an expected failure/error occured."""
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +0000212 self.expectedFailures.append(
Benjamin Peterson692428e2009-03-23 21:50:21 +0000213 (test, self._exc_info_to_string(err, test)))
214
215 def addUnexpectedSuccess(self, test):
216 """Called when a test was expected to fail, but succeed."""
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +0000217 self.unexpectedSuccesses.append(test)
Benjamin Peterson692428e2009-03-23 21:50:21 +0000218
Fred Drake02538202001-03-21 18:09:46 +0000219 def wasSuccessful(self):
220 "Tells whether or not this result was a success"
221 return len(self.failures) == len(self.errors) == 0
222
223 def stop(self):
224 "Indicates that the tests should be aborted"
Steve Purcell7e743842003-09-22 11:08:12 +0000225 self.shouldStop = True
Tim Petersa19a1682001-03-29 04:36:09 +0000226
Steve Purcellb8d5f242003-12-06 13:03:13 +0000227 def _exc_info_to_string(self, err, test):
Steve Purcell7b065702001-09-06 08:24:40 +0000228 """Converts a sys.exc_info()-style tuple of values into a string."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000229 exctype, value, tb = err
230 # Skip test runner traceback levels
231 while tb and self._is_relevant_tb_level(tb):
232 tb = tb.tb_next
233 if exctype is test.failureException:
234 # Skip assert*() traceback levels
235 length = self._count_relevant_tb_levels(tb)
236 return ''.join(traceback.format_exception(exctype, value, tb, length))
237 return ''.join(traceback.format_exception(exctype, value, tb))
238
239 def _is_relevant_tb_level(self, tb):
Georg Brandl56af5fc2008-07-18 19:30:10 +0000240 return '__unittest' in tb.tb_frame.f_globals
Steve Purcellb8d5f242003-12-06 13:03:13 +0000241
242 def _count_relevant_tb_levels(self, tb):
243 length = 0
244 while tb and not self._is_relevant_tb_level(tb):
245 length += 1
246 tb = tb.tb_next
247 return length
Steve Purcell7b065702001-09-06 08:24:40 +0000248
Fred Drake02538202001-03-21 18:09:46 +0000249 def __repr__(self):
250 return "<%s run=%i errors=%i failures=%i>" % \
Steve Purcelldc391a62002-08-09 09:46:23 +0000251 (_strclass(self.__class__), self.testsRun, len(self.errors),
Fred Drake02538202001-03-21 18:09:46 +0000252 len(self.failures))
253
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000254
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000255class AssertRaisesContext(object):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000256
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000257 def __init__(self, expected, test_case):
258 self.expected = expected
259 self.failureException = test_case.failureException
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000260
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000261 def __enter__(self):
262 pass
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000263
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000264 def __exit__(self, exc_type, exc_value, traceback):
265 if exc_type is None:
266 try:
267 exc_name = self.expected.__name__
268 except AttributeError:
269 exc_name = str(self.expected)
270 raise self.failureException(
271 "{0} not raised".format(exc_name))
272 if issubclass(exc_type, self.expected):
273 return True
274 # Let unexpected exceptions skip through
275 return False
276
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000277
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000278class TestCase(object):
Fred Drake02538202001-03-21 18:09:46 +0000279 """A class whose instances are single test cases.
280
Fred Drake02538202001-03-21 18:09:46 +0000281 By default, the test code itself should be placed in a method named
282 'runTest'.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000283
Tim Petersa19a1682001-03-29 04:36:09 +0000284 If the fixture may be used for many test cases, create as
Fred Drake02538202001-03-21 18:09:46 +0000285 many test methods as are needed. When instantiating such a TestCase
286 subclass, specify in the constructor arguments the name of the test method
287 that the instance is to execute.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000288
Tim Petersa19a1682001-03-29 04:36:09 +0000289 Test authors should subclass TestCase for their own tests. Construction
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000290 and deconstruction of the test's environment ('fixture') can be
291 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
292
293 If it is necessary to override the __init__ method, the base class
294 __init__ method must always be called. It is important that subclasses
295 should not change the signature of their __init__ method, since instances
296 of the classes are instantiated automatically by parts of the framework
297 in order to be run.
Fred Drake02538202001-03-21 18:09:46 +0000298 """
Steve Purcell15d89272001-04-12 09:05:01 +0000299
300 # This attribute determines which exception will be raised when
301 # the instance's assertion methods fail; test methods raising this
302 # exception will be deemed to have 'failed' rather than 'errored'
303
304 failureException = AssertionError
305
Fred Drake02538202001-03-21 18:09:46 +0000306 def __init__(self, methodName='runTest'):
307 """Create an instance of the class that will use the named test
308 method when executed. Raises a ValueError if the instance does
309 not have a method with the specified name.
310 """
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000311 self._testMethodName = methodName
Fred Drake02538202001-03-21 18:09:46 +0000312 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000313 testMethod = getattr(self, methodName)
Fred Drake02538202001-03-21 18:09:46 +0000314 except AttributeError:
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000315 raise ValueError("no such test method in %s: %s" % \
316 (self.__class__, methodName))
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000317 self._testMethodDoc = testMethod.__doc__
Fred Drake02538202001-03-21 18:09:46 +0000318
319 def setUp(self):
320 "Hook method for setting up the test fixture before exercising it."
321 pass
322
323 def tearDown(self):
324 "Hook method for deconstructing the test fixture after testing it."
325 pass
326
327 def countTestCases(self):
328 return 1
329
330 def defaultTestResult(self):
331 return TestResult()
332
333 def shortDescription(self):
334 """Returns a one-line description of the test, or None if no
335 description has been provided.
336
337 The default implementation of this method returns the first line of
338 the specified test method's docstring.
339 """
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000340 doc = self._testMethodDoc
Steve Purcell7e743842003-09-22 11:08:12 +0000341 return doc and doc.split("\n")[0].strip() or None
Fred Drake02538202001-03-21 18:09:46 +0000342
343 def id(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000344 return "%s.%s" % (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000345
Georg Brandl15c5ce92007-03-07 09:09:40 +0000346 def __eq__(self, other):
347 if type(self) is not type(other):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000348 return NotImplemented
Georg Brandl15c5ce92007-03-07 09:09:40 +0000349
350 return self._testMethodName == other._testMethodName
351
352 def __ne__(self, other):
353 return not self == other
354
355 def __hash__(self):
Collin Winter9453e5d2007-03-09 23:30:39 +0000356 return hash((type(self), self._testMethodName))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000357
Fred Drake02538202001-03-21 18:09:46 +0000358 def __str__(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000359 return "%s (%s)" % (self._testMethodName, _strclass(self.__class__))
Fred Drake02538202001-03-21 18:09:46 +0000360
361 def __repr__(self):
362 return "<%s testMethod=%s>" % \
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000363 (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000364
365 def run(self, result=None):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000366 if result is None:
367 result = self.defaultTestResult()
Fred Drake02538202001-03-21 18:09:46 +0000368 result.startTest(self)
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000369 testMethod = getattr(self, self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000370 try:
371 try:
372 self.setUp()
Benjamin Peterson692428e2009-03-23 21:50:21 +0000373 except SkipTest as e:
374 result.addSkip(self, str(e))
375 return
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000376 except Exception:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000377 result.addError(self, self._exc_info())
Fred Drake02538202001-03-21 18:09:46 +0000378 return
379
Benjamin Peterson692428e2009-03-23 21:50:21 +0000380 success = False
Fred Drake02538202001-03-21 18:09:46 +0000381 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000382 testMethod()
Skip Montanaroae5c37b2003-07-13 15:18:12 +0000383 except self.failureException:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000384 result.addFailure(self, self._exc_info())
Benjamin Peterson692428e2009-03-23 21:50:21 +0000385 except _ExpectedFailure as e:
386 result.addExpectedFailure(self, e.exc_info)
387 except _UnexpectedSuccess:
388 result.addUnexpectedSuccess(self)
389 except SkipTest as e:
390 result.addSkip(self, str(e))
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000391 except Exception:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000392 result.addError(self, self._exc_info())
Benjamin Peterson692428e2009-03-23 21:50:21 +0000393 else:
394 success = True
Fred Drake02538202001-03-21 18:09:46 +0000395
396 try:
397 self.tearDown()
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000398 except Exception:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000399 result.addError(self, self._exc_info())
Benjamin Peterson692428e2009-03-23 21:50:21 +0000400 success = False
401 if success:
402 result.addSuccess(self)
Fred Drake02538202001-03-21 18:09:46 +0000403 finally:
404 result.stopTest(self)
405
Raymond Hettinger664347b2004-12-04 21:21:53 +0000406 def __call__(self, *args, **kwds):
407 return self.run(*args, **kwds)
Steve Purcell7e743842003-09-22 11:08:12 +0000408
Fred Drake02538202001-03-21 18:09:46 +0000409 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000410 """Run the test without collecting errors in a TestResult"""
Fred Drake02538202001-03-21 18:09:46 +0000411 self.setUp()
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000412 getattr(self, self._testMethodName)()
Fred Drake02538202001-03-21 18:09:46 +0000413 self.tearDown()
414
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000415 def _exc_info(self):
Steve Purcell15d89272001-04-12 09:05:01 +0000416 """Return a version of sys.exc_info() with the traceback frame
417 minimised; usually the top level of the traceback frame is not
418 needed.
Fred Drake02538202001-03-21 18:09:46 +0000419 """
Georg Brandl15c5ce92007-03-07 09:09:40 +0000420 return sys.exc_info()
Fred Drake02538202001-03-21 18:09:46 +0000421
Benjamin Peterson692428e2009-03-23 21:50:21 +0000422 def skip(self, reason):
423 """Skip this test."""
424 raise SkipTest(reason)
425
Steve Purcell15d89272001-04-12 09:05:01 +0000426 def fail(self, msg=None):
427 """Fail immediately, with the given message."""
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000428 raise self.failureException(msg)
Fred Drake02538202001-03-21 18:09:46 +0000429
430 def failIf(self, expr, msg=None):
431 "Fail the test if the expression is true."
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000432 if expr:
433 raise self.failureException(msg)
Fred Drake02538202001-03-21 18:09:46 +0000434
Steve Purcell15d89272001-04-12 09:05:01 +0000435 def failUnless(self, expr, msg=None):
436 """Fail the test unless the expression is true."""
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000437 if not expr:
438 raise self.failureException(msg)
Steve Purcell15d89272001-04-12 09:05:01 +0000439
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000440 def failUnlessRaises(self, excClass, callableObj=None, *args, **kwargs):
Steve Purcell15d89272001-04-12 09:05:01 +0000441 """Fail unless an exception of class excClass is thrown
Fred Drake02538202001-03-21 18:09:46 +0000442 by callableObj when invoked with arguments args and keyword
443 arguments kwargs. If a different type of exception is
444 thrown, it will not be caught, and the test case will be
445 deemed to have suffered an error, exactly as for an
446 unexpected exception.
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000447
448 If called with callableObj omitted or None, will return a
449 context object used like this::
450
451 with self.failUnlessRaises(some_error_class):
452 do_something()
Fred Drake02538202001-03-21 18:09:46 +0000453 """
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000454 context = AssertRaisesContext(excClass, self)
455 if callableObj is None:
456 return context
457 with context:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000458 callableObj(*args, **kwargs)
Fred Drake02538202001-03-21 18:09:46 +0000459
Steve Purcell15d89272001-04-12 09:05:01 +0000460 def failUnlessEqual(self, first, second, msg=None):
Raymond Hettingerc377cbf2003-04-04 22:56:42 +0000461 """Fail if the two objects are unequal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000462 operator.
463 """
Raymond Hettingerc377cbf2003-04-04 22:56:42 +0000464 if not first == second:
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000465 raise self.failureException(msg or '%r != %r' % (first, second))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000466
Steve Purcell15d89272001-04-12 09:05:01 +0000467 def failIfEqual(self, first, second, msg=None):
468 """Fail if the two objects are equal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000469 operator.
470 """
Steve Purcell15d89272001-04-12 09:05:01 +0000471 if first == second:
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000472 raise self.failureException(msg or '%r == %r' % (first, second))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000473
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000474 def failUnlessAlmostEqual(self, first, second, places=7, msg=None):
475 """Fail if the two objects are unequal as determined by their
476 difference rounded to the given number of decimal places
477 (default 7) and comparing to zero.
478
Steve Purcell397b45d2003-10-26 10:41:03 +0000479 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000480 as significant digits (measured from the most signficant digit).
481 """
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000482 if round(abs(second-first), places) != 0:
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000483 raise self.failureException(
484 msg or '%r != %r within %r places' % (first, second, places))
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000485
486 def failIfAlmostEqual(self, first, second, places=7, msg=None):
487 """Fail if the two objects are equal as determined by their
488 difference rounded to the given number of decimal places
489 (default 7) and comparing to zero.
490
Steve Purcellcca34912003-10-26 16:38:16 +0000491 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000492 as significant digits (measured from the most signficant digit).
493 """
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000494 if round(abs(second-first), places) == 0:
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000495 raise self.failureException(
496 msg or '%r == %r within %r places' % (first, second, places))
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000497
Steve Purcell7e743842003-09-22 11:08:12 +0000498 # Synonyms for assertion methods
499
Steve Purcell15d89272001-04-12 09:05:01 +0000500 assertEqual = assertEquals = failUnlessEqual
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000501
Steve Purcell15d89272001-04-12 09:05:01 +0000502 assertNotEqual = assertNotEquals = failIfEqual
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000503
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000504 assertAlmostEqual = assertAlmostEquals = failUnlessAlmostEqual
505
506 assertNotAlmostEqual = assertNotAlmostEquals = failIfAlmostEqual
507
Steve Purcell15d89272001-04-12 09:05:01 +0000508 assertRaises = failUnlessRaises
509
Steve Purcell7e743842003-09-22 11:08:12 +0000510 assert_ = assertTrue = failUnless
511
512 assertFalse = failIf
Steve Purcell15d89272001-04-12 09:05:01 +0000513
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000514
Fred Drake02538202001-03-21 18:09:46 +0000515
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000516class TestSuite(object):
Fred Drake02538202001-03-21 18:09:46 +0000517 """A test suite is a composite test consisting of a number of TestCases.
518
519 For use, create an instance of TestSuite, then add test case instances.
520 When all tests have been added, the suite can be passed to a test
521 runner, such as TextTestRunner. It will run the individual test cases
522 in the order in which they were added, aggregating the results. When
523 subclassing, do not forget to call the base class constructor.
524 """
525 def __init__(self, tests=()):
526 self._tests = []
527 self.addTests(tests)
528
529 def __repr__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000530 return "<%s tests=%s>" % (_strclass(self.__class__), self._tests)
Fred Drake02538202001-03-21 18:09:46 +0000531
Georg Brandl15c5ce92007-03-07 09:09:40 +0000532 def __eq__(self, other):
Benjamin Peterson692428e2009-03-23 21:50:21 +0000533 if not isinstance(other, self.__class__):
534 return NotImplemented
Georg Brandl15c5ce92007-03-07 09:09:40 +0000535 return self._tests == other._tests
536
537 def __ne__(self, other):
538 return not self == other
539
Nick Coghlan48361f52008-08-11 15:45:58 +0000540 # Can't guarantee hash invariant, so flag as unhashable
541 __hash__ = None
542
Jim Fultonfafd8742004-08-28 15:22:12 +0000543 def __iter__(self):
544 return iter(self._tests)
545
Fred Drake02538202001-03-21 18:09:46 +0000546 def countTestCases(self):
547 cases = 0
548 for test in self._tests:
Steve Purcell7e743842003-09-22 11:08:12 +0000549 cases += test.countTestCases()
Fred Drake02538202001-03-21 18:09:46 +0000550 return cases
551
552 def addTest(self, test):
Georg Brandld9e50262007-03-07 11:54:49 +0000553 # sanity checks
Raymond Hettinger5930d8f2008-07-10 16:06:41 +0000554 if not hasattr(test, '__call__'):
Georg Brandld9e50262007-03-07 11:54:49 +0000555 raise TypeError("the test to add must be callable")
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000556 if isinstance(test, type) and issubclass(test, (TestCase, TestSuite)):
Georg Brandld9e50262007-03-07 11:54:49 +0000557 raise TypeError("TestCases and TestSuites must be instantiated "
558 "before passing them to addTest()")
Fred Drake02538202001-03-21 18:09:46 +0000559 self._tests.append(test)
560
561 def addTests(self, tests):
Georg Brandld9e50262007-03-07 11:54:49 +0000562 if isinstance(tests, basestring):
563 raise TypeError("tests must be an iterable of tests, not a string")
Fred Drake02538202001-03-21 18:09:46 +0000564 for test in tests:
565 self.addTest(test)
566
567 def run(self, result):
Fred Drake02538202001-03-21 18:09:46 +0000568 for test in self._tests:
569 if result.shouldStop:
570 break
571 test(result)
572 return result
573
Raymond Hettinger664347b2004-12-04 21:21:53 +0000574 def __call__(self, *args, **kwds):
575 return self.run(*args, **kwds)
576
Fred Drake02538202001-03-21 18:09:46 +0000577 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000578 """Run the tests without collecting errors in a TestResult"""
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000579 for test in self._tests:
580 test.debug()
Fred Drake02538202001-03-21 18:09:46 +0000581
582
Benjamin Peterson692428e2009-03-23 21:50:21 +0000583class ClassTestSuite(TestSuite):
584 """
585 Suite of tests derived from a single TestCase class.
586 """
587
588 def __init__(self, tests, class_collected_from):
589 super(ClassTestSuite, self).__init__(tests)
590 self.collected_from = class_collected_from
591
592 def id(self):
593 module = getattr(self.collected_from, "__module__", None)
594 if module is not None:
595 return "{0}.{1}".format(module, self.collected_from.__name__)
596 return self.collected_from.__name__
597
598 def run(self, result):
599 if getattr(self.collected_from, "__unittest_skip__", False):
600 # ClassTestSuite result pretends to be a TestCase enough to be
601 # reported.
602 result.startTest(self)
603 try:
604 result.addSkip(self, self.collected_from.__unittest_skip_why__)
605 finally:
606 result.stopTest(self)
607 else:
608 result = super(ClassTestSuite, self).run(result)
609 return result
610
611 shortDescription = id
612
613
Fred Drake02538202001-03-21 18:09:46 +0000614class FunctionTestCase(TestCase):
615 """A test case that wraps a test function.
616
617 This is useful for slipping pre-existing test functions into the
Georg Brandl15c5ce92007-03-07 09:09:40 +0000618 unittest framework. Optionally, set-up and tidy-up functions can be
Fred Drake02538202001-03-21 18:09:46 +0000619 supplied. As with TestCase, the tidy-up ('tearDown') function will
620 always be called if the set-up ('setUp') function ran successfully.
621 """
622
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000623 def __init__(self, testFunc, setUp=None, tearDown=None, description=None):
624 super(FunctionTestCase, self).__init__()
Fred Drake02538202001-03-21 18:09:46 +0000625 self.__setUpFunc = setUp
626 self.__tearDownFunc = tearDown
627 self.__testFunc = testFunc
628 self.__description = description
629
630 def setUp(self):
631 if self.__setUpFunc is not None:
632 self.__setUpFunc()
633
634 def tearDown(self):
635 if self.__tearDownFunc is not None:
636 self.__tearDownFunc()
637
638 def runTest(self):
639 self.__testFunc()
640
641 def id(self):
642 return self.__testFunc.__name__
643
Georg Brandl15c5ce92007-03-07 09:09:40 +0000644 def __eq__(self, other):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000645 if not isinstance(other, self.__class__):
646 return NotImplemented
Georg Brandl15c5ce92007-03-07 09:09:40 +0000647
648 return self.__setUpFunc == other.__setUpFunc and \
649 self.__tearDownFunc == other.__tearDownFunc and \
650 self.__testFunc == other.__testFunc and \
651 self.__description == other.__description
652
653 def __ne__(self, other):
654 return not self == other
655
656 def __hash__(self):
Collin Winter9453e5d2007-03-09 23:30:39 +0000657 return hash((type(self), self.__setUpFunc, self.__tearDownFunc,
658 self.__testFunc, self.__description))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000659
Fred Drake02538202001-03-21 18:09:46 +0000660 def __str__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000661 return "%s (%s)" % (_strclass(self.__class__), self.__testFunc.__name__)
Fred Drake02538202001-03-21 18:09:46 +0000662
663 def __repr__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000664 return "<%s testFunc=%s>" % (_strclass(self.__class__), self.__testFunc)
Fred Drake02538202001-03-21 18:09:46 +0000665
666 def shortDescription(self):
667 if self.__description is not None: return self.__description
668 doc = self.__testFunc.__doc__
Steve Purcell7e743842003-09-22 11:08:12 +0000669 return doc and doc.split("\n")[0].strip() or None
Fred Drake02538202001-03-21 18:09:46 +0000670
671
672
673##############################################################################
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000674# Locating and loading tests
Fred Drake02538202001-03-21 18:09:46 +0000675##############################################################################
676
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000677class TestLoader(object):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000678 """
679 This class is responsible for loading tests according to various criteria
680 and returning them wrapped in a TestSuite
Fred Drake02538202001-03-21 18:09:46 +0000681 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000682 testMethodPrefix = 'test'
683 sortTestMethodsUsing = cmp
684 suiteClass = TestSuite
Benjamin Peterson692428e2009-03-23 21:50:21 +0000685 classSuiteClass = ClassTestSuite
Fred Drake02538202001-03-21 18:09:46 +0000686
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000687 def loadTestsFromTestCase(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +0000688 """Return a suite of all tests cases contained in testCaseClass"""
Johannes Gijsbersd7b6ad42004-11-07 15:46:25 +0000689 if issubclass(testCaseClass, TestSuite):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000690 raise TypeError("Test cases should not be derived from TestSuite." \
691 " Maybe you meant to derive from TestCase?")
Steve Purcell7e743842003-09-22 11:08:12 +0000692 testCaseNames = self.getTestCaseNames(testCaseClass)
693 if not testCaseNames and hasattr(testCaseClass, 'runTest'):
694 testCaseNames = ['runTest']
Benjamin Peterson692428e2009-03-23 21:50:21 +0000695 suite = self.classSuiteClass(map(testCaseClass, testCaseNames),
696 testCaseClass)
697 return suite
Fred Drake02538202001-03-21 18:09:46 +0000698
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000699 def loadTestsFromModule(self, module):
Steve Purcell15d89272001-04-12 09:05:01 +0000700 """Return a suite of all tests cases contained in the given module"""
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000701 tests = []
702 for name in dir(module):
703 obj = getattr(module, name)
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000704 if isinstance(obj, type) and issubclass(obj, TestCase):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000705 tests.append(self.loadTestsFromTestCase(obj))
706 return self.suiteClass(tests)
Fred Drake02538202001-03-21 18:09:46 +0000707
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000708 def loadTestsFromName(self, name, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000709 """Return a suite of all tests cases given a string specifier.
710
711 The name may resolve either to a module, a test case class, a
712 test method within a test case class, or a callable object which
713 returns a TestCase or TestSuite instance.
Tim Peters613b2222001-04-13 05:37:27 +0000714
Steve Purcell15d89272001-04-12 09:05:01 +0000715 The method optionally resolves the names relative to a given module.
716 """
Steve Purcell7e743842003-09-22 11:08:12 +0000717 parts = name.split('.')
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000718 if module is None:
Steve Purcell7e743842003-09-22 11:08:12 +0000719 parts_copy = parts[:]
720 while parts_copy:
721 try:
722 module = __import__('.'.join(parts_copy))
723 break
724 except ImportError:
725 del parts_copy[-1]
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000726 if not parts_copy:
727 raise
Armin Rigo1b3c04b2003-10-24 17:15:29 +0000728 parts = parts[1:]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000729 obj = module
730 for part in parts:
Steve Purcell7e743842003-09-22 11:08:12 +0000731 parent, obj = obj, getattr(obj, part)
Fred Drake02538202001-03-21 18:09:46 +0000732
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000733 if isinstance(obj, types.ModuleType):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000734 return self.loadTestsFromModule(obj)
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000735 elif isinstance(obj, type) and issubclass(obj, TestCase):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000736 return self.loadTestsFromTestCase(obj)
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000737 elif (isinstance(obj, types.UnboundMethodType) and
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000738 isinstance(parent, type) and
Georg Brandl15c5ce92007-03-07 09:09:40 +0000739 issubclass(parent, TestCase)):
740 return TestSuite([parent(obj.__name__)])
Steve Purcell397b45d2003-10-26 10:41:03 +0000741 elif isinstance(obj, TestSuite):
Steve Purcell7e743842003-09-22 11:08:12 +0000742 return obj
Raymond Hettinger5930d8f2008-07-10 16:06:41 +0000743 elif hasattr(obj, '__call__'):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000744 test = obj()
Georg Brandl15c5ce92007-03-07 09:09:40 +0000745 if isinstance(test, TestSuite):
746 return test
747 elif isinstance(test, TestCase):
748 return TestSuite([test])
749 else:
750 raise TypeError("calling %s returned %s, not a test" %
751 (obj, test))
Fred Drake02538202001-03-21 18:09:46 +0000752 else:
Georg Brandl15c5ce92007-03-07 09:09:40 +0000753 raise TypeError("don't know how to make test from: %s" % obj)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000754
755 def loadTestsFromNames(self, names, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000756 """Return a suite of all tests cases found using the given sequence
757 of string specifiers. See 'loadTestsFromName()'.
758 """
Steve Purcell7e743842003-09-22 11:08:12 +0000759 suites = [self.loadTestsFromName(name, module) for name in names]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000760 return self.suiteClass(suites)
761
762 def getTestCaseNames(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +0000763 """Return a sorted sequence of method names found within testCaseClass
764 """
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000765 def isTestMethod(attrname, testCaseClass=testCaseClass,
766 prefix=self.testMethodPrefix):
767 return attrname.startswith(prefix) and \
768 hasattr(getattr(testCaseClass, attrname), '__call__')
Steve Purcell7e743842003-09-22 11:08:12 +0000769 testFnNames = filter(isTestMethod, dir(testCaseClass))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000770 if self.sortTestMethodsUsing:
Raymond Hettinger5930d8f2008-07-10 16:06:41 +0000771 testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000772 return testFnNames
773
774
775
776defaultTestLoader = TestLoader()
777
778
779##############################################################################
780# Patches for old functions: these functions should be considered obsolete
781##############################################################################
782
783def _makeLoader(prefix, sortUsing, suiteClass=None):
784 loader = TestLoader()
785 loader.sortTestMethodsUsing = sortUsing
786 loader.testMethodPrefix = prefix
787 if suiteClass: loader.suiteClass = suiteClass
788 return loader
789
790def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp):
791 return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
792
793def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
794 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
795
796def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
797 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
Fred Drake02538202001-03-21 18:09:46 +0000798
799
800##############################################################################
801# Text UI
802##############################################################################
803
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000804class _WritelnDecorator(object):
Fred Drake02538202001-03-21 18:09:46 +0000805 """Used to decorate file-like objects with a handy 'writeln' method"""
806 def __init__(self,stream):
807 self.stream = stream
Fred Drake02538202001-03-21 18:09:46 +0000808
809 def __getattr__(self, attr):
810 return getattr(self.stream,attr)
811
Raymond Hettinger91dd19d2003-09-13 02:58:00 +0000812 def writeln(self, arg=None):
813 if arg: self.write(arg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000814 self.write('\n') # text-mode streams translate to \r\n if needed
Tim Petersa19a1682001-03-29 04:36:09 +0000815
Fred Drake02538202001-03-21 18:09:46 +0000816
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000817class _TextTestResult(TestResult):
Fred Drake02538202001-03-21 18:09:46 +0000818 """A test result class that can print formatted text results to a stream.
819
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000820 Used by TextTestRunner.
Fred Drake02538202001-03-21 18:09:46 +0000821 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000822 separator1 = '=' * 70
823 separator2 = '-' * 70
Fred Drake02538202001-03-21 18:09:46 +0000824
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000825 def __init__(self, stream, descriptions, verbosity):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000826 super(_TextTestResult, self).__init__()
Fred Drake02538202001-03-21 18:09:46 +0000827 self.stream = stream
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000828 self.showAll = verbosity > 1
829 self.dots = verbosity == 1
Fred Drake02538202001-03-21 18:09:46 +0000830 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000831
832 def getDescription(self, test):
833 if self.descriptions:
834 return test.shortDescription() or str(test)
835 else:
836 return str(test)
837
Fred Drake02538202001-03-21 18:09:46 +0000838 def startTest(self, test):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000839 super(_TextTestResult, self).startTest(test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000840 if self.showAll:
841 self.stream.write(self.getDescription(test))
842 self.stream.write(" ... ")
Georg Brandld0632402008-05-11 15:17:41 +0000843 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +0000844
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000845 def addSuccess(self, test):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000846 super(_TextTestResult, self).addSuccess(test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000847 if self.showAll:
Fred Drake02538202001-03-21 18:09:46 +0000848 self.stream.writeln("ok")
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000849 elif self.dots:
850 self.stream.write('.')
Georg Brandld0632402008-05-11 15:17:41 +0000851 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +0000852
853 def addError(self, test, err):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000854 super(_TextTestResult, self).addError(test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000855 if self.showAll:
856 self.stream.writeln("ERROR")
857 elif self.dots:
858 self.stream.write('E')
Georg Brandld0632402008-05-11 15:17:41 +0000859 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +0000860
861 def addFailure(self, test, err):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000862 super(_TextTestResult, self).addFailure(test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000863 if self.showAll:
864 self.stream.writeln("FAIL")
865 elif self.dots:
866 self.stream.write('F')
Georg Brandld0632402008-05-11 15:17:41 +0000867 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +0000868
Benjamin Peterson692428e2009-03-23 21:50:21 +0000869 def addSkip(self, test, reason):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000870 super(_TextTestResult, self).addSkip(test, reason)
Benjamin Peterson692428e2009-03-23 21:50:21 +0000871 if self.showAll:
872 self.stream.writeln("skipped {0!r}".format(reason))
873 elif self.dots:
874 self.stream.write("s")
875 self.stream.flush()
876
877 def addExpectedFailure(self, test, err):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000878 super(_TextTestResult, self).addExpectedFailure(test, err)
Benjamin Peterson692428e2009-03-23 21:50:21 +0000879 if self.showAll:
880 self.stream.writeln("expected failure")
881 elif self.dots:
882 self.stream.write(".")
883 self.stream.flush()
884
885 def addUnexpectedSuccess(self, test):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000886 super(_TextTestResult, self).addUnexpectedSuccess(test)
Benjamin Peterson692428e2009-03-23 21:50:21 +0000887 if self.showAll:
888 self.stream.writeln("unexpected success")
889 elif self.dots:
890 self.stream.write(".")
891 self.stream.flush()
892
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000893 def printErrors(self):
894 if self.dots or self.showAll:
Fred Drake02538202001-03-21 18:09:46 +0000895 self.stream.writeln()
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000896 self.printErrorList('ERROR', self.errors)
897 self.printErrorList('FAIL', self.failures)
898
899 def printErrorList(self, flavour, errors):
900 for test, err in errors:
901 self.stream.writeln(self.separator1)
902 self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
903 self.stream.writeln(self.separator2)
Steve Purcell7b065702001-09-06 08:24:40 +0000904 self.stream.writeln("%s" % err)
Fred Drake02538202001-03-21 18:09:46 +0000905
906
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000907class TextTestRunner(object):
Fred Drake02538202001-03-21 18:09:46 +0000908 """A test runner class that displays results in textual form.
Tim Petersa19a1682001-03-29 04:36:09 +0000909
Fred Drake02538202001-03-21 18:09:46 +0000910 It prints out the names of tests as they are run, errors as they
911 occur, and a summary of the results at the end of the test run.
912 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000913 def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
Fred Drake02538202001-03-21 18:09:46 +0000914 self.stream = _WritelnDecorator(stream)
915 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000916 self.verbosity = verbosity
917
918 def _makeResult(self):
919 return _TextTestResult(self.stream, self.descriptions, self.verbosity)
Fred Drake02538202001-03-21 18:09:46 +0000920
921 def run(self, test):
922 "Run the given test case or test suite."
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000923 result = self._makeResult()
Fred Drake02538202001-03-21 18:09:46 +0000924 startTime = time.time()
925 test(result)
926 stopTime = time.time()
Steve Purcell397b45d2003-10-26 10:41:03 +0000927 timeTaken = stopTime - startTime
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000928 result.printErrors()
929 self.stream.writeln(result.separator2)
Fred Drake02538202001-03-21 18:09:46 +0000930 run = result.testsRun
931 self.stream.writeln("Ran %d test%s in %.3fs" %
Neal Norwitz76165042002-05-31 14:15:11 +0000932 (run, run != 1 and "s" or "", timeTaken))
Fred Drake02538202001-03-21 18:09:46 +0000933 self.stream.writeln()
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +0000934 results = map(len, (result.expectedFailures,
935 result.unexpectedSuccesses,
Benjamin Peterson692428e2009-03-23 21:50:21 +0000936 result.skipped))
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +0000937 expectedFails, unexpectedSuccesses, skipped = results
Benjamin Peterson692428e2009-03-23 21:50:21 +0000938 infos = []
Fred Drake02538202001-03-21 18:09:46 +0000939 if not result.wasSuccessful():
Benjamin Peterson692428e2009-03-23 21:50:21 +0000940 self.stream.write("FAILED")
Fred Drake02538202001-03-21 18:09:46 +0000941 failed, errored = map(len, (result.failures, result.errors))
942 if failed:
Benjamin Peterson692428e2009-03-23 21:50:21 +0000943 infos.append("failures=%d" % failed)
Fred Drake02538202001-03-21 18:09:46 +0000944 if errored:
Benjamin Peterson692428e2009-03-23 21:50:21 +0000945 infos.append("errors=%d" % errored)
Fred Drake02538202001-03-21 18:09:46 +0000946 else:
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000947 self.stream.writeln("OK")
Benjamin Peterson692428e2009-03-23 21:50:21 +0000948 if skipped:
949 infos.append("skipped=%d" % skipped)
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000950 if expectedFails:
951 infos.append("expected failures=%d" % expectedFails)
952 if unexpectedSuccesses:
953 infos.append("unexpected successes=%d" % unexpectedSuccesses)
Benjamin Peterson692428e2009-03-23 21:50:21 +0000954 if infos:
955 self.stream.writeln(" (%s)" % (", ".join(infos),))
Fred Drake02538202001-03-21 18:09:46 +0000956 return result
Tim Petersa19a1682001-03-29 04:36:09 +0000957
Fred Drake02538202001-03-21 18:09:46 +0000958
Fred Drake02538202001-03-21 18:09:46 +0000959
960##############################################################################
961# Facilities for running tests from the command line
962##############################################################################
963
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000964class TestProgram(object):
Fred Drake02538202001-03-21 18:09:46 +0000965 """A command-line program that runs a set of tests; this is primarily
966 for making test modules conveniently executable.
967 """
968 USAGE = """\
Steve Purcell17a781b2001-04-09 15:37:31 +0000969Usage: %(progName)s [options] [test] [...]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000970
971Options:
972 -h, --help Show this message
973 -v, --verbose Verbose output
974 -q, --quiet Minimal output
Fred Drake02538202001-03-21 18:09:46 +0000975
976Examples:
977 %(progName)s - run default set of tests
978 %(progName)s MyTestSuite - run suite 'MyTestSuite'
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000979 %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
980 %(progName)s MyTestCase - run all 'test*' test methods
Fred Drake02538202001-03-21 18:09:46 +0000981 in MyTestCase
982"""
983 def __init__(self, module='__main__', defaultTest=None,
Georg Brandld0a96252007-03-07 09:21:06 +0000984 argv=None, testRunner=TextTestRunner,
985 testLoader=defaultTestLoader):
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000986 if isinstance(module, basestring):
Fred Drake02538202001-03-21 18:09:46 +0000987 self.module = __import__(module)
Steve Purcell7e743842003-09-22 11:08:12 +0000988 for part in module.split('.')[1:]:
Fred Drake02538202001-03-21 18:09:46 +0000989 self.module = getattr(self.module, part)
990 else:
991 self.module = module
992 if argv is None:
993 argv = sys.argv
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000994 self.verbosity = 1
Fred Drake02538202001-03-21 18:09:46 +0000995 self.defaultTest = defaultTest
996 self.testRunner = testRunner
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000997 self.testLoader = testLoader
Fred Drake02538202001-03-21 18:09:46 +0000998 self.progName = os.path.basename(argv[0])
999 self.parseArgs(argv)
Fred Drake02538202001-03-21 18:09:46 +00001000 self.runTests()
1001
1002 def usageExit(self, msg=None):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001003 if msg:
1004 print msg
Fred Drake02538202001-03-21 18:09:46 +00001005 print self.USAGE % self.__dict__
1006 sys.exit(2)
1007
1008 def parseArgs(self, argv):
1009 import getopt
Benjamin Peterson692428e2009-03-23 21:50:21 +00001010 long_opts = ['help','verbose','quiet']
Fred Drake02538202001-03-21 18:09:46 +00001011 try:
Benjamin Peterson692428e2009-03-23 21:50:21 +00001012 options, args = getopt.getopt(argv[1:], 'hHvq', long_opts)
Fred Drake02538202001-03-21 18:09:46 +00001013 for opt, value in options:
1014 if opt in ('-h','-H','--help'):
1015 self.usageExit()
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001016 if opt in ('-q','--quiet'):
1017 self.verbosity = 0
1018 if opt in ('-v','--verbose'):
1019 self.verbosity = 2
Fred Drake02538202001-03-21 18:09:46 +00001020 if len(args) == 0 and self.defaultTest is None:
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001021 self.test = self.testLoader.loadTestsFromModule(self.module)
1022 return
Fred Drake02538202001-03-21 18:09:46 +00001023 if len(args) > 0:
1024 self.testNames = args
1025 else:
1026 self.testNames = (self.defaultTest,)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001027 self.createTests()
Fred Drake02538202001-03-21 18:09:46 +00001028 except getopt.error, msg:
1029 self.usageExit(msg)
1030
1031 def createTests(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001032 self.test = self.testLoader.loadTestsFromNames(self.testNames,
1033 self.module)
Fred Drake02538202001-03-21 18:09:46 +00001034
1035 def runTests(self):
Georg Brandld0a96252007-03-07 09:21:06 +00001036 if isinstance(self.testRunner, (type, types.ClassType)):
1037 try:
1038 testRunner = self.testRunner(verbosity=self.verbosity)
1039 except TypeError:
1040 # didn't accept the verbosity argument
1041 testRunner = self.testRunner()
1042 else:
1043 # it is assumed to be a TestRunner instance
1044 testRunner = self.testRunner
1045 result = testRunner.run(self.test)
Tim Petersa19a1682001-03-29 04:36:09 +00001046 sys.exit(not result.wasSuccessful())
Fred Drake02538202001-03-21 18:09:46 +00001047
1048main = TestProgram
1049
1050
1051##############################################################################
1052# Executing this module from the command line
1053##############################################################################
1054
1055if __name__ == "__main__":
1056 main(module=None)