blob: 034a5f0991ce8b768f98dafae2877f1a8894f03b [file] [log] [blame]
Jim Fultonfafd8742004-08-28 15:22:12 +00001"""Test script for unittest.
2
Georg Brandl15c5ce92007-03-07 09:09:40 +00003By Collin Winter <collinw at gmail.com>
4
5Still need testing:
6 TestCase.{assert,fail}* methods (some are tested implicitly)
Jim Fultonfafd8742004-08-28 15:22:12 +00007"""
8
Michael Foordb4a81c82009-05-29 20:33:46 +00009import os
Gregory P. Smith28399852009-03-31 16:54:10 +000010import re
Michael Foordb4a81c82009-05-29 20:33:46 +000011import sys
Georg Brandl15c5ce92007-03-07 09:09:40 +000012from test import test_support
Jim Fultonfafd8742004-08-28 15:22:12 +000013import unittest
Michael Foord829f6b82009-05-02 11:43:06 +000014from unittest import TestCase, TestProgram
Christian Heimesc756d002007-11-27 21:34:01 +000015import types
Michael Foorde2942d02009-04-02 05:51:54 +000016from copy import deepcopy
Michael Foord829f6b82009-05-02 11:43:06 +000017from cStringIO import StringIO
Antoine Pitrou0734c632009-11-10 20:49:30 +000018import pickle
Jim Fultonfafd8742004-08-28 15:22:12 +000019
Michael Foord225a0992010-02-18 20:30:09 +000020
Georg Brandl15c5ce92007-03-07 09:09:40 +000021### Support code
22################################################################
Jim Fultonfafd8742004-08-28 15:22:12 +000023
Michael Foord5ffa3252010-03-07 22:04:55 +000024def resultFactory(*_):
25 return unittest.TestResult()
26
Georg Brandl15c5ce92007-03-07 09:09:40 +000027class LoggingResult(unittest.TestResult):
28 def __init__(self, log):
29 self._events = log
30 super(LoggingResult, self).__init__()
31
32 def startTest(self, test):
33 self._events.append('startTest')
34 super(LoggingResult, self).startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +000035
Michael Foord07ef4872009-05-02 22:43:34 +000036 def startTestRun(self):
37 self._events.append('startTestRun')
38 super(LoggingResult, self).startTestRun()
39
Georg Brandl15c5ce92007-03-07 09:09:40 +000040 def stopTest(self, test):
41 self._events.append('stopTest')
42 super(LoggingResult, self).stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +000043
Michael Foord07ef4872009-05-02 22:43:34 +000044 def stopTestRun(self):
45 self._events.append('stopTestRun')
46 super(LoggingResult, self).stopTestRun()
47
Georg Brandl15c5ce92007-03-07 09:09:40 +000048 def addFailure(self, *args):
49 self._events.append('addFailure')
50 super(LoggingResult, self).addFailure(*args)
Tim Petersea5962f2007-03-12 18:07:52 +000051
Benjamin Peterson692428e2009-03-23 21:50:21 +000052 def addSuccess(self, *args):
53 self._events.append('addSuccess')
54 super(LoggingResult, self).addSuccess(*args)
55
Georg Brandl15c5ce92007-03-07 09:09:40 +000056 def addError(self, *args):
57 self._events.append('addError')
58 super(LoggingResult, self).addError(*args)
59
Benjamin Peterson692428e2009-03-23 21:50:21 +000060 def addSkip(self, *args):
61 self._events.append('addSkip')
62 super(LoggingResult, self).addSkip(*args)
63
64 def addExpectedFailure(self, *args):
65 self._events.append('addExpectedFailure')
66 super(LoggingResult, self).addExpectedFailure(*args)
67
68 def addUnexpectedSuccess(self, *args):
69 self._events.append('addUnexpectedSuccess')
70 super(LoggingResult, self).addUnexpectedSuccess(*args)
71
72
Georg Brandl15c5ce92007-03-07 09:09:40 +000073class TestEquality(object):
Michael Foord345b2fe2009-04-02 03:20:38 +000074 """Used as a mixin for TestCase"""
75
Tim Petersea5962f2007-03-12 18:07:52 +000076 # Check for a valid __eq__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000077 def test_eq(self):
78 for obj_1, obj_2 in self.eq_pairs:
79 self.assertEqual(obj_1, obj_2)
80 self.assertEqual(obj_2, obj_1)
Tim Petersea5962f2007-03-12 18:07:52 +000081
82 # Check for a valid __ne__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000083 def test_ne(self):
84 for obj_1, obj_2 in self.ne_pairs:
Benjamin Peterson6b0032f2009-06-30 23:30:12 +000085 self.assertNotEqual(obj_1, obj_2)
86 self.assertNotEqual(obj_2, obj_1)
Tim Petersea5962f2007-03-12 18:07:52 +000087
Georg Brandl15c5ce92007-03-07 09:09:40 +000088class TestHashing(object):
Michael Foord345b2fe2009-04-02 03:20:38 +000089 """Used as a mixin for TestCase"""
90
Tim Petersea5962f2007-03-12 18:07:52 +000091 # Check for a valid __hash__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000092 def test_hash(self):
93 for obj_1, obj_2 in self.eq_pairs:
94 try:
Gregory P. Smith28399852009-03-31 16:54:10 +000095 if not hash(obj_1) == hash(obj_2):
96 self.fail("%r and %r do not hash equal" % (obj_1, obj_2))
Georg Brandl15c5ce92007-03-07 09:09:40 +000097 except KeyboardInterrupt:
98 raise
Georg Brandl15c5ce92007-03-07 09:09:40 +000099 except Exception, e:
Gregory P. Smith28399852009-03-31 16:54:10 +0000100 self.fail("Problem hashing %r and %r: %s" % (obj_1, obj_2, e))
Tim Petersea5962f2007-03-12 18:07:52 +0000101
Georg Brandl15c5ce92007-03-07 09:09:40 +0000102 for obj_1, obj_2 in self.ne_pairs:
103 try:
Gregory P. Smith28399852009-03-31 16:54:10 +0000104 if hash(obj_1) == hash(obj_2):
105 self.fail("%s and %s hash equal, but shouldn't" %
106 (obj_1, obj_2))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000107 except KeyboardInterrupt:
108 raise
Georg Brandl15c5ce92007-03-07 09:09:40 +0000109 except Exception, e:
110 self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e))
Tim Petersea5962f2007-03-12 18:07:52 +0000111
Georg Brandl15c5ce92007-03-07 09:09:40 +0000112
Benjamin Peterson692428e2009-03-23 21:50:21 +0000113# List subclass we can add attributes to.
114class MyClassSuite(list):
115
Benjamin Peterson176a56c2009-05-25 00:48:58 +0000116 def __init__(self, tests):
Benjamin Peterson692428e2009-03-23 21:50:21 +0000117 super(MyClassSuite, self).__init__(tests)
118
119
Georg Brandl15c5ce92007-03-07 09:09:40 +0000120################################################################
121### /Support code
122
123class Test_TestLoader(TestCase):
124
125 ### Tests for TestLoader.loadTestsFromTestCase
126 ################################################################
127
128 # "Return a suite of all tests cases contained in the TestCase-derived
129 # class testCaseClass"
130 def test_loadTestsFromTestCase(self):
131 class Foo(unittest.TestCase):
132 def test_1(self): pass
133 def test_2(self): pass
134 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000135
Georg Brandl15c5ce92007-03-07 09:09:40 +0000136 tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +0000137
Georg Brandl15c5ce92007-03-07 09:09:40 +0000138 loader = unittest.TestLoader()
139 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +0000140
Georg Brandl15c5ce92007-03-07 09:09:40 +0000141 # "Return a suite of all tests cases contained in the TestCase-derived
142 # class testCaseClass"
143 #
Tim Petersea5962f2007-03-12 18:07:52 +0000144 # Make sure it does the right thing even if no tests were found
Georg Brandl15c5ce92007-03-07 09:09:40 +0000145 def test_loadTestsFromTestCase__no_matches(self):
146 class Foo(unittest.TestCase):
147 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000148
Georg Brandl15c5ce92007-03-07 09:09:40 +0000149 empty_suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +0000150
Georg Brandl15c5ce92007-03-07 09:09:40 +0000151 loader = unittest.TestLoader()
152 self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite)
Tim Petersea5962f2007-03-12 18:07:52 +0000153
Georg Brandl15c5ce92007-03-07 09:09:40 +0000154 # "Return a suite of all tests cases contained in the TestCase-derived
155 # class testCaseClass"
156 #
157 # What happens if loadTestsFromTestCase() is given an object
158 # that isn't a subclass of TestCase? Specifically, what happens
159 # if testCaseClass is a subclass of TestSuite?
160 #
161 # This is checked for specifically in the code, so we better add a
162 # test for it.
163 def test_loadTestsFromTestCase__TestSuite_subclass(self):
164 class NotATestCase(unittest.TestSuite):
165 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000166
Georg Brandl15c5ce92007-03-07 09:09:40 +0000167 loader = unittest.TestLoader()
168 try:
169 loader.loadTestsFromTestCase(NotATestCase)
170 except TypeError:
171 pass
172 else:
173 self.fail('Should raise TypeError')
Tim Petersea5962f2007-03-12 18:07:52 +0000174
Georg Brandl15c5ce92007-03-07 09:09:40 +0000175 # "Return a suite of all tests cases contained in the TestCase-derived
176 # class testCaseClass"
177 #
178 # Make sure loadTestsFromTestCase() picks up the default test method
179 # name (as specified by TestCase), even though the method name does
180 # not match the default TestLoader.testMethodPrefix string
181 def test_loadTestsFromTestCase__default_method_name(self):
182 class Foo(unittest.TestCase):
183 def runTest(self):
184 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000185
Georg Brandl15c5ce92007-03-07 09:09:40 +0000186 loader = unittest.TestLoader()
187 # This has to be false for the test to succeed
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000188 self.assertFalse('runTest'.startswith(loader.testMethodPrefix))
Tim Petersea5962f2007-03-12 18:07:52 +0000189
Georg Brandl15c5ce92007-03-07 09:09:40 +0000190 suite = loader.loadTestsFromTestCase(Foo)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000191 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000192 self.assertEqual(list(suite), [Foo('runTest')])
193
194 ################################################################
195 ### /Tests for TestLoader.loadTestsFromTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000196
Georg Brandl15c5ce92007-03-07 09:09:40 +0000197 ### Tests for TestLoader.loadTestsFromModule
198 ################################################################
199
200 # "This method searches `module` for classes derived from TestCase"
201 def test_loadTestsFromModule__TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000202 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000203 class MyTestCase(unittest.TestCase):
204 def test(self):
205 pass
206 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000207
Georg Brandl15c5ce92007-03-07 09:09:40 +0000208 loader = unittest.TestLoader()
209 suite = loader.loadTestsFromModule(m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000210 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000211
Georg Brandl15c5ce92007-03-07 09:09:40 +0000212 expected = [loader.suiteClass([MyTestCase('test')])]
213 self.assertEqual(list(suite), expected)
Tim Petersea5962f2007-03-12 18:07:52 +0000214
Georg Brandl15c5ce92007-03-07 09:09:40 +0000215 # "This method searches `module` for classes derived from TestCase"
Tim Petersea5962f2007-03-12 18:07:52 +0000216 #
Georg Brandl15c5ce92007-03-07 09:09:40 +0000217 # What happens if no tests are found (no TestCase instances)?
218 def test_loadTestsFromModule__no_TestCase_instances(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000219 m = types.ModuleType('m')
Tim Petersea5962f2007-03-12 18:07:52 +0000220
Georg Brandl15c5ce92007-03-07 09:09:40 +0000221 loader = unittest.TestLoader()
222 suite = loader.loadTestsFromModule(m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000223 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000224 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000225
Georg Brandl15c5ce92007-03-07 09:09:40 +0000226 # "This method searches `module` for classes derived from TestCase"
227 #
Tim Petersea5962f2007-03-12 18:07:52 +0000228 # What happens if no tests are found (TestCases instances, but no tests)?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000229 def test_loadTestsFromModule__no_TestCase_tests(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000230 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000231 class MyTestCase(unittest.TestCase):
232 pass
233 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000234
Georg Brandl15c5ce92007-03-07 09:09:40 +0000235 loader = unittest.TestLoader()
236 suite = loader.loadTestsFromModule(m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000237 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000238
Georg Brandl15c5ce92007-03-07 09:09:40 +0000239 self.assertEqual(list(suite), [loader.suiteClass()])
Tim Petersea5962f2007-03-12 18:07:52 +0000240
Georg Brandl15c5ce92007-03-07 09:09:40 +0000241 # "This method searches `module` for classes derived from TestCase"s
242 #
243 # What happens if loadTestsFromModule() is given something other
244 # than a module?
245 #
246 # XXX Currently, it succeeds anyway. This flexibility
247 # should either be documented or loadTestsFromModule() should
248 # raise a TypeError
249 #
250 # XXX Certain people are using this behaviour. We'll add a test for it
251 def test_loadTestsFromModule__not_a_module(self):
252 class MyTestCase(unittest.TestCase):
253 def test(self):
254 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000255
Georg Brandl15c5ce92007-03-07 09:09:40 +0000256 class NotAModule(object):
257 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000258
Georg Brandl15c5ce92007-03-07 09:09:40 +0000259 loader = unittest.TestLoader()
260 suite = loader.loadTestsFromModule(NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000261
Georg Brandl15c5ce92007-03-07 09:09:40 +0000262 reference = [unittest.TestSuite([MyTestCase('test')])]
263 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000264
Michael Foordb4a81c82009-05-29 20:33:46 +0000265
266 # Check that loadTestsFromModule honors (or not) a module
267 # with a load_tests function.
268 def test_loadTestsFromModule__load_tests(self):
269 m = types.ModuleType('m')
270 class MyTestCase(unittest.TestCase):
271 def test(self):
272 pass
273 m.testcase_1 = MyTestCase
274
275 load_tests_args = []
276 def load_tests(loader, tests, pattern):
Michael Foord08770602010-02-06 00:22:26 +0000277 self.assertIsInstance(tests, unittest.TestSuite)
Michael Foordb4a81c82009-05-29 20:33:46 +0000278 load_tests_args.extend((loader, tests, pattern))
279 return tests
280 m.load_tests = load_tests
281
282 loader = unittest.TestLoader()
283 suite = loader.loadTestsFromModule(m)
Michael Foord08770602010-02-06 00:22:26 +0000284 self.assertIsInstance(suite, unittest.TestSuite)
Michael Foordb4a81c82009-05-29 20:33:46 +0000285 self.assertEquals(load_tests_args, [loader, suite, None])
286
287 load_tests_args = []
288 suite = loader.loadTestsFromModule(m, use_load_tests=False)
289 self.assertEquals(load_tests_args, [])
290
Michael Foord73dbe042010-03-21 00:53:39 +0000291 def test_loadTestsFromModule__faulty_load_tests(self):
292 m = types.ModuleType('m')
293
294 def load_tests(loader, tests, pattern):
295 raise TypeError('some failure')
296 m.load_tests = load_tests
297
298 loader = unittest.TestLoader()
299 suite = loader.loadTestsFromModule(m)
300 self.assertIsInstance(suite, unittest.TestSuite)
301 self.assertEqual(suite.countTestCases(), 1)
302 test = list(suite)[0]
303
304 self.assertRaisesRegexp(TypeError, "some failure", test.m)
305
Georg Brandl15c5ce92007-03-07 09:09:40 +0000306 ################################################################
307 ### /Tests for TestLoader.loadTestsFromModule()
Tim Petersea5962f2007-03-12 18:07:52 +0000308
Georg Brandl15c5ce92007-03-07 09:09:40 +0000309 ### Tests for TestLoader.loadTestsFromName()
310 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000311
Georg Brandl15c5ce92007-03-07 09:09:40 +0000312 # "The specifier name is a ``dotted name'' that may resolve either to
313 # a module, a test case class, a TestSuite instance, a test method
314 # within a test case class, or a callable object which returns a
315 # TestCase or TestSuite instance."
316 #
317 # Is ValueError raised in response to an empty name?
318 def test_loadTestsFromName__empty_name(self):
319 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000320
Georg Brandl15c5ce92007-03-07 09:09:40 +0000321 try:
322 loader.loadTestsFromName('')
323 except ValueError, e:
324 self.assertEqual(str(e), "Empty module name")
325 else:
326 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000327
Georg Brandl15c5ce92007-03-07 09:09:40 +0000328 # "The specifier name is a ``dotted name'' that may resolve either to
329 # a module, a test case class, a TestSuite instance, a test method
330 # within a test case class, or a callable object which returns a
331 # TestCase or TestSuite instance."
332 #
Tim Petersea5962f2007-03-12 18:07:52 +0000333 # What happens when the name contains invalid characters?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000334 def test_loadTestsFromName__malformed_name(self):
335 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000336
Georg Brandl15c5ce92007-03-07 09:09:40 +0000337 # XXX Should this raise ValueError or ImportError?
338 try:
339 loader.loadTestsFromName('abc () //')
340 except ValueError:
341 pass
342 except ImportError:
343 pass
344 else:
345 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000346
Georg Brandl15c5ce92007-03-07 09:09:40 +0000347 # "The specifier name is a ``dotted name'' that may resolve ... to a
348 # module"
349 #
Tim Petersea5962f2007-03-12 18:07:52 +0000350 # What happens when a module by that name can't be found?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000351 def test_loadTestsFromName__unknown_module_name(self):
352 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000353
Georg Brandl15c5ce92007-03-07 09:09:40 +0000354 try:
355 loader.loadTestsFromName('sdasfasfasdf')
356 except ImportError, e:
357 self.assertEqual(str(e), "No module named sdasfasfasdf")
358 else:
359 self.fail("TestLoader.loadTestsFromName failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000360
Georg Brandl15c5ce92007-03-07 09:09:40 +0000361 # "The specifier name is a ``dotted name'' that may resolve either to
362 # a module, a test case class, a TestSuite instance, a test method
363 # within a test case class, or a callable object which returns a
364 # TestCase or TestSuite instance."
365 #
Tim Petersea5962f2007-03-12 18:07:52 +0000366 # What happens when the module is found, but the attribute can't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000367 def test_loadTestsFromName__unknown_attr_name(self):
368 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000369
Georg Brandl15c5ce92007-03-07 09:09:40 +0000370 try:
371 loader.loadTestsFromName('unittest.sdasfasfasdf')
372 except AttributeError, e:
373 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
374 else:
375 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000376
Georg Brandl15c5ce92007-03-07 09:09:40 +0000377 # "The specifier name is a ``dotted name'' that may resolve either to
378 # a module, a test case class, a TestSuite instance, a test method
379 # within a test case class, or a callable object which returns a
380 # TestCase or TestSuite instance."
381 #
382 # What happens when we provide the module, but the attribute can't be
383 # found?
384 def test_loadTestsFromName__relative_unknown_name(self):
385 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000386
Georg Brandl15c5ce92007-03-07 09:09:40 +0000387 try:
388 loader.loadTestsFromName('sdasfasfasdf', unittest)
389 except AttributeError, e:
390 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
391 else:
392 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000393
Georg Brandl15c5ce92007-03-07 09:09:40 +0000394 # "The specifier name is a ``dotted name'' that may resolve either to
395 # a module, a test case class, a TestSuite instance, a test method
396 # within a test case class, or a callable object which returns a
397 # TestCase or TestSuite instance."
398 # ...
399 # "The method optionally resolves name relative to the given module"
400 #
401 # Does loadTestsFromName raise ValueError when passed an empty
402 # name relative to a provided module?
403 #
404 # XXX Should probably raise a ValueError instead of an AttributeError
405 def test_loadTestsFromName__relative_empty_name(self):
406 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000407
Georg Brandl15c5ce92007-03-07 09:09:40 +0000408 try:
409 loader.loadTestsFromName('', unittest)
410 except AttributeError, e:
411 pass
412 else:
413 self.fail("Failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000414
Georg Brandl15c5ce92007-03-07 09:09:40 +0000415 # "The specifier name is a ``dotted name'' that may resolve either to
416 # a module, a test case class, a TestSuite instance, a test method
417 # within a test case class, or a callable object which returns a
418 # TestCase or TestSuite instance."
419 # ...
420 # "The method optionally resolves name relative to the given module"
421 #
422 # What happens when an impossible name is given, relative to the provided
423 # `module`?
424 def test_loadTestsFromName__relative_malformed_name(self):
425 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000426
Georg Brandl15c5ce92007-03-07 09:09:40 +0000427 # XXX Should this raise AttributeError or ValueError?
428 try:
429 loader.loadTestsFromName('abc () //', unittest)
430 except ValueError:
431 pass
432 except AttributeError:
433 pass
434 else:
435 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
436
437 # "The method optionally resolves name relative to the given module"
438 #
439 # Does loadTestsFromName raise TypeError when the `module` argument
440 # isn't a module object?
441 #
442 # XXX Accepts the not-a-module object, ignorning the object's type
443 # This should raise an exception or the method name should be changed
444 #
445 # XXX Some people are relying on this, so keep it for now
446 def test_loadTestsFromName__relative_not_a_module(self):
447 class MyTestCase(unittest.TestCase):
448 def test(self):
449 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000450
Georg Brandl15c5ce92007-03-07 09:09:40 +0000451 class NotAModule(object):
452 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000453
Georg Brandl15c5ce92007-03-07 09:09:40 +0000454 loader = unittest.TestLoader()
455 suite = loader.loadTestsFromName('test_2', NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000456
Georg Brandl15c5ce92007-03-07 09:09:40 +0000457 reference = [MyTestCase('test')]
458 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000459
Georg Brandl15c5ce92007-03-07 09:09:40 +0000460 # "The specifier name is a ``dotted name'' that may resolve either to
461 # a module, a test case class, a TestSuite instance, a test method
462 # within a test case class, or a callable object which returns a
463 # TestCase or TestSuite instance."
464 #
465 # Does it raise an exception if the name resolves to an invalid
466 # object?
467 def test_loadTestsFromName__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000468 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000469 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000470
Georg Brandl15c5ce92007-03-07 09:09:40 +0000471 loader = unittest.TestLoader()
472 try:
473 loader.loadTestsFromName('testcase_1', m)
474 except TypeError:
475 pass
476 else:
477 self.fail("Should have raised TypeError")
478
479 # "The specifier name is a ``dotted name'' that may
480 # resolve either to ... a test case class"
481 def test_loadTestsFromName__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000482 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000483 class MyTestCase(unittest.TestCase):
484 def test(self):
485 pass
486 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000487
Georg Brandl15c5ce92007-03-07 09:09:40 +0000488 loader = unittest.TestLoader()
489 suite = loader.loadTestsFromName('testcase_1', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000490 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000491 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000492
Georg Brandl15c5ce92007-03-07 09:09:40 +0000493 # "The specifier name is a ``dotted name'' that may resolve either to
494 # a module, a test case class, a TestSuite instance, a test method
495 # within a test case class, or a callable object which returns a
496 # TestCase or TestSuite instance."
497 def test_loadTestsFromName__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000498 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000499 class MyTestCase(unittest.TestCase):
500 def test(self):
501 pass
502 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000503
Georg Brandl15c5ce92007-03-07 09:09:40 +0000504 loader = unittest.TestLoader()
505 suite = loader.loadTestsFromName('testsuite', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000506 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000507
Georg Brandl15c5ce92007-03-07 09:09:40 +0000508 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000509
Georg Brandl15c5ce92007-03-07 09:09:40 +0000510 # "The specifier name is a ``dotted name'' that may resolve ... to
511 # ... a test method within a test case class"
512 def test_loadTestsFromName__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000513 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000514 class MyTestCase(unittest.TestCase):
515 def test(self):
516 pass
517 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000518
Georg Brandl15c5ce92007-03-07 09:09:40 +0000519 loader = unittest.TestLoader()
520 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000521 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000522
Georg Brandl15c5ce92007-03-07 09:09:40 +0000523 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000524
Georg Brandl15c5ce92007-03-07 09:09:40 +0000525 # "The specifier name is a ``dotted name'' that may resolve either to
526 # a module, a test case class, a TestSuite instance, a test method
527 # within a test case class, or a callable object which returns a
528 # TestCase or TestSuite instance."
529 #
530 # Does loadTestsFromName() raise the proper exception when trying to
531 # resolve "a test method within a test case class" that doesn't exist
532 # for the given name (relative to a provided module)?
533 def test_loadTestsFromName__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000534 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000535 class MyTestCase(unittest.TestCase):
536 def test(self):
537 pass
538 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000539
Georg Brandl15c5ce92007-03-07 09:09:40 +0000540 loader = unittest.TestLoader()
541 try:
542 loader.loadTestsFromName('testcase_1.testfoo', m)
543 except AttributeError, e:
544 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
545 else:
546 self.fail("Failed to raise AttributeError")
547
548 # "The specifier name is a ``dotted name'' that may resolve ... to
549 # ... a callable object which returns a ... TestSuite instance"
550 def test_loadTestsFromName__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000551 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000552 testcase_1 = unittest.FunctionTestCase(lambda: None)
553 testcase_2 = unittest.FunctionTestCase(lambda: None)
554 def return_TestSuite():
555 return unittest.TestSuite([testcase_1, testcase_2])
556 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000557
Georg Brandl15c5ce92007-03-07 09:09:40 +0000558 loader = unittest.TestLoader()
559 suite = loader.loadTestsFromName('return_TestSuite', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000560 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000561 self.assertEqual(list(suite), [testcase_1, testcase_2])
Tim Petersea5962f2007-03-12 18:07:52 +0000562
Georg Brandl15c5ce92007-03-07 09:09:40 +0000563 # "The specifier name is a ``dotted name'' that may resolve ... to
564 # ... a callable object which returns a TestCase ... instance"
565 def test_loadTestsFromName__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000566 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000567 testcase_1 = unittest.FunctionTestCase(lambda: None)
568 def return_TestCase():
569 return testcase_1
570 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000571
Georg Brandl15c5ce92007-03-07 09:09:40 +0000572 loader = unittest.TestLoader()
573 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000574 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000575 self.assertEqual(list(suite), [testcase_1])
Tim Petersea5962f2007-03-12 18:07:52 +0000576
Georg Brandl15c5ce92007-03-07 09:09:40 +0000577 # "The specifier name is a ``dotted name'' that may resolve ... to
Michael Foord5a9719d2009-09-13 17:28:35 +0000578 # ... a callable object which returns a TestCase ... instance"
579 #*****************************************************************
580 #Override the suiteClass attribute to ensure that the suiteClass
581 #attribute is used
582 def test_loadTestsFromName__callable__TestCase_instance_ProperSuiteClass(self):
583 class SubTestSuite(unittest.TestSuite):
584 pass
585 m = types.ModuleType('m')
586 testcase_1 = unittest.FunctionTestCase(lambda: None)
587 def return_TestCase():
588 return testcase_1
589 m.return_TestCase = return_TestCase
590
591 loader = unittest.TestLoader()
592 loader.suiteClass = SubTestSuite
593 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000594 self.assertIsInstance(suite, loader.suiteClass)
Michael Foord5a9719d2009-09-13 17:28:35 +0000595 self.assertEqual(list(suite), [testcase_1])
596
597 # "The specifier name is a ``dotted name'' that may resolve ... to
598 # ... a test method within a test case class"
599 #*****************************************************************
600 #Override the suiteClass attribute to ensure that the suiteClass
601 #attribute is used
602 def test_loadTestsFromName__relative_testmethod_ProperSuiteClass(self):
603 class SubTestSuite(unittest.TestSuite):
604 pass
605 m = types.ModuleType('m')
606 class MyTestCase(unittest.TestCase):
607 def test(self):
608 pass
609 m.testcase_1 = MyTestCase
610
611 loader = unittest.TestLoader()
612 loader.suiteClass=SubTestSuite
613 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000614 self.assertIsInstance(suite, loader.suiteClass)
Michael Foord5a9719d2009-09-13 17:28:35 +0000615
616 self.assertEqual(list(suite), [MyTestCase('test')])
617
618 # "The specifier name is a ``dotted name'' that may resolve ... to
Georg Brandl15c5ce92007-03-07 09:09:40 +0000619 # ... a callable object which returns a TestCase or TestSuite instance"
620 #
621 # What happens if the callable returns something else?
622 def test_loadTestsFromName__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000623 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000624 def return_wrong():
625 return 6
626 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000627
Georg Brandl15c5ce92007-03-07 09:09:40 +0000628 loader = unittest.TestLoader()
629 try:
630 suite = loader.loadTestsFromName('return_wrong', m)
631 except TypeError:
632 pass
633 else:
634 self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000635
Georg Brandl15c5ce92007-03-07 09:09:40 +0000636 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +0000637 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +0000638 def test_loadTestsFromName__module_not_loaded(self):
639 # We're going to try to load this module as a side-effect, so it
640 # better not be loaded before we try.
641 #
642 # Why pick audioop? Google shows it isn't used very often, so there's
643 # a good chance that it won't be imported when this test is run
644 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +0000645
Georg Brandl15c5ce92007-03-07 09:09:40 +0000646 if module_name in sys.modules:
647 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000648
Georg Brandl15c5ce92007-03-07 09:09:40 +0000649 loader = unittest.TestLoader()
650 try:
651 suite = loader.loadTestsFromName(module_name)
652
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000653 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000654 self.assertEqual(list(suite), [])
655
656 # audioop should now be loaded, thanks to loadTestsFromName()
Ezio Melottiaa980582010-01-23 23:04:36 +0000657 self.assertIn(module_name, sys.modules)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000658 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000659 if module_name in sys.modules:
660 del sys.modules[module_name]
Georg Brandl15c5ce92007-03-07 09:09:40 +0000661
662 ################################################################
663 ### Tests for TestLoader.loadTestsFromName()
664
665 ### Tests for TestLoader.loadTestsFromNames()
666 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000667
Georg Brandl15c5ce92007-03-07 09:09:40 +0000668 # "Similar to loadTestsFromName(), but takes a sequence of names rather
669 # than a single name."
670 #
671 # What happens if that sequence of names is empty?
672 def test_loadTestsFromNames__empty_name_list(self):
673 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000674
Georg Brandl15c5ce92007-03-07 09:09:40 +0000675 suite = loader.loadTestsFromNames([])
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000676 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000677 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000678
Georg Brandl15c5ce92007-03-07 09:09:40 +0000679 # "Similar to loadTestsFromName(), but takes a sequence of names rather
680 # than a single name."
681 # ...
682 # "The method optionally resolves name relative to the given module"
683 #
684 # What happens if that sequence of names is empty?
685 #
686 # XXX Should this raise a ValueError or just return an empty TestSuite?
687 def test_loadTestsFromNames__relative_empty_name_list(self):
688 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000689
Georg Brandl15c5ce92007-03-07 09:09:40 +0000690 suite = loader.loadTestsFromNames([], unittest)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000691 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000692 self.assertEqual(list(suite), [])
693
694 # "The specifier name is a ``dotted name'' that may resolve either to
695 # a module, a test case class, a TestSuite instance, a test method
696 # within a test case class, or a callable object which returns a
697 # TestCase or TestSuite instance."
698 #
699 # Is ValueError raised in response to an empty name?
700 def test_loadTestsFromNames__empty_name(self):
701 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000702
Georg Brandl15c5ce92007-03-07 09:09:40 +0000703 try:
704 loader.loadTestsFromNames([''])
705 except ValueError, e:
706 self.assertEqual(str(e), "Empty module name")
707 else:
708 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000709
Georg Brandl15c5ce92007-03-07 09:09:40 +0000710 # "The specifier name is a ``dotted name'' that may resolve either to
711 # a module, a test case class, a TestSuite instance, a test method
712 # within a test case class, or a callable object which returns a
713 # TestCase or TestSuite instance."
714 #
Tim Petersea5962f2007-03-12 18:07:52 +0000715 # What happens when presented with an impossible module name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000716 def test_loadTestsFromNames__malformed_name(self):
717 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000718
Georg Brandl15c5ce92007-03-07 09:09:40 +0000719 # XXX Should this raise ValueError or ImportError?
720 try:
721 loader.loadTestsFromNames(['abc () //'])
722 except ValueError:
723 pass
724 except ImportError:
725 pass
726 else:
727 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000728
Georg Brandl15c5ce92007-03-07 09:09:40 +0000729 # "The specifier name is a ``dotted name'' that may resolve either to
730 # a module, a test case class, a TestSuite instance, a test method
731 # within a test case class, or a callable object which returns a
732 # TestCase or TestSuite instance."
733 #
Tim Petersea5962f2007-03-12 18:07:52 +0000734 # What happens when no module can be found for the given name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000735 def test_loadTestsFromNames__unknown_module_name(self):
736 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000737
Georg Brandl15c5ce92007-03-07 09:09:40 +0000738 try:
739 loader.loadTestsFromNames(['sdasfasfasdf'])
740 except ImportError, e:
741 self.assertEqual(str(e), "No module named sdasfasfasdf")
742 else:
743 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000744
Georg Brandl15c5ce92007-03-07 09:09:40 +0000745 # "The specifier name is a ``dotted name'' that may resolve either to
746 # a module, a test case class, a TestSuite instance, a test method
747 # within a test case class, or a callable object which returns a
748 # TestCase or TestSuite instance."
749 #
Tim Petersea5962f2007-03-12 18:07:52 +0000750 # What happens when the module can be found, but not the attribute?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000751 def test_loadTestsFromNames__unknown_attr_name(self):
752 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000753
Georg Brandl15c5ce92007-03-07 09:09:40 +0000754 try:
755 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
756 except AttributeError, e:
757 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
758 else:
759 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000760
Georg Brandl15c5ce92007-03-07 09:09:40 +0000761 # "The specifier name is a ``dotted name'' that may resolve either to
762 # a module, a test case class, a TestSuite instance, a test method
763 # within a test case class, or a callable object which returns a
764 # TestCase or TestSuite instance."
765 # ...
766 # "The method optionally resolves name relative to the given module"
767 #
768 # What happens when given an unknown attribute on a specified `module`
769 # argument?
770 def test_loadTestsFromNames__unknown_name_relative_1(self):
771 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000772
Georg Brandl15c5ce92007-03-07 09:09:40 +0000773 try:
774 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
775 except AttributeError, e:
776 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
777 else:
778 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000779
Georg Brandl15c5ce92007-03-07 09:09:40 +0000780 # "The specifier name is a ``dotted name'' that may resolve either to
781 # a module, a test case class, a TestSuite instance, a test method
782 # within a test case class, or a callable object which returns a
783 # TestCase or TestSuite instance."
784 # ...
785 # "The method optionally resolves name relative to the given module"
786 #
787 # Do unknown attributes (relative to a provided module) still raise an
Tim Petersea5962f2007-03-12 18:07:52 +0000788 # exception even in the presence of valid attribute names?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000789 def test_loadTestsFromNames__unknown_name_relative_2(self):
790 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000791
Georg Brandl15c5ce92007-03-07 09:09:40 +0000792 try:
793 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
794 except AttributeError, e:
795 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
796 else:
797 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
798
799 # "The specifier name is a ``dotted name'' that may resolve either to
800 # a module, a test case class, a TestSuite instance, a test method
801 # within a test case class, or a callable object which returns a
802 # TestCase or TestSuite instance."
803 # ...
804 # "The method optionally resolves name relative to the given module"
805 #
806 # What happens when faced with the empty string?
807 #
808 # XXX This currently raises AttributeError, though ValueError is probably
809 # more appropriate
810 def test_loadTestsFromNames__relative_empty_name(self):
811 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000812
Georg Brandl15c5ce92007-03-07 09:09:40 +0000813 try:
814 loader.loadTestsFromNames([''], unittest)
815 except AttributeError:
816 pass
817 else:
818 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000819
Georg Brandl15c5ce92007-03-07 09:09:40 +0000820 # "The specifier name is a ``dotted name'' that may resolve either to
821 # a module, a test case class, a TestSuite instance, a test method
822 # within a test case class, or a callable object which returns a
823 # TestCase or TestSuite instance."
824 # ...
825 # "The method optionally resolves name relative to the given module"
826 #
Tim Petersea5962f2007-03-12 18:07:52 +0000827 # What happens when presented with an impossible attribute name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000828 def test_loadTestsFromNames__relative_malformed_name(self):
829 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000830
Georg Brandl15c5ce92007-03-07 09:09:40 +0000831 # XXX Should this raise AttributeError or ValueError?
832 try:
833 loader.loadTestsFromNames(['abc () //'], unittest)
834 except AttributeError:
835 pass
836 except ValueError:
837 pass
838 else:
839 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
840
841 # "The method optionally resolves name relative to the given module"
842 #
843 # Does loadTestsFromNames() make sure the provided `module` is in fact
844 # a module?
845 #
846 # XXX This validation is currently not done. This flexibility should
847 # either be documented or a TypeError should be raised.
848 def test_loadTestsFromNames__relative_not_a_module(self):
849 class MyTestCase(unittest.TestCase):
850 def test(self):
851 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000852
Georg Brandl15c5ce92007-03-07 09:09:40 +0000853 class NotAModule(object):
854 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000855
Georg Brandl15c5ce92007-03-07 09:09:40 +0000856 loader = unittest.TestLoader()
857 suite = loader.loadTestsFromNames(['test_2'], NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000858
Georg Brandl15c5ce92007-03-07 09:09:40 +0000859 reference = [unittest.TestSuite([MyTestCase('test')])]
860 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000861
Georg Brandl15c5ce92007-03-07 09:09:40 +0000862 # "The specifier name is a ``dotted name'' that may resolve either to
863 # a module, a test case class, a TestSuite instance, a test method
864 # within a test case class, or a callable object which returns a
865 # TestCase or TestSuite instance."
866 #
867 # Does it raise an exception if the name resolves to an invalid
868 # object?
869 def test_loadTestsFromNames__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000870 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000871 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000872
Georg Brandl15c5ce92007-03-07 09:09:40 +0000873 loader = unittest.TestLoader()
874 try:
875 loader.loadTestsFromNames(['testcase_1'], m)
876 except TypeError:
877 pass
878 else:
879 self.fail("Should have raised TypeError")
880
881 # "The specifier name is a ``dotted name'' that may resolve ... to
882 # ... a test case class"
883 def test_loadTestsFromNames__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000884 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000885 class MyTestCase(unittest.TestCase):
886 def test(self):
887 pass
888 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000889
Georg Brandl15c5ce92007-03-07 09:09:40 +0000890 loader = unittest.TestLoader()
891 suite = loader.loadTestsFromNames(['testcase_1'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000892 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000893
Georg Brandl15c5ce92007-03-07 09:09:40 +0000894 expected = loader.suiteClass([MyTestCase('test')])
895 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000896
Georg Brandl15c5ce92007-03-07 09:09:40 +0000897 # "The specifier name is a ``dotted name'' that may resolve ... to
898 # ... a TestSuite instance"
899 def test_loadTestsFromNames__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000900 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000901 class MyTestCase(unittest.TestCase):
902 def test(self):
903 pass
904 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000905
Georg Brandl15c5ce92007-03-07 09:09:40 +0000906 loader = unittest.TestLoader()
907 suite = loader.loadTestsFromNames(['testsuite'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000908 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000909
Georg Brandl15c5ce92007-03-07 09:09:40 +0000910 self.assertEqual(list(suite), [m.testsuite])
Tim Petersea5962f2007-03-12 18:07:52 +0000911
Georg Brandl15c5ce92007-03-07 09:09:40 +0000912 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
913 # test method within a test case class"
914 def test_loadTestsFromNames__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000915 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000916 class MyTestCase(unittest.TestCase):
917 def test(self):
918 pass
919 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000920
Georg Brandl15c5ce92007-03-07 09:09:40 +0000921 loader = unittest.TestLoader()
922 suite = loader.loadTestsFromNames(['testcase_1.test'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000923 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000924
Georg Brandl15c5ce92007-03-07 09:09:40 +0000925 ref_suite = unittest.TestSuite([MyTestCase('test')])
926 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000927
Georg Brandl15c5ce92007-03-07 09:09:40 +0000928 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
929 # test method within a test case class"
930 #
931 # Does the method gracefully handle names that initially look like they
Tim Petersea5962f2007-03-12 18:07:52 +0000932 # resolve to "a test method within a test case class" but don't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000933 def test_loadTestsFromNames__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000934 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000935 class MyTestCase(unittest.TestCase):
936 def test(self):
937 pass
938 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000939
Georg Brandl15c5ce92007-03-07 09:09:40 +0000940 loader = unittest.TestLoader()
941 try:
942 loader.loadTestsFromNames(['testcase_1.testfoo'], m)
943 except AttributeError, e:
944 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
945 else:
946 self.fail("Failed to raise AttributeError")
947
948 # "The specifier name is a ``dotted name'' that may resolve ... to
949 # ... a callable object which returns a ... TestSuite instance"
950 def test_loadTestsFromNames__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000951 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000952 testcase_1 = unittest.FunctionTestCase(lambda: None)
953 testcase_2 = unittest.FunctionTestCase(lambda: None)
954 def return_TestSuite():
955 return unittest.TestSuite([testcase_1, testcase_2])
956 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000957
Georg Brandl15c5ce92007-03-07 09:09:40 +0000958 loader = unittest.TestLoader()
959 suite = loader.loadTestsFromNames(['return_TestSuite'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000960 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000961
Georg Brandl15c5ce92007-03-07 09:09:40 +0000962 expected = unittest.TestSuite([testcase_1, testcase_2])
963 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000964
Georg Brandl15c5ce92007-03-07 09:09:40 +0000965 # "The specifier name is a ``dotted name'' that may resolve ... to
966 # ... a callable object which returns a TestCase ... instance"
967 def test_loadTestsFromNames__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000968 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000969 testcase_1 = unittest.FunctionTestCase(lambda: None)
970 def return_TestCase():
971 return testcase_1
972 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000973
Georg Brandl15c5ce92007-03-07 09:09:40 +0000974 loader = unittest.TestLoader()
975 suite = loader.loadTestsFromNames(['return_TestCase'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000976 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000977
Georg Brandl15c5ce92007-03-07 09:09:40 +0000978 ref_suite = unittest.TestSuite([testcase_1])
979 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000980
Georg Brandl15c5ce92007-03-07 09:09:40 +0000981 # "The specifier name is a ``dotted name'' that may resolve ... to
982 # ... a callable object which returns a TestCase or TestSuite instance"
983 #
Tim Petersea5962f2007-03-12 18:07:52 +0000984 # Are staticmethods handled correctly?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000985 def test_loadTestsFromNames__callable__call_staticmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000986 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000987 class Test1(unittest.TestCase):
988 def test(self):
989 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000990
Georg Brandl15c5ce92007-03-07 09:09:40 +0000991 testcase_1 = Test1('test')
992 class Foo(unittest.TestCase):
993 @staticmethod
994 def foo():
995 return testcase_1
996 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +0000997
Georg Brandl15c5ce92007-03-07 09:09:40 +0000998 loader = unittest.TestLoader()
999 suite = loader.loadTestsFromNames(['Foo.foo'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001000 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +00001001
Georg Brandl15c5ce92007-03-07 09:09:40 +00001002 ref_suite = unittest.TestSuite([testcase_1])
1003 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +00001004
Georg Brandl15c5ce92007-03-07 09:09:40 +00001005 # "The specifier name is a ``dotted name'' that may resolve ... to
1006 # ... a callable object which returns a TestCase or TestSuite instance"
1007 #
1008 # What happens when the callable returns something else?
1009 def test_loadTestsFromNames__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001010 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001011 def return_wrong():
1012 return 6
1013 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +00001014
Georg Brandl15c5ce92007-03-07 09:09:40 +00001015 loader = unittest.TestLoader()
1016 try:
1017 suite = loader.loadTestsFromNames(['return_wrong'], m)
1018 except TypeError:
1019 pass
1020 else:
1021 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +00001022
Georg Brandl15c5ce92007-03-07 09:09:40 +00001023 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +00001024 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001025 def test_loadTestsFromNames__module_not_loaded(self):
1026 # We're going to try to load this module as a side-effect, so it
1027 # better not be loaded before we try.
1028 #
1029 # Why pick audioop? Google shows it isn't used very often, so there's
1030 # a good chance that it won't be imported when this test is run
1031 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +00001032
Georg Brandl15c5ce92007-03-07 09:09:40 +00001033 if module_name in sys.modules:
1034 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +00001035
Georg Brandl15c5ce92007-03-07 09:09:40 +00001036 loader = unittest.TestLoader()
1037 try:
1038 suite = loader.loadTestsFromNames([module_name])
1039
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001040 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +00001041 self.assertEqual(list(suite), [unittest.TestSuite()])
1042
1043 # audioop should now be loaded, thanks to loadTestsFromName()
Ezio Melottiaa980582010-01-23 23:04:36 +00001044 self.assertIn(module_name, sys.modules)
Georg Brandl15c5ce92007-03-07 09:09:40 +00001045 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +00001046 if module_name in sys.modules:
1047 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +00001048
Georg Brandl15c5ce92007-03-07 09:09:40 +00001049 ################################################################
1050 ### /Tests for TestLoader.loadTestsFromNames()
1051
1052 ### Tests for TestLoader.getTestCaseNames()
1053 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001054
Georg Brandl15c5ce92007-03-07 09:09:40 +00001055 # "Return a sorted sequence of method names found within testCaseClass"
1056 #
1057 # Test.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +00001058 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +00001059 def test_getTestCaseNames(self):
1060 class Test(unittest.TestCase):
1061 def test_1(self): pass
1062 def test_2(self): pass
1063 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001064
Georg Brandl15c5ce92007-03-07 09:09:40 +00001065 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001066
Georg Brandl15c5ce92007-03-07 09:09:40 +00001067 self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])
Tim Petersea5962f2007-03-12 18:07:52 +00001068
Georg Brandl15c5ce92007-03-07 09:09:40 +00001069 # "Return a sorted sequence of method names found within testCaseClass"
1070 #
Tim Petersea5962f2007-03-12 18:07:52 +00001071 # Does getTestCaseNames() behave appropriately if no tests are found?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001072 def test_getTestCaseNames__no_tests(self):
1073 class Test(unittest.TestCase):
1074 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001075
Georg Brandl15c5ce92007-03-07 09:09:40 +00001076 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001077
Georg Brandl15c5ce92007-03-07 09:09:40 +00001078 self.assertEqual(loader.getTestCaseNames(Test), [])
Tim Petersea5962f2007-03-12 18:07:52 +00001079
Georg Brandl15c5ce92007-03-07 09:09:40 +00001080 # "Return a sorted sequence of method names found within testCaseClass"
1081 #
1082 # Are not-TestCases handled gracefully?
1083 #
1084 # XXX This should raise a TypeError, not return a list
1085 #
1086 # XXX It's too late in the 2.5 release cycle to fix this, but it should
1087 # probably be revisited for 2.6
1088 def test_getTestCaseNames__not_a_TestCase(self):
1089 class BadCase(int):
1090 def test_foo(self):
1091 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001092
Georg Brandl15c5ce92007-03-07 09:09:40 +00001093 loader = unittest.TestLoader()
1094 names = loader.getTestCaseNames(BadCase)
Tim Petersea5962f2007-03-12 18:07:52 +00001095
Georg Brandl15c5ce92007-03-07 09:09:40 +00001096 self.assertEqual(names, ['test_foo'])
Tim Petersea5962f2007-03-12 18:07:52 +00001097
Georg Brandl15c5ce92007-03-07 09:09:40 +00001098 # "Return a sorted sequence of method names found within testCaseClass"
1099 #
1100 # Make sure inherited names are handled.
1101 #
1102 # TestP.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +00001103 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +00001104 def test_getTestCaseNames__inheritance(self):
1105 class TestP(unittest.TestCase):
1106 def test_1(self): pass
1107 def test_2(self): pass
1108 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001109
Georg Brandl15c5ce92007-03-07 09:09:40 +00001110 class TestC(TestP):
1111 def test_1(self): pass
1112 def test_3(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001113
Georg Brandl15c5ce92007-03-07 09:09:40 +00001114 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001115
Georg Brandl15c5ce92007-03-07 09:09:40 +00001116 names = ['test_1', 'test_2', 'test_3']
1117 self.assertEqual(loader.getTestCaseNames(TestC), names)
Tim Petersea5962f2007-03-12 18:07:52 +00001118
1119 ################################################################
Georg Brandl15c5ce92007-03-07 09:09:40 +00001120 ### /Tests for TestLoader.getTestCaseNames()
1121
1122 ### Tests for TestLoader.testMethodPrefix
1123 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001124
Georg Brandl15c5ce92007-03-07 09:09:40 +00001125 # "String giving the prefix of method names which will be interpreted as
1126 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001127 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001128 # Implicit in the documentation is that testMethodPrefix is respected by
1129 # all loadTestsFrom* methods.
1130 def test_testMethodPrefix__loadTestsFromTestCase(self):
1131 class Foo(unittest.TestCase):
1132 def test_1(self): pass
1133 def test_2(self): pass
1134 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001135
Georg Brandl15c5ce92007-03-07 09:09:40 +00001136 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1137 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001138
Georg Brandl15c5ce92007-03-07 09:09:40 +00001139 loader = unittest.TestLoader()
1140 loader.testMethodPrefix = 'foo'
1141 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
1142
1143 loader.testMethodPrefix = 'test'
1144 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001145
Georg Brandl15c5ce92007-03-07 09:09:40 +00001146 # "String giving the prefix of method names which will be interpreted as
1147 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001148 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001149 # Implicit in the documentation is that testMethodPrefix is respected by
1150 # all loadTestsFrom* methods.
1151 def test_testMethodPrefix__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001152 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001153 class Foo(unittest.TestCase):
1154 def test_1(self): pass
1155 def test_2(self): pass
1156 def foo_bar(self): pass
1157 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001158
Georg Brandl15c5ce92007-03-07 09:09:40 +00001159 tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
1160 tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]
Tim Petersea5962f2007-03-12 18:07:52 +00001161
Georg Brandl15c5ce92007-03-07 09:09:40 +00001162 loader = unittest.TestLoader()
1163 loader.testMethodPrefix = 'foo'
1164 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
1165
1166 loader.testMethodPrefix = 'test'
1167 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001168
Georg Brandl15c5ce92007-03-07 09:09:40 +00001169 # "String giving the prefix of method names which will be interpreted as
1170 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001171 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001172 # Implicit in the documentation is that testMethodPrefix is respected by
1173 # all loadTestsFrom* methods.
1174 def test_testMethodPrefix__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001175 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001176 class Foo(unittest.TestCase):
1177 def test_1(self): pass
1178 def test_2(self): pass
1179 def foo_bar(self): pass
1180 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001181
Georg Brandl15c5ce92007-03-07 09:09:40 +00001182 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1183 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001184
Georg Brandl15c5ce92007-03-07 09:09:40 +00001185 loader = unittest.TestLoader()
1186 loader.testMethodPrefix = 'foo'
1187 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
1188
1189 loader.testMethodPrefix = 'test'
1190 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001191
Georg Brandl15c5ce92007-03-07 09:09:40 +00001192 # "String giving the prefix of method names which will be interpreted as
1193 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001194 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001195 # Implicit in the documentation is that testMethodPrefix is respected by
1196 # all loadTestsFrom* methods.
1197 def test_testMethodPrefix__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001198 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001199 class Foo(unittest.TestCase):
1200 def test_1(self): pass
1201 def test_2(self): pass
1202 def foo_bar(self): pass
1203 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001204
Georg Brandl15c5ce92007-03-07 09:09:40 +00001205 tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
1206 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1207 tests_2 = unittest.TestSuite([tests_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001208
Georg Brandl15c5ce92007-03-07 09:09:40 +00001209 loader = unittest.TestLoader()
1210 loader.testMethodPrefix = 'foo'
1211 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)
1212
1213 loader.testMethodPrefix = 'test'
1214 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001215
Georg Brandl15c5ce92007-03-07 09:09:40 +00001216 # "The default value is 'test'"
1217 def test_testMethodPrefix__default_value(self):
1218 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001219 self.assertTrue(loader.testMethodPrefix == 'test')
Tim Petersea5962f2007-03-12 18:07:52 +00001220
Georg Brandl15c5ce92007-03-07 09:09:40 +00001221 ################################################################
1222 ### /Tests for TestLoader.testMethodPrefix
1223
Tim Petersea5962f2007-03-12 18:07:52 +00001224 ### Tests for TestLoader.sortTestMethodsUsing
Georg Brandl15c5ce92007-03-07 09:09:40 +00001225 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001226
Georg Brandl15c5ce92007-03-07 09:09:40 +00001227 # "Function to be used to compare method names when sorting them in
1228 # getTestCaseNames() and all the loadTestsFromX() methods"
1229 def test_sortTestMethodsUsing__loadTestsFromTestCase(self):
1230 def reversed_cmp(x, y):
1231 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001232
Georg Brandl15c5ce92007-03-07 09:09:40 +00001233 class Foo(unittest.TestCase):
1234 def test_1(self): pass
1235 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001236
Georg Brandl15c5ce92007-03-07 09:09:40 +00001237 loader = unittest.TestLoader()
1238 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001239
Georg Brandl15c5ce92007-03-07 09:09:40 +00001240 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1241 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001242
Georg Brandl15c5ce92007-03-07 09:09:40 +00001243 # "Function to be used to compare method names when sorting them in
1244 # getTestCaseNames() and all the loadTestsFromX() methods"
1245 def test_sortTestMethodsUsing__loadTestsFromModule(self):
1246 def reversed_cmp(x, y):
1247 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001248
Christian Heimesc756d002007-11-27 21:34:01 +00001249 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001250 class Foo(unittest.TestCase):
1251 def test_1(self): pass
1252 def test_2(self): pass
1253 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001254
Georg Brandl15c5ce92007-03-07 09:09:40 +00001255 loader = unittest.TestLoader()
1256 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001257
Georg Brandl15c5ce92007-03-07 09:09:40 +00001258 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1259 self.assertEqual(list(loader.loadTestsFromModule(m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001260
Georg Brandl15c5ce92007-03-07 09:09:40 +00001261 # "Function to be used to compare method names when sorting them in
1262 # getTestCaseNames() and all the loadTestsFromX() methods"
1263 def test_sortTestMethodsUsing__loadTestsFromName(self):
1264 def reversed_cmp(x, y):
1265 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001266
Christian Heimesc756d002007-11-27 21:34:01 +00001267 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001268 class Foo(unittest.TestCase):
1269 def test_1(self): pass
1270 def test_2(self): pass
1271 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001272
Georg Brandl15c5ce92007-03-07 09:09:40 +00001273 loader = unittest.TestLoader()
1274 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001275
Georg Brandl15c5ce92007-03-07 09:09:40 +00001276 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1277 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001278
Georg Brandl15c5ce92007-03-07 09:09:40 +00001279 # "Function to be used to compare method names when sorting them in
1280 # getTestCaseNames() and all the loadTestsFromX() methods"
1281 def test_sortTestMethodsUsing__loadTestsFromNames(self):
1282 def reversed_cmp(x, y):
1283 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001284
Christian Heimesc756d002007-11-27 21:34:01 +00001285 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001286 class Foo(unittest.TestCase):
1287 def test_1(self): pass
1288 def test_2(self): pass
1289 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001290
Georg Brandl15c5ce92007-03-07 09:09:40 +00001291 loader = unittest.TestLoader()
1292 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001293
Georg Brandl15c5ce92007-03-07 09:09:40 +00001294 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1295 self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001296
Georg Brandl15c5ce92007-03-07 09:09:40 +00001297 # "Function to be used to compare method names when sorting them in
1298 # getTestCaseNames()"
1299 #
1300 # Does it actually affect getTestCaseNames()?
1301 def test_sortTestMethodsUsing__getTestCaseNames(self):
1302 def reversed_cmp(x, y):
1303 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001304
Georg Brandl15c5ce92007-03-07 09:09:40 +00001305 class Foo(unittest.TestCase):
1306 def test_1(self): pass
1307 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001308
Georg Brandl15c5ce92007-03-07 09:09:40 +00001309 loader = unittest.TestLoader()
1310 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001311
Georg Brandl15c5ce92007-03-07 09:09:40 +00001312 test_names = ['test_2', 'test_1']
1313 self.assertEqual(loader.getTestCaseNames(Foo), test_names)
Tim Petersea5962f2007-03-12 18:07:52 +00001314
Georg Brandl15c5ce92007-03-07 09:09:40 +00001315 # "The default value is the built-in cmp() function"
1316 def test_sortTestMethodsUsing__default_value(self):
1317 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001318 self.assertTrue(loader.sortTestMethodsUsing is cmp)
Tim Petersea5962f2007-03-12 18:07:52 +00001319
Georg Brandl15c5ce92007-03-07 09:09:40 +00001320 # "it can be set to None to disable the sort."
1321 #
1322 # XXX How is this different from reassigning cmp? Are the tests returned
1323 # in a random order or something? This behaviour should die
1324 def test_sortTestMethodsUsing__None(self):
1325 class Foo(unittest.TestCase):
1326 def test_1(self): pass
1327 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001328
Georg Brandl15c5ce92007-03-07 09:09:40 +00001329 loader = unittest.TestLoader()
1330 loader.sortTestMethodsUsing = None
Tim Petersea5962f2007-03-12 18:07:52 +00001331
Georg Brandl15c5ce92007-03-07 09:09:40 +00001332 test_names = ['test_2', 'test_1']
1333 self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))
Tim Petersea5962f2007-03-12 18:07:52 +00001334
Georg Brandl15c5ce92007-03-07 09:09:40 +00001335 ################################################################
1336 ### /Tests for TestLoader.sortTestMethodsUsing
Tim Petersea5962f2007-03-12 18:07:52 +00001337
Georg Brandl15c5ce92007-03-07 09:09:40 +00001338 ### Tests for TestLoader.suiteClass
1339 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001340
Georg Brandl15c5ce92007-03-07 09:09:40 +00001341 # "Callable object that constructs a test suite from a list of tests."
1342 def test_suiteClass__loadTestsFromTestCase(self):
1343 class Foo(unittest.TestCase):
1344 def test_1(self): pass
1345 def test_2(self): pass
1346 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001347
Georg Brandl15c5ce92007-03-07 09:09:40 +00001348 tests = [Foo('test_1'), Foo('test_2')]
1349
1350 loader = unittest.TestLoader()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001351 loader.suiteClass = list
Georg Brandl15c5ce92007-03-07 09:09:40 +00001352 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001353
Georg Brandl15c5ce92007-03-07 09:09:40 +00001354 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001355 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001356 def test_suiteClass__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001357 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001358 class Foo(unittest.TestCase):
1359 def test_1(self): pass
1360 def test_2(self): pass
1361 def foo_bar(self): pass
1362 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001363
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001364 tests = [[Foo('test_1'), Foo('test_2')]]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001365
1366 loader = unittest.TestLoader()
1367 loader.suiteClass = list
1368 self.assertEqual(loader.loadTestsFromModule(m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001369
Georg Brandl15c5ce92007-03-07 09:09:40 +00001370 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001371 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001372 def test_suiteClass__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001373 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001374 class Foo(unittest.TestCase):
1375 def test_1(self): pass
1376 def test_2(self): pass
1377 def foo_bar(self): pass
1378 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001379
Georg Brandl15c5ce92007-03-07 09:09:40 +00001380 tests = [Foo('test_1'), Foo('test_2')]
1381
1382 loader = unittest.TestLoader()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001383 loader.suiteClass = list
Georg Brandl15c5ce92007-03-07 09:09:40 +00001384 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001385
Georg Brandl15c5ce92007-03-07 09:09:40 +00001386 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001387 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001388 def test_suiteClass__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001389 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001390 class Foo(unittest.TestCase):
1391 def test_1(self): pass
1392 def test_2(self): pass
1393 def foo_bar(self): pass
1394 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001395
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001396 tests = [[Foo('test_1'), Foo('test_2')]]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001397
1398 loader = unittest.TestLoader()
1399 loader.suiteClass = list
1400 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001401
Georg Brandl15c5ce92007-03-07 09:09:40 +00001402 # "The default value is the TestSuite class"
1403 def test_suiteClass__default_value(self):
1404 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001405 self.assertTrue(loader.suiteClass is unittest.TestSuite)
Tim Petersea5962f2007-03-12 18:07:52 +00001406
Georg Brandl15c5ce92007-03-07 09:09:40 +00001407 ################################################################
1408 ### /Tests for TestLoader.suiteClass
1409
1410### Support code for Test_TestSuite
1411################################################################
1412
1413class Foo(unittest.TestCase):
1414 def test_1(self): pass
1415 def test_2(self): pass
1416 def test_3(self): pass
1417 def runTest(self): pass
1418
1419def _mk_TestSuite(*names):
1420 return unittest.TestSuite(Foo(n) for n in names)
Tim Petersea5962f2007-03-12 18:07:52 +00001421
Georg Brandl15c5ce92007-03-07 09:09:40 +00001422################################################################
1423### /Support code for Test_TestSuite
1424
1425class Test_TestSuite(TestCase, TestEquality):
1426
1427 ### Set up attributes needed by inherited tests
1428 ################################################################
1429
1430 # Used by TestEquality.test_eq
1431 eq_pairs = [(unittest.TestSuite(), unittest.TestSuite())
1432 ,(unittest.TestSuite(), unittest.TestSuite([]))
1433 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001434
1435 # Used by TestEquality.test_ne
Georg Brandl15c5ce92007-03-07 09:09:40 +00001436 ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1'))
1437 ,(unittest.TestSuite([]), _mk_TestSuite('test_1'))
1438 ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3'))
1439 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001440
Georg Brandl15c5ce92007-03-07 09:09:40 +00001441 ################################################################
1442 ### /Set up attributes needed by inherited tests
1443
1444 ### Tests for TestSuite.__init__
1445 ################################################################
1446
1447 # "class TestSuite([tests])"
1448 #
1449 # The tests iterable should be optional
1450 def test_init__tests_optional(self):
1451 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001452
Georg Brandl15c5ce92007-03-07 09:09:40 +00001453 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001454
Georg Brandl15c5ce92007-03-07 09:09:40 +00001455 # "class TestSuite([tests])"
1456 # ...
1457 # "If tests is given, it must be an iterable of individual test cases
1458 # or other test suites that will be used to build the suite initially"
1459 #
1460 # TestSuite should deal with empty tests iterables by allowing the
Tim Petersea5962f2007-03-12 18:07:52 +00001461 # creation of an empty suite
Georg Brandl15c5ce92007-03-07 09:09:40 +00001462 def test_init__empty_tests(self):
1463 suite = unittest.TestSuite([])
Tim Petersea5962f2007-03-12 18:07:52 +00001464
Georg Brandl15c5ce92007-03-07 09:09:40 +00001465 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001466
Georg Brandl15c5ce92007-03-07 09:09:40 +00001467 # "class TestSuite([tests])"
1468 # ...
1469 # "If tests is given, it must be an iterable of individual test cases
1470 # or other test suites that will be used to build the suite initially"
1471 #
Tim Petersea5962f2007-03-12 18:07:52 +00001472 # TestSuite should allow any iterable to provide tests
Georg Brandl15c5ce92007-03-07 09:09:40 +00001473 def test_init__tests_from_any_iterable(self):
1474 def tests():
1475 yield unittest.FunctionTestCase(lambda: None)
1476 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001477
Georg Brandl15c5ce92007-03-07 09:09:40 +00001478 suite_1 = unittest.TestSuite(tests())
1479 self.assertEqual(suite_1.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001480
Georg Brandl15c5ce92007-03-07 09:09:40 +00001481 suite_2 = unittest.TestSuite(suite_1)
1482 self.assertEqual(suite_2.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001483
Georg Brandl15c5ce92007-03-07 09:09:40 +00001484 suite_3 = unittest.TestSuite(set(suite_1))
1485 self.assertEqual(suite_3.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001486
Georg Brandl15c5ce92007-03-07 09:09:40 +00001487 # "class TestSuite([tests])"
1488 # ...
1489 # "If tests is given, it must be an iterable of individual test cases
1490 # or other test suites that will be used to build the suite initially"
1491 #
1492 # Does TestSuite() also allow other TestSuite() instances to be present
1493 # in the tests iterable?
1494 def test_init__TestSuite_instances_in_tests(self):
1495 def tests():
1496 ftc = unittest.FunctionTestCase(lambda: None)
1497 yield unittest.TestSuite([ftc])
1498 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001499
Georg Brandl15c5ce92007-03-07 09:09:40 +00001500 suite = unittest.TestSuite(tests())
1501 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001502
Georg Brandl15c5ce92007-03-07 09:09:40 +00001503 ################################################################
1504 ### /Tests for TestSuite.__init__
1505
1506 # Container types should support the iter protocol
1507 def test_iter(self):
1508 test1 = unittest.FunctionTestCase(lambda: None)
1509 test2 = unittest.FunctionTestCase(lambda: None)
1510 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001511
Georg Brandl15c5ce92007-03-07 09:09:40 +00001512 self.assertEqual(list(suite), [test1, test2])
Tim Petersea5962f2007-03-12 18:07:52 +00001513
Georg Brandl15c5ce92007-03-07 09:09:40 +00001514 # "Return the number of tests represented by the this test object.
1515 # ...this method is also implemented by the TestSuite class, which can
1516 # return larger [greater than 1] values"
1517 #
Tim Petersea5962f2007-03-12 18:07:52 +00001518 # Presumably an empty TestSuite returns 0?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001519 def test_countTestCases_zero_simple(self):
1520 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001521
Georg Brandl15c5ce92007-03-07 09:09:40 +00001522 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001523
Georg Brandl15c5ce92007-03-07 09:09:40 +00001524 # "Return the number of tests represented by the this test object.
1525 # ...this method is also implemented by the TestSuite class, which can
1526 # return larger [greater than 1] values"
1527 #
1528 # Presumably an empty TestSuite (even if it contains other empty
1529 # TestSuite instances) returns 0?
1530 def test_countTestCases_zero_nested(self):
1531 class Test1(unittest.TestCase):
1532 def test(self):
1533 pass
1534
1535 suite = unittest.TestSuite([unittest.TestSuite()])
Tim Petersea5962f2007-03-12 18:07:52 +00001536
Georg Brandl15c5ce92007-03-07 09:09:40 +00001537 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001538
Georg Brandl15c5ce92007-03-07 09:09:40 +00001539 # "Return the number of tests represented by the this test object.
1540 # ...this method is also implemented by the TestSuite class, which can
1541 # return larger [greater than 1] values"
1542 def test_countTestCases_simple(self):
1543 test1 = unittest.FunctionTestCase(lambda: None)
1544 test2 = unittest.FunctionTestCase(lambda: None)
1545 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001546
Georg Brandl15c5ce92007-03-07 09:09:40 +00001547 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001548
Georg Brandl15c5ce92007-03-07 09:09:40 +00001549 # "Return the number of tests represented by the this test object.
1550 # ...this method is also implemented by the TestSuite class, which can
1551 # return larger [greater than 1] values"
1552 #
1553 # Make sure this holds for nested TestSuite instances, too
1554 def test_countTestCases_nested(self):
1555 class Test1(unittest.TestCase):
1556 def test1(self): pass
1557 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001558
Georg Brandl15c5ce92007-03-07 09:09:40 +00001559 test2 = unittest.FunctionTestCase(lambda: None)
1560 test3 = unittest.FunctionTestCase(lambda: None)
1561 child = unittest.TestSuite((Test1('test2'), test2))
1562 parent = unittest.TestSuite((test3, child, Test1('test1')))
Tim Petersea5962f2007-03-12 18:07:52 +00001563
Georg Brandl15c5ce92007-03-07 09:09:40 +00001564 self.assertEqual(parent.countTestCases(), 4)
Tim Petersea5962f2007-03-12 18:07:52 +00001565
Georg Brandl15c5ce92007-03-07 09:09:40 +00001566 # "Run the tests associated with this suite, collecting the result into
1567 # the test result object passed as result."
1568 #
1569 # And if there are no tests? What then?
1570 def test_run__empty_suite(self):
1571 events = []
1572 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001573
Georg Brandl15c5ce92007-03-07 09:09:40 +00001574 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001575
Georg Brandl15c5ce92007-03-07 09:09:40 +00001576 suite.run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001577
Georg Brandl15c5ce92007-03-07 09:09:40 +00001578 self.assertEqual(events, [])
Tim Petersea5962f2007-03-12 18:07:52 +00001579
Georg Brandl15c5ce92007-03-07 09:09:40 +00001580 # "Note that unlike TestCase.run(), TestSuite.run() requires the
1581 # "result object to be passed in."
1582 def test_run__requires_result(self):
1583 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001584
Georg Brandl15c5ce92007-03-07 09:09:40 +00001585 try:
1586 suite.run()
1587 except TypeError:
1588 pass
1589 else:
1590 self.fail("Failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +00001591
Georg Brandl15c5ce92007-03-07 09:09:40 +00001592 # "Run the tests associated with this suite, collecting the result into
Tim Petersea5962f2007-03-12 18:07:52 +00001593 # the test result object passed as result."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001594 def test_run(self):
1595 events = []
1596 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001597
Georg Brandl15c5ce92007-03-07 09:09:40 +00001598 class LoggingCase(unittest.TestCase):
1599 def run(self, result):
1600 events.append('run %s' % self._testMethodName)
Tim Petersea5962f2007-03-12 18:07:52 +00001601
Georg Brandl15c5ce92007-03-07 09:09:40 +00001602 def test1(self): pass
1603 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001604
1605 tests = [LoggingCase('test1'), LoggingCase('test2')]
1606
Georg Brandl15c5ce92007-03-07 09:09:40 +00001607 unittest.TestSuite(tests).run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001608
Georg Brandl15c5ce92007-03-07 09:09:40 +00001609 self.assertEqual(events, ['run test1', 'run test2'])
Tim Petersea5962f2007-03-12 18:07:52 +00001610
1611 # "Add a TestCase ... to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001612 def test_addTest__TestCase(self):
1613 class Foo(unittest.TestCase):
1614 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001615
Georg Brandl15c5ce92007-03-07 09:09:40 +00001616 test = Foo('test')
1617 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001618
Georg Brandl15c5ce92007-03-07 09:09:40 +00001619 suite.addTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001620
Georg Brandl15c5ce92007-03-07 09:09:40 +00001621 self.assertEqual(suite.countTestCases(), 1)
1622 self.assertEqual(list(suite), [test])
Tim Petersea5962f2007-03-12 18:07:52 +00001623
1624 # "Add a ... TestSuite to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001625 def test_addTest__TestSuite(self):
1626 class Foo(unittest.TestCase):
1627 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001628
Georg Brandl15c5ce92007-03-07 09:09:40 +00001629 suite_2 = unittest.TestSuite([Foo('test')])
Tim Petersea5962f2007-03-12 18:07:52 +00001630
Georg Brandl15c5ce92007-03-07 09:09:40 +00001631 suite = unittest.TestSuite()
1632 suite.addTest(suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001633
Georg Brandl15c5ce92007-03-07 09:09:40 +00001634 self.assertEqual(suite.countTestCases(), 1)
1635 self.assertEqual(list(suite), [suite_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001636
Georg Brandl15c5ce92007-03-07 09:09:40 +00001637 # "Add all the tests from an iterable of TestCase and TestSuite
1638 # instances to this test suite."
Tim Petersea5962f2007-03-12 18:07:52 +00001639 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001640 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001641 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001642 def test_addTests(self):
1643 class Foo(unittest.TestCase):
1644 def test_1(self): pass
1645 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001646
Georg Brandl15c5ce92007-03-07 09:09:40 +00001647 test_1 = Foo('test_1')
1648 test_2 = Foo('test_2')
1649 inner_suite = unittest.TestSuite([test_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001650
Georg Brandl15c5ce92007-03-07 09:09:40 +00001651 def gen():
1652 yield test_1
1653 yield test_2
1654 yield inner_suite
Tim Petersea5962f2007-03-12 18:07:52 +00001655
Georg Brandl15c5ce92007-03-07 09:09:40 +00001656 suite_1 = unittest.TestSuite()
1657 suite_1.addTests(gen())
Tim Petersea5962f2007-03-12 18:07:52 +00001658
Georg Brandl15c5ce92007-03-07 09:09:40 +00001659 self.assertEqual(list(suite_1), list(gen()))
Tim Petersea5962f2007-03-12 18:07:52 +00001660
Georg Brandl15c5ce92007-03-07 09:09:40 +00001661 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001662 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001663 suite_2 = unittest.TestSuite()
1664 for t in gen():
1665 suite_2.addTest(t)
Tim Petersea5962f2007-03-12 18:07:52 +00001666
Georg Brandl15c5ce92007-03-07 09:09:40 +00001667 self.assertEqual(suite_1, suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001668
Georg Brandl15c5ce92007-03-07 09:09:40 +00001669 # "Add all the tests from an iterable of TestCase and TestSuite
1670 # instances to this test suite."
1671 #
Tim Petersea5962f2007-03-12 18:07:52 +00001672 # What happens if it doesn't get an iterable?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001673 def test_addTest__noniterable(self):
1674 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001675
Georg Brandl15c5ce92007-03-07 09:09:40 +00001676 try:
1677 suite.addTests(5)
1678 except TypeError:
1679 pass
1680 else:
1681 self.fail("Failed to raise TypeError")
Georg Brandld9e50262007-03-07 11:54:49 +00001682
1683 def test_addTest__noncallable(self):
1684 suite = unittest.TestSuite()
1685 self.assertRaises(TypeError, suite.addTest, 5)
1686
1687 def test_addTest__casesuiteclass(self):
1688 suite = unittest.TestSuite()
1689 self.assertRaises(TypeError, suite.addTest, Test_TestSuite)
1690 self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)
1691
1692 def test_addTests__string(self):
1693 suite = unittest.TestSuite()
1694 self.assertRaises(TypeError, suite.addTests, "foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001695
1696
Georg Brandl15c5ce92007-03-07 09:09:40 +00001697class Test_FunctionTestCase(TestCase):
Tim Petersea5962f2007-03-12 18:07:52 +00001698
Georg Brandl15c5ce92007-03-07 09:09:40 +00001699 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00001700 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001701 def test_countTestCases(self):
1702 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001703
Georg Brandl15c5ce92007-03-07 09:09:40 +00001704 self.assertEqual(test.countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00001705
Georg Brandl15c5ce92007-03-07 09:09:40 +00001706 # "When a setUp() method is defined, the test runner will run that method
1707 # prior to each test. Likewise, if a tearDown() method is defined, the
1708 # test runner will invoke that method after each test. In the example,
1709 # setUp() was used to create a fresh sequence for each test."
1710 #
1711 # Make sure the proper call order is maintained, even if setUp() raises
1712 # an exception.
1713 def test_run_call_order__error_in_setUp(self):
1714 events = []
1715 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001716
Georg Brandl15c5ce92007-03-07 09:09:40 +00001717 def setUp():
1718 events.append('setUp')
1719 raise RuntimeError('raised by setUp')
1720
1721 def test():
1722 events.append('test')
1723
1724 def tearDown():
1725 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001726
1727 expected = ['startTest', 'setUp', 'addError', 'stopTest']
Georg Brandl15c5ce92007-03-07 09:09:40 +00001728 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1729 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001730
Georg Brandl15c5ce92007-03-07 09:09:40 +00001731 # "When a setUp() method is defined, the test runner will run that method
1732 # prior to each test. Likewise, if a tearDown() method is defined, the
1733 # test runner will invoke that method after each test. In the example,
1734 # setUp() was used to create a fresh sequence for each test."
1735 #
1736 # Make sure the proper call order is maintained, even if the test raises
1737 # an error (as opposed to a failure).
1738 def test_run_call_order__error_in_test(self):
1739 events = []
1740 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001741
Georg Brandl15c5ce92007-03-07 09:09:40 +00001742 def setUp():
1743 events.append('setUp')
1744
1745 def test():
1746 events.append('test')
1747 raise RuntimeError('raised by test')
1748
1749 def tearDown():
1750 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001751
Georg Brandl15c5ce92007-03-07 09:09:40 +00001752 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
1753 'stopTest']
1754 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1755 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001756
Georg Brandl15c5ce92007-03-07 09:09:40 +00001757 # "When a setUp() method is defined, the test runner will run that method
1758 # prior to each test. Likewise, if a tearDown() method is defined, the
1759 # test runner will invoke that method after each test. In the example,
1760 # setUp() was used to create a fresh sequence for each test."
1761 #
1762 # Make sure the proper call order is maintained, even if the test signals
1763 # a failure (as opposed to an error).
1764 def test_run_call_order__failure_in_test(self):
1765 events = []
1766 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001767
Georg Brandl15c5ce92007-03-07 09:09:40 +00001768 def setUp():
1769 events.append('setUp')
1770
1771 def test():
1772 events.append('test')
1773 self.fail('raised by test')
1774
1775 def tearDown():
1776 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001777
Georg Brandl15c5ce92007-03-07 09:09:40 +00001778 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
1779 'stopTest']
1780 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1781 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001782
Georg Brandl15c5ce92007-03-07 09:09:40 +00001783 # "When a setUp() method is defined, the test runner will run that method
1784 # prior to each test. Likewise, if a tearDown() method is defined, the
1785 # test runner will invoke that method after each test. In the example,
1786 # setUp() was used to create a fresh sequence for each test."
1787 #
1788 # Make sure the proper call order is maintained, even if tearDown() raises
1789 # an exception.
1790 def test_run_call_order__error_in_tearDown(self):
1791 events = []
1792 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001793
Georg Brandl15c5ce92007-03-07 09:09:40 +00001794 def setUp():
1795 events.append('setUp')
1796
1797 def test():
1798 events.append('test')
1799
1800 def tearDown():
1801 events.append('tearDown')
1802 raise RuntimeError('raised by tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001803
Georg Brandl15c5ce92007-03-07 09:09:40 +00001804 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
1805 'stopTest']
1806 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1807 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001808
Georg Brandl15c5ce92007-03-07 09:09:40 +00001809 # "Return a string identifying the specific test case."
1810 #
1811 # Because of the vague nature of the docs, I'm not going to lock this
1812 # test down too much. Really all that can be asserted is that the id()
1813 # will be a string (either 8-byte or unicode -- again, because the docs
1814 # just say "string")
1815 def test_id(self):
1816 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001817
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001818 self.assertIsInstance(test.id(), basestring)
Tim Petersea5962f2007-03-12 18:07:52 +00001819
Georg Brandl15c5ce92007-03-07 09:09:40 +00001820 # "Returns a one-line description of the test, or None if no description
1821 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001822 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001823 def test_shortDescription__no_docstring(self):
1824 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001825
Georg Brandl15c5ce92007-03-07 09:09:40 +00001826 self.assertEqual(test.shortDescription(), None)
Tim Petersea5962f2007-03-12 18:07:52 +00001827
Georg Brandl15c5ce92007-03-07 09:09:40 +00001828 # "Returns a one-line description of the test, or None if no description
1829 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001830 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001831 def test_shortDescription__singleline_docstring(self):
1832 desc = "this tests foo"
1833 test = unittest.FunctionTestCase(lambda: None, description=desc)
Tim Petersea5962f2007-03-12 18:07:52 +00001834
Georg Brandl15c5ce92007-03-07 09:09:40 +00001835 self.assertEqual(test.shortDescription(), "this tests foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001836
Georg Brandl15c5ce92007-03-07 09:09:40 +00001837class Test_TestResult(TestCase):
1838 # Note: there are not separate tests for TestResult.wasSuccessful(),
1839 # TestResult.errors, TestResult.failures, TestResult.testsRun or
1840 # TestResult.shouldStop because these only have meaning in terms of
1841 # other TestResult methods.
1842 #
1843 # Accordingly, tests for the aforenamed attributes are incorporated
1844 # in with the tests for the defining methods.
1845 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001846
Georg Brandl15c5ce92007-03-07 09:09:40 +00001847 def test_init(self):
1848 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001849
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001850 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001851 self.assertEqual(len(result.errors), 0)
1852 self.assertEqual(len(result.failures), 0)
1853 self.assertEqual(result.testsRun, 0)
1854 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001855
Georg Brandl15c5ce92007-03-07 09:09:40 +00001856 # "This method can be called to signal that the set of tests being
1857 # run should be aborted by setting the TestResult's shouldStop
Tim Petersea5962f2007-03-12 18:07:52 +00001858 # attribute to True."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001859 def test_stop(self):
1860 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001861
Georg Brandl15c5ce92007-03-07 09:09:40 +00001862 result.stop()
Tim Petersea5962f2007-03-12 18:07:52 +00001863
Georg Brandl15c5ce92007-03-07 09:09:40 +00001864 self.assertEqual(result.shouldStop, True)
Tim Petersea5962f2007-03-12 18:07:52 +00001865
Georg Brandl15c5ce92007-03-07 09:09:40 +00001866 # "Called when the test case test is about to be run. The default
1867 # implementation simply increments the instance's testsRun counter."
1868 def test_startTest(self):
1869 class Foo(unittest.TestCase):
1870 def test_1(self):
1871 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001872
Georg Brandl15c5ce92007-03-07 09:09:40 +00001873 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001874
Georg Brandl15c5ce92007-03-07 09:09:40 +00001875 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001876
Georg Brandl15c5ce92007-03-07 09:09:40 +00001877 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001878
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001879 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001880 self.assertEqual(len(result.errors), 0)
1881 self.assertEqual(len(result.failures), 0)
1882 self.assertEqual(result.testsRun, 1)
1883 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001884
Georg Brandl15c5ce92007-03-07 09:09:40 +00001885 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001886
Georg Brandl15c5ce92007-03-07 09:09:40 +00001887 # "Called after the test case test has been executed, regardless of
1888 # the outcome. The default implementation does nothing."
1889 def test_stopTest(self):
1890 class Foo(unittest.TestCase):
1891 def test_1(self):
1892 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001893
Georg Brandl15c5ce92007-03-07 09:09:40 +00001894 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001895
Georg Brandl15c5ce92007-03-07 09:09:40 +00001896 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001897
Georg Brandl15c5ce92007-03-07 09:09:40 +00001898 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001899
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001900 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001901 self.assertEqual(len(result.errors), 0)
1902 self.assertEqual(len(result.failures), 0)
1903 self.assertEqual(result.testsRun, 1)
1904 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001905
Georg Brandl15c5ce92007-03-07 09:09:40 +00001906 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001907
Georg Brandl15c5ce92007-03-07 09:09:40 +00001908 # Same tests as above; make sure nothing has changed
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001909 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001910 self.assertEqual(len(result.errors), 0)
1911 self.assertEqual(len(result.failures), 0)
1912 self.assertEqual(result.testsRun, 1)
1913 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001914
Michael Foord07ef4872009-05-02 22:43:34 +00001915 # "Called before and after tests are run. The default implementation does nothing."
1916 def test_startTestRun_stopTestRun(self):
1917 result = unittest.TestResult()
1918 result.startTestRun()
1919 result.stopTestRun()
1920
Georg Brandl15c5ce92007-03-07 09:09:40 +00001921 # "addSuccess(test)"
1922 # ...
1923 # "Called when the test case test succeeds"
1924 # ...
1925 # "wasSuccessful() - Returns True if all tests run so far have passed,
1926 # otherwise returns False"
1927 # ...
1928 # "testsRun - The total number of tests run so far."
1929 # ...
1930 # "errors - A list containing 2-tuples of TestCase instances and
1931 # formatted tracebacks. Each tuple represents a test which raised an
1932 # unexpected exception. Contains formatted
1933 # tracebacks instead of sys.exc_info() results."
1934 # ...
1935 # "failures - A list containing 2-tuples of TestCase instances and
1936 # formatted tracebacks. Each tuple represents a test where a failure was
1937 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1938 # methods. Contains formatted tracebacks instead
1939 # of sys.exc_info() results."
1940 def test_addSuccess(self):
1941 class Foo(unittest.TestCase):
1942 def test_1(self):
1943 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001944
Georg Brandl15c5ce92007-03-07 09:09:40 +00001945 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001946
Georg Brandl15c5ce92007-03-07 09:09:40 +00001947 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001948
Georg Brandl15c5ce92007-03-07 09:09:40 +00001949 result.startTest(test)
1950 result.addSuccess(test)
1951 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001952
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001953 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001954 self.assertEqual(len(result.errors), 0)
1955 self.assertEqual(len(result.failures), 0)
1956 self.assertEqual(result.testsRun, 1)
1957 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001958
Georg Brandl15c5ce92007-03-07 09:09:40 +00001959 # "addFailure(test, err)"
1960 # ...
1961 # "Called when the test case test signals a failure. err is a tuple of
1962 # the form returned by sys.exc_info(): (type, value, traceback)"
1963 # ...
1964 # "wasSuccessful() - Returns True if all tests run so far have passed,
1965 # otherwise returns False"
1966 # ...
1967 # "testsRun - The total number of tests run so far."
1968 # ...
1969 # "errors - A list containing 2-tuples of TestCase instances and
1970 # formatted tracebacks. Each tuple represents a test which raised an
1971 # unexpected exception. Contains formatted
1972 # tracebacks instead of sys.exc_info() results."
1973 # ...
1974 # "failures - A list containing 2-tuples of TestCase instances and
1975 # formatted tracebacks. Each tuple represents a test where a failure was
1976 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1977 # methods. Contains formatted tracebacks instead
1978 # of sys.exc_info() results."
1979 def test_addFailure(self):
Georg Brandl15c5ce92007-03-07 09:09:40 +00001980 class Foo(unittest.TestCase):
1981 def test_1(self):
1982 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001983
Georg Brandl15c5ce92007-03-07 09:09:40 +00001984 test = Foo('test_1')
1985 try:
1986 test.fail("foo")
1987 except:
1988 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00001989
Georg Brandl15c5ce92007-03-07 09:09:40 +00001990 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001991
Georg Brandl15c5ce92007-03-07 09:09:40 +00001992 result.startTest(test)
1993 result.addFailure(test, exc_info_tuple)
1994 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001995
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001996 self.assertFalse(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001997 self.assertEqual(len(result.errors), 0)
1998 self.assertEqual(len(result.failures), 1)
1999 self.assertEqual(result.testsRun, 1)
2000 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00002001
Georg Brandl15c5ce92007-03-07 09:09:40 +00002002 test_case, formatted_exc = result.failures[0]
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002003 self.assertTrue(test_case is test)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002004 self.assertIsInstance(formatted_exc, str)
Tim Petersea5962f2007-03-12 18:07:52 +00002005
Georg Brandl15c5ce92007-03-07 09:09:40 +00002006 # "addError(test, err)"
2007 # ...
2008 # "Called when the test case test raises an unexpected exception err
2009 # is a tuple of the form returned by sys.exc_info():
2010 # (type, value, traceback)"
2011 # ...
2012 # "wasSuccessful() - Returns True if all tests run so far have passed,
2013 # otherwise returns False"
2014 # ...
2015 # "testsRun - The total number of tests run so far."
2016 # ...
2017 # "errors - A list containing 2-tuples of TestCase instances and
2018 # formatted tracebacks. Each tuple represents a test which raised an
2019 # unexpected exception. Contains formatted
2020 # tracebacks instead of sys.exc_info() results."
2021 # ...
2022 # "failures - A list containing 2-tuples of TestCase instances and
2023 # formatted tracebacks. Each tuple represents a test where a failure was
2024 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
2025 # methods. Contains formatted tracebacks instead
2026 # of sys.exc_info() results."
2027 def test_addError(self):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002028 class Foo(unittest.TestCase):
2029 def test_1(self):
2030 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002031
Georg Brandl15c5ce92007-03-07 09:09:40 +00002032 test = Foo('test_1')
2033 try:
2034 raise TypeError()
2035 except:
2036 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00002037
Georg Brandl15c5ce92007-03-07 09:09:40 +00002038 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00002039
Georg Brandl15c5ce92007-03-07 09:09:40 +00002040 result.startTest(test)
2041 result.addError(test, exc_info_tuple)
2042 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00002043
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002044 self.assertFalse(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00002045 self.assertEqual(len(result.errors), 1)
2046 self.assertEqual(len(result.failures), 0)
2047 self.assertEqual(result.testsRun, 1)
2048 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00002049
Georg Brandl15c5ce92007-03-07 09:09:40 +00002050 test_case, formatted_exc = result.errors[0]
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002051 self.assertTrue(test_case is test)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002052 self.assertIsInstance(formatted_exc, str)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002053
Michael Foorddb43b5a2010-02-10 14:25:12 +00002054 def testGetDescriptionWithoutDocstring(self):
Michael Foord1c3abf42010-02-10 15:50:58 +00002055 result = unittest.TextTestResult(None, True, 1)
Michael Foorddb43b5a2010-02-10 14:25:12 +00002056 self.assertEqual(
2057 result.getDescription(self),
2058 'testGetDescriptionWithoutDocstring (' + __name__ +
2059 '.Test_TestResult)')
2060
R. David Murrayf28fd242010-02-23 00:24:49 +00002061 @unittest.skipIf(sys.flags.optimize >= 2,
2062 "Docstrings are omitted with -O2 and above")
Michael Foorddb43b5a2010-02-10 14:25:12 +00002063 def testGetDescriptionWithOneLineDocstring(self):
2064 """Tests getDescription() for a method with a docstring."""
Michael Foord1c3abf42010-02-10 15:50:58 +00002065 result = unittest.TextTestResult(None, True, 1)
Michael Foorddb43b5a2010-02-10 14:25:12 +00002066 self.assertEqual(
2067 result.getDescription(self),
2068 ('testGetDescriptionWithOneLineDocstring '
2069 '(' + __name__ + '.Test_TestResult)\n'
2070 'Tests getDescription() for a method with a docstring.'))
2071
R. David Murrayf28fd242010-02-23 00:24:49 +00002072 @unittest.skipIf(sys.flags.optimize >= 2,
2073 "Docstrings are omitted with -O2 and above")
Michael Foorddb43b5a2010-02-10 14:25:12 +00002074 def testGetDescriptionWithMultiLineDocstring(self):
2075 """Tests getDescription() for a method with a longer docstring.
2076 The second line of the docstring.
2077 """
Michael Foord1c3abf42010-02-10 15:50:58 +00002078 result = unittest.TextTestResult(None, True, 1)
Michael Foorddb43b5a2010-02-10 14:25:12 +00002079 self.assertEqual(
2080 result.getDescription(self),
2081 ('testGetDescriptionWithMultiLineDocstring '
2082 '(' + __name__ + '.Test_TestResult)\n'
2083 'Tests getDescription() for a method with a longer '
2084 'docstring.'))
2085
Michael Foordb1aa30f2010-03-22 00:06:30 +00002086 def testStackFrameTrimming(self):
2087 class Frame(object):
2088 class tb_frame(object):
2089 f_globals = {}
2090 result = unittest.TestResult()
2091 self.assertFalse(result._is_relevant_tb_level(Frame))
2092
2093 Frame.tb_frame.f_globals['__unittest'] = True
2094 self.assertTrue(result._is_relevant_tb_level(Frame))
2095
Michael Foord1b9e9532010-03-22 01:01:34 +00002096 def testFailFast(self):
2097 result = unittest.TestResult()
2098 result._exc_info_to_string = lambda *_: ''
2099 result.failfast = True
2100 result.addError(None, None)
2101 self.assertTrue(result.shouldStop)
2102
2103 result = unittest.TestResult()
2104 result._exc_info_to_string = lambda *_: ''
2105 result.failfast = True
2106 result.addFailure(None, None)
2107 self.assertTrue(result.shouldStop)
2108
2109 result = unittest.TestResult()
2110 result._exc_info_to_string = lambda *_: ''
2111 result.failfast = True
2112 result.addUnexpectedSuccess(None)
2113 self.assertTrue(result.shouldStop)
2114
Michael Foord1b9e9532010-03-22 01:01:34 +00002115 def testFailFastSetByRunner(self):
2116 runner = unittest.TextTestRunner(stream=StringIO(), failfast=True)
2117 def test(result):
2118 self.assertTrue(result.failfast)
2119 result = runner.run(test)
2120
2121
Michael Foordae3db0a2010-02-22 23:28:32 +00002122classDict = dict(unittest.TestResult.__dict__)
Michael Foordd99ef9a2010-02-23 17:00:53 +00002123for m in ('addSkip', 'addExpectedFailure', 'addUnexpectedSuccess',
2124 '__init__'):
Michael Foordae3db0a2010-02-22 23:28:32 +00002125 del classDict[m]
Michael Foordd99ef9a2010-02-23 17:00:53 +00002126
2127def __init__(self, stream=None, descriptions=None, verbosity=None):
2128 self.failures = []
2129 self.errors = []
2130 self.testsRun = 0
2131 self.shouldStop = False
2132classDict['__init__'] = __init__
Michael Foordae3db0a2010-02-22 23:28:32 +00002133OldResult = type('OldResult', (object,), classDict)
2134
2135class Test_OldTestResult(unittest.TestCase):
2136
2137 def assertOldResultWarning(self, test, failures):
Florent Xiclunafd37dd42010-03-25 20:39:10 +00002138 with test_support.check_warnings(("TestResult has no add.+ method,",
2139 RuntimeWarning)):
Michael Foordae3db0a2010-02-22 23:28:32 +00002140 result = OldResult()
2141 test.run(result)
2142 self.assertEqual(len(result.failures), failures)
Michael Foordae3db0a2010-02-22 23:28:32 +00002143
2144 def testOldTestResult(self):
2145 class Test(unittest.TestCase):
2146 def testSkip(self):
2147 self.skipTest('foobar')
2148 @unittest.expectedFailure
2149 def testExpectedFail(self):
2150 raise TypeError
2151 @unittest.expectedFailure
2152 def testUnexpectedSuccess(self):
2153 pass
2154
2155 for test_name, should_pass in (('testSkip', True),
2156 ('testExpectedFail', True),
2157 ('testUnexpectedSuccess', False)):
2158 test = Test(test_name)
2159 self.assertOldResultWarning(test, int(not should_pass))
2160
2161 def testOldTestTesultSetup(self):
2162 class Test(unittest.TestCase):
2163 def setUp(self):
2164 self.skipTest('no reason')
2165 def testFoo(self):
2166 pass
2167 self.assertOldResultWarning(Test('testFoo'), 0)
2168
2169 def testOldTestResultClass(self):
2170 @unittest.skip('no reason')
2171 class Test(unittest.TestCase):
2172 def testFoo(self):
2173 pass
2174 self.assertOldResultWarning(Test('testFoo'), 0)
2175
Michael Foordd99ef9a2010-02-23 17:00:53 +00002176 def testOldResultWithRunner(self):
2177 class Test(unittest.TestCase):
2178 def testFoo(self):
2179 pass
2180 runner = unittest.TextTestRunner(resultclass=OldResult,
2181 stream=StringIO())
2182 # This will raise an exception if TextTestRunner can't handle old
2183 # test result objects
2184 runner.run(Test('testFoo'))
Michael Foorddb43b5a2010-02-10 14:25:12 +00002185
Georg Brandl15c5ce92007-03-07 09:09:40 +00002186### Support code for Test_TestCase
2187################################################################
2188
2189class Foo(unittest.TestCase):
2190 def runTest(self): pass
Michael Foorddb003cb2010-03-22 01:02:23 +00002191 def test1(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002192
Georg Brandl15c5ce92007-03-07 09:09:40 +00002193class Bar(Foo):
2194 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002195
Michael Foord1b9e9532010-03-22 01:01:34 +00002196def getLoggingTestCase():
2197 class LoggingTestCase(unittest.TestCase):
2198 """A test case which logs its calls."""
Michael Foord07ef4872009-05-02 22:43:34 +00002199
Michael Foord1b9e9532010-03-22 01:01:34 +00002200 def __init__(self, events):
2201 super(LoggingTestCase, self).__init__('test')
2202 self.events = events
Michael Foord07ef4872009-05-02 22:43:34 +00002203
Michael Foord1b9e9532010-03-22 01:01:34 +00002204 def setUp(self):
2205 self.events.append('setUp')
Michael Foord07ef4872009-05-02 22:43:34 +00002206
Michael Foord1b9e9532010-03-22 01:01:34 +00002207 def test(self):
2208 self.events.append('test')
Michael Foord07ef4872009-05-02 22:43:34 +00002209
Michael Foord1b9e9532010-03-22 01:01:34 +00002210 def tearDown(self):
2211 self.events.append('tearDown')
2212 return LoggingTestCase
Michael Foord07ef4872009-05-02 22:43:34 +00002213
2214class ResultWithNoStartTestRunStopTestRun(object):
2215 """An object honouring TestResult before startTestRun/stopTestRun."""
2216
2217 def __init__(self):
2218 self.failures = []
2219 self.errors = []
2220 self.testsRun = 0
2221 self.skipped = []
2222 self.expectedFailures = []
2223 self.unexpectedSuccesses = []
2224 self.shouldStop = False
2225
2226 def startTest(self, test):
2227 pass
2228
2229 def stopTest(self, test):
2230 pass
2231
2232 def addError(self, test):
2233 pass
2234
2235 def addFailure(self, test):
2236 pass
2237
2238 def addSuccess(self, test):
2239 pass
2240
2241 def wasSuccessful(self):
2242 return True
2243
2244
Georg Brandl15c5ce92007-03-07 09:09:40 +00002245################################################################
2246### /Support code for Test_TestCase
2247
2248class Test_TestCase(TestCase, TestEquality, TestHashing):
2249
2250 ### Set up attributes used by inherited tests
2251 ################################################################
2252
2253 # Used by TestHashing.test_hash and TestEquality.test_eq
2254 eq_pairs = [(Foo('test1'), Foo('test1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002255
Georg Brandl15c5ce92007-03-07 09:09:40 +00002256 # Used by TestEquality.test_ne
2257 ne_pairs = [(Foo('test1'), Foo('runTest'))
2258 ,(Foo('test1'), Bar('test1'))
2259 ,(Foo('test1'), Bar('test2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002260
Georg Brandl15c5ce92007-03-07 09:09:40 +00002261 ################################################################
2262 ### /Set up attributes used by inherited tests
Tim Petersea5962f2007-03-12 18:07:52 +00002263
Georg Brandl15c5ce92007-03-07 09:09:40 +00002264
2265 # "class TestCase([methodName])"
2266 # ...
2267 # "Each instance of TestCase will run a single test method: the
2268 # method named methodName."
2269 # ...
2270 # "methodName defaults to "runTest"."
2271 #
2272 # Make sure it really is optional, and that it defaults to the proper
2273 # thing.
2274 def test_init__no_test_name(self):
2275 class Test(unittest.TestCase):
2276 def runTest(self): raise MyException()
2277 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002278
Georg Brandl15c5ce92007-03-07 09:09:40 +00002279 self.assertEqual(Test().id()[-13:], '.Test.runTest')
Tim Petersea5962f2007-03-12 18:07:52 +00002280
Georg Brandl15c5ce92007-03-07 09:09:40 +00002281 # "class TestCase([methodName])"
2282 # ...
2283 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002284 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002285 def test_init__test_name__valid(self):
2286 class Test(unittest.TestCase):
2287 def runTest(self): raise MyException()
2288 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002289
Georg Brandl15c5ce92007-03-07 09:09:40 +00002290 self.assertEqual(Test('test').id()[-10:], '.Test.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002291
Georg Brandl15c5ce92007-03-07 09:09:40 +00002292 # "class TestCase([methodName])"
2293 # ...
2294 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002295 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002296 def test_init__test_name__invalid(self):
2297 class Test(unittest.TestCase):
2298 def runTest(self): raise MyException()
2299 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002300
Georg Brandl15c5ce92007-03-07 09:09:40 +00002301 try:
2302 Test('testfoo')
2303 except ValueError:
2304 pass
2305 else:
2306 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +00002307
Georg Brandl15c5ce92007-03-07 09:09:40 +00002308 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00002309 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00002310 def test_countTestCases(self):
2311 class Foo(unittest.TestCase):
2312 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002313
Georg Brandl15c5ce92007-03-07 09:09:40 +00002314 self.assertEqual(Foo('test').countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00002315
Georg Brandl15c5ce92007-03-07 09:09:40 +00002316 # "Return the default type of test result object to be used to run this
2317 # test. For TestCase instances, this will always be
2318 # unittest.TestResult; subclasses of TestCase should
2319 # override this as necessary."
2320 def test_defaultTestResult(self):
2321 class Foo(unittest.TestCase):
2322 def runTest(self):
2323 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002324
Georg Brandl15c5ce92007-03-07 09:09:40 +00002325 result = Foo().defaultTestResult()
2326 self.assertEqual(type(result), unittest.TestResult)
2327
2328 # "When a setUp() method is defined, the test runner will run that method
2329 # prior to each test. Likewise, if a tearDown() method is defined, the
2330 # test runner will invoke that method after each test. In the example,
2331 # setUp() was used to create a fresh sequence for each test."
2332 #
2333 # Make sure the proper call order is maintained, even if setUp() raises
2334 # an exception.
2335 def test_run_call_order__error_in_setUp(self):
2336 events = []
2337 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002338
Michael Foord1b9e9532010-03-22 01:01:34 +00002339 class Foo(getLoggingTestCase()):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002340 def setUp(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002341 super(Foo, self).setUp()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002342 raise RuntimeError('raised by Foo.setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002343
Michael Foord07ef4872009-05-02 22:43:34 +00002344 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002345 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2346 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002347
Michael Foord07ef4872009-05-02 22:43:34 +00002348 # "With a temporary result stopTestRun is called when setUp errors.
2349 def test_run_call_order__error_in_setUp_default_result(self):
2350 events = []
2351
Michael Foord1b9e9532010-03-22 01:01:34 +00002352 class Foo(getLoggingTestCase()):
Michael Foord07ef4872009-05-02 22:43:34 +00002353 def defaultTestResult(self):
2354 return LoggingResult(self.events)
2355
2356 def setUp(self):
2357 super(Foo, self).setUp()
2358 raise RuntimeError('raised by Foo.setUp')
2359
2360 Foo(events).run()
2361 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2362 'stopTest', 'stopTestRun']
2363 self.assertEqual(events, expected)
2364
Georg Brandl15c5ce92007-03-07 09:09:40 +00002365 # "When a setUp() method is defined, the test runner will run that method
2366 # prior to each test. Likewise, if a tearDown() method is defined, the
2367 # test runner will invoke that method after each test. In the example,
2368 # setUp() was used to create a fresh sequence for each test."
2369 #
2370 # Make sure the proper call order is maintained, even if the test raises
2371 # an error (as opposed to a failure).
2372 def test_run_call_order__error_in_test(self):
2373 events = []
2374 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002375
Michael Foord1b9e9532010-03-22 01:01:34 +00002376 class Foo(getLoggingTestCase()):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002377 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002378 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002379 raise RuntimeError('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002380
Georg Brandl15c5ce92007-03-07 09:09:40 +00002381 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2382 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002383 Foo(events).run(result)
2384 self.assertEqual(events, expected)
2385
2386 # "With a default result, an error in the test still results in stopTestRun
2387 # being called."
2388 def test_run_call_order__error_in_test_default_result(self):
2389 events = []
2390
Michael Foord1b9e9532010-03-22 01:01:34 +00002391 class Foo(getLoggingTestCase()):
Michael Foord07ef4872009-05-02 22:43:34 +00002392 def defaultTestResult(self):
2393 return LoggingResult(self.events)
2394
2395 def test(self):
2396 super(Foo, self).test()
2397 raise RuntimeError('raised by Foo.test')
2398
2399 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2400 'tearDown', 'stopTest', 'stopTestRun']
2401 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002402 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002403
Georg Brandl15c5ce92007-03-07 09:09:40 +00002404 # "When a setUp() method is defined, the test runner will run that method
2405 # prior to each test. Likewise, if a tearDown() method is defined, the
2406 # test runner will invoke that method after each test. In the example,
2407 # setUp() was used to create a fresh sequence for each test."
2408 #
2409 # Make sure the proper call order is maintained, even if the test signals
2410 # a failure (as opposed to an error).
2411 def test_run_call_order__failure_in_test(self):
2412 events = []
2413 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002414
Michael Foord1b9e9532010-03-22 01:01:34 +00002415 class Foo(getLoggingTestCase()):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002416 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002417 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002418 self.fail('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002419
Georg Brandl15c5ce92007-03-07 09:09:40 +00002420 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2421 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002422 Foo(events).run(result)
2423 self.assertEqual(events, expected)
2424
2425 # "When a test fails with a default result stopTestRun is still called."
2426 def test_run_call_order__failure_in_test_default_result(self):
2427
Michael Foord1b9e9532010-03-22 01:01:34 +00002428 class Foo(getLoggingTestCase()):
Michael Foord07ef4872009-05-02 22:43:34 +00002429 def defaultTestResult(self):
2430 return LoggingResult(self.events)
2431 def test(self):
2432 super(Foo, self).test()
2433 self.fail('raised by Foo.test')
2434
2435 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2436 'tearDown', 'stopTest', 'stopTestRun']
2437 events = []
2438 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002439 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002440
Georg Brandl15c5ce92007-03-07 09:09:40 +00002441 # "When a setUp() method is defined, the test runner will run that method
2442 # prior to each test. Likewise, if a tearDown() method is defined, the
2443 # test runner will invoke that method after each test. In the example,
2444 # setUp() was used to create a fresh sequence for each test."
2445 #
2446 # Make sure the proper call order is maintained, even if tearDown() raises
2447 # an exception.
2448 def test_run_call_order__error_in_tearDown(self):
2449 events = []
2450 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002451
Michael Foord1b9e9532010-03-22 01:01:34 +00002452 class Foo(getLoggingTestCase()):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002453 def tearDown(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002454 super(Foo, self).tearDown()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002455 raise RuntimeError('raised by Foo.tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002456
Michael Foord07ef4872009-05-02 22:43:34 +00002457 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002458 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2459 'stopTest']
2460 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002461
Michael Foord07ef4872009-05-02 22:43:34 +00002462 # "When tearDown errors with a default result stopTestRun is still called."
2463 def test_run_call_order__error_in_tearDown_default_result(self):
2464
Michael Foord1b9e9532010-03-22 01:01:34 +00002465 class Foo(getLoggingTestCase()):
Michael Foord07ef4872009-05-02 22:43:34 +00002466 def defaultTestResult(self):
2467 return LoggingResult(self.events)
2468 def tearDown(self):
2469 super(Foo, self).tearDown()
2470 raise RuntimeError('raised by Foo.tearDown')
2471
2472 events = []
2473 Foo(events).run()
2474 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2475 'addError', 'stopTest', 'stopTestRun']
2476 self.assertEqual(events, expected)
2477
2478 # "TestCase.run() still works when the defaultTestResult is a TestResult
2479 # that does not support startTestRun and stopTestRun.
2480 def test_run_call_order_default_result(self):
2481
2482 class Foo(unittest.TestCase):
2483 def defaultTestResult(self):
2484 return ResultWithNoStartTestRunStopTestRun()
2485 def test(self):
2486 pass
2487
2488 Foo('test').run()
2489
Georg Brandl15c5ce92007-03-07 09:09:40 +00002490 # "This class attribute gives the exception raised by the test() method.
2491 # If a test framework needs to use a specialized exception, possibly to
2492 # carry additional information, it must subclass this exception in
2493 # order to ``play fair'' with the framework. The initial value of this
2494 # attribute is AssertionError"
2495 def test_failureException__default(self):
2496 class Foo(unittest.TestCase):
2497 def test(self):
2498 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002499
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002500 self.assertTrue(Foo('test').failureException is AssertionError)
Tim Petersea5962f2007-03-12 18:07:52 +00002501
Georg Brandl15c5ce92007-03-07 09:09:40 +00002502 # "This class attribute gives the exception raised by the test() method.
2503 # If a test framework needs to use a specialized exception, possibly to
2504 # carry additional information, it must subclass this exception in
2505 # order to ``play fair'' with the framework."
2506 #
2507 # Make sure TestCase.run() respects the designated failureException
2508 def test_failureException__subclassing__explicit_raise(self):
2509 events = []
2510 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002511
Georg Brandl15c5ce92007-03-07 09:09:40 +00002512 class Foo(unittest.TestCase):
2513 def test(self):
2514 raise RuntimeError()
Tim Petersea5962f2007-03-12 18:07:52 +00002515
Georg Brandl15c5ce92007-03-07 09:09:40 +00002516 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002517
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002518 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002519
2520
Georg Brandl15c5ce92007-03-07 09:09:40 +00002521 Foo('test').run(result)
2522 expected = ['startTest', 'addFailure', 'stopTest']
2523 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002524
Georg Brandl15c5ce92007-03-07 09:09:40 +00002525 # "This class attribute gives the exception raised by the test() method.
2526 # If a test framework needs to use a specialized exception, possibly to
2527 # carry additional information, it must subclass this exception in
2528 # order to ``play fair'' with the framework."
2529 #
2530 # Make sure TestCase.run() respects the designated failureException
2531 def test_failureException__subclassing__implicit_raise(self):
2532 events = []
2533 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002534
Georg Brandl15c5ce92007-03-07 09:09:40 +00002535 class Foo(unittest.TestCase):
2536 def test(self):
2537 self.fail("foo")
Tim Petersea5962f2007-03-12 18:07:52 +00002538
Georg Brandl15c5ce92007-03-07 09:09:40 +00002539 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002540
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002541 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002542
2543
Georg Brandl15c5ce92007-03-07 09:09:40 +00002544 Foo('test').run(result)
2545 expected = ['startTest', 'addFailure', 'stopTest']
2546 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002547
2548 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002549 def test_setUp(self):
2550 class Foo(unittest.TestCase):
2551 def runTest(self):
2552 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002553
Georg Brandl15c5ce92007-03-07 09:09:40 +00002554 # ... and nothing should happen
2555 Foo().setUp()
Tim Petersea5962f2007-03-12 18:07:52 +00002556
2557 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002558 def test_tearDown(self):
2559 class Foo(unittest.TestCase):
2560 def runTest(self):
2561 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002562
Georg Brandl15c5ce92007-03-07 09:09:40 +00002563 # ... and nothing should happen
2564 Foo().tearDown()
Tim Petersea5962f2007-03-12 18:07:52 +00002565
Georg Brandl15c5ce92007-03-07 09:09:40 +00002566 # "Return a string identifying the specific test case."
2567 #
2568 # Because of the vague nature of the docs, I'm not going to lock this
2569 # test down too much. Really all that can be asserted is that the id()
2570 # will be a string (either 8-byte or unicode -- again, because the docs
2571 # just say "string")
2572 def test_id(self):
2573 class Foo(unittest.TestCase):
2574 def runTest(self):
2575 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002576
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002577 self.assertIsInstance(Foo().id(), basestring)
Tim Petersea5962f2007-03-12 18:07:52 +00002578
Georg Brandl15c5ce92007-03-07 09:09:40 +00002579 # "If result is omitted or None, a temporary result object is created
Michael Foord07ef4872009-05-02 22:43:34 +00002580 # and used, but is not made available to the caller. As TestCase owns the
2581 # temporary result startTestRun and stopTestRun are called.
2582
Georg Brandl15c5ce92007-03-07 09:09:40 +00002583 def test_run__uses_defaultTestResult(self):
2584 events = []
Tim Petersea5962f2007-03-12 18:07:52 +00002585
Georg Brandl15c5ce92007-03-07 09:09:40 +00002586 class Foo(unittest.TestCase):
2587 def test(self):
2588 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002589
Georg Brandl15c5ce92007-03-07 09:09:40 +00002590 def defaultTestResult(self):
2591 return LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002592
2593 # Make run() find a result object on its own
Georg Brandl15c5ce92007-03-07 09:09:40 +00002594 Foo('test').run()
Tim Petersea5962f2007-03-12 18:07:52 +00002595
Michael Foord07ef4872009-05-02 22:43:34 +00002596 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2597 'stopTest', 'stopTestRun']
Georg Brandl15c5ce92007-03-07 09:09:40 +00002598 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002599
Gregory P. Smith28399852009-03-31 16:54:10 +00002600 def testShortDescriptionWithoutDocstring(self):
Michael Foorddb43b5a2010-02-10 14:25:12 +00002601 self.assertIsNone(self.shortDescription())
Gregory P. Smith28399852009-03-31 16:54:10 +00002602
R. David Murrayf28fd242010-02-23 00:24:49 +00002603 @unittest.skipIf(sys.flags.optimize >= 2,
2604 "Docstrings are omitted with -O2 and above")
Gregory P. Smith28399852009-03-31 16:54:10 +00002605 def testShortDescriptionWithOneLineDocstring(self):
2606 """Tests shortDescription() for a method with a docstring."""
2607 self.assertEqual(
2608 self.shortDescription(),
Michael Foorddb43b5a2010-02-10 14:25:12 +00002609 'Tests shortDescription() for a method with a docstring.')
Gregory P. Smith28399852009-03-31 16:54:10 +00002610
R. David Murrayf28fd242010-02-23 00:24:49 +00002611 @unittest.skipIf(sys.flags.optimize >= 2,
2612 "Docstrings are omitted with -O2 and above")
Gregory P. Smith28399852009-03-31 16:54:10 +00002613 def testShortDescriptionWithMultiLineDocstring(self):
2614 """Tests shortDescription() for a method with a longer docstring.
2615
2616 This method ensures that only the first line of a docstring is
2617 returned used in the short description, no matter how long the
2618 whole thing is.
2619 """
2620 self.assertEqual(
2621 self.shortDescription(),
Gregory P. Smith28399852009-03-31 16:54:10 +00002622 'Tests shortDescription() for a method with a longer '
Michael Foorddb43b5a2010-02-10 14:25:12 +00002623 'docstring.')
Gregory P. Smith28399852009-03-31 16:54:10 +00002624
Gregory P. Smith28399852009-03-31 16:54:10 +00002625 def testAddTypeEqualityFunc(self):
2626 class SadSnake(object):
2627 """Dummy class for test_addTypeEqualityFunc."""
2628 s1, s2 = SadSnake(), SadSnake()
Michael Foord98e7b762010-03-20 03:00:34 +00002629 self.assertNotEqual(s1, s2)
Gregory P. Smith28399852009-03-31 16:54:10 +00002630 def AllSnakesCreatedEqual(a, b, msg=None):
Michael Foord98e7b762010-03-20 03:00:34 +00002631 return type(a) is type(b) is SadSnake
Gregory P. Smith28399852009-03-31 16:54:10 +00002632 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2633 self.assertEqual(s1, s2)
2634 # No this doesn't clean up and remove the SadSnake equality func
2635 # from this TestCase instance but since its a local nothing else
2636 # will ever notice that.
2637
Michael Foordf2dfef12009-04-05 19:19:28 +00002638 def testAssertIs(self):
2639 thing = object()
2640 self.assertIs(thing, thing)
2641 self.assertRaises(self.failureException, self.assertIs, thing, object())
2642
2643 def testAssertIsNot(self):
2644 thing = object()
2645 self.assertIsNot(thing, object())
2646 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2647
Georg Brandlf895cf52009-10-01 20:59:31 +00002648 def testAssertIsInstance(self):
2649 thing = []
2650 self.assertIsInstance(thing, list)
2651 self.assertRaises(self.failureException, self.assertIsInstance,
2652 thing, dict)
2653
2654 def testAssertNotIsInstance(self):
2655 thing = []
2656 self.assertNotIsInstance(thing, dict)
2657 self.assertRaises(self.failureException, self.assertNotIsInstance,
2658 thing, list)
2659
Gregory P. Smith28399852009-03-31 16:54:10 +00002660 def testAssertIn(self):
2661 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2662
2663 self.assertIn('a', 'abc')
2664 self.assertIn(2, [1, 2, 3])
2665 self.assertIn('monkey', animals)
2666
2667 self.assertNotIn('d', 'abc')
2668 self.assertNotIn(0, [1, 2, 3])
2669 self.assertNotIn('otter', animals)
2670
2671 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2672 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2673 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2674 animals)
2675
2676 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2677 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2678 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2679 animals)
2680
2681 def testAssertDictContainsSubset(self):
2682 self.assertDictContainsSubset({}, {})
2683 self.assertDictContainsSubset({}, {'a': 1})
2684 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2685 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2686 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2687
Michael Foord225a0992010-02-18 20:30:09 +00002688 with self.assertRaises(self.failureException):
2689 self.assertDictContainsSubset({1: "one"}, {})
Gregory P. Smith28399852009-03-31 16:54:10 +00002690
Michael Foord225a0992010-02-18 20:30:09 +00002691 with self.assertRaises(self.failureException):
2692 self.assertDictContainsSubset({'a': 2}, {'a': 1})
Gregory P. Smith28399852009-03-31 16:54:10 +00002693
Michael Foord225a0992010-02-18 20:30:09 +00002694 with self.assertRaises(self.failureException):
2695 self.assertDictContainsSubset({'c': 1}, {'a': 1})
Gregory P. Smith28399852009-03-31 16:54:10 +00002696
Michael Foord225a0992010-02-18 20:30:09 +00002697 with self.assertRaises(self.failureException):
2698 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2699
2700 with self.assertRaises(self.failureException):
2701 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2702
Florent Xiclunafd37dd42010-03-25 20:39:10 +00002703 with test_support.check_warnings(("", UnicodeWarning)):
Michael Foord2f677562010-02-21 14:48:59 +00002704 one = ''.join(chr(i) for i in range(255))
2705 # this used to cause a UnicodeDecodeError constructing the failure msg
2706 with self.assertRaises(self.failureException):
2707 self.assertDictContainsSubset({'foo': one}, {'foo': u'\uFFFD'})
Gregory P. Smith28399852009-03-31 16:54:10 +00002708
2709 def testAssertEqual(self):
2710 equal_pairs = [
2711 ((), ()),
2712 ({}, {}),
2713 ([], []),
2714 (set(), set()),
2715 (frozenset(), frozenset())]
2716 for a, b in equal_pairs:
2717 # This mess of try excepts is to test the assertEqual behavior
2718 # itself.
2719 try:
2720 self.assertEqual(a, b)
2721 except self.failureException:
2722 self.fail('assertEqual(%r, %r) failed' % (a, b))
2723 try:
2724 self.assertEqual(a, b, msg='foo')
2725 except self.failureException:
2726 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2727 try:
2728 self.assertEqual(a, b, 'foo')
2729 except self.failureException:
2730 self.fail('assertEqual(%r, %r) with third parameter failed' %
2731 (a, b))
2732
2733 unequal_pairs = [
2734 ((), []),
2735 ({}, set()),
2736 (set([4,1]), frozenset([4,2])),
2737 (frozenset([4,5]), set([2,3])),
2738 (set([3,4]), set([5,4]))]
2739 for a, b in unequal_pairs:
2740 self.assertRaises(self.failureException, self.assertEqual, a, b)
2741 self.assertRaises(self.failureException, self.assertEqual, a, b,
2742 'foo')
2743 self.assertRaises(self.failureException, self.assertEqual, a, b,
2744 msg='foo')
2745
2746 def testEquality(self):
2747 self.assertListEqual([], [])
2748 self.assertTupleEqual((), ())
2749 self.assertSequenceEqual([], ())
2750
2751 a = [0, 'a', []]
2752 b = []
2753 self.assertRaises(unittest.TestCase.failureException,
2754 self.assertListEqual, a, b)
2755 self.assertRaises(unittest.TestCase.failureException,
2756 self.assertListEqual, tuple(a), tuple(b))
2757 self.assertRaises(unittest.TestCase.failureException,
2758 self.assertSequenceEqual, a, tuple(b))
2759
2760 b.extend(a)
2761 self.assertListEqual(a, b)
2762 self.assertTupleEqual(tuple(a), tuple(b))
2763 self.assertSequenceEqual(a, tuple(b))
2764 self.assertSequenceEqual(tuple(a), b)
2765
2766 self.assertRaises(self.failureException, self.assertListEqual,
2767 a, tuple(b))
2768 self.assertRaises(self.failureException, self.assertTupleEqual,
2769 tuple(a), b)
2770 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2771 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2772 tuple(b))
2773 self.assertRaises(self.failureException, self.assertSequenceEqual,
2774 None, tuple(b))
2775 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2776 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2777 self.assertRaises(self.failureException, self.assertSequenceEqual,
2778 1, 1)
2779
2780 self.assertDictEqual({}, {})
2781
2782 c = { 'x': 1 }
2783 d = {}
2784 self.assertRaises(unittest.TestCase.failureException,
2785 self.assertDictEqual, c, d)
2786
2787 d.update(c)
2788 self.assertDictEqual(c, d)
2789
2790 d['x'] = 0
2791 self.assertRaises(unittest.TestCase.failureException,
2792 self.assertDictEqual, c, d, 'These are unequal')
2793
2794 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2795 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2796 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2797
Michael Foord98e7b762010-03-20 03:00:34 +00002798 def testAssertItemsEqual(self):
2799 a = object()
2800 self.assertItemsEqual([1, 2, 3], [3, 2, 1])
2801 self.assertItemsEqual(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2802 self.assertItemsEqual([a, a, 2, 2, 3], (a, 2, 3, a, 2))
2803 self.assertItemsEqual([1, "2", "a", "a"], ["a", "2", True, "a"])
2804 self.assertRaises(self.failureException, self.assertItemsEqual,
2805 [1, 2] + [3] * 100, [1] * 100 + [2, 3])
2806 self.assertRaises(self.failureException, self.assertItemsEqual,
2807 [1, "2", "a", "a"], ["a", "2", True, 1])
2808 self.assertRaises(self.failureException, self.assertItemsEqual,
Gregory P. Smith28399852009-03-31 16:54:10 +00002809 [10], [10, 11])
Michael Foord98e7b762010-03-20 03:00:34 +00002810 self.assertRaises(self.failureException, self.assertItemsEqual,
Gregory P. Smith28399852009-03-31 16:54:10 +00002811 [10, 11], [10])
Michael Foord98e7b762010-03-20 03:00:34 +00002812 self.assertRaises(self.failureException, self.assertItemsEqual,
2813 [10, 11, 10], [10, 11])
Gregory P. Smith28399852009-03-31 16:54:10 +00002814
2815 # Test that sequences of unhashable objects can be tested for sameness:
Michael Foord98e7b762010-03-20 03:00:34 +00002816 self.assertItemsEqual([[1, 2], [3, 4], 0], [False, [3, 4], [1, 2]])
2817 with test_support.check_warnings(quiet=True) as w:
2818 # hashable types, but not orderable
2819 self.assertRaises(self.failureException, self.assertItemsEqual,
2820 [], [divmod, 'x', 1, 5j, 2j, frozenset()])
2821 # comparing dicts raises a py3k warning
2822 self.assertItemsEqual([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2823 # comparing heterogenous non-hashable sequences raises a py3k warning
2824 self.assertItemsEqual([1, 'x', divmod, []], [divmod, [], 'x', 1])
2825 self.assertRaises(self.failureException, self.assertItemsEqual,
2826 [], [divmod, [], 'x', 1, 5j, 2j, set()])
2827 # fail the test if warnings are not silenced
2828 if w.warnings:
2829 self.fail('assertItemsEqual raised a warning: ' +
2830 str(w.warnings[0]))
2831 self.assertRaises(self.failureException, self.assertItemsEqual,
Gregory P. Smith28399852009-03-31 16:54:10 +00002832 [[1]], [[2]])
2833
Michael Foord98e7b762010-03-20 03:00:34 +00002834 # Same elements, but not same sequence length
2835 self.assertRaises(self.failureException, self.assertItemsEqual,
2836 [1, 1, 2], [2, 1])
2837 self.assertRaises(self.failureException, self.assertItemsEqual,
2838 [1, 1, "2", "a", "a"], ["2", "2", True, "a"])
2839 self.assertRaises(self.failureException, self.assertItemsEqual,
2840 [1, {'b': 2}, None, True], [{'b': 2}, True, None])
2841
2842
Gregory P. Smith28399852009-03-31 16:54:10 +00002843 def testAssertSetEqual(self):
2844 set1 = set()
2845 set2 = set()
2846 self.assertSetEqual(set1, set2)
2847
2848 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2849 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2850 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2851 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2852
2853 set1 = set(['a'])
2854 set2 = set()
2855 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2856
2857 set1 = set(['a'])
2858 set2 = set(['a'])
2859 self.assertSetEqual(set1, set2)
2860
2861 set1 = set(['a'])
2862 set2 = set(['a', 'b'])
2863 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2864
2865 set1 = set(['a'])
2866 set2 = frozenset(['a', 'b'])
2867 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2868
2869 set1 = set(['a', 'b'])
2870 set2 = frozenset(['a', 'b'])
2871 self.assertSetEqual(set1, set2)
2872
2873 set1 = set()
2874 set2 = "foo"
2875 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2876 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2877
2878 # make sure any string formatting is tuple-safe
2879 set1 = set([(0, 1), (2, 3)])
2880 set2 = set([(4, 5)])
2881 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2882
2883 def testInequality(self):
2884 # Try ints
2885 self.assertGreater(2, 1)
2886 self.assertGreaterEqual(2, 1)
2887 self.assertGreaterEqual(1, 1)
2888 self.assertLess(1, 2)
2889 self.assertLessEqual(1, 2)
2890 self.assertLessEqual(1, 1)
2891 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2892 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2893 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2894 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2895 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2896 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2897
2898 # Try Floats
2899 self.assertGreater(1.1, 1.0)
2900 self.assertGreaterEqual(1.1, 1.0)
2901 self.assertGreaterEqual(1.0, 1.0)
2902 self.assertLess(1.0, 1.1)
2903 self.assertLessEqual(1.0, 1.1)
2904 self.assertLessEqual(1.0, 1.0)
2905 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2906 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2907 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2908 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2909 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2910 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2911
2912 # Try Strings
2913 self.assertGreater('bug', 'ant')
2914 self.assertGreaterEqual('bug', 'ant')
2915 self.assertGreaterEqual('ant', 'ant')
2916 self.assertLess('ant', 'bug')
2917 self.assertLessEqual('ant', 'bug')
2918 self.assertLessEqual('ant', 'ant')
2919 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2920 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2921 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2922 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2923 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2924 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2925
2926 # Try Unicode
2927 self.assertGreater(u'bug', u'ant')
2928 self.assertGreaterEqual(u'bug', u'ant')
2929 self.assertGreaterEqual(u'ant', u'ant')
2930 self.assertLess(u'ant', u'bug')
2931 self.assertLessEqual(u'ant', u'bug')
2932 self.assertLessEqual(u'ant', u'ant')
2933 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug')
2934 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant')
2935 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2936 u'bug')
2937 self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant')
2938 self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant')
2939 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant')
2940
2941 # Try Mixed String/Unicode
2942 self.assertGreater('bug', u'ant')
2943 self.assertGreater(u'bug', 'ant')
2944 self.assertGreaterEqual('bug', u'ant')
2945 self.assertGreaterEqual(u'bug', 'ant')
2946 self.assertGreaterEqual('ant', u'ant')
2947 self.assertGreaterEqual(u'ant', 'ant')
2948 self.assertLess('ant', u'bug')
2949 self.assertLess(u'ant', 'bug')
2950 self.assertLessEqual('ant', u'bug')
2951 self.assertLessEqual(u'ant', 'bug')
2952 self.assertLessEqual('ant', u'ant')
2953 self.assertLessEqual(u'ant', 'ant')
2954 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug')
2955 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug')
2956 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant')
2957 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant')
2958 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant',
2959 u'bug')
2960 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2961 'bug')
2962 self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant')
2963 self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant')
2964 self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant')
2965 self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant')
2966 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant')
2967 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant')
2968
2969 def testAssertMultiLineEqual(self):
2970 sample_text = b"""\
2971http://www.python.org/doc/2.3/lib/module-unittest.html
2972test case
2973 A test case is the smallest unit of testing. [...]
2974"""
2975 revised_sample_text = b"""\
2976http://www.python.org/doc/2.4.1/lib/module-unittest.html
2977test case
2978 A test case is the smallest unit of testing. [...] You may provide your
2979 own implementation that does not subclass from TestCase, of course.
2980"""
2981 sample_text_error = b"""
2982- http://www.python.org/doc/2.3/lib/module-unittest.html
2983? ^
2984+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2985? ^^^
2986 test case
2987- A test case is the smallest unit of testing. [...]
2988+ A test case is the smallest unit of testing. [...] You may provide your
2989? +++++++++++++++++++++
2990+ own implementation that does not subclass from TestCase, of course.
2991"""
2992
2993 for type_changer in (lambda x: x, lambda x: x.decode('utf8')):
2994 try:
2995 self.assertMultiLineEqual(type_changer(sample_text),
2996 type_changer(revised_sample_text))
2997 except self.failureException, e:
Michael Foordfe6349c2010-02-08 22:41:16 +00002998 # assertMultiLineEqual is hooked up as the default for
2999 # unicode strings - so we can't use it for this check
3000 self.assertTrue(sample_text_error == str(e).encode('utf8'))
Gregory P. Smith28399852009-03-31 16:54:10 +00003001
3002 def testAssertIsNone(self):
3003 self.assertIsNone(None)
3004 self.assertRaises(self.failureException, self.assertIsNone, False)
3005 self.assertIsNotNone('DjZoPloGears on Rails')
3006 self.assertRaises(self.failureException, self.assertIsNotNone, None)
3007
3008 def testAssertRegexpMatches(self):
3009 self.assertRegexpMatches('asdfabasdf', r'ab+')
3010 self.assertRaises(self.failureException, self.assertRegexpMatches,
3011 'saaas', r'aaaa')
3012
3013 def testAssertRaisesRegexp(self):
3014 class ExceptionMock(Exception):
3015 pass
3016
3017 def Stub():
3018 raise ExceptionMock('We expect')
3019
3020 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
3021 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
3022 self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
3023
3024 def testAssertNotRaisesRegexp(self):
3025 self.assertRaisesRegexp(
3026 self.failureException, '^Exception not raised$',
3027 self.assertRaisesRegexp, Exception, re.compile('x'),
3028 lambda: None)
3029 self.assertRaisesRegexp(
3030 self.failureException, '^Exception not raised$',
3031 self.assertRaisesRegexp, Exception, 'x',
3032 lambda: None)
3033 self.assertRaisesRegexp(
3034 self.failureException, '^Exception not raised$',
3035 self.assertRaisesRegexp, Exception, u'x',
3036 lambda: None)
3037
3038 def testAssertRaisesRegexpMismatch(self):
3039 def Stub():
3040 raise Exception('Unexpected')
3041
3042 self.assertRaisesRegexp(
3043 self.failureException,
3044 r'"\^Expected\$" does not match "Unexpected"',
3045 self.assertRaisesRegexp, Exception, '^Expected$',
3046 Stub)
3047 self.assertRaisesRegexp(
3048 self.failureException,
3049 r'"\^Expected\$" does not match "Unexpected"',
3050 self.assertRaisesRegexp, Exception, u'^Expected$',
3051 Stub)
3052 self.assertRaisesRegexp(
3053 self.failureException,
3054 r'"\^Expected\$" does not match "Unexpected"',
3055 self.assertRaisesRegexp, Exception,
3056 re.compile('^Expected$'), Stub)
3057
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00003058 def testAssertRaisesExcValue(self):
3059 class ExceptionMock(Exception):
3060 pass
3061
3062 def Stub(foo):
3063 raise ExceptionMock(foo)
3064 v = "particular value"
3065
3066 ctx = self.assertRaises(ExceptionMock)
3067 with ctx:
3068 Stub(v)
Georg Brandldc3694b2010-02-07 17:02:22 +00003069 e = ctx.exception
Ezio Melottib0f5adc2010-01-24 16:58:36 +00003070 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00003071 self.assertEqual(e.args[0], v)
3072
Gregory P. Smith7558d572009-03-31 19:03:28 +00003073 def testSynonymAssertMethodNames(self):
3074 """Test undocumented method name synonyms.
3075
3076 Please do not use these methods names in your own code.
3077
3078 This test confirms their continued existence and functionality
3079 in order to avoid breaking existing code.
3080 """
3081 self.assertNotEquals(3, 5)
3082 self.assertEquals(3, 3)
3083 self.assertAlmostEquals(2.0, 2.0)
3084 self.assertNotAlmostEquals(3.0, 5.0)
3085 self.assert_(True)
3086
3087 def testPendingDeprecationMethodNames(self):
3088 """Test fail* methods pending deprecation, they will warn in 3.2.
3089
3090 Do not use these methods. They will go away in 3.3.
3091 """
Michael Foord98e7b762010-03-20 03:00:34 +00003092 with test_support.check_warnings():
3093 self.failIfEqual(3, 5)
3094 self.failUnlessEqual(3, 3)
3095 self.failUnlessAlmostEqual(2.0, 2.0)
3096 self.failIfAlmostEqual(3.0, 5.0)
3097 self.failUnless(True)
3098 self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam')
3099 self.failIf(False)
Gregory P. Smith7558d572009-03-31 19:03:28 +00003100
Michael Foorde2942d02009-04-02 05:51:54 +00003101 def testDeepcopy(self):
3102 # Issue: 5660
3103 class TestableTest(TestCase):
3104 def testNothing(self):
3105 pass
3106
3107 test = TestableTest('testNothing')
3108
3109 # This shouldn't blow up
3110 deepcopy(test)
3111
Benjamin Peterson692428e2009-03-23 21:50:21 +00003112
3113class Test_TestSkipping(TestCase):
3114
3115 def test_skipping(self):
3116 class Foo(unittest.TestCase):
3117 def test_skip_me(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00003118 self.skipTest("skip")
Benjamin Peterson692428e2009-03-23 21:50:21 +00003119 events = []
3120 result = LoggingResult(events)
3121 test = Foo("test_skip_me")
3122 test.run(result)
3123 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3124 self.assertEqual(result.skipped, [(test, "skip")])
3125
3126 # Try letting setUp skip the test now.
3127 class Foo(unittest.TestCase):
3128 def setUp(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00003129 self.skipTest("testing")
Benjamin Peterson692428e2009-03-23 21:50:21 +00003130 def test_nothing(self): pass
3131 events = []
3132 result = LoggingResult(events)
3133 test = Foo("test_nothing")
3134 test.run(result)
3135 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3136 self.assertEqual(result.skipped, [(test, "testing")])
3137 self.assertEqual(result.testsRun, 1)
3138
3139 def test_skipping_decorators(self):
3140 op_table = ((unittest.skipUnless, False, True),
3141 (unittest.skipIf, True, False))
3142 for deco, do_skip, dont_skip in op_table:
3143 class Foo(unittest.TestCase):
3144 @deco(do_skip, "testing")
3145 def test_skip(self): pass
3146
3147 @deco(dont_skip, "testing")
3148 def test_dont_skip(self): pass
3149 test_do_skip = Foo("test_skip")
3150 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003151 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003152 events = []
3153 result = LoggingResult(events)
3154 suite.run(result)
3155 self.assertEqual(len(result.skipped), 1)
3156 expected = ['startTest', 'addSkip', 'stopTest',
3157 'startTest', 'addSuccess', 'stopTest']
3158 self.assertEqual(events, expected)
3159 self.assertEqual(result.testsRun, 2)
3160 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
3161 self.assertTrue(result.wasSuccessful())
3162
3163 def test_skip_class(self):
3164 @unittest.skip("testing")
3165 class Foo(unittest.TestCase):
3166 def test_1(self):
3167 record.append(1)
3168 record = []
3169 result = unittest.TestResult()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003170 test = Foo("test_1")
3171 suite = unittest.TestSuite([test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003172 suite.run(result)
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003173 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003174 self.assertEqual(record, [])
3175
3176 def test_expected_failure(self):
3177 class Foo(unittest.TestCase):
3178 @unittest.expectedFailure
3179 def test_die(self):
3180 self.fail("help me!")
3181 events = []
3182 result = LoggingResult(events)
3183 test = Foo("test_die")
3184 test.run(result)
3185 self.assertEqual(events,
3186 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003187 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00003188 self.assertTrue(result.wasSuccessful())
3189
3190 def test_unexpected_success(self):
3191 class Foo(unittest.TestCase):
3192 @unittest.expectedFailure
3193 def test_die(self):
3194 pass
3195 events = []
3196 result = LoggingResult(events)
3197 test = Foo("test_die")
3198 test.run(result)
3199 self.assertEqual(events,
3200 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3201 self.assertFalse(result.failures)
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003202 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003203 self.assertTrue(result.wasSuccessful())
3204
Michael Foord53e8eea2010-03-07 20:22:12 +00003205 def test_skip_doesnt_run_setup(self):
3206 class Foo(unittest.TestCase):
3207 wasSetUp = False
3208 wasTornDown = False
3209 def setUp(self):
3210 Foo.wasSetUp = True
3211 def tornDown(self):
3212 Foo.wasTornDown = True
3213 @unittest.skip('testing')
3214 def test_1(self):
3215 pass
3216
3217 result = unittest.TestResult()
3218 test = Foo("test_1")
3219 suite = unittest.TestSuite([test])
3220 suite.run(result)
3221 self.assertEqual(result.skipped, [(test, "testing")])
3222 self.assertFalse(Foo.wasSetUp)
3223 self.assertFalse(Foo.wasTornDown)
3224
3225 def test_decorated_skip(self):
3226 def decorator(func):
3227 def inner(*a):
3228 return func(*a)
3229 return inner
3230
3231 class Foo(unittest.TestCase):
3232 @decorator
3233 @unittest.skip('testing')
3234 def test_1(self):
3235 pass
3236
3237 result = unittest.TestResult()
3238 test = Foo("test_1")
3239 suite = unittest.TestSuite([test])
3240 suite.run(result)
3241 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003242
3243
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003244class Test_Assertions(TestCase):
3245 def test_AlmostEqual(self):
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003246 self.assertAlmostEqual(1.00000001, 1.0)
3247 self.assertNotAlmostEqual(1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003248 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003249 self.assertAlmostEqual, 1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003250 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003251 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003252
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003253 self.assertAlmostEqual(1.1, 1.0, places=0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003254 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003255 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003256
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003257 self.assertAlmostEqual(0, .1+.1j, places=0)
3258 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003259 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003260 self.assertAlmostEqual, 0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003261 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003262 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003263
Michael Foordc3f79372009-09-13 16:40:02 +00003264 self.assertAlmostEqual(float('inf'), float('inf'))
3265 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3266 float('inf'), float('inf'))
3267
3268
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003269 def test_assertRaises(self):
3270 def _raise(e):
3271 raise e
3272 self.assertRaises(KeyError, _raise, KeyError)
3273 self.assertRaises(KeyError, _raise, KeyError("key"))
3274 try:
3275 self.assertRaises(KeyError, lambda: None)
Gregory P. Smith28399852009-03-31 16:54:10 +00003276 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003277 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003278 else:
3279 self.fail("assertRaises() didn't fail")
3280 try:
3281 self.assertRaises(KeyError, _raise, ValueError)
3282 except ValueError:
3283 pass
3284 else:
3285 self.fail("assertRaises() didn't let exception pass through")
Michael Foord2bd52dc2010-02-07 18:44:12 +00003286 with self.assertRaises(KeyError) as cm:
3287 try:
3288 raise KeyError
3289 except Exception, e:
3290 raise
3291 self.assertIs(cm.exception, e)
3292
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003293 with self.assertRaises(KeyError):
3294 raise KeyError("key")
3295 try:
3296 with self.assertRaises(KeyError):
3297 pass
Gregory P. Smith28399852009-03-31 16:54:10 +00003298 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003299 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003300 else:
3301 self.fail("assertRaises() didn't fail")
3302 try:
3303 with self.assertRaises(KeyError):
3304 raise ValueError
3305 except ValueError:
3306 pass
3307 else:
3308 self.fail("assertRaises() didn't let exception pass through")
3309
3310
Michael Foord345b2fe2009-04-02 03:20:38 +00003311class TestLongMessage(TestCase):
3312 """Test that the individual asserts honour longMessage.
3313 This actually tests all the message behaviour for
3314 asserts that use longMessage."""
3315
3316 def setUp(self):
3317 class TestableTestFalse(TestCase):
3318 longMessage = False
3319 failureException = self.failureException
3320
3321 def testTest(self):
3322 pass
3323
3324 class TestableTestTrue(TestCase):
3325 longMessage = True
3326 failureException = self.failureException
3327
3328 def testTest(self):
3329 pass
3330
3331 self.testableTrue = TestableTestTrue('testTest')
3332 self.testableFalse = TestableTestFalse('testTest')
3333
3334 def testDefault(self):
3335 self.assertFalse(TestCase.longMessage)
3336
3337 def test_formatMsg(self):
3338 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3339 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3340
3341 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3342 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3343
Michael Foord53e8eea2010-03-07 20:22:12 +00003344 # This blows up if _formatMessage uses string concatenation
3345 self.testableTrue._formatMessage(object(), 'foo')
3346
3347 def test_formatMessage_unicode_error(self):
Florent Xiclunafd37dd42010-03-25 20:39:10 +00003348 one = ''.join(chr(i) for i in range(255))
3349 # this used to cause a UnicodeDecodeError constructing msg
3350 self.testableTrue._formatMessage(one, u'\uFFFD')
Michael Foord53e8eea2010-03-07 20:22:12 +00003351
Michael Foord345b2fe2009-04-02 03:20:38 +00003352 def assertMessages(self, methodName, args, errors):
3353 def getMethod(i):
3354 useTestableFalse = i < 2
3355 if useTestableFalse:
3356 test = self.testableFalse
3357 else:
3358 test = self.testableTrue
3359 return getattr(test, methodName)
3360
3361 for i, expected_regexp in enumerate(errors):
3362 testMethod = getMethod(i)
3363 kwargs = {}
3364 withMsg = i % 2
3365 if withMsg:
3366 kwargs = {"msg": "oops"}
3367
3368 with self.assertRaisesRegexp(self.failureException,
3369 expected_regexp=expected_regexp):
3370 testMethod(*args, **kwargs)
3371
3372 def testAssertTrue(self):
3373 self.assertMessages('assertTrue', (False,),
3374 ["^False is not True$", "^oops$", "^False is not True$",
3375 "^False is not True : oops$"])
3376
3377 def testAssertFalse(self):
3378 self.assertMessages('assertFalse', (True,),
3379 ["^True is not False$", "^oops$", "^True is not False$",
3380 "^True is not False : oops$"])
3381
3382 def testNotEqual(self):
3383 self.assertMessages('assertNotEqual', (1, 1),
3384 ["^1 == 1$", "^oops$", "^1 == 1$",
3385 "^1 == 1 : oops$"])
3386
3387 def testAlmostEqual(self):
3388 self.assertMessages('assertAlmostEqual', (1, 2),
3389 ["^1 != 2 within 7 places$", "^oops$",
3390 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3391
3392 def testNotAlmostEqual(self):
3393 self.assertMessages('assertNotAlmostEqual', (1, 1),
3394 ["^1 == 1 within 7 places$", "^oops$",
3395 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3396
3397 def test_baseAssertEqual(self):
3398 self.assertMessages('_baseAssertEqual', (1, 2),
3399 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3400
3401 def testAssertSequenceEqual(self):
3402 # Error messages are multiline so not testing on full message
3403 # assertTupleEqual and assertListEqual delegate to this method
3404 self.assertMessages('assertSequenceEqual', ([], [None]),
3405 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3406 r"\+ \[None\] : oops$"])
3407
3408 def testAssertSetEqual(self):
3409 self.assertMessages('assertSetEqual', (set(), set([None])),
3410 ["None$", "^oops$", "None$",
3411 "None : oops$"])
3412
3413 def testAssertIn(self):
3414 self.assertMessages('assertIn', (None, []),
3415 ['^None not found in \[\]$', "^oops$",
3416 '^None not found in \[\]$',
3417 '^None not found in \[\] : oops$'])
3418
3419 def testAssertNotIn(self):
3420 self.assertMessages('assertNotIn', (None, [None]),
3421 ['^None unexpectedly found in \[None\]$', "^oops$",
3422 '^None unexpectedly found in \[None\]$',
3423 '^None unexpectedly found in \[None\] : oops$'])
3424
3425 def testAssertDictEqual(self):
3426 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3427 [r"\+ \{'key': 'value'\}$", "^oops$",
3428 "\+ \{'key': 'value'\}$",
3429 "\+ \{'key': 'value'\} : oops$"])
3430
3431 def testAssertDictContainsSubset(self):
3432 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3433 ["^Missing: 'key'$", "^oops$",
3434 "^Missing: 'key'$",
3435 "^Missing: 'key' : oops$"])
3436
Michael Foord98e7b762010-03-20 03:00:34 +00003437 def testAssertItemsEqual(self):
3438 self.assertMessages('assertItemsEqual', ([], [None]),
Michael Foord345b2fe2009-04-02 03:20:38 +00003439 [r"\[None\]$", "^oops$",
3440 r"\[None\]$",
3441 r"\[None\] : oops$"])
3442
3443 def testAssertMultiLineEqual(self):
3444 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3445 [r"\+ foo$", "^oops$",
3446 r"\+ foo$",
3447 r"\+ foo : oops$"])
3448
3449 def testAssertLess(self):
3450 self.assertMessages('assertLess', (2, 1),
3451 ["^2 not less than 1$", "^oops$",
3452 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3453
3454 def testAssertLessEqual(self):
3455 self.assertMessages('assertLessEqual', (2, 1),
3456 ["^2 not less than or equal to 1$", "^oops$",
3457 "^2 not less than or equal to 1$",
3458 "^2 not less than or equal to 1 : oops$"])
3459
3460 def testAssertGreater(self):
3461 self.assertMessages('assertGreater', (1, 2),
3462 ["^1 not greater than 2$", "^oops$",
3463 "^1 not greater than 2$",
3464 "^1 not greater than 2 : oops$"])
3465
3466 def testAssertGreaterEqual(self):
3467 self.assertMessages('assertGreaterEqual', (1, 2),
3468 ["^1 not greater than or equal to 2$", "^oops$",
3469 "^1 not greater than or equal to 2$",
3470 "^1 not greater than or equal to 2 : oops$"])
3471
3472 def testAssertIsNone(self):
3473 self.assertMessages('assertIsNone', ('not None',),
3474 ["^'not None' is not None$", "^oops$",
3475 "^'not None' is not None$",
3476 "^'not None' is not None : oops$"])
3477
3478 def testAssertIsNotNone(self):
3479 self.assertMessages('assertIsNotNone', (None,),
3480 ["^unexpectedly None$", "^oops$",
3481 "^unexpectedly None$",
3482 "^unexpectedly None : oops$"])
3483
Michael Foordf2dfef12009-04-05 19:19:28 +00003484 def testAssertIs(self):
3485 self.assertMessages('assertIs', (None, 'foo'),
3486 ["^None is not 'foo'$", "^oops$",
3487 "^None is not 'foo'$",
3488 "^None is not 'foo' : oops$"])
3489
3490 def testAssertIsNot(self):
3491 self.assertMessages('assertIsNot', (None, None),
3492 ["^unexpectedly identical: None$", "^oops$",
3493 "^unexpectedly identical: None$",
3494 "^unexpectedly identical: None : oops$"])
3495
Michael Foord345b2fe2009-04-02 03:20:38 +00003496
Michael Foorde2fb98f2009-05-02 20:15:05 +00003497class TestCleanUp(TestCase):
3498
3499 def testCleanUp(self):
3500 class TestableTest(TestCase):
3501 def testNothing(self):
3502 pass
3503
3504 test = TestableTest('testNothing')
3505 self.assertEqual(test._cleanups, [])
3506
3507 cleanups = []
3508
3509 def cleanup1(*args, **kwargs):
3510 cleanups.append((1, args, kwargs))
3511
3512 def cleanup2(*args, **kwargs):
3513 cleanups.append((2, args, kwargs))
3514
3515 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3516 test.addCleanup(cleanup2)
3517
3518 self.assertEqual(test._cleanups,
3519 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3520 (cleanup2, (), {})])
3521
3522 result = test.doCleanups()
3523 self.assertTrue(result)
3524
3525 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3526
3527 def testCleanUpWithErrors(self):
3528 class TestableTest(TestCase):
3529 def testNothing(self):
3530 pass
3531
3532 class MockResult(object):
3533 errors = []
3534 def addError(self, test, exc_info):
3535 self.errors.append((test, exc_info))
3536
3537 result = MockResult()
3538 test = TestableTest('testNothing')
Michael Foorda50af062009-05-21 22:57:02 +00003539 test._resultForDoCleanups = result
Michael Foorde2fb98f2009-05-02 20:15:05 +00003540
3541 exc1 = Exception('foo')
3542 exc2 = Exception('bar')
3543 def cleanup1():
3544 raise exc1
3545
3546 def cleanup2():
3547 raise exc2
3548
3549 test.addCleanup(cleanup1)
3550 test.addCleanup(cleanup2)
3551
3552 self.assertFalse(test.doCleanups())
3553
3554 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3555 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3556 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3557
3558 def testCleanupInRun(self):
3559 blowUp = False
3560 ordering = []
3561
3562 class TestableTest(TestCase):
3563 def setUp(self):
3564 ordering.append('setUp')
3565 if blowUp:
3566 raise Exception('foo')
3567
3568 def testNothing(self):
3569 ordering.append('test')
3570
3571 def tearDown(self):
3572 ordering.append('tearDown')
3573
3574 test = TestableTest('testNothing')
3575
3576 def cleanup1():
3577 ordering.append('cleanup1')
3578 def cleanup2():
3579 ordering.append('cleanup2')
3580 test.addCleanup(cleanup1)
3581 test.addCleanup(cleanup2)
3582
3583 def success(some_test):
3584 self.assertEqual(some_test, test)
3585 ordering.append('success')
3586
3587 result = unittest.TestResult()
3588 result.addSuccess = success
3589
3590 test.run(result)
3591 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3592 'cleanup2', 'cleanup1', 'success'])
3593
3594 blowUp = True
3595 ordering = []
3596 test = TestableTest('testNothing')
3597 test.addCleanup(cleanup1)
3598 test.run(result)
3599 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3600
3601
Michael Foord829f6b82009-05-02 11:43:06 +00003602class Test_TestProgram(TestCase):
3603
3604 # Horrible white box test
3605 def testNoExit(self):
3606 result = object()
3607 test = object()
3608
3609 class FakeRunner(object):
3610 def run(self, test):
3611 self.test = test
3612 return result
3613
3614 runner = FakeRunner()
3615
Michael Foord5d31e052009-05-11 17:59:43 +00003616 oldParseArgs = TestProgram.parseArgs
3617 def restoreParseArgs():
Michael Foord829f6b82009-05-02 11:43:06 +00003618 TestProgram.parseArgs = oldParseArgs
Michael Foord5d31e052009-05-11 17:59:43 +00003619 TestProgram.parseArgs = lambda *args: None
3620 self.addCleanup(restoreParseArgs)
3621
3622 def removeTest():
Michael Foord829f6b82009-05-02 11:43:06 +00003623 del TestProgram.test
Michael Foord5d31e052009-05-11 17:59:43 +00003624 TestProgram.test = test
3625 self.addCleanup(removeTest)
3626
3627 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3628
3629 self.assertEqual(program.result, result)
3630 self.assertEqual(runner.test, test)
3631 self.assertEqual(program.verbosity, 2)
Michael Foord829f6b82009-05-02 11:43:06 +00003632
Michael Foord829f6b82009-05-02 11:43:06 +00003633 class FooBar(unittest.TestCase):
3634 def testPass(self):
3635 assert True
3636 def testFail(self):
3637 assert False
3638
3639 class FooBarLoader(unittest.TestLoader):
3640 """Test loader that returns a suite containing FooBar."""
3641 def loadTestsFromModule(self, module):
3642 return self.suiteClass(
3643 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3644
3645
3646 def test_NonExit(self):
3647 program = unittest.main(exit=False,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003648 argv=["foobar"],
3649 testRunner=unittest.TextTestRunner(stream=StringIO()),
3650 testLoader=self.FooBarLoader())
Michael Foord829f6b82009-05-02 11:43:06 +00003651 self.assertTrue(hasattr(program, 'result'))
3652
3653
3654 def test_Exit(self):
3655 self.assertRaises(
3656 SystemExit,
3657 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003658 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003659 testRunner=unittest.TextTestRunner(stream=StringIO()),
3660 exit=True,
3661 testLoader=self.FooBarLoader())
3662
3663
3664 def test_ExitAsDefault(self):
3665 self.assertRaises(
3666 SystemExit,
3667 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003668 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003669 testRunner=unittest.TextTestRunner(stream=StringIO()),
3670 testLoader=self.FooBarLoader())
3671
3672
Michael Foord07ef4872009-05-02 22:43:34 +00003673class Test_TextTestRunner(TestCase):
3674 """Tests for TextTestRunner."""
3675
3676 def test_works_with_result_without_startTestRun_stopTestRun(self):
3677 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3678 separator2 = ''
3679 def printErrors(self):
3680 pass
3681
3682 class Runner(unittest.TextTestRunner):
3683 def __init__(self):
3684 super(Runner, self).__init__(StringIO())
3685
3686 def _makeResult(self):
3687 return OldTextResult()
3688
3689 runner = Runner()
3690 runner.run(unittest.TestSuite())
3691
3692 def test_startTestRun_stopTestRun_called(self):
3693 class LoggingTextResult(LoggingResult):
3694 separator2 = ''
3695 def printErrors(self):
3696 pass
3697
3698 class LoggingRunner(unittest.TextTestRunner):
3699 def __init__(self, events):
3700 super(LoggingRunner, self).__init__(StringIO())
3701 self._events = events
3702
3703 def _makeResult(self):
3704 return LoggingTextResult(self._events)
3705
3706 events = []
3707 runner = LoggingRunner(events)
3708 runner.run(unittest.TestSuite())
3709 expected = ['startTestRun', 'stopTestRun']
3710 self.assertEqual(events, expected)
3711
Antoine Pitrou0734c632009-11-10 20:49:30 +00003712 def test_pickle_unpickle(self):
3713 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3714 # required by test_multiprocessing under Windows (in verbose mode).
3715 import StringIO
3716 # cStringIO objects are not pickleable, but StringIO objects are.
3717 stream = StringIO.StringIO("foo")
3718 runner = unittest.TextTestRunner(stream)
3719 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
3720 s = pickle.dumps(runner, protocol=protocol)
3721 obj = pickle.loads(s)
3722 # StringIO objects never compare equal, a cheap test instead.
3723 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3724
Michael Foorddb43b5a2010-02-10 14:25:12 +00003725 def test_resultclass(self):
3726 def MockResultClass(*args):
3727 return args
3728 STREAM = object()
3729 DESCRIPTIONS = object()
3730 VERBOSITY = object()
3731 runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY,
3732 resultclass=MockResultClass)
3733 self.assertEqual(runner.resultclass, MockResultClass)
3734
3735 expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY)
3736 self.assertEqual(runner._makeResult(), expectedresult)
3737
Michael Foord07ef4872009-05-02 22:43:34 +00003738
Michael Foordb4a81c82009-05-29 20:33:46 +00003739class TestDiscovery(TestCase):
3740
3741 # Heavily mocked tests so I can avoid hitting the filesystem
Michael Foorde91ea562009-09-13 19:07:03 +00003742 def test_get_name_from_path(self):
Michael Foordb4a81c82009-05-29 20:33:46 +00003743 loader = unittest.TestLoader()
3744
Michael Foordb4a81c82009-05-29 20:33:46 +00003745 loader._top_level_dir = '/foo'
Michael Foorde91ea562009-09-13 19:07:03 +00003746 name = loader._get_name_from_path('/foo/bar/baz.py')
3747 self.assertEqual(name, 'bar.baz')
Michael Foordb4a81c82009-05-29 20:33:46 +00003748
3749 if not __debug__:
3750 # asserts are off
3751 return
3752
3753 with self.assertRaises(AssertionError):
Michael Foorde91ea562009-09-13 19:07:03 +00003754 loader._get_name_from_path('/bar/baz.py')
Michael Foordb4a81c82009-05-29 20:33:46 +00003755
3756 def test_find_tests(self):
3757 loader = unittest.TestLoader()
3758
3759 original_listdir = os.listdir
3760 def restore_listdir():
3761 os.listdir = original_listdir
3762 original_isfile = os.path.isfile
3763 def restore_isfile():
3764 os.path.isfile = original_isfile
3765 original_isdir = os.path.isdir
3766 def restore_isdir():
3767 os.path.isdir = original_isdir
3768
3769 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Michael Foorde91ea562009-09-13 19:07:03 +00003770 'test.foo', 'test-not-a-module.py', 'another_dir'],
Michael Foordb4a81c82009-05-29 20:33:46 +00003771 ['test3.py', 'test4.py', ]]
3772 os.listdir = lambda path: path_lists.pop(0)
3773 self.addCleanup(restore_listdir)
3774
3775 def isdir(path):
3776 return path.endswith('dir')
3777 os.path.isdir = isdir
3778 self.addCleanup(restore_isdir)
3779
3780 def isfile(path):
3781 # another_dir is not a package and so shouldn't be recursed into
3782 return not path.endswith('dir') and not 'another_dir' in path
3783 os.path.isfile = isfile
3784 self.addCleanup(restore_isfile)
3785
Michael Foorde91ea562009-09-13 19:07:03 +00003786 loader._get_module_from_name = lambda path: path + ' module'
Michael Foordb4a81c82009-05-29 20:33:46 +00003787 loader.loadTestsFromModule = lambda module: module + ' tests'
3788
3789 loader._top_level_dir = '/foo'
3790 suite = list(loader._find_tests('/foo', 'test*.py'))
3791
Michael Foorde91ea562009-09-13 19:07:03 +00003792 expected = [name + ' module tests' for name in
3793 ('test1', 'test2')]
3794 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3795 ('test3', 'test4')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003796 self.assertEqual(suite, expected)
3797
3798 def test_find_tests_with_package(self):
3799 loader = unittest.TestLoader()
3800
3801 original_listdir = os.listdir
3802 def restore_listdir():
3803 os.listdir = original_listdir
3804 original_isfile = os.path.isfile
3805 def restore_isfile():
3806 os.path.isfile = original_isfile
3807 original_isdir = os.path.isdir
3808 def restore_isdir():
3809 os.path.isdir = original_isdir
3810
3811 directories = ['a_directory', 'test_directory', 'test_directory2']
3812 path_lists = [directories, [], [], []]
3813 os.listdir = lambda path: path_lists.pop(0)
3814 self.addCleanup(restore_listdir)
3815
3816 os.path.isdir = lambda path: True
3817 self.addCleanup(restore_isdir)
3818
3819 os.path.isfile = lambda path: os.path.basename(path) not in directories
3820 self.addCleanup(restore_isfile)
3821
3822 class Module(object):
3823 paths = []
3824 load_tests_args = []
3825
3826 def __init__(self, path):
3827 self.path = path
3828 self.paths.append(path)
3829 if os.path.basename(path) == 'test_directory':
3830 def load_tests(loader, tests, pattern):
3831 self.load_tests_args.append((loader, tests, pattern))
3832 return 'load_tests'
3833 self.load_tests = load_tests
3834
3835 def __eq__(self, other):
3836 return self.path == other.path
3837
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003838 # Silence py3k warning
3839 __hash__ = None
3840
Michael Foorde91ea562009-09-13 19:07:03 +00003841 loader._get_module_from_name = lambda name: Module(name)
Michael Foordb4a81c82009-05-29 20:33:46 +00003842 def loadTestsFromModule(module, use_load_tests):
3843 if use_load_tests:
3844 raise self.failureException('use_load_tests should be False for packages')
3845 return module.path + ' module tests'
3846 loader.loadTestsFromModule = loadTestsFromModule
3847
3848 loader._top_level_dir = '/foo'
3849 # this time no '.py' on the pattern so that it can match
3850 # a test package
3851 suite = list(loader._find_tests('/foo', 'test*'))
3852
3853 # We should have loaded tests from the test_directory package by calling load_tests
3854 # and directly from the test_directory2 package
Michael Foordd53d0852009-06-05 14:14:34 +00003855 self.assertEqual(suite,
Michael Foorde91ea562009-09-13 19:07:03 +00003856 ['load_tests', 'test_directory2' + ' module tests'])
3857 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Michael Foordb4a81c82009-05-29 20:33:46 +00003858
3859 # load_tests should have been called once with loader, tests and pattern
3860 self.assertEqual(Module.load_tests_args,
Michael Foorde91ea562009-09-13 19:07:03 +00003861 [(loader, 'test_directory' + ' module tests', 'test*')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003862
3863 def test_discover(self):
3864 loader = unittest.TestLoader()
3865
3866 original_isfile = os.path.isfile
3867 def restore_isfile():
3868 os.path.isfile = original_isfile
3869
3870 os.path.isfile = lambda path: False
3871 self.addCleanup(restore_isfile)
3872
Nick Coghlanb6edf192009-10-17 08:21:21 +00003873 orig_sys_path = sys.path[:]
3874 def restore_path():
3875 sys.path[:] = orig_sys_path
3876 self.addCleanup(restore_path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003877
Nick Coghlanb6edf192009-10-17 08:21:21 +00003878 full_path = os.path.abspath(os.path.normpath('/foo'))
Michael Foordb4a81c82009-05-29 20:33:46 +00003879 with self.assertRaises(ImportError):
3880 loader.discover('/foo/bar', top_level_dir='/foo')
3881
3882 self.assertEqual(loader._top_level_dir, full_path)
3883 self.assertIn(full_path, sys.path)
3884
3885 os.path.isfile = lambda path: True
3886 _find_tests_args = []
3887 def _find_tests(start_dir, pattern):
3888 _find_tests_args.append((start_dir, pattern))
3889 return ['tests']
3890 loader._find_tests = _find_tests
3891 loader.suiteClass = str
3892
3893 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3894
3895 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3896 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3897 self.assertEqual(suite, "['tests']")
3898 self.assertEqual(loader._top_level_dir, top_level_dir)
3899 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlanb6edf192009-10-17 08:21:21 +00003900 self.assertIn(top_level_dir, sys.path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003901
Michael Foorde91ea562009-09-13 19:07:03 +00003902 def test_discover_with_modules_that_fail_to_import(self):
3903 loader = unittest.TestLoader()
3904
3905 listdir = os.listdir
3906 os.listdir = lambda _: ['test_this_does_not_exist.py']
3907 isfile = os.path.isfile
3908 os.path.isfile = lambda _: True
Nick Coghlanb6edf192009-10-17 08:21:21 +00003909 orig_sys_path = sys.path[:]
Michael Foorde91ea562009-09-13 19:07:03 +00003910 def restore():
3911 os.path.isfile = isfile
3912 os.listdir = listdir
Nick Coghlanb6edf192009-10-17 08:21:21 +00003913 sys.path[:] = orig_sys_path
Michael Foorde91ea562009-09-13 19:07:03 +00003914 self.addCleanup(restore)
3915
3916 suite = loader.discover('.')
Nick Coghlanb6edf192009-10-17 08:21:21 +00003917 self.assertIn(os.getcwd(), sys.path)
Michael Foorde91ea562009-09-13 19:07:03 +00003918 self.assertEqual(suite.countTestCases(), 1)
3919 test = list(list(suite)[0])[0] # extract test from suite
3920
3921 with self.assertRaises(ImportError):
3922 test.test_this_does_not_exist()
3923
Michael Foordb4a81c82009-05-29 20:33:46 +00003924 def test_command_line_handling_parseArgs(self):
3925 # Haha - take that uninstantiable class
3926 program = object.__new__(TestProgram)
3927
3928 args = []
3929 def do_discovery(argv):
3930 args.extend(argv)
3931 program._do_discovery = do_discovery
3932 program.parseArgs(['something', 'discover'])
3933 self.assertEqual(args, [])
3934
3935 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3936 self.assertEqual(args, ['foo', 'bar'])
3937
3938 def test_command_line_handling_do_discovery_too_many_arguments(self):
3939 class Stop(Exception):
3940 pass
3941 def usageExit():
3942 raise Stop
3943
3944 program = object.__new__(TestProgram)
3945 program.usageExit = usageExit
3946
3947 with self.assertRaises(Stop):
3948 # too many args
3949 program._do_discovery(['one', 'two', 'three', 'four'])
3950
3951
3952 def test_command_line_handling_do_discovery_calls_loader(self):
3953 program = object.__new__(TestProgram)
3954
3955 class Loader(object):
3956 args = []
3957 def discover(self, start_dir, pattern, top_level_dir):
3958 self.args.append((start_dir, pattern, top_level_dir))
3959 return 'tests'
3960
3961 program._do_discovery(['-v'], Loader=Loader)
3962 self.assertEqual(program.verbosity, 2)
3963 self.assertEqual(program.test, 'tests')
3964 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3965
3966 Loader.args = []
3967 program = object.__new__(TestProgram)
3968 program._do_discovery(['--verbose'], Loader=Loader)
3969 self.assertEqual(program.test, 'tests')
3970 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3971
3972 Loader.args = []
3973 program = object.__new__(TestProgram)
3974 program._do_discovery([], Loader=Loader)
3975 self.assertEqual(program.test, 'tests')
3976 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3977
3978 Loader.args = []
3979 program = object.__new__(TestProgram)
3980 program._do_discovery(['fish'], Loader=Loader)
3981 self.assertEqual(program.test, 'tests')
3982 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3983
3984 Loader.args = []
3985 program = object.__new__(TestProgram)
3986 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3987 self.assertEqual(program.test, 'tests')
3988 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3989
3990 Loader.args = []
3991 program = object.__new__(TestProgram)
3992 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3993 self.assertEqual(program.test, 'tests')
3994 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3995
3996 Loader.args = []
3997 program = object.__new__(TestProgram)
3998 program._do_discovery(['-s', 'fish'], Loader=Loader)
3999 self.assertEqual(program.test, 'tests')
4000 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
4001
4002 Loader.args = []
4003 program = object.__new__(TestProgram)
4004 program._do_discovery(['-t', 'fish'], Loader=Loader)
4005 self.assertEqual(program.test, 'tests')
4006 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
4007
4008 Loader.args = []
4009 program = object.__new__(TestProgram)
4010 program._do_discovery(['-p', 'fish'], Loader=Loader)
4011 self.assertEqual(program.test, 'tests')
4012 self.assertEqual(Loader.args, [('.', 'fish', None)])
Michael Foord49899692010-03-22 01:41:11 +00004013 self.assertFalse(program.failfast)
Michael Foordb4a81c82009-05-29 20:33:46 +00004014
4015 Loader.args = []
4016 program = object.__new__(TestProgram)
Michael Foord49899692010-03-22 01:41:11 +00004017 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v', '-f'], Loader=Loader)
Michael Foordb4a81c82009-05-29 20:33:46 +00004018 self.assertEqual(program.test, 'tests')
4019 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
4020 self.assertEqual(program.verbosity, 2)
Michael Foord49899692010-03-22 01:41:11 +00004021 self.assertTrue(program.failfast)
Michael Foordb4a81c82009-05-29 20:33:46 +00004022
4023
Michael Foord5ffa3252010-03-07 22:04:55 +00004024class TestSetups(unittest.TestCase):
4025
4026 def getRunner(self):
4027 return unittest.TextTestRunner(resultclass=resultFactory,
4028 stream=StringIO())
4029 def runTests(self, *cases):
4030 suite = unittest.TestSuite()
4031 for case in cases:
4032 tests = unittest.defaultTestLoader.loadTestsFromTestCase(case)
4033 suite.addTests(tests)
4034
4035 runner = self.getRunner()
4036
4037 # creating a nested suite exposes some potential bugs
4038 realSuite = unittest.TestSuite()
4039 realSuite.addTest(suite)
4040 # adding empty suites to the end exposes potential bugs
4041 suite.addTest(unittest.TestSuite())
4042 realSuite.addTest(unittest.TestSuite())
4043 return runner.run(realSuite)
4044
4045 def test_setup_class(self):
4046 class Test(unittest.TestCase):
4047 setUpCalled = 0
4048 @classmethod
4049 def setUpClass(cls):
4050 Test.setUpCalled += 1
4051 unittest.TestCase.setUpClass()
4052 def test_one(self):
4053 pass
4054 def test_two(self):
4055 pass
4056
4057 result = self.runTests(Test)
4058
4059 self.assertEqual(Test.setUpCalled, 1)
4060 self.assertEqual(result.testsRun, 2)
4061 self.assertEqual(len(result.errors), 0)
4062
4063 def test_teardown_class(self):
4064 class Test(unittest.TestCase):
4065 tearDownCalled = 0
4066 @classmethod
4067 def tearDownClass(cls):
4068 Test.tearDownCalled += 1
4069 unittest.TestCase.tearDownClass()
4070 def test_one(self):
4071 pass
4072 def test_two(self):
4073 pass
4074
4075 result = self.runTests(Test)
4076
4077 self.assertEqual(Test.tearDownCalled, 1)
4078 self.assertEqual(result.testsRun, 2)
4079 self.assertEqual(len(result.errors), 0)
4080
4081 def test_teardown_class_two_classes(self):
4082 class Test(unittest.TestCase):
4083 tearDownCalled = 0
4084 @classmethod
4085 def tearDownClass(cls):
4086 Test.tearDownCalled += 1
4087 unittest.TestCase.tearDownClass()
4088 def test_one(self):
4089 pass
4090 def test_two(self):
4091 pass
4092
4093 class Test2(unittest.TestCase):
4094 tearDownCalled = 0
4095 @classmethod
4096 def tearDownClass(cls):
4097 Test2.tearDownCalled += 1
4098 unittest.TestCase.tearDownClass()
4099 def test_one(self):
4100 pass
4101 def test_two(self):
4102 pass
4103
4104 result = self.runTests(Test, Test2)
4105
4106 self.assertEqual(Test.tearDownCalled, 1)
4107 self.assertEqual(Test2.tearDownCalled, 1)
4108 self.assertEqual(result.testsRun, 4)
4109 self.assertEqual(len(result.errors), 0)
4110
4111 def test_error_in_setupclass(self):
4112 class BrokenTest(unittest.TestCase):
4113 @classmethod
4114 def setUpClass(cls):
4115 raise TypeError('foo')
4116 def test_one(self):
4117 pass
4118 def test_two(self):
4119 pass
4120
4121 result = self.runTests(BrokenTest)
4122
4123 self.assertEqual(result.testsRun, 0)
4124 self.assertEqual(len(result.errors), 1)
4125 error, _ = result.errors[0]
4126 self.assertEqual(str(error),
4127 'classSetUp (%s.BrokenTest)' % __name__)
4128
4129 def test_error_in_teardown_class(self):
4130 class Test(unittest.TestCase):
4131 tornDown = 0
4132 @classmethod
4133 def tearDownClass(cls):
4134 Test.tornDown += 1
4135 raise TypeError('foo')
4136 def test_one(self):
4137 pass
4138 def test_two(self):
4139 pass
4140
4141 class Test2(unittest.TestCase):
4142 tornDown = 0
4143 @classmethod
4144 def tearDownClass(cls):
4145 Test2.tornDown += 1
4146 raise TypeError('foo')
4147 def test_one(self):
4148 pass
4149 def test_two(self):
4150 pass
4151
4152 result = self.runTests(Test, Test2)
4153 self.assertEqual(result.testsRun, 4)
4154 self.assertEqual(len(result.errors), 2)
4155 self.assertEqual(Test.tornDown, 1)
4156 self.assertEqual(Test2.tornDown, 1)
4157
4158 error, _ = result.errors[0]
4159 self.assertEqual(str(error),
4160 'classTearDown (%s.Test)' % __name__)
4161
4162 def test_class_not_torndown_when_setup_fails(self):
4163 class Test(unittest.TestCase):
4164 tornDown = False
4165 @classmethod
4166 def setUpClass(cls):
4167 raise TypeError
4168 @classmethod
4169 def tearDownClass(cls):
4170 Test.tornDown = True
4171 raise TypeError('foo')
4172 def test_one(self):
4173 pass
4174
4175 self.runTests(Test)
4176 self.assertFalse(Test.tornDown)
4177
4178 def test_class_not_setup_or_torndown_when_skipped(self):
4179 class Test(unittest.TestCase):
4180 classSetUp = False
4181 tornDown = False
4182 @classmethod
4183 def setUpClass(cls):
4184 Test.classSetUp = True
4185 @classmethod
4186 def tearDownClass(cls):
4187 Test.tornDown = True
4188 def test_one(self):
4189 pass
4190
4191 Test = unittest.skip("hop")(Test)
4192 self.runTests(Test)
4193 self.assertFalse(Test.classSetUp)
4194 self.assertFalse(Test.tornDown)
4195
4196 def test_setup_teardown_order_with_pathological_suite(self):
4197 results = []
4198
4199 class Module1(object):
4200 @staticmethod
4201 def setUpModule():
4202 results.append('Module1.setUpModule')
4203 @staticmethod
4204 def tearDownModule():
4205 results.append('Module1.tearDownModule')
4206
4207 class Module2(object):
4208 @staticmethod
4209 def setUpModule():
4210 results.append('Module2.setUpModule')
4211 @staticmethod
4212 def tearDownModule():
4213 results.append('Module2.tearDownModule')
4214
4215 class Test1(unittest.TestCase):
4216 @classmethod
4217 def setUpClass(cls):
4218 results.append('setup 1')
4219 @classmethod
4220 def tearDownClass(cls):
4221 results.append('teardown 1')
4222 def testOne(self):
4223 results.append('Test1.testOne')
4224 def testTwo(self):
4225 results.append('Test1.testTwo')
4226
4227 class Test2(unittest.TestCase):
4228 @classmethod
4229 def setUpClass(cls):
4230 results.append('setup 2')
4231 @classmethod
4232 def tearDownClass(cls):
4233 results.append('teardown 2')
4234 def testOne(self):
4235 results.append('Test2.testOne')
4236 def testTwo(self):
4237 results.append('Test2.testTwo')
4238
4239 class Test3(unittest.TestCase):
4240 @classmethod
4241 def setUpClass(cls):
4242 results.append('setup 3')
4243 @classmethod
4244 def tearDownClass(cls):
4245 results.append('teardown 3')
4246 def testOne(self):
4247 results.append('Test3.testOne')
4248 def testTwo(self):
4249 results.append('Test3.testTwo')
4250
4251 Test1.__module__ = Test2.__module__ = 'Module'
4252 Test3.__module__ = 'Module2'
4253 sys.modules['Module'] = Module1
4254 sys.modules['Module2'] = Module2
4255
4256 first = unittest.TestSuite((Test1('testOne'),))
4257 second = unittest.TestSuite((Test1('testTwo'),))
4258 third = unittest.TestSuite((Test2('testOne'),))
4259 fourth = unittest.TestSuite((Test2('testTwo'),))
4260 fifth = unittest.TestSuite((Test3('testOne'),))
4261 sixth = unittest.TestSuite((Test3('testTwo'),))
4262 suite = unittest.TestSuite((first, second, third, fourth, fifth, sixth))
4263
4264 runner = self.getRunner()
4265 result = runner.run(suite)
4266 self.assertEqual(result.testsRun, 6)
4267 self.assertEqual(len(result.errors), 0)
4268
4269 self.assertEqual(results,
4270 ['Module1.setUpModule', 'setup 1',
4271 'Test1.testOne', 'Test1.testTwo', 'teardown 1',
4272 'setup 2', 'Test2.testOne', 'Test2.testTwo',
4273 'teardown 2', 'Module1.tearDownModule',
4274 'Module2.setUpModule', 'setup 3',
4275 'Test3.testOne', 'Test3.testTwo',
4276 'teardown 3', 'Module2.tearDownModule'])
4277
4278 def test_setup_module(self):
4279 class Module(object):
4280 moduleSetup = 0
4281 @staticmethod
4282 def setUpModule():
4283 Module.moduleSetup += 1
4284
4285 class Test(unittest.TestCase):
4286 def test_one(self):
4287 pass
4288 def test_two(self):
4289 pass
4290 Test.__module__ = 'Module'
4291 sys.modules['Module'] = Module
4292
4293 result = self.runTests(Test)
4294 self.assertEqual(Module.moduleSetup, 1)
4295 self.assertEqual(result.testsRun, 2)
4296 self.assertEqual(len(result.errors), 0)
4297
4298 def test_error_in_setup_module(self):
4299 class Module(object):
4300 moduleSetup = 0
4301 moduleTornDown = 0
4302 @staticmethod
4303 def setUpModule():
4304 Module.moduleSetup += 1
4305 raise TypeError('foo')
4306 @staticmethod
4307 def tearDownModule():
4308 Module.moduleTornDown += 1
4309
4310 class Test(unittest.TestCase):
4311 classSetUp = False
4312 classTornDown = False
4313 @classmethod
4314 def setUpClass(cls):
4315 Test.classSetUp = True
4316 @classmethod
4317 def tearDownClass(cls):
4318 Test.classTornDown = True
4319 def test_one(self):
4320 pass
4321 def test_two(self):
4322 pass
4323
4324 class Test2(unittest.TestCase):
4325 def test_one(self):
4326 pass
4327 def test_two(self):
4328 pass
4329 Test.__module__ = 'Module'
4330 Test2.__module__ = 'Module'
4331 sys.modules['Module'] = Module
4332
4333 result = self.runTests(Test, Test2)
4334 self.assertEqual(Module.moduleSetup, 1)
4335 self.assertEqual(Module.moduleTornDown, 0)
4336 self.assertEqual(result.testsRun, 0)
4337 self.assertFalse(Test.classSetUp)
4338 self.assertFalse(Test.classTornDown)
4339 self.assertEqual(len(result.errors), 1)
4340 error, _ = result.errors[0]
4341 self.assertEqual(str(error), 'setUpModule (Module)')
4342
4343 def test_testcase_with_missing_module(self):
4344 class Test(unittest.TestCase):
4345 def test_one(self):
4346 pass
4347 def test_two(self):
4348 pass
4349 Test.__module__ = 'Module'
4350 sys.modules.pop('Module', None)
4351
4352 result = self.runTests(Test)
4353 self.assertEqual(result.testsRun, 2)
4354
4355 def test_teardown_module(self):
4356 class Module(object):
4357 moduleTornDown = 0
4358 @staticmethod
4359 def tearDownModule():
4360 Module.moduleTornDown += 1
4361
4362 class Test(unittest.TestCase):
4363 def test_one(self):
4364 pass
4365 def test_two(self):
4366 pass
4367 Test.__module__ = 'Module'
4368 sys.modules['Module'] = Module
4369
4370 result = self.runTests(Test)
4371 self.assertEqual(Module.moduleTornDown, 1)
4372 self.assertEqual(result.testsRun, 2)
4373 self.assertEqual(len(result.errors), 0)
4374
4375 def test_error_in_teardown_module(self):
4376 class Module(object):
4377 moduleTornDown = 0
4378 @staticmethod
4379 def tearDownModule():
4380 Module.moduleTornDown += 1
4381 raise TypeError('foo')
4382
4383 class Test(unittest.TestCase):
4384 classSetUp = False
4385 classTornDown = False
4386 @classmethod
4387 def setUpClass(cls):
4388 Test.classSetUp = True
4389 @classmethod
4390 def tearDownClass(cls):
4391 Test.classTornDown = True
4392 def test_one(self):
4393 pass
4394 def test_two(self):
4395 pass
4396
4397 class Test2(unittest.TestCase):
4398 def test_one(self):
4399 pass
4400 def test_two(self):
4401 pass
4402 Test.__module__ = 'Module'
4403 Test2.__module__ = 'Module'
4404 sys.modules['Module'] = Module
4405
4406 result = self.runTests(Test, Test2)
4407 self.assertEqual(Module.moduleTornDown, 1)
4408 self.assertEqual(result.testsRun, 4)
4409 self.assertTrue(Test.classSetUp)
4410 self.assertTrue(Test.classTornDown)
4411 self.assertEqual(len(result.errors), 1)
4412 error, _ = result.errors[0]
4413 self.assertEqual(str(error), 'tearDownModule (Module)')
4414
Jim Fultonfafd8742004-08-28 15:22:12 +00004415######################################################################
4416## Main
4417######################################################################
4418
4419def test_main():
Georg Brandl15c5ce92007-03-07 09:09:40 +00004420 test_support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004421 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Michael Foord829f6b82009-05-02 11:43:06 +00004422 Test_TestSkipping, Test_Assertions, TestLongMessage,
Michael Foordae3db0a2010-02-22 23:28:32 +00004423 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner,
Michael Foord5ffa3252010-03-07 22:04:55 +00004424 Test_OldTestResult, TestSetups)
Jim Fultonfafd8742004-08-28 15:22:12 +00004425
Georg Brandl15c5ce92007-03-07 09:09:40 +00004426if __name__ == "__main__":
Tim Petersea5962f2007-03-12 18:07:52 +00004427 test_main()