blob: 9dbb0dbc2191d25dcaaa7c3e34b588a2d629ec72 [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
Michael Foord2f677562010-02-21 14:48:59 +000019import warnings
Jim Fultonfafd8742004-08-28 15:22:12 +000020
Michael Foord225a0992010-02-18 20:30:09 +000021
Georg Brandl15c5ce92007-03-07 09:09:40 +000022### Support code
23################################################################
Jim Fultonfafd8742004-08-28 15:22:12 +000024
Michael Foord5ffa3252010-03-07 22:04:55 +000025def resultFactory(*_):
26 return unittest.TestResult()
27
Georg Brandl15c5ce92007-03-07 09:09:40 +000028class LoggingResult(unittest.TestResult):
29 def __init__(self, log):
30 self._events = log
31 super(LoggingResult, self).__init__()
32
33 def startTest(self, test):
34 self._events.append('startTest')
35 super(LoggingResult, self).startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +000036
Michael Foord07ef4872009-05-02 22:43:34 +000037 def startTestRun(self):
38 self._events.append('startTestRun')
39 super(LoggingResult, self).startTestRun()
40
Georg Brandl15c5ce92007-03-07 09:09:40 +000041 def stopTest(self, test):
42 self._events.append('stopTest')
43 super(LoggingResult, self).stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +000044
Michael Foord07ef4872009-05-02 22:43:34 +000045 def stopTestRun(self):
46 self._events.append('stopTestRun')
47 super(LoggingResult, self).stopTestRun()
48
Georg Brandl15c5ce92007-03-07 09:09:40 +000049 def addFailure(self, *args):
50 self._events.append('addFailure')
51 super(LoggingResult, self).addFailure(*args)
Tim Petersea5962f2007-03-12 18:07:52 +000052
Benjamin Peterson692428e2009-03-23 21:50:21 +000053 def addSuccess(self, *args):
54 self._events.append('addSuccess')
55 super(LoggingResult, self).addSuccess(*args)
56
Georg Brandl15c5ce92007-03-07 09:09:40 +000057 def addError(self, *args):
58 self._events.append('addError')
59 super(LoggingResult, self).addError(*args)
60
Benjamin Peterson692428e2009-03-23 21:50:21 +000061 def addSkip(self, *args):
62 self._events.append('addSkip')
63 super(LoggingResult, self).addSkip(*args)
64
65 def addExpectedFailure(self, *args):
66 self._events.append('addExpectedFailure')
67 super(LoggingResult, self).addExpectedFailure(*args)
68
69 def addUnexpectedSuccess(self, *args):
70 self._events.append('addUnexpectedSuccess')
71 super(LoggingResult, self).addUnexpectedSuccess(*args)
72
73
Georg Brandl15c5ce92007-03-07 09:09:40 +000074class TestEquality(object):
Michael Foord345b2fe2009-04-02 03:20:38 +000075 """Used as a mixin for TestCase"""
76
Tim Petersea5962f2007-03-12 18:07:52 +000077 # Check for a valid __eq__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000078 def test_eq(self):
79 for obj_1, obj_2 in self.eq_pairs:
80 self.assertEqual(obj_1, obj_2)
81 self.assertEqual(obj_2, obj_1)
Tim Petersea5962f2007-03-12 18:07:52 +000082
83 # Check for a valid __ne__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000084 def test_ne(self):
85 for obj_1, obj_2 in self.ne_pairs:
Benjamin Peterson6b0032f2009-06-30 23:30:12 +000086 self.assertNotEqual(obj_1, obj_2)
87 self.assertNotEqual(obj_2, obj_1)
Tim Petersea5962f2007-03-12 18:07:52 +000088
Georg Brandl15c5ce92007-03-07 09:09:40 +000089class TestHashing(object):
Michael Foord345b2fe2009-04-02 03:20:38 +000090 """Used as a mixin for TestCase"""
91
Tim Petersea5962f2007-03-12 18:07:52 +000092 # Check for a valid __hash__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000093 def test_hash(self):
94 for obj_1, obj_2 in self.eq_pairs:
95 try:
Gregory P. Smith28399852009-03-31 16:54:10 +000096 if not hash(obj_1) == hash(obj_2):
97 self.fail("%r and %r do not hash equal" % (obj_1, obj_2))
Georg Brandl15c5ce92007-03-07 09:09:40 +000098 except KeyboardInterrupt:
99 raise
Georg Brandl15c5ce92007-03-07 09:09:40 +0000100 except Exception, e:
Gregory P. Smith28399852009-03-31 16:54:10 +0000101 self.fail("Problem hashing %r and %r: %s" % (obj_1, obj_2, e))
Tim Petersea5962f2007-03-12 18:07:52 +0000102
Georg Brandl15c5ce92007-03-07 09:09:40 +0000103 for obj_1, obj_2 in self.ne_pairs:
104 try:
Gregory P. Smith28399852009-03-31 16:54:10 +0000105 if hash(obj_1) == hash(obj_2):
106 self.fail("%s and %s hash equal, but shouldn't" %
107 (obj_1, obj_2))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000108 except KeyboardInterrupt:
109 raise
Georg Brandl15c5ce92007-03-07 09:09:40 +0000110 except Exception, e:
111 self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e))
Tim Petersea5962f2007-03-12 18:07:52 +0000112
Georg Brandl15c5ce92007-03-07 09:09:40 +0000113
Benjamin Peterson692428e2009-03-23 21:50:21 +0000114# List subclass we can add attributes to.
115class MyClassSuite(list):
116
Benjamin Peterson176a56c2009-05-25 00:48:58 +0000117 def __init__(self, tests):
Benjamin Peterson692428e2009-03-23 21:50:21 +0000118 super(MyClassSuite, self).__init__(tests)
119
120
Georg Brandl15c5ce92007-03-07 09:09:40 +0000121################################################################
122### /Support code
123
124class Test_TestLoader(TestCase):
125
126 ### Tests for TestLoader.loadTestsFromTestCase
127 ################################################################
128
129 # "Return a suite of all tests cases contained in the TestCase-derived
130 # class testCaseClass"
131 def test_loadTestsFromTestCase(self):
132 class Foo(unittest.TestCase):
133 def test_1(self): pass
134 def test_2(self): pass
135 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000136
Georg Brandl15c5ce92007-03-07 09:09:40 +0000137 tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +0000138
Georg Brandl15c5ce92007-03-07 09:09:40 +0000139 loader = unittest.TestLoader()
140 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +0000141
Georg Brandl15c5ce92007-03-07 09:09:40 +0000142 # "Return a suite of all tests cases contained in the TestCase-derived
143 # class testCaseClass"
144 #
Tim Petersea5962f2007-03-12 18:07:52 +0000145 # Make sure it does the right thing even if no tests were found
Georg Brandl15c5ce92007-03-07 09:09:40 +0000146 def test_loadTestsFromTestCase__no_matches(self):
147 class Foo(unittest.TestCase):
148 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000149
Georg Brandl15c5ce92007-03-07 09:09:40 +0000150 empty_suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +0000151
Georg Brandl15c5ce92007-03-07 09:09:40 +0000152 loader = unittest.TestLoader()
153 self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite)
Tim Petersea5962f2007-03-12 18:07:52 +0000154
Georg Brandl15c5ce92007-03-07 09:09:40 +0000155 # "Return a suite of all tests cases contained in the TestCase-derived
156 # class testCaseClass"
157 #
158 # What happens if loadTestsFromTestCase() is given an object
159 # that isn't a subclass of TestCase? Specifically, what happens
160 # if testCaseClass is a subclass of TestSuite?
161 #
162 # This is checked for specifically in the code, so we better add a
163 # test for it.
164 def test_loadTestsFromTestCase__TestSuite_subclass(self):
165 class NotATestCase(unittest.TestSuite):
166 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000167
Georg Brandl15c5ce92007-03-07 09:09:40 +0000168 loader = unittest.TestLoader()
169 try:
170 loader.loadTestsFromTestCase(NotATestCase)
171 except TypeError:
172 pass
173 else:
174 self.fail('Should raise TypeError')
Tim Petersea5962f2007-03-12 18:07:52 +0000175
Georg Brandl15c5ce92007-03-07 09:09:40 +0000176 # "Return a suite of all tests cases contained in the TestCase-derived
177 # class testCaseClass"
178 #
179 # Make sure loadTestsFromTestCase() picks up the default test method
180 # name (as specified by TestCase), even though the method name does
181 # not match the default TestLoader.testMethodPrefix string
182 def test_loadTestsFromTestCase__default_method_name(self):
183 class Foo(unittest.TestCase):
184 def runTest(self):
185 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000186
Georg Brandl15c5ce92007-03-07 09:09:40 +0000187 loader = unittest.TestLoader()
188 # This has to be false for the test to succeed
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000189 self.assertFalse('runTest'.startswith(loader.testMethodPrefix))
Tim Petersea5962f2007-03-12 18:07:52 +0000190
Georg Brandl15c5ce92007-03-07 09:09:40 +0000191 suite = loader.loadTestsFromTestCase(Foo)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000192 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000193 self.assertEqual(list(suite), [Foo('runTest')])
194
195 ################################################################
196 ### /Tests for TestLoader.loadTestsFromTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000197
Georg Brandl15c5ce92007-03-07 09:09:40 +0000198 ### Tests for TestLoader.loadTestsFromModule
199 ################################################################
200
201 # "This method searches `module` for classes derived from TestCase"
202 def test_loadTestsFromModule__TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000203 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000204 class MyTestCase(unittest.TestCase):
205 def test(self):
206 pass
207 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000208
Georg Brandl15c5ce92007-03-07 09:09:40 +0000209 loader = unittest.TestLoader()
210 suite = loader.loadTestsFromModule(m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000211 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000212
Georg Brandl15c5ce92007-03-07 09:09:40 +0000213 expected = [loader.suiteClass([MyTestCase('test')])]
214 self.assertEqual(list(suite), expected)
Tim Petersea5962f2007-03-12 18:07:52 +0000215
Georg Brandl15c5ce92007-03-07 09:09:40 +0000216 # "This method searches `module` for classes derived from TestCase"
Tim Petersea5962f2007-03-12 18:07:52 +0000217 #
Georg Brandl15c5ce92007-03-07 09:09:40 +0000218 # What happens if no tests are found (no TestCase instances)?
219 def test_loadTestsFromModule__no_TestCase_instances(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000220 m = types.ModuleType('m')
Tim Petersea5962f2007-03-12 18:07:52 +0000221
Georg Brandl15c5ce92007-03-07 09:09:40 +0000222 loader = unittest.TestLoader()
223 suite = loader.loadTestsFromModule(m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000224 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000225 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000226
Georg Brandl15c5ce92007-03-07 09:09:40 +0000227 # "This method searches `module` for classes derived from TestCase"
228 #
Tim Petersea5962f2007-03-12 18:07:52 +0000229 # What happens if no tests are found (TestCases instances, but no tests)?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000230 def test_loadTestsFromModule__no_TestCase_tests(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000231 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000232 class MyTestCase(unittest.TestCase):
233 pass
234 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000235
Georg Brandl15c5ce92007-03-07 09:09:40 +0000236 loader = unittest.TestLoader()
237 suite = loader.loadTestsFromModule(m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000238 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000239
Georg Brandl15c5ce92007-03-07 09:09:40 +0000240 self.assertEqual(list(suite), [loader.suiteClass()])
Tim Petersea5962f2007-03-12 18:07:52 +0000241
Georg Brandl15c5ce92007-03-07 09:09:40 +0000242 # "This method searches `module` for classes derived from TestCase"s
243 #
244 # What happens if loadTestsFromModule() is given something other
245 # than a module?
246 #
247 # XXX Currently, it succeeds anyway. This flexibility
248 # should either be documented or loadTestsFromModule() should
249 # raise a TypeError
250 #
251 # XXX Certain people are using this behaviour. We'll add a test for it
252 def test_loadTestsFromModule__not_a_module(self):
253 class MyTestCase(unittest.TestCase):
254 def test(self):
255 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000256
Georg Brandl15c5ce92007-03-07 09:09:40 +0000257 class NotAModule(object):
258 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000259
Georg Brandl15c5ce92007-03-07 09:09:40 +0000260 loader = unittest.TestLoader()
261 suite = loader.loadTestsFromModule(NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000262
Georg Brandl15c5ce92007-03-07 09:09:40 +0000263 reference = [unittest.TestSuite([MyTestCase('test')])]
264 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000265
Michael Foordb4a81c82009-05-29 20:33:46 +0000266
267 # Check that loadTestsFromModule honors (or not) a module
268 # with a load_tests function.
269 def test_loadTestsFromModule__load_tests(self):
270 m = types.ModuleType('m')
271 class MyTestCase(unittest.TestCase):
272 def test(self):
273 pass
274 m.testcase_1 = MyTestCase
275
276 load_tests_args = []
277 def load_tests(loader, tests, pattern):
Michael Foord08770602010-02-06 00:22:26 +0000278 self.assertIsInstance(tests, unittest.TestSuite)
Michael Foordb4a81c82009-05-29 20:33:46 +0000279 load_tests_args.extend((loader, tests, pattern))
280 return tests
281 m.load_tests = load_tests
282
283 loader = unittest.TestLoader()
284 suite = loader.loadTestsFromModule(m)
Michael Foord08770602010-02-06 00:22:26 +0000285 self.assertIsInstance(suite, unittest.TestSuite)
Michael Foordb4a81c82009-05-29 20:33:46 +0000286 self.assertEquals(load_tests_args, [loader, suite, None])
287
288 load_tests_args = []
289 suite = loader.loadTestsFromModule(m, use_load_tests=False)
290 self.assertEquals(load_tests_args, [])
291
Michael Foord73dbe042010-03-21 00:53:39 +0000292 def test_loadTestsFromModule__faulty_load_tests(self):
293 m = types.ModuleType('m')
294
295 def load_tests(loader, tests, pattern):
296 raise TypeError('some failure')
297 m.load_tests = load_tests
298
299 loader = unittest.TestLoader()
300 suite = loader.loadTestsFromModule(m)
301 self.assertIsInstance(suite, unittest.TestSuite)
302 self.assertEqual(suite.countTestCases(), 1)
303 test = list(suite)[0]
304
305 self.assertRaisesRegexp(TypeError, "some failure", test.m)
306
Georg Brandl15c5ce92007-03-07 09:09:40 +0000307 ################################################################
308 ### /Tests for TestLoader.loadTestsFromModule()
Tim Petersea5962f2007-03-12 18:07:52 +0000309
Georg Brandl15c5ce92007-03-07 09:09:40 +0000310 ### Tests for TestLoader.loadTestsFromName()
311 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000312
Georg Brandl15c5ce92007-03-07 09:09:40 +0000313 # "The specifier name is a ``dotted name'' that may resolve either to
314 # a module, a test case class, a TestSuite instance, a test method
315 # within a test case class, or a callable object which returns a
316 # TestCase or TestSuite instance."
317 #
318 # Is ValueError raised in response to an empty name?
319 def test_loadTestsFromName__empty_name(self):
320 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000321
Georg Brandl15c5ce92007-03-07 09:09:40 +0000322 try:
323 loader.loadTestsFromName('')
324 except ValueError, e:
325 self.assertEqual(str(e), "Empty module name")
326 else:
327 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000328
Georg Brandl15c5ce92007-03-07 09:09:40 +0000329 # "The specifier name is a ``dotted name'' that may resolve either to
330 # a module, a test case class, a TestSuite instance, a test method
331 # within a test case class, or a callable object which returns a
332 # TestCase or TestSuite instance."
333 #
Tim Petersea5962f2007-03-12 18:07:52 +0000334 # What happens when the name contains invalid characters?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000335 def test_loadTestsFromName__malformed_name(self):
336 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000337
Georg Brandl15c5ce92007-03-07 09:09:40 +0000338 # XXX Should this raise ValueError or ImportError?
339 try:
340 loader.loadTestsFromName('abc () //')
341 except ValueError:
342 pass
343 except ImportError:
344 pass
345 else:
346 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000347
Georg Brandl15c5ce92007-03-07 09:09:40 +0000348 # "The specifier name is a ``dotted name'' that may resolve ... to a
349 # module"
350 #
Tim Petersea5962f2007-03-12 18:07:52 +0000351 # What happens when a module by that name can't be found?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000352 def test_loadTestsFromName__unknown_module_name(self):
353 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000354
Georg Brandl15c5ce92007-03-07 09:09:40 +0000355 try:
356 loader.loadTestsFromName('sdasfasfasdf')
357 except ImportError, e:
358 self.assertEqual(str(e), "No module named sdasfasfasdf")
359 else:
360 self.fail("TestLoader.loadTestsFromName failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000361
Georg Brandl15c5ce92007-03-07 09:09:40 +0000362 # "The specifier name is a ``dotted name'' that may resolve either to
363 # a module, a test case class, a TestSuite instance, a test method
364 # within a test case class, or a callable object which returns a
365 # TestCase or TestSuite instance."
366 #
Tim Petersea5962f2007-03-12 18:07:52 +0000367 # What happens when the module is found, but the attribute can't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000368 def test_loadTestsFromName__unknown_attr_name(self):
369 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000370
Georg Brandl15c5ce92007-03-07 09:09:40 +0000371 try:
372 loader.loadTestsFromName('unittest.sdasfasfasdf')
373 except AttributeError, e:
374 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
375 else:
376 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000377
Georg Brandl15c5ce92007-03-07 09:09:40 +0000378 # "The specifier name is a ``dotted name'' that may resolve either to
379 # a module, a test case class, a TestSuite instance, a test method
380 # within a test case class, or a callable object which returns a
381 # TestCase or TestSuite instance."
382 #
383 # What happens when we provide the module, but the attribute can't be
384 # found?
385 def test_loadTestsFromName__relative_unknown_name(self):
386 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000387
Georg Brandl15c5ce92007-03-07 09:09:40 +0000388 try:
389 loader.loadTestsFromName('sdasfasfasdf', unittest)
390 except AttributeError, e:
391 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
392 else:
393 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000394
Georg Brandl15c5ce92007-03-07 09:09:40 +0000395 # "The specifier name is a ``dotted name'' that may resolve either to
396 # a module, a test case class, a TestSuite instance, a test method
397 # within a test case class, or a callable object which returns a
398 # TestCase or TestSuite instance."
399 # ...
400 # "The method optionally resolves name relative to the given module"
401 #
402 # Does loadTestsFromName raise ValueError when passed an empty
403 # name relative to a provided module?
404 #
405 # XXX Should probably raise a ValueError instead of an AttributeError
406 def test_loadTestsFromName__relative_empty_name(self):
407 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000408
Georg Brandl15c5ce92007-03-07 09:09:40 +0000409 try:
410 loader.loadTestsFromName('', unittest)
411 except AttributeError, e:
412 pass
413 else:
414 self.fail("Failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000415
Georg Brandl15c5ce92007-03-07 09:09:40 +0000416 # "The specifier name is a ``dotted name'' that may resolve either to
417 # a module, a test case class, a TestSuite instance, a test method
418 # within a test case class, or a callable object which returns a
419 # TestCase or TestSuite instance."
420 # ...
421 # "The method optionally resolves name relative to the given module"
422 #
423 # What happens when an impossible name is given, relative to the provided
424 # `module`?
425 def test_loadTestsFromName__relative_malformed_name(self):
426 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000427
Georg Brandl15c5ce92007-03-07 09:09:40 +0000428 # XXX Should this raise AttributeError or ValueError?
429 try:
430 loader.loadTestsFromName('abc () //', unittest)
431 except ValueError:
432 pass
433 except AttributeError:
434 pass
435 else:
436 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
437
438 # "The method optionally resolves name relative to the given module"
439 #
440 # Does loadTestsFromName raise TypeError when the `module` argument
441 # isn't a module object?
442 #
443 # XXX Accepts the not-a-module object, ignorning the object's type
444 # This should raise an exception or the method name should be changed
445 #
446 # XXX Some people are relying on this, so keep it for now
447 def test_loadTestsFromName__relative_not_a_module(self):
448 class MyTestCase(unittest.TestCase):
449 def test(self):
450 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000451
Georg Brandl15c5ce92007-03-07 09:09:40 +0000452 class NotAModule(object):
453 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000454
Georg Brandl15c5ce92007-03-07 09:09:40 +0000455 loader = unittest.TestLoader()
456 suite = loader.loadTestsFromName('test_2', NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000457
Georg Brandl15c5ce92007-03-07 09:09:40 +0000458 reference = [MyTestCase('test')]
459 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000460
Georg Brandl15c5ce92007-03-07 09:09:40 +0000461 # "The specifier name is a ``dotted name'' that may resolve either to
462 # a module, a test case class, a TestSuite instance, a test method
463 # within a test case class, or a callable object which returns a
464 # TestCase or TestSuite instance."
465 #
466 # Does it raise an exception if the name resolves to an invalid
467 # object?
468 def test_loadTestsFromName__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000469 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000470 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000471
Georg Brandl15c5ce92007-03-07 09:09:40 +0000472 loader = unittest.TestLoader()
473 try:
474 loader.loadTestsFromName('testcase_1', m)
475 except TypeError:
476 pass
477 else:
478 self.fail("Should have raised TypeError")
479
480 # "The specifier name is a ``dotted name'' that may
481 # resolve either to ... a test case class"
482 def test_loadTestsFromName__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000483 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000484 class MyTestCase(unittest.TestCase):
485 def test(self):
486 pass
487 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000488
Georg Brandl15c5ce92007-03-07 09:09:40 +0000489 loader = unittest.TestLoader()
490 suite = loader.loadTestsFromName('testcase_1', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000491 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000492 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000493
Georg Brandl15c5ce92007-03-07 09:09:40 +0000494 # "The specifier name is a ``dotted name'' that may resolve either to
495 # a module, a test case class, a TestSuite instance, a test method
496 # within a test case class, or a callable object which returns a
497 # TestCase or TestSuite instance."
498 def test_loadTestsFromName__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000499 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000500 class MyTestCase(unittest.TestCase):
501 def test(self):
502 pass
503 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000504
Georg Brandl15c5ce92007-03-07 09:09:40 +0000505 loader = unittest.TestLoader()
506 suite = loader.loadTestsFromName('testsuite', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000507 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000508
Georg Brandl15c5ce92007-03-07 09:09:40 +0000509 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000510
Georg Brandl15c5ce92007-03-07 09:09:40 +0000511 # "The specifier name is a ``dotted name'' that may resolve ... to
512 # ... a test method within a test case class"
513 def test_loadTestsFromName__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000514 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000515 class MyTestCase(unittest.TestCase):
516 def test(self):
517 pass
518 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000519
Georg Brandl15c5ce92007-03-07 09:09:40 +0000520 loader = unittest.TestLoader()
521 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000522 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000523
Georg Brandl15c5ce92007-03-07 09:09:40 +0000524 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000525
Georg Brandl15c5ce92007-03-07 09:09:40 +0000526 # "The specifier name is a ``dotted name'' that may resolve either to
527 # a module, a test case class, a TestSuite instance, a test method
528 # within a test case class, or a callable object which returns a
529 # TestCase or TestSuite instance."
530 #
531 # Does loadTestsFromName() raise the proper exception when trying to
532 # resolve "a test method within a test case class" that doesn't exist
533 # for the given name (relative to a provided module)?
534 def test_loadTestsFromName__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000535 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000536 class MyTestCase(unittest.TestCase):
537 def test(self):
538 pass
539 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000540
Georg Brandl15c5ce92007-03-07 09:09:40 +0000541 loader = unittest.TestLoader()
542 try:
543 loader.loadTestsFromName('testcase_1.testfoo', m)
544 except AttributeError, e:
545 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
546 else:
547 self.fail("Failed to raise AttributeError")
548
549 # "The specifier name is a ``dotted name'' that may resolve ... to
550 # ... a callable object which returns a ... TestSuite instance"
551 def test_loadTestsFromName__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000552 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000553 testcase_1 = unittest.FunctionTestCase(lambda: None)
554 testcase_2 = unittest.FunctionTestCase(lambda: None)
555 def return_TestSuite():
556 return unittest.TestSuite([testcase_1, testcase_2])
557 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000558
Georg Brandl15c5ce92007-03-07 09:09:40 +0000559 loader = unittest.TestLoader()
560 suite = loader.loadTestsFromName('return_TestSuite', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000561 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000562 self.assertEqual(list(suite), [testcase_1, testcase_2])
Tim Petersea5962f2007-03-12 18:07:52 +0000563
Georg Brandl15c5ce92007-03-07 09:09:40 +0000564 # "The specifier name is a ``dotted name'' that may resolve ... to
565 # ... a callable object which returns a TestCase ... instance"
566 def test_loadTestsFromName__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000567 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000568 testcase_1 = unittest.FunctionTestCase(lambda: None)
569 def return_TestCase():
570 return testcase_1
571 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000572
Georg Brandl15c5ce92007-03-07 09:09:40 +0000573 loader = unittest.TestLoader()
574 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000575 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000576 self.assertEqual(list(suite), [testcase_1])
Tim Petersea5962f2007-03-12 18:07:52 +0000577
Georg Brandl15c5ce92007-03-07 09:09:40 +0000578 # "The specifier name is a ``dotted name'' that may resolve ... to
Michael Foord5a9719d2009-09-13 17:28:35 +0000579 # ... a callable object which returns a TestCase ... instance"
580 #*****************************************************************
581 #Override the suiteClass attribute to ensure that the suiteClass
582 #attribute is used
583 def test_loadTestsFromName__callable__TestCase_instance_ProperSuiteClass(self):
584 class SubTestSuite(unittest.TestSuite):
585 pass
586 m = types.ModuleType('m')
587 testcase_1 = unittest.FunctionTestCase(lambda: None)
588 def return_TestCase():
589 return testcase_1
590 m.return_TestCase = return_TestCase
591
592 loader = unittest.TestLoader()
593 loader.suiteClass = SubTestSuite
594 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000595 self.assertIsInstance(suite, loader.suiteClass)
Michael Foord5a9719d2009-09-13 17:28:35 +0000596 self.assertEqual(list(suite), [testcase_1])
597
598 # "The specifier name is a ``dotted name'' that may resolve ... to
599 # ... a test method within a test case class"
600 #*****************************************************************
601 #Override the suiteClass attribute to ensure that the suiteClass
602 #attribute is used
603 def test_loadTestsFromName__relative_testmethod_ProperSuiteClass(self):
604 class SubTestSuite(unittest.TestSuite):
605 pass
606 m = types.ModuleType('m')
607 class MyTestCase(unittest.TestCase):
608 def test(self):
609 pass
610 m.testcase_1 = MyTestCase
611
612 loader = unittest.TestLoader()
613 loader.suiteClass=SubTestSuite
614 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000615 self.assertIsInstance(suite, loader.suiteClass)
Michael Foord5a9719d2009-09-13 17:28:35 +0000616
617 self.assertEqual(list(suite), [MyTestCase('test')])
618
619 # "The specifier name is a ``dotted name'' that may resolve ... to
Georg Brandl15c5ce92007-03-07 09:09:40 +0000620 # ... a callable object which returns a TestCase or TestSuite instance"
621 #
622 # What happens if the callable returns something else?
623 def test_loadTestsFromName__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000624 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000625 def return_wrong():
626 return 6
627 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000628
Georg Brandl15c5ce92007-03-07 09:09:40 +0000629 loader = unittest.TestLoader()
630 try:
631 suite = loader.loadTestsFromName('return_wrong', m)
632 except TypeError:
633 pass
634 else:
635 self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000636
Georg Brandl15c5ce92007-03-07 09:09:40 +0000637 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +0000638 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +0000639 def test_loadTestsFromName__module_not_loaded(self):
640 # We're going to try to load this module as a side-effect, so it
641 # better not be loaded before we try.
642 #
643 # Why pick audioop? Google shows it isn't used very often, so there's
644 # a good chance that it won't be imported when this test is run
645 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +0000646
Georg Brandl15c5ce92007-03-07 09:09:40 +0000647 if module_name in sys.modules:
648 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000649
Georg Brandl15c5ce92007-03-07 09:09:40 +0000650 loader = unittest.TestLoader()
651 try:
652 suite = loader.loadTestsFromName(module_name)
653
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000654 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000655 self.assertEqual(list(suite), [])
656
657 # audioop should now be loaded, thanks to loadTestsFromName()
Ezio Melottiaa980582010-01-23 23:04:36 +0000658 self.assertIn(module_name, sys.modules)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000659 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000660 if module_name in sys.modules:
661 del sys.modules[module_name]
Georg Brandl15c5ce92007-03-07 09:09:40 +0000662
663 ################################################################
664 ### Tests for TestLoader.loadTestsFromName()
665
666 ### Tests for TestLoader.loadTestsFromNames()
667 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000668
Georg Brandl15c5ce92007-03-07 09:09:40 +0000669 # "Similar to loadTestsFromName(), but takes a sequence of names rather
670 # than a single name."
671 #
672 # What happens if that sequence of names is empty?
673 def test_loadTestsFromNames__empty_name_list(self):
674 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000675
Georg Brandl15c5ce92007-03-07 09:09:40 +0000676 suite = loader.loadTestsFromNames([])
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000677 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000678 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000679
Georg Brandl15c5ce92007-03-07 09:09:40 +0000680 # "Similar to loadTestsFromName(), but takes a sequence of names rather
681 # than a single name."
682 # ...
683 # "The method optionally resolves name relative to the given module"
684 #
685 # What happens if that sequence of names is empty?
686 #
687 # XXX Should this raise a ValueError or just return an empty TestSuite?
688 def test_loadTestsFromNames__relative_empty_name_list(self):
689 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000690
Georg Brandl15c5ce92007-03-07 09:09:40 +0000691 suite = loader.loadTestsFromNames([], unittest)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000692 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000693 self.assertEqual(list(suite), [])
694
695 # "The specifier name is a ``dotted name'' that may resolve either to
696 # a module, a test case class, a TestSuite instance, a test method
697 # within a test case class, or a callable object which returns a
698 # TestCase or TestSuite instance."
699 #
700 # Is ValueError raised in response to an empty name?
701 def test_loadTestsFromNames__empty_name(self):
702 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000703
Georg Brandl15c5ce92007-03-07 09:09:40 +0000704 try:
705 loader.loadTestsFromNames([''])
706 except ValueError, e:
707 self.assertEqual(str(e), "Empty module name")
708 else:
709 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000710
Georg Brandl15c5ce92007-03-07 09:09:40 +0000711 # "The specifier name is a ``dotted name'' that may resolve either to
712 # a module, a test case class, a TestSuite instance, a test method
713 # within a test case class, or a callable object which returns a
714 # TestCase or TestSuite instance."
715 #
Tim Petersea5962f2007-03-12 18:07:52 +0000716 # What happens when presented with an impossible module name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000717 def test_loadTestsFromNames__malformed_name(self):
718 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000719
Georg Brandl15c5ce92007-03-07 09:09:40 +0000720 # XXX Should this raise ValueError or ImportError?
721 try:
722 loader.loadTestsFromNames(['abc () //'])
723 except ValueError:
724 pass
725 except ImportError:
726 pass
727 else:
728 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000729
Georg Brandl15c5ce92007-03-07 09:09:40 +0000730 # "The specifier name is a ``dotted name'' that may resolve either to
731 # a module, a test case class, a TestSuite instance, a test method
732 # within a test case class, or a callable object which returns a
733 # TestCase or TestSuite instance."
734 #
Tim Petersea5962f2007-03-12 18:07:52 +0000735 # What happens when no module can be found for the given name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000736 def test_loadTestsFromNames__unknown_module_name(self):
737 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000738
Georg Brandl15c5ce92007-03-07 09:09:40 +0000739 try:
740 loader.loadTestsFromNames(['sdasfasfasdf'])
741 except ImportError, e:
742 self.assertEqual(str(e), "No module named sdasfasfasdf")
743 else:
744 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000745
Georg Brandl15c5ce92007-03-07 09:09:40 +0000746 # "The specifier name is a ``dotted name'' that may resolve either to
747 # a module, a test case class, a TestSuite instance, a test method
748 # within a test case class, or a callable object which returns a
749 # TestCase or TestSuite instance."
750 #
Tim Petersea5962f2007-03-12 18:07:52 +0000751 # What happens when the module can be found, but not the attribute?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000752 def test_loadTestsFromNames__unknown_attr_name(self):
753 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000754
Georg Brandl15c5ce92007-03-07 09:09:40 +0000755 try:
756 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
757 except AttributeError, e:
758 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
759 else:
760 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000761
Georg Brandl15c5ce92007-03-07 09:09:40 +0000762 # "The specifier name is a ``dotted name'' that may resolve either to
763 # a module, a test case class, a TestSuite instance, a test method
764 # within a test case class, or a callable object which returns a
765 # TestCase or TestSuite instance."
766 # ...
767 # "The method optionally resolves name relative to the given module"
768 #
769 # What happens when given an unknown attribute on a specified `module`
770 # argument?
771 def test_loadTestsFromNames__unknown_name_relative_1(self):
772 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000773
Georg Brandl15c5ce92007-03-07 09:09:40 +0000774 try:
775 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
776 except AttributeError, e:
777 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
778 else:
779 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000780
Georg Brandl15c5ce92007-03-07 09:09:40 +0000781 # "The specifier name is a ``dotted name'' that may resolve either to
782 # a module, a test case class, a TestSuite instance, a test method
783 # within a test case class, or a callable object which returns a
784 # TestCase or TestSuite instance."
785 # ...
786 # "The method optionally resolves name relative to the given module"
787 #
788 # Do unknown attributes (relative to a provided module) still raise an
Tim Petersea5962f2007-03-12 18:07:52 +0000789 # exception even in the presence of valid attribute names?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000790 def test_loadTestsFromNames__unknown_name_relative_2(self):
791 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000792
Georg Brandl15c5ce92007-03-07 09:09:40 +0000793 try:
794 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
795 except AttributeError, e:
796 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
797 else:
798 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
799
800 # "The specifier name is a ``dotted name'' that may resolve either to
801 # a module, a test case class, a TestSuite instance, a test method
802 # within a test case class, or a callable object which returns a
803 # TestCase or TestSuite instance."
804 # ...
805 # "The method optionally resolves name relative to the given module"
806 #
807 # What happens when faced with the empty string?
808 #
809 # XXX This currently raises AttributeError, though ValueError is probably
810 # more appropriate
811 def test_loadTestsFromNames__relative_empty_name(self):
812 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000813
Georg Brandl15c5ce92007-03-07 09:09:40 +0000814 try:
815 loader.loadTestsFromNames([''], unittest)
816 except AttributeError:
817 pass
818 else:
819 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000820
Georg Brandl15c5ce92007-03-07 09:09:40 +0000821 # "The specifier name is a ``dotted name'' that may resolve either to
822 # a module, a test case class, a TestSuite instance, a test method
823 # within a test case class, or a callable object which returns a
824 # TestCase or TestSuite instance."
825 # ...
826 # "The method optionally resolves name relative to the given module"
827 #
Tim Petersea5962f2007-03-12 18:07:52 +0000828 # What happens when presented with an impossible attribute name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000829 def test_loadTestsFromNames__relative_malformed_name(self):
830 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000831
Georg Brandl15c5ce92007-03-07 09:09:40 +0000832 # XXX Should this raise AttributeError or ValueError?
833 try:
834 loader.loadTestsFromNames(['abc () //'], unittest)
835 except AttributeError:
836 pass
837 except ValueError:
838 pass
839 else:
840 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
841
842 # "The method optionally resolves name relative to the given module"
843 #
844 # Does loadTestsFromNames() make sure the provided `module` is in fact
845 # a module?
846 #
847 # XXX This validation is currently not done. This flexibility should
848 # either be documented or a TypeError should be raised.
849 def test_loadTestsFromNames__relative_not_a_module(self):
850 class MyTestCase(unittest.TestCase):
851 def test(self):
852 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000853
Georg Brandl15c5ce92007-03-07 09:09:40 +0000854 class NotAModule(object):
855 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000856
Georg Brandl15c5ce92007-03-07 09:09:40 +0000857 loader = unittest.TestLoader()
858 suite = loader.loadTestsFromNames(['test_2'], NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000859
Georg Brandl15c5ce92007-03-07 09:09:40 +0000860 reference = [unittest.TestSuite([MyTestCase('test')])]
861 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000862
Georg Brandl15c5ce92007-03-07 09:09:40 +0000863 # "The specifier name is a ``dotted name'' that may resolve either to
864 # a module, a test case class, a TestSuite instance, a test method
865 # within a test case class, or a callable object which returns a
866 # TestCase or TestSuite instance."
867 #
868 # Does it raise an exception if the name resolves to an invalid
869 # object?
870 def test_loadTestsFromNames__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000871 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000872 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000873
Georg Brandl15c5ce92007-03-07 09:09:40 +0000874 loader = unittest.TestLoader()
875 try:
876 loader.loadTestsFromNames(['testcase_1'], m)
877 except TypeError:
878 pass
879 else:
880 self.fail("Should have raised TypeError")
881
882 # "The specifier name is a ``dotted name'' that may resolve ... to
883 # ... a test case class"
884 def test_loadTestsFromNames__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000885 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000886 class MyTestCase(unittest.TestCase):
887 def test(self):
888 pass
889 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000890
Georg Brandl15c5ce92007-03-07 09:09:40 +0000891 loader = unittest.TestLoader()
892 suite = loader.loadTestsFromNames(['testcase_1'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000893 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000894
Georg Brandl15c5ce92007-03-07 09:09:40 +0000895 expected = loader.suiteClass([MyTestCase('test')])
896 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000897
Georg Brandl15c5ce92007-03-07 09:09:40 +0000898 # "The specifier name is a ``dotted name'' that may resolve ... to
899 # ... a TestSuite instance"
900 def test_loadTestsFromNames__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000901 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000902 class MyTestCase(unittest.TestCase):
903 def test(self):
904 pass
905 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000906
Georg Brandl15c5ce92007-03-07 09:09:40 +0000907 loader = unittest.TestLoader()
908 suite = loader.loadTestsFromNames(['testsuite'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000909 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000910
Georg Brandl15c5ce92007-03-07 09:09:40 +0000911 self.assertEqual(list(suite), [m.testsuite])
Tim Petersea5962f2007-03-12 18:07:52 +0000912
Georg Brandl15c5ce92007-03-07 09:09:40 +0000913 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
914 # test method within a test case class"
915 def test_loadTestsFromNames__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000916 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000917 class MyTestCase(unittest.TestCase):
918 def test(self):
919 pass
920 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000921
Georg Brandl15c5ce92007-03-07 09:09:40 +0000922 loader = unittest.TestLoader()
923 suite = loader.loadTestsFromNames(['testcase_1.test'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000924 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000925
Georg Brandl15c5ce92007-03-07 09:09:40 +0000926 ref_suite = unittest.TestSuite([MyTestCase('test')])
927 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000928
Georg Brandl15c5ce92007-03-07 09:09:40 +0000929 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
930 # test method within a test case class"
931 #
932 # Does the method gracefully handle names that initially look like they
Tim Petersea5962f2007-03-12 18:07:52 +0000933 # resolve to "a test method within a test case class" but don't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000934 def test_loadTestsFromNames__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000935 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000936 class MyTestCase(unittest.TestCase):
937 def test(self):
938 pass
939 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000940
Georg Brandl15c5ce92007-03-07 09:09:40 +0000941 loader = unittest.TestLoader()
942 try:
943 loader.loadTestsFromNames(['testcase_1.testfoo'], m)
944 except AttributeError, e:
945 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
946 else:
947 self.fail("Failed to raise AttributeError")
948
949 # "The specifier name is a ``dotted name'' that may resolve ... to
950 # ... a callable object which returns a ... TestSuite instance"
951 def test_loadTestsFromNames__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000952 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000953 testcase_1 = unittest.FunctionTestCase(lambda: None)
954 testcase_2 = unittest.FunctionTestCase(lambda: None)
955 def return_TestSuite():
956 return unittest.TestSuite([testcase_1, testcase_2])
957 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000958
Georg Brandl15c5ce92007-03-07 09:09:40 +0000959 loader = unittest.TestLoader()
960 suite = loader.loadTestsFromNames(['return_TestSuite'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000961 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000962
Georg Brandl15c5ce92007-03-07 09:09:40 +0000963 expected = unittest.TestSuite([testcase_1, testcase_2])
964 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000965
Georg Brandl15c5ce92007-03-07 09:09:40 +0000966 # "The specifier name is a ``dotted name'' that may resolve ... to
967 # ... a callable object which returns a TestCase ... instance"
968 def test_loadTestsFromNames__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000969 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000970 testcase_1 = unittest.FunctionTestCase(lambda: None)
971 def return_TestCase():
972 return testcase_1
973 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000974
Georg Brandl15c5ce92007-03-07 09:09:40 +0000975 loader = unittest.TestLoader()
976 suite = loader.loadTestsFromNames(['return_TestCase'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000977 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000978
Georg Brandl15c5ce92007-03-07 09:09:40 +0000979 ref_suite = unittest.TestSuite([testcase_1])
980 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000981
Georg Brandl15c5ce92007-03-07 09:09:40 +0000982 # "The specifier name is a ``dotted name'' that may resolve ... to
983 # ... a callable object which returns a TestCase or TestSuite instance"
984 #
Tim Petersea5962f2007-03-12 18:07:52 +0000985 # Are staticmethods handled correctly?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000986 def test_loadTestsFromNames__callable__call_staticmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000987 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000988 class Test1(unittest.TestCase):
989 def test(self):
990 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000991
Georg Brandl15c5ce92007-03-07 09:09:40 +0000992 testcase_1 = Test1('test')
993 class Foo(unittest.TestCase):
994 @staticmethod
995 def foo():
996 return testcase_1
997 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +0000998
Georg Brandl15c5ce92007-03-07 09:09:40 +0000999 loader = unittest.TestLoader()
1000 suite = loader.loadTestsFromNames(['Foo.foo'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001001 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +00001002
Georg Brandl15c5ce92007-03-07 09:09:40 +00001003 ref_suite = unittest.TestSuite([testcase_1])
1004 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +00001005
Georg Brandl15c5ce92007-03-07 09:09:40 +00001006 # "The specifier name is a ``dotted name'' that may resolve ... to
1007 # ... a callable object which returns a TestCase or TestSuite instance"
1008 #
1009 # What happens when the callable returns something else?
1010 def test_loadTestsFromNames__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001011 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001012 def return_wrong():
1013 return 6
1014 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +00001015
Georg Brandl15c5ce92007-03-07 09:09:40 +00001016 loader = unittest.TestLoader()
1017 try:
1018 suite = loader.loadTestsFromNames(['return_wrong'], m)
1019 except TypeError:
1020 pass
1021 else:
1022 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +00001023
Georg Brandl15c5ce92007-03-07 09:09:40 +00001024 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +00001025 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001026 def test_loadTestsFromNames__module_not_loaded(self):
1027 # We're going to try to load this module as a side-effect, so it
1028 # better not be loaded before we try.
1029 #
1030 # Why pick audioop? Google shows it isn't used very often, so there's
1031 # a good chance that it won't be imported when this test is run
1032 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +00001033
Georg Brandl15c5ce92007-03-07 09:09:40 +00001034 if module_name in sys.modules:
1035 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +00001036
Georg Brandl15c5ce92007-03-07 09:09:40 +00001037 loader = unittest.TestLoader()
1038 try:
1039 suite = loader.loadTestsFromNames([module_name])
1040
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001041 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +00001042 self.assertEqual(list(suite), [unittest.TestSuite()])
1043
1044 # audioop should now be loaded, thanks to loadTestsFromName()
Ezio Melottiaa980582010-01-23 23:04:36 +00001045 self.assertIn(module_name, sys.modules)
Georg Brandl15c5ce92007-03-07 09:09:40 +00001046 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +00001047 if module_name in sys.modules:
1048 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +00001049
Georg Brandl15c5ce92007-03-07 09:09:40 +00001050 ################################################################
1051 ### /Tests for TestLoader.loadTestsFromNames()
1052
1053 ### Tests for TestLoader.getTestCaseNames()
1054 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001055
Georg Brandl15c5ce92007-03-07 09:09:40 +00001056 # "Return a sorted sequence of method names found within testCaseClass"
1057 #
1058 # Test.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +00001059 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +00001060 def test_getTestCaseNames(self):
1061 class Test(unittest.TestCase):
1062 def test_1(self): pass
1063 def test_2(self): pass
1064 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001065
Georg Brandl15c5ce92007-03-07 09:09:40 +00001066 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001067
Georg Brandl15c5ce92007-03-07 09:09:40 +00001068 self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])
Tim Petersea5962f2007-03-12 18:07:52 +00001069
Georg Brandl15c5ce92007-03-07 09:09:40 +00001070 # "Return a sorted sequence of method names found within testCaseClass"
1071 #
Tim Petersea5962f2007-03-12 18:07:52 +00001072 # Does getTestCaseNames() behave appropriately if no tests are found?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001073 def test_getTestCaseNames__no_tests(self):
1074 class Test(unittest.TestCase):
1075 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001076
Georg Brandl15c5ce92007-03-07 09:09:40 +00001077 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001078
Georg Brandl15c5ce92007-03-07 09:09:40 +00001079 self.assertEqual(loader.getTestCaseNames(Test), [])
Tim Petersea5962f2007-03-12 18:07:52 +00001080
Georg Brandl15c5ce92007-03-07 09:09:40 +00001081 # "Return a sorted sequence of method names found within testCaseClass"
1082 #
1083 # Are not-TestCases handled gracefully?
1084 #
1085 # XXX This should raise a TypeError, not return a list
1086 #
1087 # XXX It's too late in the 2.5 release cycle to fix this, but it should
1088 # probably be revisited for 2.6
1089 def test_getTestCaseNames__not_a_TestCase(self):
1090 class BadCase(int):
1091 def test_foo(self):
1092 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001093
Georg Brandl15c5ce92007-03-07 09:09:40 +00001094 loader = unittest.TestLoader()
1095 names = loader.getTestCaseNames(BadCase)
Tim Petersea5962f2007-03-12 18:07:52 +00001096
Georg Brandl15c5ce92007-03-07 09:09:40 +00001097 self.assertEqual(names, ['test_foo'])
Tim Petersea5962f2007-03-12 18:07:52 +00001098
Georg Brandl15c5ce92007-03-07 09:09:40 +00001099 # "Return a sorted sequence of method names found within testCaseClass"
1100 #
1101 # Make sure inherited names are handled.
1102 #
1103 # TestP.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +00001104 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +00001105 def test_getTestCaseNames__inheritance(self):
1106 class TestP(unittest.TestCase):
1107 def test_1(self): pass
1108 def test_2(self): pass
1109 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001110
Georg Brandl15c5ce92007-03-07 09:09:40 +00001111 class TestC(TestP):
1112 def test_1(self): pass
1113 def test_3(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001114
Georg Brandl15c5ce92007-03-07 09:09:40 +00001115 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001116
Georg Brandl15c5ce92007-03-07 09:09:40 +00001117 names = ['test_1', 'test_2', 'test_3']
1118 self.assertEqual(loader.getTestCaseNames(TestC), names)
Tim Petersea5962f2007-03-12 18:07:52 +00001119
1120 ################################################################
Georg Brandl15c5ce92007-03-07 09:09:40 +00001121 ### /Tests for TestLoader.getTestCaseNames()
1122
1123 ### Tests for TestLoader.testMethodPrefix
1124 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001125
Georg Brandl15c5ce92007-03-07 09:09:40 +00001126 # "String giving the prefix of method names which will be interpreted as
1127 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001128 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001129 # Implicit in the documentation is that testMethodPrefix is respected by
1130 # all loadTestsFrom* methods.
1131 def test_testMethodPrefix__loadTestsFromTestCase(self):
1132 class Foo(unittest.TestCase):
1133 def test_1(self): pass
1134 def test_2(self): pass
1135 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001136
Georg Brandl15c5ce92007-03-07 09:09:40 +00001137 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1138 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001139
Georg Brandl15c5ce92007-03-07 09:09:40 +00001140 loader = unittest.TestLoader()
1141 loader.testMethodPrefix = 'foo'
1142 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
1143
1144 loader.testMethodPrefix = 'test'
1145 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001146
Georg Brandl15c5ce92007-03-07 09:09:40 +00001147 # "String giving the prefix of method names which will be interpreted as
1148 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001149 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001150 # Implicit in the documentation is that testMethodPrefix is respected by
1151 # all loadTestsFrom* methods.
1152 def test_testMethodPrefix__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001153 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001154 class Foo(unittest.TestCase):
1155 def test_1(self): pass
1156 def test_2(self): pass
1157 def foo_bar(self): pass
1158 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001159
Georg Brandl15c5ce92007-03-07 09:09:40 +00001160 tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
1161 tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]
Tim Petersea5962f2007-03-12 18:07:52 +00001162
Georg Brandl15c5ce92007-03-07 09:09:40 +00001163 loader = unittest.TestLoader()
1164 loader.testMethodPrefix = 'foo'
1165 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
1166
1167 loader.testMethodPrefix = 'test'
1168 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001169
Georg Brandl15c5ce92007-03-07 09:09:40 +00001170 # "String giving the prefix of method names which will be interpreted as
1171 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001172 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001173 # Implicit in the documentation is that testMethodPrefix is respected by
1174 # all loadTestsFrom* methods.
1175 def test_testMethodPrefix__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001176 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001177 class Foo(unittest.TestCase):
1178 def test_1(self): pass
1179 def test_2(self): pass
1180 def foo_bar(self): pass
1181 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001182
Georg Brandl15c5ce92007-03-07 09:09:40 +00001183 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1184 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001185
Georg Brandl15c5ce92007-03-07 09:09:40 +00001186 loader = unittest.TestLoader()
1187 loader.testMethodPrefix = 'foo'
1188 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
1189
1190 loader.testMethodPrefix = 'test'
1191 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001192
Georg Brandl15c5ce92007-03-07 09:09:40 +00001193 # "String giving the prefix of method names which will be interpreted as
1194 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001195 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001196 # Implicit in the documentation is that testMethodPrefix is respected by
1197 # all loadTestsFrom* methods.
1198 def test_testMethodPrefix__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001199 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001200 class Foo(unittest.TestCase):
1201 def test_1(self): pass
1202 def test_2(self): pass
1203 def foo_bar(self): pass
1204 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001205
Georg Brandl15c5ce92007-03-07 09:09:40 +00001206 tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
1207 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1208 tests_2 = unittest.TestSuite([tests_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001209
Georg Brandl15c5ce92007-03-07 09:09:40 +00001210 loader = unittest.TestLoader()
1211 loader.testMethodPrefix = 'foo'
1212 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)
1213
1214 loader.testMethodPrefix = 'test'
1215 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001216
Georg Brandl15c5ce92007-03-07 09:09:40 +00001217 # "The default value is 'test'"
1218 def test_testMethodPrefix__default_value(self):
1219 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001220 self.assertTrue(loader.testMethodPrefix == 'test')
Tim Petersea5962f2007-03-12 18:07:52 +00001221
Georg Brandl15c5ce92007-03-07 09:09:40 +00001222 ################################################################
1223 ### /Tests for TestLoader.testMethodPrefix
1224
Tim Petersea5962f2007-03-12 18:07:52 +00001225 ### Tests for TestLoader.sortTestMethodsUsing
Georg Brandl15c5ce92007-03-07 09:09:40 +00001226 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001227
Georg Brandl15c5ce92007-03-07 09:09:40 +00001228 # "Function to be used to compare method names when sorting them in
1229 # getTestCaseNames() and all the loadTestsFromX() methods"
1230 def test_sortTestMethodsUsing__loadTestsFromTestCase(self):
1231 def reversed_cmp(x, y):
1232 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001233
Georg Brandl15c5ce92007-03-07 09:09:40 +00001234 class Foo(unittest.TestCase):
1235 def test_1(self): pass
1236 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001237
Georg Brandl15c5ce92007-03-07 09:09:40 +00001238 loader = unittest.TestLoader()
1239 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001240
Georg Brandl15c5ce92007-03-07 09:09:40 +00001241 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1242 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001243
Georg Brandl15c5ce92007-03-07 09:09:40 +00001244 # "Function to be used to compare method names when sorting them in
1245 # getTestCaseNames() and all the loadTestsFromX() methods"
1246 def test_sortTestMethodsUsing__loadTestsFromModule(self):
1247 def reversed_cmp(x, y):
1248 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001249
Christian Heimesc756d002007-11-27 21:34:01 +00001250 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001251 class Foo(unittest.TestCase):
1252 def test_1(self): pass
1253 def test_2(self): pass
1254 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001255
Georg Brandl15c5ce92007-03-07 09:09:40 +00001256 loader = unittest.TestLoader()
1257 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001258
Georg Brandl15c5ce92007-03-07 09:09:40 +00001259 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1260 self.assertEqual(list(loader.loadTestsFromModule(m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001261
Georg Brandl15c5ce92007-03-07 09:09:40 +00001262 # "Function to be used to compare method names when sorting them in
1263 # getTestCaseNames() and all the loadTestsFromX() methods"
1264 def test_sortTestMethodsUsing__loadTestsFromName(self):
1265 def reversed_cmp(x, y):
1266 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001267
Christian Heimesc756d002007-11-27 21:34:01 +00001268 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001269 class Foo(unittest.TestCase):
1270 def test_1(self): pass
1271 def test_2(self): pass
1272 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001273
Georg Brandl15c5ce92007-03-07 09:09:40 +00001274 loader = unittest.TestLoader()
1275 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001276
Georg Brandl15c5ce92007-03-07 09:09:40 +00001277 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1278 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001279
Georg Brandl15c5ce92007-03-07 09:09:40 +00001280 # "Function to be used to compare method names when sorting them in
1281 # getTestCaseNames() and all the loadTestsFromX() methods"
1282 def test_sortTestMethodsUsing__loadTestsFromNames(self):
1283 def reversed_cmp(x, y):
1284 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001285
Christian Heimesc756d002007-11-27 21:34:01 +00001286 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001287 class Foo(unittest.TestCase):
1288 def test_1(self): pass
1289 def test_2(self): pass
1290 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001291
Georg Brandl15c5ce92007-03-07 09:09:40 +00001292 loader = unittest.TestLoader()
1293 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001294
Georg Brandl15c5ce92007-03-07 09:09:40 +00001295 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1296 self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001297
Georg Brandl15c5ce92007-03-07 09:09:40 +00001298 # "Function to be used to compare method names when sorting them in
1299 # getTestCaseNames()"
1300 #
1301 # Does it actually affect getTestCaseNames()?
1302 def test_sortTestMethodsUsing__getTestCaseNames(self):
1303 def reversed_cmp(x, y):
1304 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001305
Georg Brandl15c5ce92007-03-07 09:09:40 +00001306 class Foo(unittest.TestCase):
1307 def test_1(self): pass
1308 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001309
Georg Brandl15c5ce92007-03-07 09:09:40 +00001310 loader = unittest.TestLoader()
1311 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001312
Georg Brandl15c5ce92007-03-07 09:09:40 +00001313 test_names = ['test_2', 'test_1']
1314 self.assertEqual(loader.getTestCaseNames(Foo), test_names)
Tim Petersea5962f2007-03-12 18:07:52 +00001315
Georg Brandl15c5ce92007-03-07 09:09:40 +00001316 # "The default value is the built-in cmp() function"
1317 def test_sortTestMethodsUsing__default_value(self):
1318 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001319 self.assertTrue(loader.sortTestMethodsUsing is cmp)
Tim Petersea5962f2007-03-12 18:07:52 +00001320
Georg Brandl15c5ce92007-03-07 09:09:40 +00001321 # "it can be set to None to disable the sort."
1322 #
1323 # XXX How is this different from reassigning cmp? Are the tests returned
1324 # in a random order or something? This behaviour should die
1325 def test_sortTestMethodsUsing__None(self):
1326 class Foo(unittest.TestCase):
1327 def test_1(self): pass
1328 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001329
Georg Brandl15c5ce92007-03-07 09:09:40 +00001330 loader = unittest.TestLoader()
1331 loader.sortTestMethodsUsing = None
Tim Petersea5962f2007-03-12 18:07:52 +00001332
Georg Brandl15c5ce92007-03-07 09:09:40 +00001333 test_names = ['test_2', 'test_1']
1334 self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))
Tim Petersea5962f2007-03-12 18:07:52 +00001335
Georg Brandl15c5ce92007-03-07 09:09:40 +00001336 ################################################################
1337 ### /Tests for TestLoader.sortTestMethodsUsing
Tim Petersea5962f2007-03-12 18:07:52 +00001338
Georg Brandl15c5ce92007-03-07 09:09:40 +00001339 ### Tests for TestLoader.suiteClass
1340 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001341
Georg Brandl15c5ce92007-03-07 09:09:40 +00001342 # "Callable object that constructs a test suite from a list of tests."
1343 def test_suiteClass__loadTestsFromTestCase(self):
1344 class Foo(unittest.TestCase):
1345 def test_1(self): pass
1346 def test_2(self): pass
1347 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001348
Georg Brandl15c5ce92007-03-07 09:09:40 +00001349 tests = [Foo('test_1'), Foo('test_2')]
1350
1351 loader = unittest.TestLoader()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001352 loader.suiteClass = list
Georg Brandl15c5ce92007-03-07 09:09:40 +00001353 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001354
Georg Brandl15c5ce92007-03-07 09:09:40 +00001355 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001356 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001357 def test_suiteClass__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001358 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001359 class Foo(unittest.TestCase):
1360 def test_1(self): pass
1361 def test_2(self): pass
1362 def foo_bar(self): pass
1363 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001364
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001365 tests = [[Foo('test_1'), Foo('test_2')]]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001366
1367 loader = unittest.TestLoader()
1368 loader.suiteClass = list
1369 self.assertEqual(loader.loadTestsFromModule(m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001370
Georg Brandl15c5ce92007-03-07 09:09:40 +00001371 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001372 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001373 def test_suiteClass__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001374 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001375 class Foo(unittest.TestCase):
1376 def test_1(self): pass
1377 def test_2(self): pass
1378 def foo_bar(self): pass
1379 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001380
Georg Brandl15c5ce92007-03-07 09:09:40 +00001381 tests = [Foo('test_1'), Foo('test_2')]
1382
1383 loader = unittest.TestLoader()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001384 loader.suiteClass = list
Georg Brandl15c5ce92007-03-07 09:09:40 +00001385 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001386
Georg Brandl15c5ce92007-03-07 09:09:40 +00001387 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001388 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001389 def test_suiteClass__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001390 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001391 class Foo(unittest.TestCase):
1392 def test_1(self): pass
1393 def test_2(self): pass
1394 def foo_bar(self): pass
1395 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001396
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001397 tests = [[Foo('test_1'), Foo('test_2')]]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001398
1399 loader = unittest.TestLoader()
1400 loader.suiteClass = list
1401 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001402
Georg Brandl15c5ce92007-03-07 09:09:40 +00001403 # "The default value is the TestSuite class"
1404 def test_suiteClass__default_value(self):
1405 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001406 self.assertTrue(loader.suiteClass is unittest.TestSuite)
Tim Petersea5962f2007-03-12 18:07:52 +00001407
Georg Brandl15c5ce92007-03-07 09:09:40 +00001408 ################################################################
1409 ### /Tests for TestLoader.suiteClass
1410
1411### Support code for Test_TestSuite
1412################################################################
1413
1414class Foo(unittest.TestCase):
1415 def test_1(self): pass
1416 def test_2(self): pass
1417 def test_3(self): pass
1418 def runTest(self): pass
1419
1420def _mk_TestSuite(*names):
1421 return unittest.TestSuite(Foo(n) for n in names)
Tim Petersea5962f2007-03-12 18:07:52 +00001422
Georg Brandl15c5ce92007-03-07 09:09:40 +00001423################################################################
1424### /Support code for Test_TestSuite
1425
1426class Test_TestSuite(TestCase, TestEquality):
1427
1428 ### Set up attributes needed by inherited tests
1429 ################################################################
1430
1431 # Used by TestEquality.test_eq
1432 eq_pairs = [(unittest.TestSuite(), unittest.TestSuite())
1433 ,(unittest.TestSuite(), unittest.TestSuite([]))
1434 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001435
1436 # Used by TestEquality.test_ne
Georg Brandl15c5ce92007-03-07 09:09:40 +00001437 ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1'))
1438 ,(unittest.TestSuite([]), _mk_TestSuite('test_1'))
1439 ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3'))
1440 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001441
Georg Brandl15c5ce92007-03-07 09:09:40 +00001442 ################################################################
1443 ### /Set up attributes needed by inherited tests
1444
1445 ### Tests for TestSuite.__init__
1446 ################################################################
1447
1448 # "class TestSuite([tests])"
1449 #
1450 # The tests iterable should be optional
1451 def test_init__tests_optional(self):
1452 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001453
Georg Brandl15c5ce92007-03-07 09:09:40 +00001454 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001455
Georg Brandl15c5ce92007-03-07 09:09:40 +00001456 # "class TestSuite([tests])"
1457 # ...
1458 # "If tests is given, it must be an iterable of individual test cases
1459 # or other test suites that will be used to build the suite initially"
1460 #
1461 # TestSuite should deal with empty tests iterables by allowing the
Tim Petersea5962f2007-03-12 18:07:52 +00001462 # creation of an empty suite
Georg Brandl15c5ce92007-03-07 09:09:40 +00001463 def test_init__empty_tests(self):
1464 suite = unittest.TestSuite([])
Tim Petersea5962f2007-03-12 18:07:52 +00001465
Georg Brandl15c5ce92007-03-07 09:09:40 +00001466 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001467
Georg Brandl15c5ce92007-03-07 09:09:40 +00001468 # "class TestSuite([tests])"
1469 # ...
1470 # "If tests is given, it must be an iterable of individual test cases
1471 # or other test suites that will be used to build the suite initially"
1472 #
Tim Petersea5962f2007-03-12 18:07:52 +00001473 # TestSuite should allow any iterable to provide tests
Georg Brandl15c5ce92007-03-07 09:09:40 +00001474 def test_init__tests_from_any_iterable(self):
1475 def tests():
1476 yield unittest.FunctionTestCase(lambda: None)
1477 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001478
Georg Brandl15c5ce92007-03-07 09:09:40 +00001479 suite_1 = unittest.TestSuite(tests())
1480 self.assertEqual(suite_1.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001481
Georg Brandl15c5ce92007-03-07 09:09:40 +00001482 suite_2 = unittest.TestSuite(suite_1)
1483 self.assertEqual(suite_2.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001484
Georg Brandl15c5ce92007-03-07 09:09:40 +00001485 suite_3 = unittest.TestSuite(set(suite_1))
1486 self.assertEqual(suite_3.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001487
Georg Brandl15c5ce92007-03-07 09:09:40 +00001488 # "class TestSuite([tests])"
1489 # ...
1490 # "If tests is given, it must be an iterable of individual test cases
1491 # or other test suites that will be used to build the suite initially"
1492 #
1493 # Does TestSuite() also allow other TestSuite() instances to be present
1494 # in the tests iterable?
1495 def test_init__TestSuite_instances_in_tests(self):
1496 def tests():
1497 ftc = unittest.FunctionTestCase(lambda: None)
1498 yield unittest.TestSuite([ftc])
1499 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001500
Georg Brandl15c5ce92007-03-07 09:09:40 +00001501 suite = unittest.TestSuite(tests())
1502 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001503
Georg Brandl15c5ce92007-03-07 09:09:40 +00001504 ################################################################
1505 ### /Tests for TestSuite.__init__
1506
1507 # Container types should support the iter protocol
1508 def test_iter(self):
1509 test1 = unittest.FunctionTestCase(lambda: None)
1510 test2 = unittest.FunctionTestCase(lambda: None)
1511 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001512
Georg Brandl15c5ce92007-03-07 09:09:40 +00001513 self.assertEqual(list(suite), [test1, test2])
Tim Petersea5962f2007-03-12 18:07:52 +00001514
Georg Brandl15c5ce92007-03-07 09:09:40 +00001515 # "Return the number of tests represented by the this test object.
1516 # ...this method is also implemented by the TestSuite class, which can
1517 # return larger [greater than 1] values"
1518 #
Tim Petersea5962f2007-03-12 18:07:52 +00001519 # Presumably an empty TestSuite returns 0?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001520 def test_countTestCases_zero_simple(self):
1521 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001522
Georg Brandl15c5ce92007-03-07 09:09:40 +00001523 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001524
Georg Brandl15c5ce92007-03-07 09:09:40 +00001525 # "Return the number of tests represented by the this test object.
1526 # ...this method is also implemented by the TestSuite class, which can
1527 # return larger [greater than 1] values"
1528 #
1529 # Presumably an empty TestSuite (even if it contains other empty
1530 # TestSuite instances) returns 0?
1531 def test_countTestCases_zero_nested(self):
1532 class Test1(unittest.TestCase):
1533 def test(self):
1534 pass
1535
1536 suite = unittest.TestSuite([unittest.TestSuite()])
Tim Petersea5962f2007-03-12 18:07:52 +00001537
Georg Brandl15c5ce92007-03-07 09:09:40 +00001538 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001539
Georg Brandl15c5ce92007-03-07 09:09:40 +00001540 # "Return the number of tests represented by the this test object.
1541 # ...this method is also implemented by the TestSuite class, which can
1542 # return larger [greater than 1] values"
1543 def test_countTestCases_simple(self):
1544 test1 = unittest.FunctionTestCase(lambda: None)
1545 test2 = unittest.FunctionTestCase(lambda: None)
1546 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001547
Georg Brandl15c5ce92007-03-07 09:09:40 +00001548 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001549
Georg Brandl15c5ce92007-03-07 09:09:40 +00001550 # "Return the number of tests represented by the this test object.
1551 # ...this method is also implemented by the TestSuite class, which can
1552 # return larger [greater than 1] values"
1553 #
1554 # Make sure this holds for nested TestSuite instances, too
1555 def test_countTestCases_nested(self):
1556 class Test1(unittest.TestCase):
1557 def test1(self): pass
1558 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001559
Georg Brandl15c5ce92007-03-07 09:09:40 +00001560 test2 = unittest.FunctionTestCase(lambda: None)
1561 test3 = unittest.FunctionTestCase(lambda: None)
1562 child = unittest.TestSuite((Test1('test2'), test2))
1563 parent = unittest.TestSuite((test3, child, Test1('test1')))
Tim Petersea5962f2007-03-12 18:07:52 +00001564
Georg Brandl15c5ce92007-03-07 09:09:40 +00001565 self.assertEqual(parent.countTestCases(), 4)
Tim Petersea5962f2007-03-12 18:07:52 +00001566
Georg Brandl15c5ce92007-03-07 09:09:40 +00001567 # "Run the tests associated with this suite, collecting the result into
1568 # the test result object passed as result."
1569 #
1570 # And if there are no tests? What then?
1571 def test_run__empty_suite(self):
1572 events = []
1573 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001574
Georg Brandl15c5ce92007-03-07 09:09:40 +00001575 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001576
Georg Brandl15c5ce92007-03-07 09:09:40 +00001577 suite.run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001578
Georg Brandl15c5ce92007-03-07 09:09:40 +00001579 self.assertEqual(events, [])
Tim Petersea5962f2007-03-12 18:07:52 +00001580
Georg Brandl15c5ce92007-03-07 09:09:40 +00001581 # "Note that unlike TestCase.run(), TestSuite.run() requires the
1582 # "result object to be passed in."
1583 def test_run__requires_result(self):
1584 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001585
Georg Brandl15c5ce92007-03-07 09:09:40 +00001586 try:
1587 suite.run()
1588 except TypeError:
1589 pass
1590 else:
1591 self.fail("Failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +00001592
Georg Brandl15c5ce92007-03-07 09:09:40 +00001593 # "Run the tests associated with this suite, collecting the result into
Tim Petersea5962f2007-03-12 18:07:52 +00001594 # the test result object passed as result."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001595 def test_run(self):
1596 events = []
1597 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001598
Georg Brandl15c5ce92007-03-07 09:09:40 +00001599 class LoggingCase(unittest.TestCase):
1600 def run(self, result):
1601 events.append('run %s' % self._testMethodName)
Tim Petersea5962f2007-03-12 18:07:52 +00001602
Georg Brandl15c5ce92007-03-07 09:09:40 +00001603 def test1(self): pass
1604 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001605
1606 tests = [LoggingCase('test1'), LoggingCase('test2')]
1607
Georg Brandl15c5ce92007-03-07 09:09:40 +00001608 unittest.TestSuite(tests).run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001609
Georg Brandl15c5ce92007-03-07 09:09:40 +00001610 self.assertEqual(events, ['run test1', 'run test2'])
Tim Petersea5962f2007-03-12 18:07:52 +00001611
1612 # "Add a TestCase ... to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001613 def test_addTest__TestCase(self):
1614 class Foo(unittest.TestCase):
1615 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001616
Georg Brandl15c5ce92007-03-07 09:09:40 +00001617 test = Foo('test')
1618 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001619
Georg Brandl15c5ce92007-03-07 09:09:40 +00001620 suite.addTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001621
Georg Brandl15c5ce92007-03-07 09:09:40 +00001622 self.assertEqual(suite.countTestCases(), 1)
1623 self.assertEqual(list(suite), [test])
Tim Petersea5962f2007-03-12 18:07:52 +00001624
1625 # "Add a ... TestSuite to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001626 def test_addTest__TestSuite(self):
1627 class Foo(unittest.TestCase):
1628 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001629
Georg Brandl15c5ce92007-03-07 09:09:40 +00001630 suite_2 = unittest.TestSuite([Foo('test')])
Tim Petersea5962f2007-03-12 18:07:52 +00001631
Georg Brandl15c5ce92007-03-07 09:09:40 +00001632 suite = unittest.TestSuite()
1633 suite.addTest(suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001634
Georg Brandl15c5ce92007-03-07 09:09:40 +00001635 self.assertEqual(suite.countTestCases(), 1)
1636 self.assertEqual(list(suite), [suite_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001637
Georg Brandl15c5ce92007-03-07 09:09:40 +00001638 # "Add all the tests from an iterable of TestCase and TestSuite
1639 # instances to this test suite."
Tim Petersea5962f2007-03-12 18:07:52 +00001640 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001641 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001642 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001643 def test_addTests(self):
1644 class Foo(unittest.TestCase):
1645 def test_1(self): pass
1646 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001647
Georg Brandl15c5ce92007-03-07 09:09:40 +00001648 test_1 = Foo('test_1')
1649 test_2 = Foo('test_2')
1650 inner_suite = unittest.TestSuite([test_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001651
Georg Brandl15c5ce92007-03-07 09:09:40 +00001652 def gen():
1653 yield test_1
1654 yield test_2
1655 yield inner_suite
Tim Petersea5962f2007-03-12 18:07:52 +00001656
Georg Brandl15c5ce92007-03-07 09:09:40 +00001657 suite_1 = unittest.TestSuite()
1658 suite_1.addTests(gen())
Tim Petersea5962f2007-03-12 18:07:52 +00001659
Georg Brandl15c5ce92007-03-07 09:09:40 +00001660 self.assertEqual(list(suite_1), list(gen()))
Tim Petersea5962f2007-03-12 18:07:52 +00001661
Georg Brandl15c5ce92007-03-07 09:09:40 +00001662 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001663 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001664 suite_2 = unittest.TestSuite()
1665 for t in gen():
1666 suite_2.addTest(t)
Tim Petersea5962f2007-03-12 18:07:52 +00001667
Georg Brandl15c5ce92007-03-07 09:09:40 +00001668 self.assertEqual(suite_1, suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001669
Georg Brandl15c5ce92007-03-07 09:09:40 +00001670 # "Add all the tests from an iterable of TestCase and TestSuite
1671 # instances to this test suite."
1672 #
Tim Petersea5962f2007-03-12 18:07:52 +00001673 # What happens if it doesn't get an iterable?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001674 def test_addTest__noniterable(self):
1675 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001676
Georg Brandl15c5ce92007-03-07 09:09:40 +00001677 try:
1678 suite.addTests(5)
1679 except TypeError:
1680 pass
1681 else:
1682 self.fail("Failed to raise TypeError")
Georg Brandld9e50262007-03-07 11:54:49 +00001683
1684 def test_addTest__noncallable(self):
1685 suite = unittest.TestSuite()
1686 self.assertRaises(TypeError, suite.addTest, 5)
1687
1688 def test_addTest__casesuiteclass(self):
1689 suite = unittest.TestSuite()
1690 self.assertRaises(TypeError, suite.addTest, Test_TestSuite)
1691 self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)
1692
1693 def test_addTests__string(self):
1694 suite = unittest.TestSuite()
1695 self.assertRaises(TypeError, suite.addTests, "foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001696
1697
Georg Brandl15c5ce92007-03-07 09:09:40 +00001698class Test_FunctionTestCase(TestCase):
Tim Petersea5962f2007-03-12 18:07:52 +00001699
Georg Brandl15c5ce92007-03-07 09:09:40 +00001700 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00001701 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001702 def test_countTestCases(self):
1703 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001704
Georg Brandl15c5ce92007-03-07 09:09:40 +00001705 self.assertEqual(test.countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00001706
Georg Brandl15c5ce92007-03-07 09:09:40 +00001707 # "When a setUp() method is defined, the test runner will run that method
1708 # prior to each test. Likewise, if a tearDown() method is defined, the
1709 # test runner will invoke that method after each test. In the example,
1710 # setUp() was used to create a fresh sequence for each test."
1711 #
1712 # Make sure the proper call order is maintained, even if setUp() raises
1713 # an exception.
1714 def test_run_call_order__error_in_setUp(self):
1715 events = []
1716 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001717
Georg Brandl15c5ce92007-03-07 09:09:40 +00001718 def setUp():
1719 events.append('setUp')
1720 raise RuntimeError('raised by setUp')
1721
1722 def test():
1723 events.append('test')
1724
1725 def tearDown():
1726 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001727
1728 expected = ['startTest', 'setUp', 'addError', 'stopTest']
Georg Brandl15c5ce92007-03-07 09:09:40 +00001729 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1730 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001731
Georg Brandl15c5ce92007-03-07 09:09:40 +00001732 # "When a setUp() method is defined, the test runner will run that method
1733 # prior to each test. Likewise, if a tearDown() method is defined, the
1734 # test runner will invoke that method after each test. In the example,
1735 # setUp() was used to create a fresh sequence for each test."
1736 #
1737 # Make sure the proper call order is maintained, even if the test raises
1738 # an error (as opposed to a failure).
1739 def test_run_call_order__error_in_test(self):
1740 events = []
1741 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001742
Georg Brandl15c5ce92007-03-07 09:09:40 +00001743 def setUp():
1744 events.append('setUp')
1745
1746 def test():
1747 events.append('test')
1748 raise RuntimeError('raised by test')
1749
1750 def tearDown():
1751 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001752
Georg Brandl15c5ce92007-03-07 09:09:40 +00001753 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
1754 'stopTest']
1755 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1756 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001757
Georg Brandl15c5ce92007-03-07 09:09:40 +00001758 # "When a setUp() method is defined, the test runner will run that method
1759 # prior to each test. Likewise, if a tearDown() method is defined, the
1760 # test runner will invoke that method after each test. In the example,
1761 # setUp() was used to create a fresh sequence for each test."
1762 #
1763 # Make sure the proper call order is maintained, even if the test signals
1764 # a failure (as opposed to an error).
1765 def test_run_call_order__failure_in_test(self):
1766 events = []
1767 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001768
Georg Brandl15c5ce92007-03-07 09:09:40 +00001769 def setUp():
1770 events.append('setUp')
1771
1772 def test():
1773 events.append('test')
1774 self.fail('raised by test')
1775
1776 def tearDown():
1777 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001778
Georg Brandl15c5ce92007-03-07 09:09:40 +00001779 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
1780 'stopTest']
1781 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1782 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001783
Georg Brandl15c5ce92007-03-07 09:09:40 +00001784 # "When a setUp() method is defined, the test runner will run that method
1785 # prior to each test. Likewise, if a tearDown() method is defined, the
1786 # test runner will invoke that method after each test. In the example,
1787 # setUp() was used to create a fresh sequence for each test."
1788 #
1789 # Make sure the proper call order is maintained, even if tearDown() raises
1790 # an exception.
1791 def test_run_call_order__error_in_tearDown(self):
1792 events = []
1793 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001794
Georg Brandl15c5ce92007-03-07 09:09:40 +00001795 def setUp():
1796 events.append('setUp')
1797
1798 def test():
1799 events.append('test')
1800
1801 def tearDown():
1802 events.append('tearDown')
1803 raise RuntimeError('raised by tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001804
Georg Brandl15c5ce92007-03-07 09:09:40 +00001805 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
1806 'stopTest']
1807 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1808 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001809
Georg Brandl15c5ce92007-03-07 09:09:40 +00001810 # "Return a string identifying the specific test case."
1811 #
1812 # Because of the vague nature of the docs, I'm not going to lock this
1813 # test down too much. Really all that can be asserted is that the id()
1814 # will be a string (either 8-byte or unicode -- again, because the docs
1815 # just say "string")
1816 def test_id(self):
1817 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001818
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001819 self.assertIsInstance(test.id(), basestring)
Tim Petersea5962f2007-03-12 18:07:52 +00001820
Georg Brandl15c5ce92007-03-07 09:09:40 +00001821 # "Returns a one-line description of the test, or None if no description
1822 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001823 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001824 def test_shortDescription__no_docstring(self):
1825 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001826
Georg Brandl15c5ce92007-03-07 09:09:40 +00001827 self.assertEqual(test.shortDescription(), None)
Tim Petersea5962f2007-03-12 18:07:52 +00001828
Georg Brandl15c5ce92007-03-07 09:09:40 +00001829 # "Returns a one-line description of the test, or None if no description
1830 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001831 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001832 def test_shortDescription__singleline_docstring(self):
1833 desc = "this tests foo"
1834 test = unittest.FunctionTestCase(lambda: None, description=desc)
Tim Petersea5962f2007-03-12 18:07:52 +00001835
Georg Brandl15c5ce92007-03-07 09:09:40 +00001836 self.assertEqual(test.shortDescription(), "this tests foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001837
Georg Brandl15c5ce92007-03-07 09:09:40 +00001838class Test_TestResult(TestCase):
1839 # Note: there are not separate tests for TestResult.wasSuccessful(),
1840 # TestResult.errors, TestResult.failures, TestResult.testsRun or
1841 # TestResult.shouldStop because these only have meaning in terms of
1842 # other TestResult methods.
1843 #
1844 # Accordingly, tests for the aforenamed attributes are incorporated
1845 # in with the tests for the defining methods.
1846 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001847
Georg Brandl15c5ce92007-03-07 09:09:40 +00001848 def test_init(self):
1849 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001850
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001851 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001852 self.assertEqual(len(result.errors), 0)
1853 self.assertEqual(len(result.failures), 0)
1854 self.assertEqual(result.testsRun, 0)
1855 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001856
Georg Brandl15c5ce92007-03-07 09:09:40 +00001857 # "This method can be called to signal that the set of tests being
1858 # run should be aborted by setting the TestResult's shouldStop
Tim Petersea5962f2007-03-12 18:07:52 +00001859 # attribute to True."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001860 def test_stop(self):
1861 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001862
Georg Brandl15c5ce92007-03-07 09:09:40 +00001863 result.stop()
Tim Petersea5962f2007-03-12 18:07:52 +00001864
Georg Brandl15c5ce92007-03-07 09:09:40 +00001865 self.assertEqual(result.shouldStop, True)
Tim Petersea5962f2007-03-12 18:07:52 +00001866
Georg Brandl15c5ce92007-03-07 09:09:40 +00001867 # "Called when the test case test is about to be run. The default
1868 # implementation simply increments the instance's testsRun counter."
1869 def test_startTest(self):
1870 class Foo(unittest.TestCase):
1871 def test_1(self):
1872 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001873
Georg Brandl15c5ce92007-03-07 09:09:40 +00001874 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001875
Georg Brandl15c5ce92007-03-07 09:09:40 +00001876 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001877
Georg Brandl15c5ce92007-03-07 09:09:40 +00001878 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001879
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001880 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001881 self.assertEqual(len(result.errors), 0)
1882 self.assertEqual(len(result.failures), 0)
1883 self.assertEqual(result.testsRun, 1)
1884 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001885
Georg Brandl15c5ce92007-03-07 09:09:40 +00001886 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001887
Georg Brandl15c5ce92007-03-07 09:09:40 +00001888 # "Called after the test case test has been executed, regardless of
1889 # the outcome. The default implementation does nothing."
1890 def test_stopTest(self):
1891 class Foo(unittest.TestCase):
1892 def test_1(self):
1893 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001894
Georg Brandl15c5ce92007-03-07 09:09:40 +00001895 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001896
Georg Brandl15c5ce92007-03-07 09:09:40 +00001897 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001898
Georg Brandl15c5ce92007-03-07 09:09:40 +00001899 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001900
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001901 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001902 self.assertEqual(len(result.errors), 0)
1903 self.assertEqual(len(result.failures), 0)
1904 self.assertEqual(result.testsRun, 1)
1905 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001906
Georg Brandl15c5ce92007-03-07 09:09:40 +00001907 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001908
Georg Brandl15c5ce92007-03-07 09:09:40 +00001909 # Same tests as above; make sure nothing has changed
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001910 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001911 self.assertEqual(len(result.errors), 0)
1912 self.assertEqual(len(result.failures), 0)
1913 self.assertEqual(result.testsRun, 1)
1914 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001915
Michael Foord07ef4872009-05-02 22:43:34 +00001916 # "Called before and after tests are run. The default implementation does nothing."
1917 def test_startTestRun_stopTestRun(self):
1918 result = unittest.TestResult()
1919 result.startTestRun()
1920 result.stopTestRun()
1921
Georg Brandl15c5ce92007-03-07 09:09:40 +00001922 # "addSuccess(test)"
1923 # ...
1924 # "Called when the test case test succeeds"
1925 # ...
1926 # "wasSuccessful() - Returns True if all tests run so far have passed,
1927 # otherwise returns False"
1928 # ...
1929 # "testsRun - The total number of tests run so far."
1930 # ...
1931 # "errors - A list containing 2-tuples of TestCase instances and
1932 # formatted tracebacks. Each tuple represents a test which raised an
1933 # unexpected exception. Contains formatted
1934 # tracebacks instead of sys.exc_info() results."
1935 # ...
1936 # "failures - A list containing 2-tuples of TestCase instances and
1937 # formatted tracebacks. Each tuple represents a test where a failure was
1938 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1939 # methods. Contains formatted tracebacks instead
1940 # of sys.exc_info() results."
1941 def test_addSuccess(self):
1942 class Foo(unittest.TestCase):
1943 def test_1(self):
1944 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001945
Georg Brandl15c5ce92007-03-07 09:09:40 +00001946 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001947
Georg Brandl15c5ce92007-03-07 09:09:40 +00001948 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001949
Georg Brandl15c5ce92007-03-07 09:09:40 +00001950 result.startTest(test)
1951 result.addSuccess(test)
1952 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001953
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001954 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001955 self.assertEqual(len(result.errors), 0)
1956 self.assertEqual(len(result.failures), 0)
1957 self.assertEqual(result.testsRun, 1)
1958 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001959
Georg Brandl15c5ce92007-03-07 09:09:40 +00001960 # "addFailure(test, err)"
1961 # ...
1962 # "Called when the test case test signals a failure. err is a tuple of
1963 # the form returned by sys.exc_info(): (type, value, traceback)"
1964 # ...
1965 # "wasSuccessful() - Returns True if all tests run so far have passed,
1966 # otherwise returns False"
1967 # ...
1968 # "testsRun - The total number of tests run so far."
1969 # ...
1970 # "errors - A list containing 2-tuples of TestCase instances and
1971 # formatted tracebacks. Each tuple represents a test which raised an
1972 # unexpected exception. Contains formatted
1973 # tracebacks instead of sys.exc_info() results."
1974 # ...
1975 # "failures - A list containing 2-tuples of TestCase instances and
1976 # formatted tracebacks. Each tuple represents a test where a failure was
1977 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1978 # methods. Contains formatted tracebacks instead
1979 # of sys.exc_info() results."
1980 def test_addFailure(self):
Georg Brandl15c5ce92007-03-07 09:09:40 +00001981 class Foo(unittest.TestCase):
1982 def test_1(self):
1983 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001984
Georg Brandl15c5ce92007-03-07 09:09:40 +00001985 test = Foo('test_1')
1986 try:
1987 test.fail("foo")
1988 except:
1989 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00001990
Georg Brandl15c5ce92007-03-07 09:09:40 +00001991 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001992
Georg Brandl15c5ce92007-03-07 09:09:40 +00001993 result.startTest(test)
1994 result.addFailure(test, exc_info_tuple)
1995 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001996
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001997 self.assertFalse(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001998 self.assertEqual(len(result.errors), 0)
1999 self.assertEqual(len(result.failures), 1)
2000 self.assertEqual(result.testsRun, 1)
2001 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00002002
Georg Brandl15c5ce92007-03-07 09:09:40 +00002003 test_case, formatted_exc = result.failures[0]
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002004 self.assertTrue(test_case is test)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002005 self.assertIsInstance(formatted_exc, str)
Tim Petersea5962f2007-03-12 18:07:52 +00002006
Georg Brandl15c5ce92007-03-07 09:09:40 +00002007 # "addError(test, err)"
2008 # ...
2009 # "Called when the test case test raises an unexpected exception err
2010 # is a tuple of the form returned by sys.exc_info():
2011 # (type, value, traceback)"
2012 # ...
2013 # "wasSuccessful() - Returns True if all tests run so far have passed,
2014 # otherwise returns False"
2015 # ...
2016 # "testsRun - The total number of tests run so far."
2017 # ...
2018 # "errors - A list containing 2-tuples of TestCase instances and
2019 # formatted tracebacks. Each tuple represents a test which raised an
2020 # unexpected exception. Contains formatted
2021 # tracebacks instead of sys.exc_info() results."
2022 # ...
2023 # "failures - A list containing 2-tuples of TestCase instances and
2024 # formatted tracebacks. Each tuple represents a test where a failure was
2025 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
2026 # methods. Contains formatted tracebacks instead
2027 # of sys.exc_info() results."
2028 def test_addError(self):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002029 class Foo(unittest.TestCase):
2030 def test_1(self):
2031 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002032
Georg Brandl15c5ce92007-03-07 09:09:40 +00002033 test = Foo('test_1')
2034 try:
2035 raise TypeError()
2036 except:
2037 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00002038
Georg Brandl15c5ce92007-03-07 09:09:40 +00002039 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00002040
Georg Brandl15c5ce92007-03-07 09:09:40 +00002041 result.startTest(test)
2042 result.addError(test, exc_info_tuple)
2043 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00002044
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002045 self.assertFalse(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00002046 self.assertEqual(len(result.errors), 1)
2047 self.assertEqual(len(result.failures), 0)
2048 self.assertEqual(result.testsRun, 1)
2049 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00002050
Georg Brandl15c5ce92007-03-07 09:09:40 +00002051 test_case, formatted_exc = result.errors[0]
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002052 self.assertTrue(test_case is test)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002053 self.assertIsInstance(formatted_exc, str)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002054
Michael Foorddb43b5a2010-02-10 14:25:12 +00002055 def testGetDescriptionWithoutDocstring(self):
Michael Foord1c3abf42010-02-10 15:50:58 +00002056 result = unittest.TextTestResult(None, True, 1)
Michael Foorddb43b5a2010-02-10 14:25:12 +00002057 self.assertEqual(
2058 result.getDescription(self),
2059 'testGetDescriptionWithoutDocstring (' + __name__ +
2060 '.Test_TestResult)')
2061
R. David Murrayf28fd242010-02-23 00:24:49 +00002062 @unittest.skipIf(sys.flags.optimize >= 2,
2063 "Docstrings are omitted with -O2 and above")
Michael Foorddb43b5a2010-02-10 14:25:12 +00002064 def testGetDescriptionWithOneLineDocstring(self):
2065 """Tests getDescription() for a method with a docstring."""
Michael Foord1c3abf42010-02-10 15:50:58 +00002066 result = unittest.TextTestResult(None, True, 1)
Michael Foorddb43b5a2010-02-10 14:25:12 +00002067 self.assertEqual(
2068 result.getDescription(self),
2069 ('testGetDescriptionWithOneLineDocstring '
2070 '(' + __name__ + '.Test_TestResult)\n'
2071 'Tests getDescription() for a method with a docstring.'))
2072
R. David Murrayf28fd242010-02-23 00:24:49 +00002073 @unittest.skipIf(sys.flags.optimize >= 2,
2074 "Docstrings are omitted with -O2 and above")
Michael Foorddb43b5a2010-02-10 14:25:12 +00002075 def testGetDescriptionWithMultiLineDocstring(self):
2076 """Tests getDescription() for a method with a longer docstring.
2077 The second line of the docstring.
2078 """
Michael Foord1c3abf42010-02-10 15:50:58 +00002079 result = unittest.TextTestResult(None, True, 1)
Michael Foorddb43b5a2010-02-10 14:25:12 +00002080 self.assertEqual(
2081 result.getDescription(self),
2082 ('testGetDescriptionWithMultiLineDocstring '
2083 '(' + __name__ + '.Test_TestResult)\n'
2084 'Tests getDescription() for a method with a longer '
2085 'docstring.'))
2086
Michael Foordb1aa30f2010-03-22 00:06:30 +00002087 def testStackFrameTrimming(self):
2088 class Frame(object):
2089 class tb_frame(object):
2090 f_globals = {}
2091 result = unittest.TestResult()
2092 self.assertFalse(result._is_relevant_tb_level(Frame))
2093
2094 Frame.tb_frame.f_globals['__unittest'] = True
2095 self.assertTrue(result._is_relevant_tb_level(Frame))
2096
Michael Foordae3db0a2010-02-22 23:28:32 +00002097classDict = dict(unittest.TestResult.__dict__)
Michael Foordd99ef9a2010-02-23 17:00:53 +00002098for m in ('addSkip', 'addExpectedFailure', 'addUnexpectedSuccess',
2099 '__init__'):
Michael Foordae3db0a2010-02-22 23:28:32 +00002100 del classDict[m]
Michael Foordd99ef9a2010-02-23 17:00:53 +00002101
2102def __init__(self, stream=None, descriptions=None, verbosity=None):
2103 self.failures = []
2104 self.errors = []
2105 self.testsRun = 0
2106 self.shouldStop = False
2107classDict['__init__'] = __init__
Michael Foordae3db0a2010-02-22 23:28:32 +00002108OldResult = type('OldResult', (object,), classDict)
2109
2110class Test_OldTestResult(unittest.TestCase):
2111
2112 def assertOldResultWarning(self, test, failures):
2113 with warnings.catch_warnings(record=True) as log:
2114 result = OldResult()
2115 test.run(result)
2116 self.assertEqual(len(result.failures), failures)
2117 warning, = log
2118 self.assertIs(warning.category, RuntimeWarning)
2119
2120 def testOldTestResult(self):
2121 class Test(unittest.TestCase):
2122 def testSkip(self):
2123 self.skipTest('foobar')
2124 @unittest.expectedFailure
2125 def testExpectedFail(self):
2126 raise TypeError
2127 @unittest.expectedFailure
2128 def testUnexpectedSuccess(self):
2129 pass
2130
2131 for test_name, should_pass in (('testSkip', True),
2132 ('testExpectedFail', True),
2133 ('testUnexpectedSuccess', False)):
2134 test = Test(test_name)
2135 self.assertOldResultWarning(test, int(not should_pass))
2136
2137 def testOldTestTesultSetup(self):
2138 class Test(unittest.TestCase):
2139 def setUp(self):
2140 self.skipTest('no reason')
2141 def testFoo(self):
2142 pass
2143 self.assertOldResultWarning(Test('testFoo'), 0)
2144
2145 def testOldTestResultClass(self):
2146 @unittest.skip('no reason')
2147 class Test(unittest.TestCase):
2148 def testFoo(self):
2149 pass
2150 self.assertOldResultWarning(Test('testFoo'), 0)
2151
Michael Foordd99ef9a2010-02-23 17:00:53 +00002152 def testOldResultWithRunner(self):
2153 class Test(unittest.TestCase):
2154 def testFoo(self):
2155 pass
2156 runner = unittest.TextTestRunner(resultclass=OldResult,
2157 stream=StringIO())
2158 # This will raise an exception if TextTestRunner can't handle old
2159 # test result objects
2160 runner.run(Test('testFoo'))
Michael Foorddb43b5a2010-02-10 14:25:12 +00002161
Georg Brandl15c5ce92007-03-07 09:09:40 +00002162### Support code for Test_TestCase
2163################################################################
2164
2165class Foo(unittest.TestCase):
2166 def runTest(self): pass
2167 def test1(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002168
Georg Brandl15c5ce92007-03-07 09:09:40 +00002169class Bar(Foo):
2170 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002171
Michael Foord07ef4872009-05-02 22:43:34 +00002172class LoggingTestCase(unittest.TestCase):
2173 """A test case which logs its calls."""
2174
2175 def __init__(self, events):
2176 super(LoggingTestCase, self).__init__('test')
2177 self.events = events
2178
2179 def setUp(self):
2180 self.events.append('setUp')
2181
2182 def test(self):
2183 self.events.append('test')
2184
2185 def tearDown(self):
2186 self.events.append('tearDown')
2187
2188class ResultWithNoStartTestRunStopTestRun(object):
2189 """An object honouring TestResult before startTestRun/stopTestRun."""
2190
2191 def __init__(self):
2192 self.failures = []
2193 self.errors = []
2194 self.testsRun = 0
2195 self.skipped = []
2196 self.expectedFailures = []
2197 self.unexpectedSuccesses = []
2198 self.shouldStop = False
2199
2200 def startTest(self, test):
2201 pass
2202
2203 def stopTest(self, test):
2204 pass
2205
2206 def addError(self, test):
2207 pass
2208
2209 def addFailure(self, test):
2210 pass
2211
2212 def addSuccess(self, test):
2213 pass
2214
2215 def wasSuccessful(self):
2216 return True
2217
2218
Georg Brandl15c5ce92007-03-07 09:09:40 +00002219################################################################
2220### /Support code for Test_TestCase
2221
2222class Test_TestCase(TestCase, TestEquality, TestHashing):
2223
2224 ### Set up attributes used by inherited tests
2225 ################################################################
2226
2227 # Used by TestHashing.test_hash and TestEquality.test_eq
2228 eq_pairs = [(Foo('test1'), Foo('test1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002229
Georg Brandl15c5ce92007-03-07 09:09:40 +00002230 # Used by TestEquality.test_ne
2231 ne_pairs = [(Foo('test1'), Foo('runTest'))
2232 ,(Foo('test1'), Bar('test1'))
2233 ,(Foo('test1'), Bar('test2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002234
Georg Brandl15c5ce92007-03-07 09:09:40 +00002235 ################################################################
2236 ### /Set up attributes used by inherited tests
Tim Petersea5962f2007-03-12 18:07:52 +00002237
Georg Brandl15c5ce92007-03-07 09:09:40 +00002238
2239 # "class TestCase([methodName])"
2240 # ...
2241 # "Each instance of TestCase will run a single test method: the
2242 # method named methodName."
2243 # ...
2244 # "methodName defaults to "runTest"."
2245 #
2246 # Make sure it really is optional, and that it defaults to the proper
2247 # thing.
2248 def test_init__no_test_name(self):
2249 class Test(unittest.TestCase):
2250 def runTest(self): raise MyException()
2251 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002252
Georg Brandl15c5ce92007-03-07 09:09:40 +00002253 self.assertEqual(Test().id()[-13:], '.Test.runTest')
Tim Petersea5962f2007-03-12 18:07:52 +00002254
Georg Brandl15c5ce92007-03-07 09:09:40 +00002255 # "class TestCase([methodName])"
2256 # ...
2257 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002258 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002259 def test_init__test_name__valid(self):
2260 class Test(unittest.TestCase):
2261 def runTest(self): raise MyException()
2262 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002263
Georg Brandl15c5ce92007-03-07 09:09:40 +00002264 self.assertEqual(Test('test').id()[-10:], '.Test.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002265
Georg Brandl15c5ce92007-03-07 09:09:40 +00002266 # "class TestCase([methodName])"
2267 # ...
2268 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002269 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002270 def test_init__test_name__invalid(self):
2271 class Test(unittest.TestCase):
2272 def runTest(self): raise MyException()
2273 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002274
Georg Brandl15c5ce92007-03-07 09:09:40 +00002275 try:
2276 Test('testfoo')
2277 except ValueError:
2278 pass
2279 else:
2280 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +00002281
Georg Brandl15c5ce92007-03-07 09:09:40 +00002282 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00002283 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00002284 def test_countTestCases(self):
2285 class Foo(unittest.TestCase):
2286 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002287
Georg Brandl15c5ce92007-03-07 09:09:40 +00002288 self.assertEqual(Foo('test').countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00002289
Georg Brandl15c5ce92007-03-07 09:09:40 +00002290 # "Return the default type of test result object to be used to run this
2291 # test. For TestCase instances, this will always be
2292 # unittest.TestResult; subclasses of TestCase should
2293 # override this as necessary."
2294 def test_defaultTestResult(self):
2295 class Foo(unittest.TestCase):
2296 def runTest(self):
2297 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002298
Georg Brandl15c5ce92007-03-07 09:09:40 +00002299 result = Foo().defaultTestResult()
2300 self.assertEqual(type(result), unittest.TestResult)
2301
2302 # "When a setUp() method is defined, the test runner will run that method
2303 # prior to each test. Likewise, if a tearDown() method is defined, the
2304 # test runner will invoke that method after each test. In the example,
2305 # setUp() was used to create a fresh sequence for each test."
2306 #
2307 # Make sure the proper call order is maintained, even if setUp() raises
2308 # an exception.
2309 def test_run_call_order__error_in_setUp(self):
2310 events = []
2311 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002312
Michael Foord07ef4872009-05-02 22:43:34 +00002313 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002314 def setUp(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002315 super(Foo, self).setUp()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002316 raise RuntimeError('raised by Foo.setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002317
Michael Foord07ef4872009-05-02 22:43:34 +00002318 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002319 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2320 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002321
Michael Foord07ef4872009-05-02 22:43:34 +00002322 # "With a temporary result stopTestRun is called when setUp errors.
2323 def test_run_call_order__error_in_setUp_default_result(self):
2324 events = []
2325
2326 class Foo(LoggingTestCase):
2327 def defaultTestResult(self):
2328 return LoggingResult(self.events)
2329
2330 def setUp(self):
2331 super(Foo, self).setUp()
2332 raise RuntimeError('raised by Foo.setUp')
2333
2334 Foo(events).run()
2335 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2336 'stopTest', 'stopTestRun']
2337 self.assertEqual(events, expected)
2338
Georg Brandl15c5ce92007-03-07 09:09:40 +00002339 # "When a setUp() method is defined, the test runner will run that method
2340 # prior to each test. Likewise, if a tearDown() method is defined, the
2341 # test runner will invoke that method after each test. In the example,
2342 # setUp() was used to create a fresh sequence for each test."
2343 #
2344 # Make sure the proper call order is maintained, even if the test raises
2345 # an error (as opposed to a failure).
2346 def test_run_call_order__error_in_test(self):
2347 events = []
2348 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002349
Michael Foord07ef4872009-05-02 22:43:34 +00002350 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002351 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002352 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002353 raise RuntimeError('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002354
Georg Brandl15c5ce92007-03-07 09:09:40 +00002355 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2356 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002357 Foo(events).run(result)
2358 self.assertEqual(events, expected)
2359
2360 # "With a default result, an error in the test still results in stopTestRun
2361 # being called."
2362 def test_run_call_order__error_in_test_default_result(self):
2363 events = []
2364
2365 class Foo(LoggingTestCase):
2366 def defaultTestResult(self):
2367 return LoggingResult(self.events)
2368
2369 def test(self):
2370 super(Foo, self).test()
2371 raise RuntimeError('raised by Foo.test')
2372
2373 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2374 'tearDown', 'stopTest', 'stopTestRun']
2375 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002376 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002377
Georg Brandl15c5ce92007-03-07 09:09:40 +00002378 # "When a setUp() method is defined, the test runner will run that method
2379 # prior to each test. Likewise, if a tearDown() method is defined, the
2380 # test runner will invoke that method after each test. In the example,
2381 # setUp() was used to create a fresh sequence for each test."
2382 #
2383 # Make sure the proper call order is maintained, even if the test signals
2384 # a failure (as opposed to an error).
2385 def test_run_call_order__failure_in_test(self):
2386 events = []
2387 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002388
Michael Foord07ef4872009-05-02 22:43:34 +00002389 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002390 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002391 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002392 self.fail('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002393
Georg Brandl15c5ce92007-03-07 09:09:40 +00002394 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2395 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002396 Foo(events).run(result)
2397 self.assertEqual(events, expected)
2398
2399 # "When a test fails with a default result stopTestRun is still called."
2400 def test_run_call_order__failure_in_test_default_result(self):
2401
2402 class Foo(LoggingTestCase):
2403 def defaultTestResult(self):
2404 return LoggingResult(self.events)
2405 def test(self):
2406 super(Foo, self).test()
2407 self.fail('raised by Foo.test')
2408
2409 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2410 'tearDown', 'stopTest', 'stopTestRun']
2411 events = []
2412 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002413 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002414
Georg Brandl15c5ce92007-03-07 09:09:40 +00002415 # "When a setUp() method is defined, the test runner will run that method
2416 # prior to each test. Likewise, if a tearDown() method is defined, the
2417 # test runner will invoke that method after each test. In the example,
2418 # setUp() was used to create a fresh sequence for each test."
2419 #
2420 # Make sure the proper call order is maintained, even if tearDown() raises
2421 # an exception.
2422 def test_run_call_order__error_in_tearDown(self):
2423 events = []
2424 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002425
Michael Foord07ef4872009-05-02 22:43:34 +00002426 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002427 def tearDown(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002428 super(Foo, self).tearDown()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002429 raise RuntimeError('raised by Foo.tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002430
Michael Foord07ef4872009-05-02 22:43:34 +00002431 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002432 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2433 'stopTest']
2434 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002435
Michael Foord07ef4872009-05-02 22:43:34 +00002436 # "When tearDown errors with a default result stopTestRun is still called."
2437 def test_run_call_order__error_in_tearDown_default_result(self):
2438
2439 class Foo(LoggingTestCase):
2440 def defaultTestResult(self):
2441 return LoggingResult(self.events)
2442 def tearDown(self):
2443 super(Foo, self).tearDown()
2444 raise RuntimeError('raised by Foo.tearDown')
2445
2446 events = []
2447 Foo(events).run()
2448 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2449 'addError', 'stopTest', 'stopTestRun']
2450 self.assertEqual(events, expected)
2451
2452 # "TestCase.run() still works when the defaultTestResult is a TestResult
2453 # that does not support startTestRun and stopTestRun.
2454 def test_run_call_order_default_result(self):
2455
2456 class Foo(unittest.TestCase):
2457 def defaultTestResult(self):
2458 return ResultWithNoStartTestRunStopTestRun()
2459 def test(self):
2460 pass
2461
2462 Foo('test').run()
2463
Georg Brandl15c5ce92007-03-07 09:09:40 +00002464 # "This class attribute gives the exception raised by the test() method.
2465 # If a test framework needs to use a specialized exception, possibly to
2466 # carry additional information, it must subclass this exception in
2467 # order to ``play fair'' with the framework. The initial value of this
2468 # attribute is AssertionError"
2469 def test_failureException__default(self):
2470 class Foo(unittest.TestCase):
2471 def test(self):
2472 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002473
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002474 self.assertTrue(Foo('test').failureException is AssertionError)
Tim Petersea5962f2007-03-12 18:07:52 +00002475
Georg Brandl15c5ce92007-03-07 09:09:40 +00002476 # "This class attribute gives the exception raised by the test() method.
2477 # If a test framework needs to use a specialized exception, possibly to
2478 # carry additional information, it must subclass this exception in
2479 # order to ``play fair'' with the framework."
2480 #
2481 # Make sure TestCase.run() respects the designated failureException
2482 def test_failureException__subclassing__explicit_raise(self):
2483 events = []
2484 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002485
Georg Brandl15c5ce92007-03-07 09:09:40 +00002486 class Foo(unittest.TestCase):
2487 def test(self):
2488 raise RuntimeError()
Tim Petersea5962f2007-03-12 18:07:52 +00002489
Georg Brandl15c5ce92007-03-07 09:09:40 +00002490 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002491
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002492 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002493
2494
Georg Brandl15c5ce92007-03-07 09:09:40 +00002495 Foo('test').run(result)
2496 expected = ['startTest', 'addFailure', 'stopTest']
2497 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002498
Georg Brandl15c5ce92007-03-07 09:09:40 +00002499 # "This class attribute gives the exception raised by the test() method.
2500 # If a test framework needs to use a specialized exception, possibly to
2501 # carry additional information, it must subclass this exception in
2502 # order to ``play fair'' with the framework."
2503 #
2504 # Make sure TestCase.run() respects the designated failureException
2505 def test_failureException__subclassing__implicit_raise(self):
2506 events = []
2507 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002508
Georg Brandl15c5ce92007-03-07 09:09:40 +00002509 class Foo(unittest.TestCase):
2510 def test(self):
2511 self.fail("foo")
Tim Petersea5962f2007-03-12 18:07:52 +00002512
Georg Brandl15c5ce92007-03-07 09:09:40 +00002513 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002514
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002515 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002516
2517
Georg Brandl15c5ce92007-03-07 09:09:40 +00002518 Foo('test').run(result)
2519 expected = ['startTest', 'addFailure', 'stopTest']
2520 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002521
2522 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002523 def test_setUp(self):
2524 class Foo(unittest.TestCase):
2525 def runTest(self):
2526 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002527
Georg Brandl15c5ce92007-03-07 09:09:40 +00002528 # ... and nothing should happen
2529 Foo().setUp()
Tim Petersea5962f2007-03-12 18:07:52 +00002530
2531 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002532 def test_tearDown(self):
2533 class Foo(unittest.TestCase):
2534 def runTest(self):
2535 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002536
Georg Brandl15c5ce92007-03-07 09:09:40 +00002537 # ... and nothing should happen
2538 Foo().tearDown()
Tim Petersea5962f2007-03-12 18:07:52 +00002539
Georg Brandl15c5ce92007-03-07 09:09:40 +00002540 # "Return a string identifying the specific test case."
2541 #
2542 # Because of the vague nature of the docs, I'm not going to lock this
2543 # test down too much. Really all that can be asserted is that the id()
2544 # will be a string (either 8-byte or unicode -- again, because the docs
2545 # just say "string")
2546 def test_id(self):
2547 class Foo(unittest.TestCase):
2548 def runTest(self):
2549 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002550
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002551 self.assertIsInstance(Foo().id(), basestring)
Tim Petersea5962f2007-03-12 18:07:52 +00002552
Georg Brandl15c5ce92007-03-07 09:09:40 +00002553 # "If result is omitted or None, a temporary result object is created
Michael Foord07ef4872009-05-02 22:43:34 +00002554 # and used, but is not made available to the caller. As TestCase owns the
2555 # temporary result startTestRun and stopTestRun are called.
2556
Georg Brandl15c5ce92007-03-07 09:09:40 +00002557 def test_run__uses_defaultTestResult(self):
2558 events = []
Tim Petersea5962f2007-03-12 18:07:52 +00002559
Georg Brandl15c5ce92007-03-07 09:09:40 +00002560 class Foo(unittest.TestCase):
2561 def test(self):
2562 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002563
Georg Brandl15c5ce92007-03-07 09:09:40 +00002564 def defaultTestResult(self):
2565 return LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002566
2567 # Make run() find a result object on its own
Georg Brandl15c5ce92007-03-07 09:09:40 +00002568 Foo('test').run()
Tim Petersea5962f2007-03-12 18:07:52 +00002569
Michael Foord07ef4872009-05-02 22:43:34 +00002570 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2571 'stopTest', 'stopTestRun']
Georg Brandl15c5ce92007-03-07 09:09:40 +00002572 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002573
Gregory P. Smith28399852009-03-31 16:54:10 +00002574 def testShortDescriptionWithoutDocstring(self):
Michael Foorddb43b5a2010-02-10 14:25:12 +00002575 self.assertIsNone(self.shortDescription())
Gregory P. Smith28399852009-03-31 16:54:10 +00002576
R. David Murrayf28fd242010-02-23 00:24:49 +00002577 @unittest.skipIf(sys.flags.optimize >= 2,
2578 "Docstrings are omitted with -O2 and above")
Gregory P. Smith28399852009-03-31 16:54:10 +00002579 def testShortDescriptionWithOneLineDocstring(self):
2580 """Tests shortDescription() for a method with a docstring."""
2581 self.assertEqual(
2582 self.shortDescription(),
Michael Foorddb43b5a2010-02-10 14:25:12 +00002583 'Tests shortDescription() for a method with a docstring.')
Gregory P. Smith28399852009-03-31 16:54:10 +00002584
R. David Murrayf28fd242010-02-23 00:24:49 +00002585 @unittest.skipIf(sys.flags.optimize >= 2,
2586 "Docstrings are omitted with -O2 and above")
Gregory P. Smith28399852009-03-31 16:54:10 +00002587 def testShortDescriptionWithMultiLineDocstring(self):
2588 """Tests shortDescription() for a method with a longer docstring.
2589
2590 This method ensures that only the first line of a docstring is
2591 returned used in the short description, no matter how long the
2592 whole thing is.
2593 """
2594 self.assertEqual(
2595 self.shortDescription(),
Gregory P. Smith28399852009-03-31 16:54:10 +00002596 'Tests shortDescription() for a method with a longer '
Michael Foorddb43b5a2010-02-10 14:25:12 +00002597 'docstring.')
Gregory P. Smith28399852009-03-31 16:54:10 +00002598
Gregory P. Smith28399852009-03-31 16:54:10 +00002599 def testAddTypeEqualityFunc(self):
2600 class SadSnake(object):
2601 """Dummy class for test_addTypeEqualityFunc."""
2602 s1, s2 = SadSnake(), SadSnake()
Michael Foord98e7b762010-03-20 03:00:34 +00002603 self.assertNotEqual(s1, s2)
Gregory P. Smith28399852009-03-31 16:54:10 +00002604 def AllSnakesCreatedEqual(a, b, msg=None):
Michael Foord98e7b762010-03-20 03:00:34 +00002605 return type(a) is type(b) is SadSnake
Gregory P. Smith28399852009-03-31 16:54:10 +00002606 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2607 self.assertEqual(s1, s2)
2608 # No this doesn't clean up and remove the SadSnake equality func
2609 # from this TestCase instance but since its a local nothing else
2610 # will ever notice that.
2611
Michael Foordf2dfef12009-04-05 19:19:28 +00002612 def testAssertIs(self):
2613 thing = object()
2614 self.assertIs(thing, thing)
2615 self.assertRaises(self.failureException, self.assertIs, thing, object())
2616
2617 def testAssertIsNot(self):
2618 thing = object()
2619 self.assertIsNot(thing, object())
2620 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2621
Georg Brandlf895cf52009-10-01 20:59:31 +00002622 def testAssertIsInstance(self):
2623 thing = []
2624 self.assertIsInstance(thing, list)
2625 self.assertRaises(self.failureException, self.assertIsInstance,
2626 thing, dict)
2627
2628 def testAssertNotIsInstance(self):
2629 thing = []
2630 self.assertNotIsInstance(thing, dict)
2631 self.assertRaises(self.failureException, self.assertNotIsInstance,
2632 thing, list)
2633
Gregory P. Smith28399852009-03-31 16:54:10 +00002634 def testAssertIn(self):
2635 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2636
2637 self.assertIn('a', 'abc')
2638 self.assertIn(2, [1, 2, 3])
2639 self.assertIn('monkey', animals)
2640
2641 self.assertNotIn('d', 'abc')
2642 self.assertNotIn(0, [1, 2, 3])
2643 self.assertNotIn('otter', animals)
2644
2645 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2646 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2647 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2648 animals)
2649
2650 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2651 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2652 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2653 animals)
2654
2655 def testAssertDictContainsSubset(self):
2656 self.assertDictContainsSubset({}, {})
2657 self.assertDictContainsSubset({}, {'a': 1})
2658 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2659 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2660 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2661
Michael Foord225a0992010-02-18 20:30:09 +00002662 with self.assertRaises(self.failureException):
2663 self.assertDictContainsSubset({1: "one"}, {})
Gregory P. Smith28399852009-03-31 16:54:10 +00002664
Michael Foord225a0992010-02-18 20:30:09 +00002665 with self.assertRaises(self.failureException):
2666 self.assertDictContainsSubset({'a': 2}, {'a': 1})
Gregory P. Smith28399852009-03-31 16:54:10 +00002667
Michael Foord225a0992010-02-18 20:30:09 +00002668 with self.assertRaises(self.failureException):
2669 self.assertDictContainsSubset({'c': 1}, {'a': 1})
Gregory P. Smith28399852009-03-31 16:54:10 +00002670
Michael Foord225a0992010-02-18 20:30:09 +00002671 with self.assertRaises(self.failureException):
2672 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2673
2674 with self.assertRaises(self.failureException):
2675 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2676
Michael Foord2f677562010-02-21 14:48:59 +00002677 with warnings.catch_warnings(record=True):
2678 # silence the UnicodeWarning
2679 one = ''.join(chr(i) for i in range(255))
2680 # this used to cause a UnicodeDecodeError constructing the failure msg
2681 with self.assertRaises(self.failureException):
2682 self.assertDictContainsSubset({'foo': one}, {'foo': u'\uFFFD'})
Gregory P. Smith28399852009-03-31 16:54:10 +00002683
2684 def testAssertEqual(self):
2685 equal_pairs = [
2686 ((), ()),
2687 ({}, {}),
2688 ([], []),
2689 (set(), set()),
2690 (frozenset(), frozenset())]
2691 for a, b in equal_pairs:
2692 # This mess of try excepts is to test the assertEqual behavior
2693 # itself.
2694 try:
2695 self.assertEqual(a, b)
2696 except self.failureException:
2697 self.fail('assertEqual(%r, %r) failed' % (a, b))
2698 try:
2699 self.assertEqual(a, b, msg='foo')
2700 except self.failureException:
2701 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2702 try:
2703 self.assertEqual(a, b, 'foo')
2704 except self.failureException:
2705 self.fail('assertEqual(%r, %r) with third parameter failed' %
2706 (a, b))
2707
2708 unequal_pairs = [
2709 ((), []),
2710 ({}, set()),
2711 (set([4,1]), frozenset([4,2])),
2712 (frozenset([4,5]), set([2,3])),
2713 (set([3,4]), set([5,4]))]
2714 for a, b in unequal_pairs:
2715 self.assertRaises(self.failureException, self.assertEqual, a, b)
2716 self.assertRaises(self.failureException, self.assertEqual, a, b,
2717 'foo')
2718 self.assertRaises(self.failureException, self.assertEqual, a, b,
2719 msg='foo')
2720
2721 def testEquality(self):
2722 self.assertListEqual([], [])
2723 self.assertTupleEqual((), ())
2724 self.assertSequenceEqual([], ())
2725
2726 a = [0, 'a', []]
2727 b = []
2728 self.assertRaises(unittest.TestCase.failureException,
2729 self.assertListEqual, a, b)
2730 self.assertRaises(unittest.TestCase.failureException,
2731 self.assertListEqual, tuple(a), tuple(b))
2732 self.assertRaises(unittest.TestCase.failureException,
2733 self.assertSequenceEqual, a, tuple(b))
2734
2735 b.extend(a)
2736 self.assertListEqual(a, b)
2737 self.assertTupleEqual(tuple(a), tuple(b))
2738 self.assertSequenceEqual(a, tuple(b))
2739 self.assertSequenceEqual(tuple(a), b)
2740
2741 self.assertRaises(self.failureException, self.assertListEqual,
2742 a, tuple(b))
2743 self.assertRaises(self.failureException, self.assertTupleEqual,
2744 tuple(a), b)
2745 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2746 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2747 tuple(b))
2748 self.assertRaises(self.failureException, self.assertSequenceEqual,
2749 None, tuple(b))
2750 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2751 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2752 self.assertRaises(self.failureException, self.assertSequenceEqual,
2753 1, 1)
2754
2755 self.assertDictEqual({}, {})
2756
2757 c = { 'x': 1 }
2758 d = {}
2759 self.assertRaises(unittest.TestCase.failureException,
2760 self.assertDictEqual, c, d)
2761
2762 d.update(c)
2763 self.assertDictEqual(c, d)
2764
2765 d['x'] = 0
2766 self.assertRaises(unittest.TestCase.failureException,
2767 self.assertDictEqual, c, d, 'These are unequal')
2768
2769 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2770 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2771 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2772
Michael Foord98e7b762010-03-20 03:00:34 +00002773 def testAssertItemsEqual(self):
2774 a = object()
2775 self.assertItemsEqual([1, 2, 3], [3, 2, 1])
2776 self.assertItemsEqual(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2777 self.assertItemsEqual([a, a, 2, 2, 3], (a, 2, 3, a, 2))
2778 self.assertItemsEqual([1, "2", "a", "a"], ["a", "2", True, "a"])
2779 self.assertRaises(self.failureException, self.assertItemsEqual,
2780 [1, 2] + [3] * 100, [1] * 100 + [2, 3])
2781 self.assertRaises(self.failureException, self.assertItemsEqual,
2782 [1, "2", "a", "a"], ["a", "2", True, 1])
2783 self.assertRaises(self.failureException, self.assertItemsEqual,
Gregory P. Smith28399852009-03-31 16:54:10 +00002784 [10], [10, 11])
Michael Foord98e7b762010-03-20 03:00:34 +00002785 self.assertRaises(self.failureException, self.assertItemsEqual,
Gregory P. Smith28399852009-03-31 16:54:10 +00002786 [10, 11], [10])
Michael Foord98e7b762010-03-20 03:00:34 +00002787 self.assertRaises(self.failureException, self.assertItemsEqual,
2788 [10, 11, 10], [10, 11])
Gregory P. Smith28399852009-03-31 16:54:10 +00002789
2790 # Test that sequences of unhashable objects can be tested for sameness:
Michael Foord98e7b762010-03-20 03:00:34 +00002791 self.assertItemsEqual([[1, 2], [3, 4], 0], [False, [3, 4], [1, 2]])
2792 with test_support.check_warnings(quiet=True) as w:
2793 # hashable types, but not orderable
2794 self.assertRaises(self.failureException, self.assertItemsEqual,
2795 [], [divmod, 'x', 1, 5j, 2j, frozenset()])
2796 # comparing dicts raises a py3k warning
2797 self.assertItemsEqual([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2798 # comparing heterogenous non-hashable sequences raises a py3k warning
2799 self.assertItemsEqual([1, 'x', divmod, []], [divmod, [], 'x', 1])
2800 self.assertRaises(self.failureException, self.assertItemsEqual,
2801 [], [divmod, [], 'x', 1, 5j, 2j, set()])
2802 # fail the test if warnings are not silenced
2803 if w.warnings:
2804 self.fail('assertItemsEqual raised a warning: ' +
2805 str(w.warnings[0]))
2806 self.assertRaises(self.failureException, self.assertItemsEqual,
Gregory P. Smith28399852009-03-31 16:54:10 +00002807 [[1]], [[2]])
2808
Michael Foord98e7b762010-03-20 03:00:34 +00002809 # Same elements, but not same sequence length
2810 self.assertRaises(self.failureException, self.assertItemsEqual,
2811 [1, 1, 2], [2, 1])
2812 self.assertRaises(self.failureException, self.assertItemsEqual,
2813 [1, 1, "2", "a", "a"], ["2", "2", True, "a"])
2814 self.assertRaises(self.failureException, self.assertItemsEqual,
2815 [1, {'b': 2}, None, True], [{'b': 2}, True, None])
2816
2817
Gregory P. Smith28399852009-03-31 16:54:10 +00002818 def testAssertSetEqual(self):
2819 set1 = set()
2820 set2 = set()
2821 self.assertSetEqual(set1, set2)
2822
2823 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2824 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2825 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2826 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2827
2828 set1 = set(['a'])
2829 set2 = set()
2830 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2831
2832 set1 = set(['a'])
2833 set2 = set(['a'])
2834 self.assertSetEqual(set1, set2)
2835
2836 set1 = set(['a'])
2837 set2 = set(['a', 'b'])
2838 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2839
2840 set1 = set(['a'])
2841 set2 = frozenset(['a', 'b'])
2842 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2843
2844 set1 = set(['a', 'b'])
2845 set2 = frozenset(['a', 'b'])
2846 self.assertSetEqual(set1, set2)
2847
2848 set1 = set()
2849 set2 = "foo"
2850 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2851 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2852
2853 # make sure any string formatting is tuple-safe
2854 set1 = set([(0, 1), (2, 3)])
2855 set2 = set([(4, 5)])
2856 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2857
2858 def testInequality(self):
2859 # Try ints
2860 self.assertGreater(2, 1)
2861 self.assertGreaterEqual(2, 1)
2862 self.assertGreaterEqual(1, 1)
2863 self.assertLess(1, 2)
2864 self.assertLessEqual(1, 2)
2865 self.assertLessEqual(1, 1)
2866 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2867 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2868 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2869 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2870 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2871 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2872
2873 # Try Floats
2874 self.assertGreater(1.1, 1.0)
2875 self.assertGreaterEqual(1.1, 1.0)
2876 self.assertGreaterEqual(1.0, 1.0)
2877 self.assertLess(1.0, 1.1)
2878 self.assertLessEqual(1.0, 1.1)
2879 self.assertLessEqual(1.0, 1.0)
2880 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2881 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2882 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2883 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2884 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2885 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2886
2887 # Try Strings
2888 self.assertGreater('bug', 'ant')
2889 self.assertGreaterEqual('bug', 'ant')
2890 self.assertGreaterEqual('ant', 'ant')
2891 self.assertLess('ant', 'bug')
2892 self.assertLessEqual('ant', 'bug')
2893 self.assertLessEqual('ant', 'ant')
2894 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2895 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2896 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2897 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2898 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2899 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2900
2901 # Try Unicode
2902 self.assertGreater(u'bug', u'ant')
2903 self.assertGreaterEqual(u'bug', u'ant')
2904 self.assertGreaterEqual(u'ant', u'ant')
2905 self.assertLess(u'ant', u'bug')
2906 self.assertLessEqual(u'ant', u'bug')
2907 self.assertLessEqual(u'ant', u'ant')
2908 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug')
2909 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant')
2910 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2911 u'bug')
2912 self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant')
2913 self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant')
2914 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant')
2915
2916 # Try Mixed String/Unicode
2917 self.assertGreater('bug', u'ant')
2918 self.assertGreater(u'bug', 'ant')
2919 self.assertGreaterEqual('bug', u'ant')
2920 self.assertGreaterEqual(u'bug', 'ant')
2921 self.assertGreaterEqual('ant', u'ant')
2922 self.assertGreaterEqual(u'ant', 'ant')
2923 self.assertLess('ant', u'bug')
2924 self.assertLess(u'ant', 'bug')
2925 self.assertLessEqual('ant', u'bug')
2926 self.assertLessEqual(u'ant', 'bug')
2927 self.assertLessEqual('ant', u'ant')
2928 self.assertLessEqual(u'ant', 'ant')
2929 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug')
2930 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug')
2931 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant')
2932 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant')
2933 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant',
2934 u'bug')
2935 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2936 'bug')
2937 self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant')
2938 self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant')
2939 self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant')
2940 self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant')
2941 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant')
2942 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant')
2943
2944 def testAssertMultiLineEqual(self):
2945 sample_text = b"""\
2946http://www.python.org/doc/2.3/lib/module-unittest.html
2947test case
2948 A test case is the smallest unit of testing. [...]
2949"""
2950 revised_sample_text = b"""\
2951http://www.python.org/doc/2.4.1/lib/module-unittest.html
2952test case
2953 A test case is the smallest unit of testing. [...] You may provide your
2954 own implementation that does not subclass from TestCase, of course.
2955"""
2956 sample_text_error = b"""
2957- http://www.python.org/doc/2.3/lib/module-unittest.html
2958? ^
2959+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2960? ^^^
2961 test case
2962- A test case is the smallest unit of testing. [...]
2963+ A test case is the smallest unit of testing. [...] You may provide your
2964? +++++++++++++++++++++
2965+ own implementation that does not subclass from TestCase, of course.
2966"""
2967
2968 for type_changer in (lambda x: x, lambda x: x.decode('utf8')):
2969 try:
2970 self.assertMultiLineEqual(type_changer(sample_text),
2971 type_changer(revised_sample_text))
2972 except self.failureException, e:
Michael Foordfe6349c2010-02-08 22:41:16 +00002973 # assertMultiLineEqual is hooked up as the default for
2974 # unicode strings - so we can't use it for this check
2975 self.assertTrue(sample_text_error == str(e).encode('utf8'))
Gregory P. Smith28399852009-03-31 16:54:10 +00002976
2977 def testAssertIsNone(self):
2978 self.assertIsNone(None)
2979 self.assertRaises(self.failureException, self.assertIsNone, False)
2980 self.assertIsNotNone('DjZoPloGears on Rails')
2981 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2982
2983 def testAssertRegexpMatches(self):
2984 self.assertRegexpMatches('asdfabasdf', r'ab+')
2985 self.assertRaises(self.failureException, self.assertRegexpMatches,
2986 'saaas', r'aaaa')
2987
2988 def testAssertRaisesRegexp(self):
2989 class ExceptionMock(Exception):
2990 pass
2991
2992 def Stub():
2993 raise ExceptionMock('We expect')
2994
2995 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2996 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2997 self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
2998
2999 def testAssertNotRaisesRegexp(self):
3000 self.assertRaisesRegexp(
3001 self.failureException, '^Exception not raised$',
3002 self.assertRaisesRegexp, Exception, re.compile('x'),
3003 lambda: None)
3004 self.assertRaisesRegexp(
3005 self.failureException, '^Exception not raised$',
3006 self.assertRaisesRegexp, Exception, 'x',
3007 lambda: None)
3008 self.assertRaisesRegexp(
3009 self.failureException, '^Exception not raised$',
3010 self.assertRaisesRegexp, Exception, u'x',
3011 lambda: None)
3012
3013 def testAssertRaisesRegexpMismatch(self):
3014 def Stub():
3015 raise Exception('Unexpected')
3016
3017 self.assertRaisesRegexp(
3018 self.failureException,
3019 r'"\^Expected\$" does not match "Unexpected"',
3020 self.assertRaisesRegexp, Exception, '^Expected$',
3021 Stub)
3022 self.assertRaisesRegexp(
3023 self.failureException,
3024 r'"\^Expected\$" does not match "Unexpected"',
3025 self.assertRaisesRegexp, Exception, u'^Expected$',
3026 Stub)
3027 self.assertRaisesRegexp(
3028 self.failureException,
3029 r'"\^Expected\$" does not match "Unexpected"',
3030 self.assertRaisesRegexp, Exception,
3031 re.compile('^Expected$'), Stub)
3032
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00003033 def testAssertRaisesExcValue(self):
3034 class ExceptionMock(Exception):
3035 pass
3036
3037 def Stub(foo):
3038 raise ExceptionMock(foo)
3039 v = "particular value"
3040
3041 ctx = self.assertRaises(ExceptionMock)
3042 with ctx:
3043 Stub(v)
Georg Brandldc3694b2010-02-07 17:02:22 +00003044 e = ctx.exception
Ezio Melottib0f5adc2010-01-24 16:58:36 +00003045 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00003046 self.assertEqual(e.args[0], v)
3047
Gregory P. Smith7558d572009-03-31 19:03:28 +00003048 def testSynonymAssertMethodNames(self):
3049 """Test undocumented method name synonyms.
3050
3051 Please do not use these methods names in your own code.
3052
3053 This test confirms their continued existence and functionality
3054 in order to avoid breaking existing code.
3055 """
3056 self.assertNotEquals(3, 5)
3057 self.assertEquals(3, 3)
3058 self.assertAlmostEquals(2.0, 2.0)
3059 self.assertNotAlmostEquals(3.0, 5.0)
3060 self.assert_(True)
3061
3062 def testPendingDeprecationMethodNames(self):
3063 """Test fail* methods pending deprecation, they will warn in 3.2.
3064
3065 Do not use these methods. They will go away in 3.3.
3066 """
Michael Foord98e7b762010-03-20 03:00:34 +00003067 with test_support.check_warnings():
3068 self.failIfEqual(3, 5)
3069 self.failUnlessEqual(3, 3)
3070 self.failUnlessAlmostEqual(2.0, 2.0)
3071 self.failIfAlmostEqual(3.0, 5.0)
3072 self.failUnless(True)
3073 self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam')
3074 self.failIf(False)
Gregory P. Smith7558d572009-03-31 19:03:28 +00003075
Michael Foorde2942d02009-04-02 05:51:54 +00003076 def testDeepcopy(self):
3077 # Issue: 5660
3078 class TestableTest(TestCase):
3079 def testNothing(self):
3080 pass
3081
3082 test = TestableTest('testNothing')
3083
3084 # This shouldn't blow up
3085 deepcopy(test)
3086
Benjamin Peterson692428e2009-03-23 21:50:21 +00003087
3088class Test_TestSkipping(TestCase):
3089
3090 def test_skipping(self):
3091 class Foo(unittest.TestCase):
3092 def test_skip_me(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00003093 self.skipTest("skip")
Benjamin Peterson692428e2009-03-23 21:50:21 +00003094 events = []
3095 result = LoggingResult(events)
3096 test = Foo("test_skip_me")
3097 test.run(result)
3098 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3099 self.assertEqual(result.skipped, [(test, "skip")])
3100
3101 # Try letting setUp skip the test now.
3102 class Foo(unittest.TestCase):
3103 def setUp(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00003104 self.skipTest("testing")
Benjamin Peterson692428e2009-03-23 21:50:21 +00003105 def test_nothing(self): pass
3106 events = []
3107 result = LoggingResult(events)
3108 test = Foo("test_nothing")
3109 test.run(result)
3110 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3111 self.assertEqual(result.skipped, [(test, "testing")])
3112 self.assertEqual(result.testsRun, 1)
3113
3114 def test_skipping_decorators(self):
3115 op_table = ((unittest.skipUnless, False, True),
3116 (unittest.skipIf, True, False))
3117 for deco, do_skip, dont_skip in op_table:
3118 class Foo(unittest.TestCase):
3119 @deco(do_skip, "testing")
3120 def test_skip(self): pass
3121
3122 @deco(dont_skip, "testing")
3123 def test_dont_skip(self): pass
3124 test_do_skip = Foo("test_skip")
3125 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003126 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003127 events = []
3128 result = LoggingResult(events)
3129 suite.run(result)
3130 self.assertEqual(len(result.skipped), 1)
3131 expected = ['startTest', 'addSkip', 'stopTest',
3132 'startTest', 'addSuccess', 'stopTest']
3133 self.assertEqual(events, expected)
3134 self.assertEqual(result.testsRun, 2)
3135 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
3136 self.assertTrue(result.wasSuccessful())
3137
3138 def test_skip_class(self):
3139 @unittest.skip("testing")
3140 class Foo(unittest.TestCase):
3141 def test_1(self):
3142 record.append(1)
3143 record = []
3144 result = unittest.TestResult()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003145 test = Foo("test_1")
3146 suite = unittest.TestSuite([test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003147 suite.run(result)
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003148 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003149 self.assertEqual(record, [])
3150
3151 def test_expected_failure(self):
3152 class Foo(unittest.TestCase):
3153 @unittest.expectedFailure
3154 def test_die(self):
3155 self.fail("help me!")
3156 events = []
3157 result = LoggingResult(events)
3158 test = Foo("test_die")
3159 test.run(result)
3160 self.assertEqual(events,
3161 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003162 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00003163 self.assertTrue(result.wasSuccessful())
3164
3165 def test_unexpected_success(self):
3166 class Foo(unittest.TestCase):
3167 @unittest.expectedFailure
3168 def test_die(self):
3169 pass
3170 events = []
3171 result = LoggingResult(events)
3172 test = Foo("test_die")
3173 test.run(result)
3174 self.assertEqual(events,
3175 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3176 self.assertFalse(result.failures)
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003177 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003178 self.assertTrue(result.wasSuccessful())
3179
Michael Foord53e8eea2010-03-07 20:22:12 +00003180 def test_skip_doesnt_run_setup(self):
3181 class Foo(unittest.TestCase):
3182 wasSetUp = False
3183 wasTornDown = False
3184 def setUp(self):
3185 Foo.wasSetUp = True
3186 def tornDown(self):
3187 Foo.wasTornDown = True
3188 @unittest.skip('testing')
3189 def test_1(self):
3190 pass
3191
3192 result = unittest.TestResult()
3193 test = Foo("test_1")
3194 suite = unittest.TestSuite([test])
3195 suite.run(result)
3196 self.assertEqual(result.skipped, [(test, "testing")])
3197 self.assertFalse(Foo.wasSetUp)
3198 self.assertFalse(Foo.wasTornDown)
3199
3200 def test_decorated_skip(self):
3201 def decorator(func):
3202 def inner(*a):
3203 return func(*a)
3204 return inner
3205
3206 class Foo(unittest.TestCase):
3207 @decorator
3208 @unittest.skip('testing')
3209 def test_1(self):
3210 pass
3211
3212 result = unittest.TestResult()
3213 test = Foo("test_1")
3214 suite = unittest.TestSuite([test])
3215 suite.run(result)
3216 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003217
3218
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003219class Test_Assertions(TestCase):
3220 def test_AlmostEqual(self):
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003221 self.assertAlmostEqual(1.00000001, 1.0)
3222 self.assertNotAlmostEqual(1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003223 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003224 self.assertAlmostEqual, 1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003225 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003226 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003227
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003228 self.assertAlmostEqual(1.1, 1.0, places=0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003229 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003230 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003231
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003232 self.assertAlmostEqual(0, .1+.1j, places=0)
3233 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003234 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003235 self.assertAlmostEqual, 0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003236 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003237 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003238
Michael Foordc3f79372009-09-13 16:40:02 +00003239 self.assertAlmostEqual(float('inf'), float('inf'))
3240 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3241 float('inf'), float('inf'))
3242
3243
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003244 def test_assertRaises(self):
3245 def _raise(e):
3246 raise e
3247 self.assertRaises(KeyError, _raise, KeyError)
3248 self.assertRaises(KeyError, _raise, KeyError("key"))
3249 try:
3250 self.assertRaises(KeyError, lambda: None)
Gregory P. Smith28399852009-03-31 16:54:10 +00003251 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003252 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003253 else:
3254 self.fail("assertRaises() didn't fail")
3255 try:
3256 self.assertRaises(KeyError, _raise, ValueError)
3257 except ValueError:
3258 pass
3259 else:
3260 self.fail("assertRaises() didn't let exception pass through")
Michael Foord2bd52dc2010-02-07 18:44:12 +00003261 with self.assertRaises(KeyError) as cm:
3262 try:
3263 raise KeyError
3264 except Exception, e:
3265 raise
3266 self.assertIs(cm.exception, e)
3267
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003268 with self.assertRaises(KeyError):
3269 raise KeyError("key")
3270 try:
3271 with self.assertRaises(KeyError):
3272 pass
Gregory P. Smith28399852009-03-31 16:54:10 +00003273 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003274 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003275 else:
3276 self.fail("assertRaises() didn't fail")
3277 try:
3278 with self.assertRaises(KeyError):
3279 raise ValueError
3280 except ValueError:
3281 pass
3282 else:
3283 self.fail("assertRaises() didn't let exception pass through")
3284
3285
Michael Foord345b2fe2009-04-02 03:20:38 +00003286class TestLongMessage(TestCase):
3287 """Test that the individual asserts honour longMessage.
3288 This actually tests all the message behaviour for
3289 asserts that use longMessage."""
3290
3291 def setUp(self):
3292 class TestableTestFalse(TestCase):
3293 longMessage = False
3294 failureException = self.failureException
3295
3296 def testTest(self):
3297 pass
3298
3299 class TestableTestTrue(TestCase):
3300 longMessage = True
3301 failureException = self.failureException
3302
3303 def testTest(self):
3304 pass
3305
3306 self.testableTrue = TestableTestTrue('testTest')
3307 self.testableFalse = TestableTestFalse('testTest')
3308
3309 def testDefault(self):
3310 self.assertFalse(TestCase.longMessage)
3311
3312 def test_formatMsg(self):
3313 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3314 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3315
3316 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3317 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3318
Michael Foord53e8eea2010-03-07 20:22:12 +00003319 # This blows up if _formatMessage uses string concatenation
3320 self.testableTrue._formatMessage(object(), 'foo')
3321
3322 def test_formatMessage_unicode_error(self):
3323 with warnings.catch_warnings(record=True):
3324 # This causes a UnicodeWarning due to its craziness
3325 one = ''.join(chr(i) for i in range(255))
3326 # this used to cause a UnicodeDecodeError constructing msg
3327 self.testableTrue._formatMessage(one, u'\uFFFD')
3328
Michael Foord345b2fe2009-04-02 03:20:38 +00003329 def assertMessages(self, methodName, args, errors):
3330 def getMethod(i):
3331 useTestableFalse = i < 2
3332 if useTestableFalse:
3333 test = self.testableFalse
3334 else:
3335 test = self.testableTrue
3336 return getattr(test, methodName)
3337
3338 for i, expected_regexp in enumerate(errors):
3339 testMethod = getMethod(i)
3340 kwargs = {}
3341 withMsg = i % 2
3342 if withMsg:
3343 kwargs = {"msg": "oops"}
3344
3345 with self.assertRaisesRegexp(self.failureException,
3346 expected_regexp=expected_regexp):
3347 testMethod(*args, **kwargs)
3348
3349 def testAssertTrue(self):
3350 self.assertMessages('assertTrue', (False,),
3351 ["^False is not True$", "^oops$", "^False is not True$",
3352 "^False is not True : oops$"])
3353
3354 def testAssertFalse(self):
3355 self.assertMessages('assertFalse', (True,),
3356 ["^True is not False$", "^oops$", "^True is not False$",
3357 "^True is not False : oops$"])
3358
3359 def testNotEqual(self):
3360 self.assertMessages('assertNotEqual', (1, 1),
3361 ["^1 == 1$", "^oops$", "^1 == 1$",
3362 "^1 == 1 : oops$"])
3363
3364 def testAlmostEqual(self):
3365 self.assertMessages('assertAlmostEqual', (1, 2),
3366 ["^1 != 2 within 7 places$", "^oops$",
3367 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3368
3369 def testNotAlmostEqual(self):
3370 self.assertMessages('assertNotAlmostEqual', (1, 1),
3371 ["^1 == 1 within 7 places$", "^oops$",
3372 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3373
3374 def test_baseAssertEqual(self):
3375 self.assertMessages('_baseAssertEqual', (1, 2),
3376 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3377
3378 def testAssertSequenceEqual(self):
3379 # Error messages are multiline so not testing on full message
3380 # assertTupleEqual and assertListEqual delegate to this method
3381 self.assertMessages('assertSequenceEqual', ([], [None]),
3382 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3383 r"\+ \[None\] : oops$"])
3384
3385 def testAssertSetEqual(self):
3386 self.assertMessages('assertSetEqual', (set(), set([None])),
3387 ["None$", "^oops$", "None$",
3388 "None : oops$"])
3389
3390 def testAssertIn(self):
3391 self.assertMessages('assertIn', (None, []),
3392 ['^None not found in \[\]$', "^oops$",
3393 '^None not found in \[\]$',
3394 '^None not found in \[\] : oops$'])
3395
3396 def testAssertNotIn(self):
3397 self.assertMessages('assertNotIn', (None, [None]),
3398 ['^None unexpectedly found in \[None\]$', "^oops$",
3399 '^None unexpectedly found in \[None\]$',
3400 '^None unexpectedly found in \[None\] : oops$'])
3401
3402 def testAssertDictEqual(self):
3403 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3404 [r"\+ \{'key': 'value'\}$", "^oops$",
3405 "\+ \{'key': 'value'\}$",
3406 "\+ \{'key': 'value'\} : oops$"])
3407
3408 def testAssertDictContainsSubset(self):
3409 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3410 ["^Missing: 'key'$", "^oops$",
3411 "^Missing: 'key'$",
3412 "^Missing: 'key' : oops$"])
3413
Michael Foord98e7b762010-03-20 03:00:34 +00003414 def testAssertItemsEqual(self):
3415 self.assertMessages('assertItemsEqual', ([], [None]),
Michael Foord345b2fe2009-04-02 03:20:38 +00003416 [r"\[None\]$", "^oops$",
3417 r"\[None\]$",
3418 r"\[None\] : oops$"])
3419
3420 def testAssertMultiLineEqual(self):
3421 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3422 [r"\+ foo$", "^oops$",
3423 r"\+ foo$",
3424 r"\+ foo : oops$"])
3425
3426 def testAssertLess(self):
3427 self.assertMessages('assertLess', (2, 1),
3428 ["^2 not less than 1$", "^oops$",
3429 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3430
3431 def testAssertLessEqual(self):
3432 self.assertMessages('assertLessEqual', (2, 1),
3433 ["^2 not less than or equal to 1$", "^oops$",
3434 "^2 not less than or equal to 1$",
3435 "^2 not less than or equal to 1 : oops$"])
3436
3437 def testAssertGreater(self):
3438 self.assertMessages('assertGreater', (1, 2),
3439 ["^1 not greater than 2$", "^oops$",
3440 "^1 not greater than 2$",
3441 "^1 not greater than 2 : oops$"])
3442
3443 def testAssertGreaterEqual(self):
3444 self.assertMessages('assertGreaterEqual', (1, 2),
3445 ["^1 not greater than or equal to 2$", "^oops$",
3446 "^1 not greater than or equal to 2$",
3447 "^1 not greater than or equal to 2 : oops$"])
3448
3449 def testAssertIsNone(self):
3450 self.assertMessages('assertIsNone', ('not None',),
3451 ["^'not None' is not None$", "^oops$",
3452 "^'not None' is not None$",
3453 "^'not None' is not None : oops$"])
3454
3455 def testAssertIsNotNone(self):
3456 self.assertMessages('assertIsNotNone', (None,),
3457 ["^unexpectedly None$", "^oops$",
3458 "^unexpectedly None$",
3459 "^unexpectedly None : oops$"])
3460
Michael Foordf2dfef12009-04-05 19:19:28 +00003461 def testAssertIs(self):
3462 self.assertMessages('assertIs', (None, 'foo'),
3463 ["^None is not 'foo'$", "^oops$",
3464 "^None is not 'foo'$",
3465 "^None is not 'foo' : oops$"])
3466
3467 def testAssertIsNot(self):
3468 self.assertMessages('assertIsNot', (None, None),
3469 ["^unexpectedly identical: None$", "^oops$",
3470 "^unexpectedly identical: None$",
3471 "^unexpectedly identical: None : oops$"])
3472
Michael Foord345b2fe2009-04-02 03:20:38 +00003473
Michael Foorde2fb98f2009-05-02 20:15:05 +00003474class TestCleanUp(TestCase):
3475
3476 def testCleanUp(self):
3477 class TestableTest(TestCase):
3478 def testNothing(self):
3479 pass
3480
3481 test = TestableTest('testNothing')
3482 self.assertEqual(test._cleanups, [])
3483
3484 cleanups = []
3485
3486 def cleanup1(*args, **kwargs):
3487 cleanups.append((1, args, kwargs))
3488
3489 def cleanup2(*args, **kwargs):
3490 cleanups.append((2, args, kwargs))
3491
3492 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3493 test.addCleanup(cleanup2)
3494
3495 self.assertEqual(test._cleanups,
3496 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3497 (cleanup2, (), {})])
3498
3499 result = test.doCleanups()
3500 self.assertTrue(result)
3501
3502 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3503
3504 def testCleanUpWithErrors(self):
3505 class TestableTest(TestCase):
3506 def testNothing(self):
3507 pass
3508
3509 class MockResult(object):
3510 errors = []
3511 def addError(self, test, exc_info):
3512 self.errors.append((test, exc_info))
3513
3514 result = MockResult()
3515 test = TestableTest('testNothing')
Michael Foorda50af062009-05-21 22:57:02 +00003516 test._resultForDoCleanups = result
Michael Foorde2fb98f2009-05-02 20:15:05 +00003517
3518 exc1 = Exception('foo')
3519 exc2 = Exception('bar')
3520 def cleanup1():
3521 raise exc1
3522
3523 def cleanup2():
3524 raise exc2
3525
3526 test.addCleanup(cleanup1)
3527 test.addCleanup(cleanup2)
3528
3529 self.assertFalse(test.doCleanups())
3530
3531 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3532 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3533 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3534
3535 def testCleanupInRun(self):
3536 blowUp = False
3537 ordering = []
3538
3539 class TestableTest(TestCase):
3540 def setUp(self):
3541 ordering.append('setUp')
3542 if blowUp:
3543 raise Exception('foo')
3544
3545 def testNothing(self):
3546 ordering.append('test')
3547
3548 def tearDown(self):
3549 ordering.append('tearDown')
3550
3551 test = TestableTest('testNothing')
3552
3553 def cleanup1():
3554 ordering.append('cleanup1')
3555 def cleanup2():
3556 ordering.append('cleanup2')
3557 test.addCleanup(cleanup1)
3558 test.addCleanup(cleanup2)
3559
3560 def success(some_test):
3561 self.assertEqual(some_test, test)
3562 ordering.append('success')
3563
3564 result = unittest.TestResult()
3565 result.addSuccess = success
3566
3567 test.run(result)
3568 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3569 'cleanup2', 'cleanup1', 'success'])
3570
3571 blowUp = True
3572 ordering = []
3573 test = TestableTest('testNothing')
3574 test.addCleanup(cleanup1)
3575 test.run(result)
3576 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3577
3578
Michael Foord829f6b82009-05-02 11:43:06 +00003579class Test_TestProgram(TestCase):
3580
3581 # Horrible white box test
3582 def testNoExit(self):
3583 result = object()
3584 test = object()
3585
3586 class FakeRunner(object):
3587 def run(self, test):
3588 self.test = test
3589 return result
3590
3591 runner = FakeRunner()
3592
Michael Foord5d31e052009-05-11 17:59:43 +00003593 oldParseArgs = TestProgram.parseArgs
3594 def restoreParseArgs():
Michael Foord829f6b82009-05-02 11:43:06 +00003595 TestProgram.parseArgs = oldParseArgs
Michael Foord5d31e052009-05-11 17:59:43 +00003596 TestProgram.parseArgs = lambda *args: None
3597 self.addCleanup(restoreParseArgs)
3598
3599 def removeTest():
Michael Foord829f6b82009-05-02 11:43:06 +00003600 del TestProgram.test
Michael Foord5d31e052009-05-11 17:59:43 +00003601 TestProgram.test = test
3602 self.addCleanup(removeTest)
3603
3604 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3605
3606 self.assertEqual(program.result, result)
3607 self.assertEqual(runner.test, test)
3608 self.assertEqual(program.verbosity, 2)
Michael Foord829f6b82009-05-02 11:43:06 +00003609
Michael Foord829f6b82009-05-02 11:43:06 +00003610 class FooBar(unittest.TestCase):
3611 def testPass(self):
3612 assert True
3613 def testFail(self):
3614 assert False
3615
3616 class FooBarLoader(unittest.TestLoader):
3617 """Test loader that returns a suite containing FooBar."""
3618 def loadTestsFromModule(self, module):
3619 return self.suiteClass(
3620 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3621
3622
3623 def test_NonExit(self):
3624 program = unittest.main(exit=False,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003625 argv=["foobar"],
3626 testRunner=unittest.TextTestRunner(stream=StringIO()),
3627 testLoader=self.FooBarLoader())
Michael Foord829f6b82009-05-02 11:43:06 +00003628 self.assertTrue(hasattr(program, 'result'))
3629
3630
3631 def test_Exit(self):
3632 self.assertRaises(
3633 SystemExit,
3634 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003635 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003636 testRunner=unittest.TextTestRunner(stream=StringIO()),
3637 exit=True,
3638 testLoader=self.FooBarLoader())
3639
3640
3641 def test_ExitAsDefault(self):
3642 self.assertRaises(
3643 SystemExit,
3644 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003645 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003646 testRunner=unittest.TextTestRunner(stream=StringIO()),
3647 testLoader=self.FooBarLoader())
3648
3649
Michael Foord07ef4872009-05-02 22:43:34 +00003650class Test_TextTestRunner(TestCase):
3651 """Tests for TextTestRunner."""
3652
3653 def test_works_with_result_without_startTestRun_stopTestRun(self):
3654 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3655 separator2 = ''
3656 def printErrors(self):
3657 pass
3658
3659 class Runner(unittest.TextTestRunner):
3660 def __init__(self):
3661 super(Runner, self).__init__(StringIO())
3662
3663 def _makeResult(self):
3664 return OldTextResult()
3665
3666 runner = Runner()
3667 runner.run(unittest.TestSuite())
3668
3669 def test_startTestRun_stopTestRun_called(self):
3670 class LoggingTextResult(LoggingResult):
3671 separator2 = ''
3672 def printErrors(self):
3673 pass
3674
3675 class LoggingRunner(unittest.TextTestRunner):
3676 def __init__(self, events):
3677 super(LoggingRunner, self).__init__(StringIO())
3678 self._events = events
3679
3680 def _makeResult(self):
3681 return LoggingTextResult(self._events)
3682
3683 events = []
3684 runner = LoggingRunner(events)
3685 runner.run(unittest.TestSuite())
3686 expected = ['startTestRun', 'stopTestRun']
3687 self.assertEqual(events, expected)
3688
Antoine Pitrou0734c632009-11-10 20:49:30 +00003689 def test_pickle_unpickle(self):
3690 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3691 # required by test_multiprocessing under Windows (in verbose mode).
3692 import StringIO
3693 # cStringIO objects are not pickleable, but StringIO objects are.
3694 stream = StringIO.StringIO("foo")
3695 runner = unittest.TextTestRunner(stream)
3696 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
3697 s = pickle.dumps(runner, protocol=protocol)
3698 obj = pickle.loads(s)
3699 # StringIO objects never compare equal, a cheap test instead.
3700 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3701
Michael Foorddb43b5a2010-02-10 14:25:12 +00003702 def test_resultclass(self):
3703 def MockResultClass(*args):
3704 return args
3705 STREAM = object()
3706 DESCRIPTIONS = object()
3707 VERBOSITY = object()
3708 runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY,
3709 resultclass=MockResultClass)
3710 self.assertEqual(runner.resultclass, MockResultClass)
3711
3712 expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY)
3713 self.assertEqual(runner._makeResult(), expectedresult)
3714
Michael Foord07ef4872009-05-02 22:43:34 +00003715
Michael Foordb4a81c82009-05-29 20:33:46 +00003716class TestDiscovery(TestCase):
3717
3718 # Heavily mocked tests so I can avoid hitting the filesystem
Michael Foorde91ea562009-09-13 19:07:03 +00003719 def test_get_name_from_path(self):
Michael Foordb4a81c82009-05-29 20:33:46 +00003720 loader = unittest.TestLoader()
3721
Michael Foordb4a81c82009-05-29 20:33:46 +00003722 loader._top_level_dir = '/foo'
Michael Foorde91ea562009-09-13 19:07:03 +00003723 name = loader._get_name_from_path('/foo/bar/baz.py')
3724 self.assertEqual(name, 'bar.baz')
Michael Foordb4a81c82009-05-29 20:33:46 +00003725
3726 if not __debug__:
3727 # asserts are off
3728 return
3729
3730 with self.assertRaises(AssertionError):
Michael Foorde91ea562009-09-13 19:07:03 +00003731 loader._get_name_from_path('/bar/baz.py')
Michael Foordb4a81c82009-05-29 20:33:46 +00003732
3733 def test_find_tests(self):
3734 loader = unittest.TestLoader()
3735
3736 original_listdir = os.listdir
3737 def restore_listdir():
3738 os.listdir = original_listdir
3739 original_isfile = os.path.isfile
3740 def restore_isfile():
3741 os.path.isfile = original_isfile
3742 original_isdir = os.path.isdir
3743 def restore_isdir():
3744 os.path.isdir = original_isdir
3745
3746 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Michael Foorde91ea562009-09-13 19:07:03 +00003747 'test.foo', 'test-not-a-module.py', 'another_dir'],
Michael Foordb4a81c82009-05-29 20:33:46 +00003748 ['test3.py', 'test4.py', ]]
3749 os.listdir = lambda path: path_lists.pop(0)
3750 self.addCleanup(restore_listdir)
3751
3752 def isdir(path):
3753 return path.endswith('dir')
3754 os.path.isdir = isdir
3755 self.addCleanup(restore_isdir)
3756
3757 def isfile(path):
3758 # another_dir is not a package and so shouldn't be recursed into
3759 return not path.endswith('dir') and not 'another_dir' in path
3760 os.path.isfile = isfile
3761 self.addCleanup(restore_isfile)
3762
Michael Foorde91ea562009-09-13 19:07:03 +00003763 loader._get_module_from_name = lambda path: path + ' module'
Michael Foordb4a81c82009-05-29 20:33:46 +00003764 loader.loadTestsFromModule = lambda module: module + ' tests'
3765
3766 loader._top_level_dir = '/foo'
3767 suite = list(loader._find_tests('/foo', 'test*.py'))
3768
Michael Foorde91ea562009-09-13 19:07:03 +00003769 expected = [name + ' module tests' for name in
3770 ('test1', 'test2')]
3771 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3772 ('test3', 'test4')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003773 self.assertEqual(suite, expected)
3774
3775 def test_find_tests_with_package(self):
3776 loader = unittest.TestLoader()
3777
3778 original_listdir = os.listdir
3779 def restore_listdir():
3780 os.listdir = original_listdir
3781 original_isfile = os.path.isfile
3782 def restore_isfile():
3783 os.path.isfile = original_isfile
3784 original_isdir = os.path.isdir
3785 def restore_isdir():
3786 os.path.isdir = original_isdir
3787
3788 directories = ['a_directory', 'test_directory', 'test_directory2']
3789 path_lists = [directories, [], [], []]
3790 os.listdir = lambda path: path_lists.pop(0)
3791 self.addCleanup(restore_listdir)
3792
3793 os.path.isdir = lambda path: True
3794 self.addCleanup(restore_isdir)
3795
3796 os.path.isfile = lambda path: os.path.basename(path) not in directories
3797 self.addCleanup(restore_isfile)
3798
3799 class Module(object):
3800 paths = []
3801 load_tests_args = []
3802
3803 def __init__(self, path):
3804 self.path = path
3805 self.paths.append(path)
3806 if os.path.basename(path) == 'test_directory':
3807 def load_tests(loader, tests, pattern):
3808 self.load_tests_args.append((loader, tests, pattern))
3809 return 'load_tests'
3810 self.load_tests = load_tests
3811
3812 def __eq__(self, other):
3813 return self.path == other.path
3814
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003815 # Silence py3k warning
3816 __hash__ = None
3817
Michael Foorde91ea562009-09-13 19:07:03 +00003818 loader._get_module_from_name = lambda name: Module(name)
Michael Foordb4a81c82009-05-29 20:33:46 +00003819 def loadTestsFromModule(module, use_load_tests):
3820 if use_load_tests:
3821 raise self.failureException('use_load_tests should be False for packages')
3822 return module.path + ' module tests'
3823 loader.loadTestsFromModule = loadTestsFromModule
3824
3825 loader._top_level_dir = '/foo'
3826 # this time no '.py' on the pattern so that it can match
3827 # a test package
3828 suite = list(loader._find_tests('/foo', 'test*'))
3829
3830 # We should have loaded tests from the test_directory package by calling load_tests
3831 # and directly from the test_directory2 package
Michael Foordd53d0852009-06-05 14:14:34 +00003832 self.assertEqual(suite,
Michael Foorde91ea562009-09-13 19:07:03 +00003833 ['load_tests', 'test_directory2' + ' module tests'])
3834 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Michael Foordb4a81c82009-05-29 20:33:46 +00003835
3836 # load_tests should have been called once with loader, tests and pattern
3837 self.assertEqual(Module.load_tests_args,
Michael Foorde91ea562009-09-13 19:07:03 +00003838 [(loader, 'test_directory' + ' module tests', 'test*')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003839
3840 def test_discover(self):
3841 loader = unittest.TestLoader()
3842
3843 original_isfile = os.path.isfile
3844 def restore_isfile():
3845 os.path.isfile = original_isfile
3846
3847 os.path.isfile = lambda path: False
3848 self.addCleanup(restore_isfile)
3849
Nick Coghlanb6edf192009-10-17 08:21:21 +00003850 orig_sys_path = sys.path[:]
3851 def restore_path():
3852 sys.path[:] = orig_sys_path
3853 self.addCleanup(restore_path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003854
Nick Coghlanb6edf192009-10-17 08:21:21 +00003855 full_path = os.path.abspath(os.path.normpath('/foo'))
Michael Foordb4a81c82009-05-29 20:33:46 +00003856 with self.assertRaises(ImportError):
3857 loader.discover('/foo/bar', top_level_dir='/foo')
3858
3859 self.assertEqual(loader._top_level_dir, full_path)
3860 self.assertIn(full_path, sys.path)
3861
3862 os.path.isfile = lambda path: True
3863 _find_tests_args = []
3864 def _find_tests(start_dir, pattern):
3865 _find_tests_args.append((start_dir, pattern))
3866 return ['tests']
3867 loader._find_tests = _find_tests
3868 loader.suiteClass = str
3869
3870 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3871
3872 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3873 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3874 self.assertEqual(suite, "['tests']")
3875 self.assertEqual(loader._top_level_dir, top_level_dir)
3876 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlanb6edf192009-10-17 08:21:21 +00003877 self.assertIn(top_level_dir, sys.path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003878
Michael Foorde91ea562009-09-13 19:07:03 +00003879 def test_discover_with_modules_that_fail_to_import(self):
3880 loader = unittest.TestLoader()
3881
3882 listdir = os.listdir
3883 os.listdir = lambda _: ['test_this_does_not_exist.py']
3884 isfile = os.path.isfile
3885 os.path.isfile = lambda _: True
Nick Coghlanb6edf192009-10-17 08:21:21 +00003886 orig_sys_path = sys.path[:]
Michael Foorde91ea562009-09-13 19:07:03 +00003887 def restore():
3888 os.path.isfile = isfile
3889 os.listdir = listdir
Nick Coghlanb6edf192009-10-17 08:21:21 +00003890 sys.path[:] = orig_sys_path
Michael Foorde91ea562009-09-13 19:07:03 +00003891 self.addCleanup(restore)
3892
3893 suite = loader.discover('.')
Nick Coghlanb6edf192009-10-17 08:21:21 +00003894 self.assertIn(os.getcwd(), sys.path)
Michael Foorde91ea562009-09-13 19:07:03 +00003895 self.assertEqual(suite.countTestCases(), 1)
3896 test = list(list(suite)[0])[0] # extract test from suite
3897
3898 with self.assertRaises(ImportError):
3899 test.test_this_does_not_exist()
3900
Michael Foordb4a81c82009-05-29 20:33:46 +00003901 def test_command_line_handling_parseArgs(self):
3902 # Haha - take that uninstantiable class
3903 program = object.__new__(TestProgram)
3904
3905 args = []
3906 def do_discovery(argv):
3907 args.extend(argv)
3908 program._do_discovery = do_discovery
3909 program.parseArgs(['something', 'discover'])
3910 self.assertEqual(args, [])
3911
3912 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3913 self.assertEqual(args, ['foo', 'bar'])
3914
3915 def test_command_line_handling_do_discovery_too_many_arguments(self):
3916 class Stop(Exception):
3917 pass
3918 def usageExit():
3919 raise Stop
3920
3921 program = object.__new__(TestProgram)
3922 program.usageExit = usageExit
3923
3924 with self.assertRaises(Stop):
3925 # too many args
3926 program._do_discovery(['one', 'two', 'three', 'four'])
3927
3928
3929 def test_command_line_handling_do_discovery_calls_loader(self):
3930 program = object.__new__(TestProgram)
3931
3932 class Loader(object):
3933 args = []
3934 def discover(self, start_dir, pattern, top_level_dir):
3935 self.args.append((start_dir, pattern, top_level_dir))
3936 return 'tests'
3937
3938 program._do_discovery(['-v'], Loader=Loader)
3939 self.assertEqual(program.verbosity, 2)
3940 self.assertEqual(program.test, 'tests')
3941 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3942
3943 Loader.args = []
3944 program = object.__new__(TestProgram)
3945 program._do_discovery(['--verbose'], Loader=Loader)
3946 self.assertEqual(program.test, 'tests')
3947 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3948
3949 Loader.args = []
3950 program = object.__new__(TestProgram)
3951 program._do_discovery([], Loader=Loader)
3952 self.assertEqual(program.test, 'tests')
3953 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3954
3955 Loader.args = []
3956 program = object.__new__(TestProgram)
3957 program._do_discovery(['fish'], Loader=Loader)
3958 self.assertEqual(program.test, 'tests')
3959 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3960
3961 Loader.args = []
3962 program = object.__new__(TestProgram)
3963 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3964 self.assertEqual(program.test, 'tests')
3965 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3966
3967 Loader.args = []
3968 program = object.__new__(TestProgram)
3969 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3970 self.assertEqual(program.test, 'tests')
3971 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3972
3973 Loader.args = []
3974 program = object.__new__(TestProgram)
3975 program._do_discovery(['-s', 'fish'], Loader=Loader)
3976 self.assertEqual(program.test, 'tests')
3977 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3978
3979 Loader.args = []
3980 program = object.__new__(TestProgram)
3981 program._do_discovery(['-t', 'fish'], Loader=Loader)
3982 self.assertEqual(program.test, 'tests')
3983 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3984
3985 Loader.args = []
3986 program = object.__new__(TestProgram)
3987 program._do_discovery(['-p', 'fish'], Loader=Loader)
3988 self.assertEqual(program.test, 'tests')
3989 self.assertEqual(Loader.args, [('.', 'fish', None)])
3990
3991 Loader.args = []
3992 program = object.__new__(TestProgram)
3993 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3994 self.assertEqual(program.test, 'tests')
3995 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3996 self.assertEqual(program.verbosity, 2)
3997
3998
Michael Foord5ffa3252010-03-07 22:04:55 +00003999class TestSetups(unittest.TestCase):
4000
4001 def getRunner(self):
4002 return unittest.TextTestRunner(resultclass=resultFactory,
4003 stream=StringIO())
4004 def runTests(self, *cases):
4005 suite = unittest.TestSuite()
4006 for case in cases:
4007 tests = unittest.defaultTestLoader.loadTestsFromTestCase(case)
4008 suite.addTests(tests)
4009
4010 runner = self.getRunner()
4011
4012 # creating a nested suite exposes some potential bugs
4013 realSuite = unittest.TestSuite()
4014 realSuite.addTest(suite)
4015 # adding empty suites to the end exposes potential bugs
4016 suite.addTest(unittest.TestSuite())
4017 realSuite.addTest(unittest.TestSuite())
4018 return runner.run(realSuite)
4019
4020 def test_setup_class(self):
4021 class Test(unittest.TestCase):
4022 setUpCalled = 0
4023 @classmethod
4024 def setUpClass(cls):
4025 Test.setUpCalled += 1
4026 unittest.TestCase.setUpClass()
4027 def test_one(self):
4028 pass
4029 def test_two(self):
4030 pass
4031
4032 result = self.runTests(Test)
4033
4034 self.assertEqual(Test.setUpCalled, 1)
4035 self.assertEqual(result.testsRun, 2)
4036 self.assertEqual(len(result.errors), 0)
4037
4038 def test_teardown_class(self):
4039 class Test(unittest.TestCase):
4040 tearDownCalled = 0
4041 @classmethod
4042 def tearDownClass(cls):
4043 Test.tearDownCalled += 1
4044 unittest.TestCase.tearDownClass()
4045 def test_one(self):
4046 pass
4047 def test_two(self):
4048 pass
4049
4050 result = self.runTests(Test)
4051
4052 self.assertEqual(Test.tearDownCalled, 1)
4053 self.assertEqual(result.testsRun, 2)
4054 self.assertEqual(len(result.errors), 0)
4055
4056 def test_teardown_class_two_classes(self):
4057 class Test(unittest.TestCase):
4058 tearDownCalled = 0
4059 @classmethod
4060 def tearDownClass(cls):
4061 Test.tearDownCalled += 1
4062 unittest.TestCase.tearDownClass()
4063 def test_one(self):
4064 pass
4065 def test_two(self):
4066 pass
4067
4068 class Test2(unittest.TestCase):
4069 tearDownCalled = 0
4070 @classmethod
4071 def tearDownClass(cls):
4072 Test2.tearDownCalled += 1
4073 unittest.TestCase.tearDownClass()
4074 def test_one(self):
4075 pass
4076 def test_two(self):
4077 pass
4078
4079 result = self.runTests(Test, Test2)
4080
4081 self.assertEqual(Test.tearDownCalled, 1)
4082 self.assertEqual(Test2.tearDownCalled, 1)
4083 self.assertEqual(result.testsRun, 4)
4084 self.assertEqual(len(result.errors), 0)
4085
4086 def test_error_in_setupclass(self):
4087 class BrokenTest(unittest.TestCase):
4088 @classmethod
4089 def setUpClass(cls):
4090 raise TypeError('foo')
4091 def test_one(self):
4092 pass
4093 def test_two(self):
4094 pass
4095
4096 result = self.runTests(BrokenTest)
4097
4098 self.assertEqual(result.testsRun, 0)
4099 self.assertEqual(len(result.errors), 1)
4100 error, _ = result.errors[0]
4101 self.assertEqual(str(error),
4102 'classSetUp (%s.BrokenTest)' % __name__)
4103
4104 def test_error_in_teardown_class(self):
4105 class Test(unittest.TestCase):
4106 tornDown = 0
4107 @classmethod
4108 def tearDownClass(cls):
4109 Test.tornDown += 1
4110 raise TypeError('foo')
4111 def test_one(self):
4112 pass
4113 def test_two(self):
4114 pass
4115
4116 class Test2(unittest.TestCase):
4117 tornDown = 0
4118 @classmethod
4119 def tearDownClass(cls):
4120 Test2.tornDown += 1
4121 raise TypeError('foo')
4122 def test_one(self):
4123 pass
4124 def test_two(self):
4125 pass
4126
4127 result = self.runTests(Test, Test2)
4128 self.assertEqual(result.testsRun, 4)
4129 self.assertEqual(len(result.errors), 2)
4130 self.assertEqual(Test.tornDown, 1)
4131 self.assertEqual(Test2.tornDown, 1)
4132
4133 error, _ = result.errors[0]
4134 self.assertEqual(str(error),
4135 'classTearDown (%s.Test)' % __name__)
4136
4137 def test_class_not_torndown_when_setup_fails(self):
4138 class Test(unittest.TestCase):
4139 tornDown = False
4140 @classmethod
4141 def setUpClass(cls):
4142 raise TypeError
4143 @classmethod
4144 def tearDownClass(cls):
4145 Test.tornDown = True
4146 raise TypeError('foo')
4147 def test_one(self):
4148 pass
4149
4150 self.runTests(Test)
4151 self.assertFalse(Test.tornDown)
4152
4153 def test_class_not_setup_or_torndown_when_skipped(self):
4154 class Test(unittest.TestCase):
4155 classSetUp = False
4156 tornDown = False
4157 @classmethod
4158 def setUpClass(cls):
4159 Test.classSetUp = True
4160 @classmethod
4161 def tearDownClass(cls):
4162 Test.tornDown = True
4163 def test_one(self):
4164 pass
4165
4166 Test = unittest.skip("hop")(Test)
4167 self.runTests(Test)
4168 self.assertFalse(Test.classSetUp)
4169 self.assertFalse(Test.tornDown)
4170
4171 def test_setup_teardown_order_with_pathological_suite(self):
4172 results = []
4173
4174 class Module1(object):
4175 @staticmethod
4176 def setUpModule():
4177 results.append('Module1.setUpModule')
4178 @staticmethod
4179 def tearDownModule():
4180 results.append('Module1.tearDownModule')
4181
4182 class Module2(object):
4183 @staticmethod
4184 def setUpModule():
4185 results.append('Module2.setUpModule')
4186 @staticmethod
4187 def tearDownModule():
4188 results.append('Module2.tearDownModule')
4189
4190 class Test1(unittest.TestCase):
4191 @classmethod
4192 def setUpClass(cls):
4193 results.append('setup 1')
4194 @classmethod
4195 def tearDownClass(cls):
4196 results.append('teardown 1')
4197 def testOne(self):
4198 results.append('Test1.testOne')
4199 def testTwo(self):
4200 results.append('Test1.testTwo')
4201
4202 class Test2(unittest.TestCase):
4203 @classmethod
4204 def setUpClass(cls):
4205 results.append('setup 2')
4206 @classmethod
4207 def tearDownClass(cls):
4208 results.append('teardown 2')
4209 def testOne(self):
4210 results.append('Test2.testOne')
4211 def testTwo(self):
4212 results.append('Test2.testTwo')
4213
4214 class Test3(unittest.TestCase):
4215 @classmethod
4216 def setUpClass(cls):
4217 results.append('setup 3')
4218 @classmethod
4219 def tearDownClass(cls):
4220 results.append('teardown 3')
4221 def testOne(self):
4222 results.append('Test3.testOne')
4223 def testTwo(self):
4224 results.append('Test3.testTwo')
4225
4226 Test1.__module__ = Test2.__module__ = 'Module'
4227 Test3.__module__ = 'Module2'
4228 sys.modules['Module'] = Module1
4229 sys.modules['Module2'] = Module2
4230
4231 first = unittest.TestSuite((Test1('testOne'),))
4232 second = unittest.TestSuite((Test1('testTwo'),))
4233 third = unittest.TestSuite((Test2('testOne'),))
4234 fourth = unittest.TestSuite((Test2('testTwo'),))
4235 fifth = unittest.TestSuite((Test3('testOne'),))
4236 sixth = unittest.TestSuite((Test3('testTwo'),))
4237 suite = unittest.TestSuite((first, second, third, fourth, fifth, sixth))
4238
4239 runner = self.getRunner()
4240 result = runner.run(suite)
4241 self.assertEqual(result.testsRun, 6)
4242 self.assertEqual(len(result.errors), 0)
4243
4244 self.assertEqual(results,
4245 ['Module1.setUpModule', 'setup 1',
4246 'Test1.testOne', 'Test1.testTwo', 'teardown 1',
4247 'setup 2', 'Test2.testOne', 'Test2.testTwo',
4248 'teardown 2', 'Module1.tearDownModule',
4249 'Module2.setUpModule', 'setup 3',
4250 'Test3.testOne', 'Test3.testTwo',
4251 'teardown 3', 'Module2.tearDownModule'])
4252
4253 def test_setup_module(self):
4254 class Module(object):
4255 moduleSetup = 0
4256 @staticmethod
4257 def setUpModule():
4258 Module.moduleSetup += 1
4259
4260 class Test(unittest.TestCase):
4261 def test_one(self):
4262 pass
4263 def test_two(self):
4264 pass
4265 Test.__module__ = 'Module'
4266 sys.modules['Module'] = Module
4267
4268 result = self.runTests(Test)
4269 self.assertEqual(Module.moduleSetup, 1)
4270 self.assertEqual(result.testsRun, 2)
4271 self.assertEqual(len(result.errors), 0)
4272
4273 def test_error_in_setup_module(self):
4274 class Module(object):
4275 moduleSetup = 0
4276 moduleTornDown = 0
4277 @staticmethod
4278 def setUpModule():
4279 Module.moduleSetup += 1
4280 raise TypeError('foo')
4281 @staticmethod
4282 def tearDownModule():
4283 Module.moduleTornDown += 1
4284
4285 class Test(unittest.TestCase):
4286 classSetUp = False
4287 classTornDown = False
4288 @classmethod
4289 def setUpClass(cls):
4290 Test.classSetUp = True
4291 @classmethod
4292 def tearDownClass(cls):
4293 Test.classTornDown = True
4294 def test_one(self):
4295 pass
4296 def test_two(self):
4297 pass
4298
4299 class Test2(unittest.TestCase):
4300 def test_one(self):
4301 pass
4302 def test_two(self):
4303 pass
4304 Test.__module__ = 'Module'
4305 Test2.__module__ = 'Module'
4306 sys.modules['Module'] = Module
4307
4308 result = self.runTests(Test, Test2)
4309 self.assertEqual(Module.moduleSetup, 1)
4310 self.assertEqual(Module.moduleTornDown, 0)
4311 self.assertEqual(result.testsRun, 0)
4312 self.assertFalse(Test.classSetUp)
4313 self.assertFalse(Test.classTornDown)
4314 self.assertEqual(len(result.errors), 1)
4315 error, _ = result.errors[0]
4316 self.assertEqual(str(error), 'setUpModule (Module)')
4317
4318 def test_testcase_with_missing_module(self):
4319 class Test(unittest.TestCase):
4320 def test_one(self):
4321 pass
4322 def test_two(self):
4323 pass
4324 Test.__module__ = 'Module'
4325 sys.modules.pop('Module', None)
4326
4327 result = self.runTests(Test)
4328 self.assertEqual(result.testsRun, 2)
4329
4330 def test_teardown_module(self):
4331 class Module(object):
4332 moduleTornDown = 0
4333 @staticmethod
4334 def tearDownModule():
4335 Module.moduleTornDown += 1
4336
4337 class Test(unittest.TestCase):
4338 def test_one(self):
4339 pass
4340 def test_two(self):
4341 pass
4342 Test.__module__ = 'Module'
4343 sys.modules['Module'] = Module
4344
4345 result = self.runTests(Test)
4346 self.assertEqual(Module.moduleTornDown, 1)
4347 self.assertEqual(result.testsRun, 2)
4348 self.assertEqual(len(result.errors), 0)
4349
4350 def test_error_in_teardown_module(self):
4351 class Module(object):
4352 moduleTornDown = 0
4353 @staticmethod
4354 def tearDownModule():
4355 Module.moduleTornDown += 1
4356 raise TypeError('foo')
4357
4358 class Test(unittest.TestCase):
4359 classSetUp = False
4360 classTornDown = False
4361 @classmethod
4362 def setUpClass(cls):
4363 Test.classSetUp = True
4364 @classmethod
4365 def tearDownClass(cls):
4366 Test.classTornDown = True
4367 def test_one(self):
4368 pass
4369 def test_two(self):
4370 pass
4371
4372 class Test2(unittest.TestCase):
4373 def test_one(self):
4374 pass
4375 def test_two(self):
4376 pass
4377 Test.__module__ = 'Module'
4378 Test2.__module__ = 'Module'
4379 sys.modules['Module'] = Module
4380
4381 result = self.runTests(Test, Test2)
4382 self.assertEqual(Module.moduleTornDown, 1)
4383 self.assertEqual(result.testsRun, 4)
4384 self.assertTrue(Test.classSetUp)
4385 self.assertTrue(Test.classTornDown)
4386 self.assertEqual(len(result.errors), 1)
4387 error, _ = result.errors[0]
4388 self.assertEqual(str(error), 'tearDownModule (Module)')
4389
Jim Fultonfafd8742004-08-28 15:22:12 +00004390######################################################################
4391## Main
4392######################################################################
4393
4394def test_main():
Georg Brandl15c5ce92007-03-07 09:09:40 +00004395 test_support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004396 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Michael Foord829f6b82009-05-02 11:43:06 +00004397 Test_TestSkipping, Test_Assertions, TestLongMessage,
Michael Foordae3db0a2010-02-22 23:28:32 +00004398 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner,
Michael Foord5ffa3252010-03-07 22:04:55 +00004399 Test_OldTestResult, TestSetups)
Jim Fultonfafd8742004-08-28 15:22:12 +00004400
Georg Brandl15c5ce92007-03-07 09:09:40 +00004401if __name__ == "__main__":
Tim Petersea5962f2007-03-12 18:07:52 +00004402 test_main()