blob: ade806c97ee02d6519a14cc7717c574893482811 [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
Benjamin Peterson52baa292009-03-24 00:56:30 +000028 http://docs.python.org/library/unittest.html
Steve Purcell5ddd1a82001-03-22 08:45:36 +000029
Steve Purcell7e743842003-09-22 11:08:12 +000030Copyright (c) 1999-2003 Steve Purcell
Benjamin Peterson52baa292009-03-24 00:56:30 +000031Copyright (c) 2003-2009 Python Software Foundation
Fred Drake02538202001-03-21 18:09:46 +000032This module is free software, and you may redistribute it and/or modify
33it under the same terms as Python itself, so long as this copyright message
34and disclaimer are retained in their original form.
35
36IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
37SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
38THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
39DAMAGE.
40
41THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
42LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
43PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
44AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
45SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
Steve Purcell5ddd1a82001-03-22 08:45:36 +000046'''
Fred Drake02538202001-03-21 18:09:46 +000047
Fred Drake02538202001-03-21 18:09:46 +000048import time
49import sys
50import traceback
Fred Drake02538202001-03-21 18:09:46 +000051import os
Steve Purcell5ddd1a82001-03-22 08:45:36 +000052import types
Benjamin Peterson5254c042009-03-23 22:25:03 +000053import functools
Fred Drake02538202001-03-21 18:09:46 +000054
55##############################################################################
Steve Purcelld75e7e42003-09-15 11:01:21 +000056# Exported classes and functions
57##############################################################################
Benjamin Peterson52baa292009-03-24 00:56:30 +000058__all__ = ['TestResult', 'TestCase', 'TestSuite', 'ClassTestSuite',
59 'TextTestRunner', 'TestLoader', 'FunctionTestCase', 'main',
Benjamin Peterson4c93dcb2009-03-24 01:33:55 +000060 'defaultTestLoader', 'SkipTest', 'skip', 'skipIf', 'skipUnless',
Benjamin Peterson52baa292009-03-24 00:56:30 +000061 'expectedFailure']
Steve Purcelld75e7e42003-09-15 11:01:21 +000062
Steve Purcell7e743842003-09-22 11:08:12 +000063# Expose obsolete functions for backwards compatibility
Steve Purcelld75e7e42003-09-15 11:01:21 +000064__all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases'])
65
66
67##############################################################################
Fred Drake02538202001-03-21 18:09:46 +000068# Test framework core
69##############################################################################
70
Steve Purcelldc391a62002-08-09 09:46:23 +000071def _strclass(cls):
72 return "%s.%s" % (cls.__module__, cls.__name__)
73
Benjamin Peterson5254c042009-03-23 22:25:03 +000074
75class SkipTest(Exception):
76 """
77 Raise this exception in a test to skip it.
78
79 Usually you can use TestResult.skip() or one of the skipping decorators
80 instead of raising this directly.
81 """
82 pass
83
84class _ExpectedFailure(Exception):
85 """
86 Raise this when a test is expected to fail.
87
88 This is an implementation detail.
89 """
90
91 def __init__(self, exc_info):
92 super(_ExpectedFailure, self).__init__()
93 self.exc_info = exc_info
94
95class _UnexpectedSuccess(Exception):
96 """
97 The test was supposed to fail, but it didn't!
98 """
99 pass
100
101def _id(obj):
102 return obj
103
104def skip(reason):
105 """
106 Unconditionally skip a test.
107 """
108 def decorator(test_item):
109 if isinstance(test_item, type) and issubclass(test_item, TestCase):
110 test_item.__unittest_skip__ = True
111 test_item.__unittest_skip_why__ = reason
112 return test_item
113 @functools.wraps(test_item)
114 def skip_wrapper(*args, **kwargs):
115 raise SkipTest(reason)
116 return skip_wrapper
117 return decorator
118
119def skipIf(condition, reason):
120 """
121 Skip a test if the condition is true.
122 """
123 if condition:
124 return skip(reason)
125 return _id
126
127def skipUnless(condition, reason):
128 """
129 Skip a test unless the condition is true.
130 """
131 if not condition:
132 return skip(reason)
133 return _id
134
135
136def expectedFailure(func):
137 @functools.wraps(func)
138 def wrapper(*args, **kwargs):
139 try:
140 func(*args, **kwargs)
141 except Exception:
142 raise _ExpectedFailure(sys.exc_info())
143 raise _UnexpectedSuccess
144 return wrapper
145
146
Steve Purcellb8d5f242003-12-06 13:03:13 +0000147__unittest = 1
148
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000149class TestResult(object):
Fred Drake02538202001-03-21 18:09:46 +0000150 """Holder for test result information.
151
152 Test results are automatically managed by the TestCase and TestSuite
153 classes, and do not need to be explicitly manipulated by writers of tests.
154
155 Each instance holds the total number of tests run, and collections of
156 failures and errors that occurred among those test runs. The collections
Steve Purcell7b065702001-09-06 08:24:40 +0000157 contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
Fred Drake656f9ec2001-09-06 19:13:14 +0000158 formatted traceback of the error that occurred.
Fred Drake02538202001-03-21 18:09:46 +0000159 """
160 def __init__(self):
161 self.failures = []
162 self.errors = []
163 self.testsRun = 0
Benjamin Peterson5254c042009-03-23 22:25:03 +0000164 self.skipped = []
Benjamin Peterson52baa292009-03-24 00:56:30 +0000165 self.expectedFailures = []
166 self.unexpectedSuccesses = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000167 self.shouldStop = False
Fred Drake02538202001-03-21 18:09:46 +0000168
169 def startTest(self, test):
170 "Called when the given test is about to be run"
171 self.testsRun = self.testsRun + 1
172
173 def stopTest(self, test):
174 "Called when the given test has been run"
175 pass
176
177 def addError(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000178 """Called when an error has occurred. 'err' is a tuple of values as
179 returned by sys.exc_info().
180 """
Steve Purcellb8d5f242003-12-06 13:03:13 +0000181 self.errors.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000182
183 def addFailure(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000184 """Called when an error has occurred. 'err' is a tuple of values as
185 returned by sys.exc_info()."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000186 self.failures.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000187
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000188 def addSuccess(self, test):
189 "Called when a test has completed successfully"
190 pass
191
Benjamin Peterson5254c042009-03-23 22:25:03 +0000192 def addSkip(self, test, reason):
193 """Called when a test is skipped."""
194 self.skipped.append((test, reason))
195
196 def addExpectedFailure(self, test, err):
197 """Called when an expected failure/error occured."""
Benjamin Peterson52baa292009-03-24 00:56:30 +0000198 self.expectedFailures.append(
Benjamin Peterson5254c042009-03-23 22:25:03 +0000199 (test, self._exc_info_to_string(err, test)))
200
201 def addUnexpectedSuccess(self, test):
202 """Called when a test was expected to fail, but succeed."""
Benjamin Peterson52baa292009-03-24 00:56:30 +0000203 self.unexpectedSuccesses.append(test)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000204
Fred Drake02538202001-03-21 18:09:46 +0000205 def wasSuccessful(self):
206 "Tells whether or not this result was a success"
207 return len(self.failures) == len(self.errors) == 0
208
209 def stop(self):
210 "Indicates that the tests should be aborted"
Steve Purcell7e743842003-09-22 11:08:12 +0000211 self.shouldStop = True
Tim Petersa19a1682001-03-29 04:36:09 +0000212
Steve Purcellb8d5f242003-12-06 13:03:13 +0000213 def _exc_info_to_string(self, err, test):
Steve Purcell7b065702001-09-06 08:24:40 +0000214 """Converts a sys.exc_info()-style tuple of values into a string."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000215 exctype, value, tb = err
216 # Skip test runner traceback levels
217 while tb and self._is_relevant_tb_level(tb):
218 tb = tb.tb_next
219 if exctype is test.failureException:
220 # Skip assert*() traceback levels
221 length = self._count_relevant_tb_levels(tb)
Collin Winterce36ad82007-08-30 01:19:48 +0000222 return ''.join(traceback.format_exception(exctype, value,
223 tb, length))
Steve Purcellb8d5f242003-12-06 13:03:13 +0000224 return ''.join(traceback.format_exception(exctype, value, tb))
225
226 def _is_relevant_tb_level(self, tb):
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000227 return '__unittest' in tb.tb_frame.f_globals
Steve Purcellb8d5f242003-12-06 13:03:13 +0000228
229 def _count_relevant_tb_levels(self, tb):
230 length = 0
231 while tb and not self._is_relevant_tb_level(tb):
232 length += 1
233 tb = tb.tb_next
234 return length
Steve Purcell7b065702001-09-06 08:24:40 +0000235
Fred Drake02538202001-03-21 18:09:46 +0000236 def __repr__(self):
237 return "<%s run=%i errors=%i failures=%i>" % \
Steve Purcelldc391a62002-08-09 09:46:23 +0000238 (_strclass(self.__class__), self.testsRun, len(self.errors),
Fred Drake02538202001-03-21 18:09:46 +0000239 len(self.failures))
240
Benjamin Peterson52baa292009-03-24 00:56:30 +0000241
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000242class AssertRaisesContext(object):
Benjamin Peterson52baa292009-03-24 00:56:30 +0000243
244
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000245 def __init__(self, expected, test_case, callable_obj=None):
246 self.expected = expected
247 self.failureException = test_case.failureException
248 if callable_obj is not None:
249 try:
250 self.obj_name = callable_obj.__name__
251 except AttributeError:
252 self.obj_name = str(callable_obj)
253 else:
254 self.obj_name = None
Benjamin Peterson52baa292009-03-24 00:56:30 +0000255
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000256 def __enter__(self):
257 pass
Benjamin Peterson52baa292009-03-24 00:56:30 +0000258
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000259 def __exit__(self, exc_type, exc_value, traceback):
260 if exc_type is None:
261 try:
262 exc_name = self.expected.__name__
263 except AttributeError:
264 exc_name = str(self.expected)
265 if self.obj_name:
266 raise self.failureException("{0} not raised by {1}"
267 .format(exc_name, self.obj_name))
268 else:
269 raise self.failureException("{0} not raised"
270 .format(exc_name))
271 if issubclass(exc_type, self.expected):
272 return True
273 # Let unexpected exceptions skip through
274 return False
275
Benjamin Peterson52baa292009-03-24 00:56:30 +0000276
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000277class TestCase(object):
Fred Drake02538202001-03-21 18:09:46 +0000278 """A class whose instances are single test cases.
279
Fred Drake02538202001-03-21 18:09:46 +0000280 By default, the test code itself should be placed in a method named
281 'runTest'.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000282
Tim Petersa19a1682001-03-29 04:36:09 +0000283 If the fixture may be used for many test cases, create as
Fred Drake02538202001-03-21 18:09:46 +0000284 many test methods as are needed. When instantiating such a TestCase
285 subclass, specify in the constructor arguments the name of the test method
286 that the instance is to execute.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000287
Tim Petersa19a1682001-03-29 04:36:09 +0000288 Test authors should subclass TestCase for their own tests. Construction
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000289 and deconstruction of the test's environment ('fixture') can be
290 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
291
292 If it is necessary to override the __init__ method, the base class
293 __init__ method must always be called. It is important that subclasses
294 should not change the signature of their __init__ method, since instances
295 of the classes are instantiated automatically by parts of the framework
296 in order to be run.
Fred Drake02538202001-03-21 18:09:46 +0000297 """
Steve Purcell15d89272001-04-12 09:05:01 +0000298
299 # This attribute determines which exception will be raised when
300 # the instance's assertion methods fail; test methods raising this
301 # exception will be deemed to have 'failed' rather than 'errored'
302
303 failureException = AssertionError
304
Fred Drake02538202001-03-21 18:09:46 +0000305 def __init__(self, methodName='runTest'):
306 """Create an instance of the class that will use the named test
307 method when executed. Raises a ValueError if the instance does
308 not have a method with the specified name.
309 """
Benjamin Peterson52baa292009-03-24 00:56:30 +0000310 self._testMethodName = methodName
Fred Drake02538202001-03-21 18:09:46 +0000311 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000312 testMethod = getattr(self, methodName)
Fred Drake02538202001-03-21 18:09:46 +0000313 except AttributeError:
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000314 raise ValueError("no such test method in %s: %s" % \
315 (self.__class__, methodName))
Benjamin Peterson52baa292009-03-24 00:56:30 +0000316 self._testMethodDoc = testMethod.__doc__
Fred Drake02538202001-03-21 18:09:46 +0000317
318 def setUp(self):
319 "Hook method for setting up the test fixture before exercising it."
320 pass
321
322 def tearDown(self):
323 "Hook method for deconstructing the test fixture after testing it."
324 pass
325
326 def countTestCases(self):
327 return 1
328
329 def defaultTestResult(self):
330 return TestResult()
331
332 def shortDescription(self):
333 """Returns a one-line description of the test, or None if no
334 description has been provided.
335
336 The default implementation of this method returns the first line of
337 the specified test method's docstring.
338 """
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000339 doc = self._testMethodDoc
Steve Purcell7e743842003-09-22 11:08:12 +0000340 return doc and doc.split("\n")[0].strip() or None
Fred Drake02538202001-03-21 18:09:46 +0000341
342 def id(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000343 return "%s.%s" % (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000344
Guido van Rossumd8faa362007-04-27 19:54:29 +0000345 def __eq__(self, other):
346 if type(self) is not type(other):
Benjamin Peterson52baa292009-03-24 00:56:30 +0000347 return NotImplemented
Guido van Rossumd8faa362007-04-27 19:54:29 +0000348
349 return self._testMethodName == other._testMethodName
350
351 def __ne__(self, other):
352 return not self == other
353
354 def __hash__(self):
355 return hash((type(self), self._testMethodName))
356
Fred Drake02538202001-03-21 18:09:46 +0000357 def __str__(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000358 return "%s (%s)" % (self._testMethodName, _strclass(self.__class__))
Fred Drake02538202001-03-21 18:09:46 +0000359
360 def __repr__(self):
361 return "<%s testMethod=%s>" % \
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000362 (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000363
364 def run(self, result=None):
Benjamin Peterson52baa292009-03-24 00:56:30 +0000365 if result is None:
366 result = self.defaultTestResult()
Fred Drake02538202001-03-21 18:09:46 +0000367 result.startTest(self)
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000368 testMethod = getattr(self, self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000369 try:
370 try:
371 self.setUp()
Benjamin Peterson5254c042009-03-23 22:25:03 +0000372 except SkipTest as e:
373 result.addSkip(self, str(e))
374 return
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000375 except Exception:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000376 result.addError(self, sys.exc_info())
Fred Drake02538202001-03-21 18:09:46 +0000377 return
378
Benjamin Peterson5254c042009-03-23 22:25:03 +0000379 success = False
Fred Drake02538202001-03-21 18:09:46 +0000380 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000381 testMethod()
Skip Montanaroae5c37b2003-07-13 15:18:12 +0000382 except self.failureException:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000383 result.addFailure(self, sys.exc_info())
Benjamin Peterson5254c042009-03-23 22:25:03 +0000384 except _ExpectedFailure as e:
385 result.addExpectedFailure(self, e.exc_info)
386 except _UnexpectedSuccess:
387 result.addUnexpectedSuccess(self)
388 except SkipTest as e:
389 result.addSkip(self, str(e))
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000390 except Exception:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000391 result.addError(self, sys.exc_info())
Benjamin Peterson5254c042009-03-23 22:25:03 +0000392 else:
393 success = True
Fred Drake02538202001-03-21 18:09:46 +0000394
395 try:
396 self.tearDown()
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000397 except Exception:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000398 result.addError(self, sys.exc_info())
Benjamin Peterson5254c042009-03-23 22:25:03 +0000399 success = False
400 if success:
401 result.addSuccess(self)
Fred Drake02538202001-03-21 18:09:46 +0000402 finally:
403 result.stopTest(self)
404
Raymond Hettinger664347b2004-12-04 21:21:53 +0000405 def __call__(self, *args, **kwds):
406 return self.run(*args, **kwds)
Steve Purcell7e743842003-09-22 11:08:12 +0000407
Fred Drake02538202001-03-21 18:09:46 +0000408 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000409 """Run the test without collecting errors in a TestResult"""
Fred Drake02538202001-03-21 18:09:46 +0000410 self.setUp()
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000411 getattr(self, self._testMethodName)()
Fred Drake02538202001-03-21 18:09:46 +0000412 self.tearDown()
413
Benjamin Petersone549ead2009-03-28 21:42:05 +0000414 def skipTest(self, reason):
Benjamin Peterson5254c042009-03-23 22:25:03 +0000415 """Skip this test."""
416 raise SkipTest(reason)
417
Steve Purcell15d89272001-04-12 09:05:01 +0000418 def fail(self, msg=None):
419 """Fail immediately, with the given message."""
Collin Winterce36ad82007-08-30 01:19:48 +0000420 raise self.failureException(msg)
Fred Drake02538202001-03-21 18:09:46 +0000421
422 def failIf(self, expr, msg=None):
423 "Fail the test if the expression is true."
Benjamin Peterson52baa292009-03-24 00:56:30 +0000424 if expr:
425 raise self.failureException(msg)
Fred Drake02538202001-03-21 18:09:46 +0000426
Steve Purcell15d89272001-04-12 09:05:01 +0000427 def failUnless(self, expr, msg=None):
428 """Fail the test unless the expression is true."""
Benjamin Peterson52baa292009-03-24 00:56:30 +0000429 if not expr:
430 raise self.failureException(msg)
Steve Purcell15d89272001-04-12 09:05:01 +0000431
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000432 def failUnlessRaises(self, excClass, callableObj=None, *args, **kwargs):
Steve Purcell15d89272001-04-12 09:05:01 +0000433 """Fail unless an exception of class excClass is thrown
Fred Drake02538202001-03-21 18:09:46 +0000434 by callableObj when invoked with arguments args and keyword
435 arguments kwargs. If a different type of exception is
436 thrown, it will not be caught, and the test case will be
437 deemed to have suffered an error, exactly as for an
438 unexpected exception.
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000439
440 If called with callableObj omitted or None, will return a
441 context object used like this::
442
443 with self.failUnlessRaises(some_error_class):
444 do_something()
Fred Drake02538202001-03-21 18:09:46 +0000445 """
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000446 context = AssertRaisesContext(excClass, self, callableObj)
447 if callableObj is None:
448 return context
449 with context:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000450 callableObj(*args, **kwargs)
Fred Drake02538202001-03-21 18:09:46 +0000451
Steve Purcell15d89272001-04-12 09:05:01 +0000452 def failUnlessEqual(self, first, second, msg=None):
Raymond Hettingerc377cbf2003-04-04 22:56:42 +0000453 """Fail if the two objects are unequal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000454 operator.
455 """
Raymond Hettingerc377cbf2003-04-04 22:56:42 +0000456 if not first == second:
Collin Winterce36ad82007-08-30 01:19:48 +0000457 raise self.failureException(msg or '%r != %r' % (first, second))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000458
Steve Purcell15d89272001-04-12 09:05:01 +0000459 def failIfEqual(self, first, second, msg=None):
460 """Fail if the two objects are equal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000461 operator.
462 """
Steve Purcell15d89272001-04-12 09:05:01 +0000463 if first == second:
Collin Winterce36ad82007-08-30 01:19:48 +0000464 raise self.failureException(msg or '%r == %r' % (first, second))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000465
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +0000466 def failUnlessAlmostEqual(self, first, second, *, places=7, msg=None):
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000467 """Fail if the two objects are unequal as determined by their
468 difference rounded to the given number of decimal places
469 (default 7) and comparing to zero.
470
Steve Purcell397b45d2003-10-26 10:41:03 +0000471 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000472 as significant digits (measured from the most signficant digit).
473 """
Jeffrey Yasskin1cc55442007-09-06 18:55:17 +0000474 if round(abs(second-first), places) != 0:
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000475 raise self.failureException(
476 msg or '%r != %r within %r places' % (first, second, places))
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000477
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +0000478 def failIfAlmostEqual(self, first, second, *, places=7, msg=None):
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000479 """Fail if the two objects are equal as determined by their
480 difference rounded to the given number of decimal places
481 (default 7) and comparing to zero.
482
Steve Purcellcca34912003-10-26 16:38:16 +0000483 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000484 as significant digits (measured from the most signficant digit).
485 """
Jeffrey Yasskin1cc55442007-09-06 18:55:17 +0000486 if round(abs(second-first), places) == 0:
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000487 raise self.failureException(
488 msg or '%r == %r within %r places' % (first, second, places))
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000489
Steve Purcell7e743842003-09-22 11:08:12 +0000490 # Synonyms for assertion methods
491
Steve Purcell15d89272001-04-12 09:05:01 +0000492 assertEqual = assertEquals = failUnlessEqual
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000493
Steve Purcell15d89272001-04-12 09:05:01 +0000494 assertNotEqual = assertNotEquals = failIfEqual
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000495
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000496 assertAlmostEqual = assertAlmostEquals = failUnlessAlmostEqual
497
498 assertNotAlmostEqual = assertNotAlmostEquals = failIfAlmostEqual
499
Steve Purcell15d89272001-04-12 09:05:01 +0000500 assertRaises = failUnlessRaises
501
Steve Purcell7e743842003-09-22 11:08:12 +0000502 assert_ = assertTrue = failUnless
503
504 assertFalse = failIf
Steve Purcell15d89272001-04-12 09:05:01 +0000505
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000506
Fred Drake02538202001-03-21 18:09:46 +0000507
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000508class TestSuite(object):
Fred Drake02538202001-03-21 18:09:46 +0000509 """A test suite is a composite test consisting of a number of TestCases.
510
511 For use, create an instance of TestSuite, then add test case instances.
512 When all tests have been added, the suite can be passed to a test
513 runner, such as TextTestRunner. It will run the individual test cases
514 in the order in which they were added, aggregating the results. When
515 subclassing, do not forget to call the base class constructor.
516 """
517 def __init__(self, tests=()):
518 self._tests = []
519 self.addTests(tests)
520
521 def __repr__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000522 return "<%s tests=%s>" % (_strclass(self.__class__), self._tests)
Fred Drake02538202001-03-21 18:09:46 +0000523
Guido van Rossumd8faa362007-04-27 19:54:29 +0000524 def __eq__(self, other):
Benjamin Peterson5254c042009-03-23 22:25:03 +0000525 if not isinstance(other, self.__class__):
526 return NotImplemented
Guido van Rossumd8faa362007-04-27 19:54:29 +0000527 return self._tests == other._tests
528
529 def __ne__(self, other):
530 return not self == other
531
Jim Fultonfafd8742004-08-28 15:22:12 +0000532 def __iter__(self):
533 return iter(self._tests)
534
Fred Drake02538202001-03-21 18:09:46 +0000535 def countTestCases(self):
536 cases = 0
537 for test in self._tests:
Steve Purcell7e743842003-09-22 11:08:12 +0000538 cases += test.countTestCases()
Fred Drake02538202001-03-21 18:09:46 +0000539 return cases
540
541 def addTest(self, test):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000542 # sanity checks
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000543 if not hasattr(test, '__call__'):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000544 raise TypeError("the test to add must be callable")
Guido van Rossum13257902007-06-07 23:15:56 +0000545 if isinstance(test, type) and issubclass(test, (TestCase, TestSuite)):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000546 raise TypeError("TestCases and TestSuites must be instantiated "
547 "before passing them to addTest()")
Fred Drake02538202001-03-21 18:09:46 +0000548 self._tests.append(test)
549
550 def addTests(self, tests):
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000551 if isinstance(tests, str):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000552 raise TypeError("tests must be an iterable of tests, not a string")
Fred Drake02538202001-03-21 18:09:46 +0000553 for test in tests:
554 self.addTest(test)
555
556 def run(self, result):
Fred Drake02538202001-03-21 18:09:46 +0000557 for test in self._tests:
558 if result.shouldStop:
559 break
560 test(result)
561 return result
562
Raymond Hettinger664347b2004-12-04 21:21:53 +0000563 def __call__(self, *args, **kwds):
564 return self.run(*args, **kwds)
565
Fred Drake02538202001-03-21 18:09:46 +0000566 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000567 """Run the tests without collecting errors in a TestResult"""
Benjamin Peterson52baa292009-03-24 00:56:30 +0000568 for test in self._tests:
569 test.debug()
Fred Drake02538202001-03-21 18:09:46 +0000570
571
Benjamin Peterson5254c042009-03-23 22:25:03 +0000572class ClassTestSuite(TestSuite):
573 """
574 Suite of tests derived from a single TestCase class.
575 """
576
577 def __init__(self, tests, class_collected_from):
578 super(ClassTestSuite, self).__init__(tests)
579 self.collected_from = class_collected_from
580
581 def id(self):
582 module = getattr(self.collected_from, "__module__", None)
583 if module is not None:
584 return "{0}.{1}".format(module, self.collected_from.__name__)
585 return self.collected_from.__name__
586
587 def run(self, result):
588 if getattr(self.collected_from, "__unittest_skip__", False):
589 # ClassTestSuite result pretends to be a TestCase enough to be
590 # reported.
591 result.startTest(self)
592 try:
593 result.addSkip(self, self.collected_from.__unittest_skip_why__)
594 finally:
595 result.stopTest(self)
596 else:
597 result = super(ClassTestSuite, self).run(result)
598 return result
599
600 shortDescription = id
601
602
Fred Drake02538202001-03-21 18:09:46 +0000603class FunctionTestCase(TestCase):
604 """A test case that wraps a test function.
605
606 This is useful for slipping pre-existing test functions into the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000607 unittest framework. Optionally, set-up and tidy-up functions can be
Fred Drake02538202001-03-21 18:09:46 +0000608 supplied. As with TestCase, the tidy-up ('tearDown') function will
609 always be called if the set-up ('setUp') function ran successfully.
610 """
611
Benjamin Peterson52baa292009-03-24 00:56:30 +0000612 def __init__(self, testFunc, setUp=None, tearDown=None, description=None):
613 super(FunctionTestCase, self).__init__()
Fred Drake02538202001-03-21 18:09:46 +0000614 self.__setUpFunc = setUp
615 self.__tearDownFunc = tearDown
616 self.__testFunc = testFunc
617 self.__description = description
618
619 def setUp(self):
620 if self.__setUpFunc is not None:
621 self.__setUpFunc()
622
623 def tearDown(self):
624 if self.__tearDownFunc is not None:
625 self.__tearDownFunc()
626
627 def runTest(self):
628 self.__testFunc()
629
630 def id(self):
631 return self.__testFunc.__name__
632
Guido van Rossumd8faa362007-04-27 19:54:29 +0000633 def __eq__(self, other):
Benjamin Peterson52baa292009-03-24 00:56:30 +0000634 if not isinstance(other, self.__class__):
635 return NotImplemented
Guido van Rossumd8faa362007-04-27 19:54:29 +0000636
637 return self.__setUpFunc == other.__setUpFunc and \
638 self.__tearDownFunc == other.__tearDownFunc and \
639 self.__testFunc == other.__testFunc and \
640 self.__description == other.__description
641
642 def __ne__(self, other):
643 return not self == other
644
645 def __hash__(self):
646 return hash((type(self), self.__setUpFunc, self.__tearDownFunc,
Collin Winterce36ad82007-08-30 01:19:48 +0000647 self.__testFunc, self.__description))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000648
Fred Drake02538202001-03-21 18:09:46 +0000649 def __str__(self):
Collin Winterce36ad82007-08-30 01:19:48 +0000650 return "%s (%s)" % (_strclass(self.__class__),
651 self.__testFunc.__name__)
Fred Drake02538202001-03-21 18:09:46 +0000652
653 def __repr__(self):
Collin Winterce36ad82007-08-30 01:19:48 +0000654 return "<%s testFunc=%s>" % (_strclass(self.__class__),
655 self.__testFunc)
Fred Drake02538202001-03-21 18:09:46 +0000656
657 def shortDescription(self):
658 if self.__description is not None: return self.__description
659 doc = self.__testFunc.__doc__
Steve Purcell7e743842003-09-22 11:08:12 +0000660 return doc and doc.split("\n")[0].strip() or None
Fred Drake02538202001-03-21 18:09:46 +0000661
662
663
664##############################################################################
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000665# Locating and loading tests
Fred Drake02538202001-03-21 18:09:46 +0000666##############################################################################
667
Raymond Hettingerd4cb56d2008-01-30 02:55:10 +0000668def CmpToKey(mycmp):
669 'Convert a cmp= function into a key= function'
670 class K(object):
671 def __init__(self, obj, *args):
672 self.obj = obj
673 def __lt__(self, other):
674 return mycmp(self.obj, other.obj) == -1
675 return K
676
Mark Dickinsona56c4672009-01-27 18:17:45 +0000677def three_way_cmp(x, y):
678 """Return -1 if x < y, 0 if x == y and 1 if x > y"""
679 return (x > y) - (x < y)
680
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000681class TestLoader(object):
Benjamin Peterson52baa292009-03-24 00:56:30 +0000682 """
683 This class is responsible for loading tests according to various criteria
684 and returning them wrapped in a TestSuite
Fred Drake02538202001-03-21 18:09:46 +0000685 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000686 testMethodPrefix = 'test'
Mark Dickinsona56c4672009-01-27 18:17:45 +0000687 sortTestMethodsUsing = staticmethod(three_way_cmp)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000688 suiteClass = TestSuite
Benjamin Peterson5254c042009-03-23 22:25:03 +0000689 classSuiteClass = ClassTestSuite
Fred Drake02538202001-03-21 18:09:46 +0000690
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000691 def loadTestsFromTestCase(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +0000692 """Return a suite of all tests cases contained in testCaseClass"""
Johannes Gijsbersd7b6ad42004-11-07 15:46:25 +0000693 if issubclass(testCaseClass, TestSuite):
Benjamin Peterson52baa292009-03-24 00:56:30 +0000694 raise TypeError("Test cases should not be derived from TestSuite." \
695 " Maybe you meant to derive from TestCase?")
Steve Purcell7e743842003-09-22 11:08:12 +0000696 testCaseNames = self.getTestCaseNames(testCaseClass)
697 if not testCaseNames and hasattr(testCaseClass, 'runTest'):
698 testCaseNames = ['runTest']
Benjamin Peterson5254c042009-03-23 22:25:03 +0000699 suite = self.classSuiteClass(map(testCaseClass, testCaseNames),
700 testCaseClass)
701 return suite
Fred Drake02538202001-03-21 18:09:46 +0000702
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000703 def loadTestsFromModule(self, module):
Steve Purcell15d89272001-04-12 09:05:01 +0000704 """Return a suite of all tests cases contained in the given module"""
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000705 tests = []
706 for name in dir(module):
707 obj = getattr(module, name)
Guido van Rossum13257902007-06-07 23:15:56 +0000708 if isinstance(obj, type) and issubclass(obj, TestCase):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000709 tests.append(self.loadTestsFromTestCase(obj))
710 return self.suiteClass(tests)
Fred Drake02538202001-03-21 18:09:46 +0000711
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000712 def loadTestsFromName(self, name, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000713 """Return a suite of all tests cases given a string specifier.
714
715 The name may resolve either to a module, a test case class, a
716 test method within a test case class, or a callable object which
717 returns a TestCase or TestSuite instance.
Tim Peters613b2222001-04-13 05:37:27 +0000718
Steve Purcell15d89272001-04-12 09:05:01 +0000719 The method optionally resolves the names relative to a given module.
720 """
Steve Purcell7e743842003-09-22 11:08:12 +0000721 parts = name.split('.')
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000722 if module is None:
Steve Purcell7e743842003-09-22 11:08:12 +0000723 parts_copy = parts[:]
724 while parts_copy:
725 try:
726 module = __import__('.'.join(parts_copy))
727 break
728 except ImportError:
729 del parts_copy[-1]
Benjamin Peterson52baa292009-03-24 00:56:30 +0000730 if not parts_copy:
731 raise
Armin Rigo1b3c04b2003-10-24 17:15:29 +0000732 parts = parts[1:]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000733 obj = module
734 for part in parts:
Steve Purcell7e743842003-09-22 11:08:12 +0000735 parent, obj = obj, getattr(obj, part)
Fred Drake02538202001-03-21 18:09:46 +0000736
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000737 if isinstance(obj, types.ModuleType):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000738 return self.loadTestsFromModule(obj)
Guido van Rossum13257902007-06-07 23:15:56 +0000739 elif isinstance(obj, type) and issubclass(obj, TestCase):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000740 return self.loadTestsFromTestCase(obj)
Christian Heimes4a22b5d2007-11-25 09:39:14 +0000741 elif (isinstance(obj, types.FunctionType) and
Guido van Rossum13257902007-06-07 23:15:56 +0000742 isinstance(parent, type) and
Guido van Rossumd8faa362007-04-27 19:54:29 +0000743 issubclass(parent, TestCase)):
Christian Heimes4a22b5d2007-11-25 09:39:14 +0000744 name = obj.__name__
745 inst = parent(name)
746 # static methods follow a different path
Christian Heimes4975a1f2007-11-26 10:14:51 +0000747 if not isinstance(getattr(inst, name), types.FunctionType):
Christian Heimes4a22b5d2007-11-25 09:39:14 +0000748 return TestSuite([inst])
Steve Purcell397b45d2003-10-26 10:41:03 +0000749 elif isinstance(obj, TestSuite):
Steve Purcell7e743842003-09-22 11:08:12 +0000750 return obj
Christian Heimes4a22b5d2007-11-25 09:39:14 +0000751
752 if hasattr(obj, '__call__'):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000753 test = obj()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000754 if isinstance(test, TestSuite):
755 return test
756 elif isinstance(test, TestCase):
757 return TestSuite([test])
758 else:
759 raise TypeError("calling %s returned %s, not a test" %
760 (obj, test))
Fred Drake02538202001-03-21 18:09:46 +0000761 else:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000762 raise TypeError("don't know how to make test from: %s" % obj)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000763
764 def loadTestsFromNames(self, names, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000765 """Return a suite of all tests cases found using the given sequence
766 of string specifiers. See 'loadTestsFromName()'.
767 """
Steve Purcell7e743842003-09-22 11:08:12 +0000768 suites = [self.loadTestsFromName(name, module) for name in names]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000769 return self.suiteClass(suites)
770
771 def getTestCaseNames(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +0000772 """Return a sorted sequence of method names found within testCaseClass
773 """
Collin Winterce36ad82007-08-30 01:19:48 +0000774 def isTestMethod(attrname, testCaseClass=testCaseClass,
775 prefix=self.testMethodPrefix):
Benjamin Peterson52baa292009-03-24 00:56:30 +0000776 return attrname.startswith(prefix) and \
777 hasattr(getattr(testCaseClass, attrname), '__call__')
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000778 testFnNames = list(filter(isTestMethod, dir(testCaseClass)))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000779 if self.sortTestMethodsUsing:
Raymond Hettingerd4cb56d2008-01-30 02:55:10 +0000780 testFnNames.sort(key=CmpToKey(self.sortTestMethodsUsing))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000781 return testFnNames
782
783
784
785defaultTestLoader = TestLoader()
786
787
788##############################################################################
789# Patches for old functions: these functions should be considered obsolete
790##############################################################################
791
792def _makeLoader(prefix, sortUsing, suiteClass=None):
793 loader = TestLoader()
794 loader.sortTestMethodsUsing = sortUsing
795 loader.testMethodPrefix = prefix
796 if suiteClass: loader.suiteClass = suiteClass
797 return loader
798
Mark Dickinsonc429a832009-01-27 20:27:05 +0000799def getTestCaseNames(testCaseClass, prefix, sortUsing=three_way_cmp):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000800 return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
801
Mark Dickinsonc429a832009-01-27 20:27:05 +0000802def makeSuite(testCaseClass, prefix='test', sortUsing=three_way_cmp,
803 suiteClass=TestSuite):
804 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(
805 testCaseClass)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000806
Mark Dickinsonc429a832009-01-27 20:27:05 +0000807def findTestCases(module, prefix='test', sortUsing=three_way_cmp,
808 suiteClass=TestSuite):
809 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(
810 module)
Fred Drake02538202001-03-21 18:09:46 +0000811
812
813##############################################################################
814# Text UI
815##############################################################################
816
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000817class _WritelnDecorator(object):
Fred Drake02538202001-03-21 18:09:46 +0000818 """Used to decorate file-like objects with a handy 'writeln' method"""
819 def __init__(self,stream):
820 self.stream = stream
Fred Drake02538202001-03-21 18:09:46 +0000821
822 def __getattr__(self, attr):
823 return getattr(self.stream,attr)
824
Raymond Hettinger91dd19d2003-09-13 02:58:00 +0000825 def writeln(self, arg=None):
Benjamin Petersone549ead2009-03-28 21:42:05 +0000826 if arg:
827 self.write(arg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000828 self.write('\n') # text-mode streams translate to \r\n if needed
Tim Petersa19a1682001-03-29 04:36:09 +0000829
Fred Drake02538202001-03-21 18:09:46 +0000830
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000831class _TextTestResult(TestResult):
Fred Drake02538202001-03-21 18:09:46 +0000832 """A test result class that can print formatted text results to a stream.
833
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000834 Used by TextTestRunner.
Fred Drake02538202001-03-21 18:09:46 +0000835 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000836 separator1 = '=' * 70
837 separator2 = '-' * 70
Fred Drake02538202001-03-21 18:09:46 +0000838
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000839 def __init__(self, stream, descriptions, verbosity):
Benjamin Peterson52baa292009-03-24 00:56:30 +0000840 super(_TextTestResult, self).__init__()
Fred Drake02538202001-03-21 18:09:46 +0000841 self.stream = stream
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000842 self.showAll = verbosity > 1
843 self.dots = verbosity == 1
Fred Drake02538202001-03-21 18:09:46 +0000844 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000845
846 def getDescription(self, test):
847 if self.descriptions:
848 return test.shortDescription() or str(test)
849 else:
850 return str(test)
851
Fred Drake02538202001-03-21 18:09:46 +0000852 def startTest(self, test):
Benjamin Peterson52baa292009-03-24 00:56:30 +0000853 super(_TextTestResult, self).startTest(test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000854 if self.showAll:
855 self.stream.write(self.getDescription(test))
856 self.stream.write(" ... ")
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000857 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +0000858
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000859 def addSuccess(self, test):
Benjamin Peterson52baa292009-03-24 00:56:30 +0000860 super(_TextTestResult, self).addSuccess(test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000861 if self.showAll:
Fred Drake02538202001-03-21 18:09:46 +0000862 self.stream.writeln("ok")
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000863 elif self.dots:
864 self.stream.write('.')
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000865 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +0000866
867 def addError(self, test, err):
Benjamin Peterson52baa292009-03-24 00:56:30 +0000868 super(_TextTestResult, self).addError(test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000869 if self.showAll:
870 self.stream.writeln("ERROR")
871 elif self.dots:
872 self.stream.write('E')
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000873 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +0000874
875 def addFailure(self, test, err):
Benjamin Peterson52baa292009-03-24 00:56:30 +0000876 super(_TextTestResult, self).addFailure(test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000877 if self.showAll:
878 self.stream.writeln("FAIL")
879 elif self.dots:
880 self.stream.write('F')
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000881 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +0000882
Benjamin Peterson5254c042009-03-23 22:25:03 +0000883 def addSkip(self, test, reason):
Benjamin Peterson52baa292009-03-24 00:56:30 +0000884 super(_TextTestResult, self).addSkip(test, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000885 if self.showAll:
886 self.stream.writeln("skipped {0!r}".format(reason))
887 elif self.dots:
888 self.stream.write("s")
889 self.stream.flush()
890
891 def addExpectedFailure(self, test, err):
Benjamin Peterson52baa292009-03-24 00:56:30 +0000892 super(_TextTestResult, self).addExpectedFailure(test, err)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000893 if self.showAll:
894 self.stream.writeln("expected failure")
895 elif self.dots:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000896 self.stream.write("x")
Benjamin Peterson5254c042009-03-23 22:25:03 +0000897 self.stream.flush()
898
899 def addUnexpectedSuccess(self, test):
Benjamin Peterson52baa292009-03-24 00:56:30 +0000900 super(_TextTestResult, self).addUnexpectedSuccess(test)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000901 if self.showAll:
902 self.stream.writeln("unexpected success")
903 elif self.dots:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000904 self.stream.write("u")
Benjamin Peterson5254c042009-03-23 22:25:03 +0000905 self.stream.flush()
906
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000907 def printErrors(self):
908 if self.dots or self.showAll:
Fred Drake02538202001-03-21 18:09:46 +0000909 self.stream.writeln()
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000910 self.printErrorList('ERROR', self.errors)
911 self.printErrorList('FAIL', self.failures)
912
913 def printErrorList(self, flavour, errors):
914 for test, err in errors:
915 self.stream.writeln(self.separator1)
916 self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
917 self.stream.writeln(self.separator2)
Steve Purcell7b065702001-09-06 08:24:40 +0000918 self.stream.writeln("%s" % err)
Fred Drake02538202001-03-21 18:09:46 +0000919
920
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000921class TextTestRunner(object):
Fred Drake02538202001-03-21 18:09:46 +0000922 """A test runner class that displays results in textual form.
Tim Petersa19a1682001-03-29 04:36:09 +0000923
Fred Drake02538202001-03-21 18:09:46 +0000924 It prints out the names of tests as they are run, errors as they
925 occur, and a summary of the results at the end of the test run.
926 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000927 def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
Fred Drake02538202001-03-21 18:09:46 +0000928 self.stream = _WritelnDecorator(stream)
929 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000930 self.verbosity = verbosity
931
932 def _makeResult(self):
933 return _TextTestResult(self.stream, self.descriptions, self.verbosity)
Fred Drake02538202001-03-21 18:09:46 +0000934
935 def run(self, test):
936 "Run the given test case or test suite."
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000937 result = self._makeResult()
Fred Drake02538202001-03-21 18:09:46 +0000938 startTime = time.time()
939 test(result)
940 stopTime = time.time()
Steve Purcell397b45d2003-10-26 10:41:03 +0000941 timeTaken = stopTime - startTime
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000942 result.printErrors()
943 self.stream.writeln(result.separator2)
Fred Drake02538202001-03-21 18:09:46 +0000944 run = result.testsRun
945 self.stream.writeln("Ran %d test%s in %.3fs" %
Neal Norwitz76165042002-05-31 14:15:11 +0000946 (run, run != 1 and "s" or "", timeTaken))
Fred Drake02538202001-03-21 18:09:46 +0000947 self.stream.writeln()
Benjamin Peterson52baa292009-03-24 00:56:30 +0000948 results = map(len, (result.expectedFailures,
949 result.unexpectedSuccesses,
Benjamin Peterson5254c042009-03-23 22:25:03 +0000950 result.skipped))
Benjamin Peterson52baa292009-03-24 00:56:30 +0000951 expectedFails, unexpectedSuccesses, skipped = results
Benjamin Peterson5254c042009-03-23 22:25:03 +0000952 infos = []
Fred Drake02538202001-03-21 18:09:46 +0000953 if not result.wasSuccessful():
Benjamin Peterson5254c042009-03-23 22:25:03 +0000954 self.stream.write("FAILED")
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000955 failed, errored = len(result.failures), len(result.errors)
Fred Drake02538202001-03-21 18:09:46 +0000956 if failed:
Benjamin Peterson5254c042009-03-23 22:25:03 +0000957 infos.append("failures=%d" % failed)
Fred Drake02538202001-03-21 18:09:46 +0000958 if errored:
Benjamin Peterson5254c042009-03-23 22:25:03 +0000959 infos.append("errors=%d" % errored)
Fred Drake02538202001-03-21 18:09:46 +0000960 else:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000961 self.stream.write("OK")
Benjamin Peterson5254c042009-03-23 22:25:03 +0000962 if skipped:
963 infos.append("skipped=%d" % skipped)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000964 if expectedFails:
965 infos.append("expected failures=%d" % expectedFails)
966 if unexpectedSuccesses:
967 infos.append("unexpected successes=%d" % unexpectedSuccesses)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000968 if infos:
969 self.stream.writeln(" (%s)" % (", ".join(infos),))
Benjamin Petersone549ead2009-03-28 21:42:05 +0000970 else:
971 self.stream.write("\n")
Fred Drake02538202001-03-21 18:09:46 +0000972 return result
Tim Petersa19a1682001-03-29 04:36:09 +0000973
Fred Drake02538202001-03-21 18:09:46 +0000974
Fred Drake02538202001-03-21 18:09:46 +0000975
976##############################################################################
977# Facilities for running tests from the command line
978##############################################################################
979
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000980class TestProgram(object):
Fred Drake02538202001-03-21 18:09:46 +0000981 """A command-line program that runs a set of tests; this is primarily
982 for making test modules conveniently executable.
983 """
984 USAGE = """\
Steve Purcell17a781b2001-04-09 15:37:31 +0000985Usage: %(progName)s [options] [test] [...]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000986
987Options:
988 -h, --help Show this message
989 -v, --verbose Verbose output
990 -q, --quiet Minimal output
Fred Drake02538202001-03-21 18:09:46 +0000991
992Examples:
993 %(progName)s - run default set of tests
994 %(progName)s MyTestSuite - run suite 'MyTestSuite'
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000995 %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
996 %(progName)s MyTestCase - run all 'test*' test methods
Fred Drake02538202001-03-21 18:09:46 +0000997 in MyTestCase
998"""
999 def __init__(self, module='__main__', defaultTest=None,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001000 argv=None, testRunner=TextTestRunner,
1001 testLoader=defaultTestLoader):
Antoine Pitroue7bd8682009-01-09 19:29:16 +00001002 if isinstance(module, str):
Fred Drake02538202001-03-21 18:09:46 +00001003 self.module = __import__(module)
Steve Purcell7e743842003-09-22 11:08:12 +00001004 for part in module.split('.')[1:]:
Fred Drake02538202001-03-21 18:09:46 +00001005 self.module = getattr(self.module, part)
1006 else:
1007 self.module = module
1008 if argv is None:
1009 argv = sys.argv
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001010 self.verbosity = 1
Fred Drake02538202001-03-21 18:09:46 +00001011 self.defaultTest = defaultTest
1012 self.testRunner = testRunner
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001013 self.testLoader = testLoader
Fred Drake02538202001-03-21 18:09:46 +00001014 self.progName = os.path.basename(argv[0])
1015 self.parseArgs(argv)
Fred Drake02538202001-03-21 18:09:46 +00001016 self.runTests()
1017
1018 def usageExit(self, msg=None):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001019 if msg:
1020 print(msg)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001021 print(self.USAGE % self.__dict__)
Fred Drake02538202001-03-21 18:09:46 +00001022 sys.exit(2)
1023
1024 def parseArgs(self, argv):
1025 import getopt
Benjamin Peterson5254c042009-03-23 22:25:03 +00001026 long_opts = ['help','verbose','quiet']
Fred Drake02538202001-03-21 18:09:46 +00001027 try:
Benjamin Peterson5254c042009-03-23 22:25:03 +00001028 options, args = getopt.getopt(argv[1:], 'hHvq', long_opts)
Fred Drake02538202001-03-21 18:09:46 +00001029 for opt, value in options:
1030 if opt in ('-h','-H','--help'):
1031 self.usageExit()
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001032 if opt in ('-q','--quiet'):
1033 self.verbosity = 0
1034 if opt in ('-v','--verbose'):
1035 self.verbosity = 2
Fred Drake02538202001-03-21 18:09:46 +00001036 if len(args) == 0 and self.defaultTest is None:
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001037 self.test = self.testLoader.loadTestsFromModule(self.module)
1038 return
Fred Drake02538202001-03-21 18:09:46 +00001039 if len(args) > 0:
1040 self.testNames = args
1041 else:
1042 self.testNames = (self.defaultTest,)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001043 self.createTests()
Guido van Rossumb940e112007-01-10 16:19:56 +00001044 except getopt.error as msg:
Fred Drake02538202001-03-21 18:09:46 +00001045 self.usageExit(msg)
1046
1047 def createTests(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001048 self.test = self.testLoader.loadTestsFromNames(self.testNames,
1049 self.module)
Fred Drake02538202001-03-21 18:09:46 +00001050
1051 def runTests(self):
Guido van Rossum13257902007-06-07 23:15:56 +00001052 if isinstance(self.testRunner, type):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001053 try:
1054 testRunner = self.testRunner(verbosity=self.verbosity)
1055 except TypeError:
1056 # didn't accept the verbosity argument
1057 testRunner = self.testRunner()
1058 else:
1059 # it is assumed to be a TestRunner instance
1060 testRunner = self.testRunner
1061 result = testRunner.run(self.test)
Tim Petersa19a1682001-03-29 04:36:09 +00001062 sys.exit(not result.wasSuccessful())
Fred Drake02538202001-03-21 18:09:46 +00001063
1064main = TestProgram
1065
1066
1067##############################################################################
1068# Executing this module from the command line
1069##############################################################################
1070
1071if __name__ == "__main__":
1072 main(module=None)