blob: f003208a0a3e337159e686c11c0de5fe6fdc2b74 [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 Foord1b9e9532010-03-22 01:01:34 +00002097 def testFailFast(self):
2098 result = unittest.TestResult()
2099 result._exc_info_to_string = lambda *_: ''
2100 result.failfast = True
2101 result.addError(None, None)
2102 self.assertTrue(result.shouldStop)
2103
2104 result = unittest.TestResult()
2105 result._exc_info_to_string = lambda *_: ''
2106 result.failfast = True
2107 result.addFailure(None, None)
2108 self.assertTrue(result.shouldStop)
2109
2110 result = unittest.TestResult()
2111 result._exc_info_to_string = lambda *_: ''
2112 result.failfast = True
2113 result.addUnexpectedSuccess(None)
2114 self.assertTrue(result.shouldStop)
2115
2116 result = unittest.TestResult()
2117 result._exc_info_to_string = lambda *_: ''
2118 result.failfast = True
2119 result.addExpectedFailure(None, None)
2120 self.assertTrue(result.shouldStop)
2121
2122 def testFailFastSetByRunner(self):
2123 runner = unittest.TextTestRunner(stream=StringIO(), failfast=True)
2124 def test(result):
2125 self.assertTrue(result.failfast)
2126 result = runner.run(test)
2127
2128
Michael Foordae3db0a2010-02-22 23:28:32 +00002129classDict = dict(unittest.TestResult.__dict__)
Michael Foordd99ef9a2010-02-23 17:00:53 +00002130for m in ('addSkip', 'addExpectedFailure', 'addUnexpectedSuccess',
2131 '__init__'):
Michael Foordae3db0a2010-02-22 23:28:32 +00002132 del classDict[m]
Michael Foordd99ef9a2010-02-23 17:00:53 +00002133
2134def __init__(self, stream=None, descriptions=None, verbosity=None):
2135 self.failures = []
2136 self.errors = []
2137 self.testsRun = 0
2138 self.shouldStop = False
2139classDict['__init__'] = __init__
Michael Foordae3db0a2010-02-22 23:28:32 +00002140OldResult = type('OldResult', (object,), classDict)
2141
2142class Test_OldTestResult(unittest.TestCase):
2143
2144 def assertOldResultWarning(self, test, failures):
2145 with warnings.catch_warnings(record=True) as log:
2146 result = OldResult()
2147 test.run(result)
2148 self.assertEqual(len(result.failures), failures)
2149 warning, = log
2150 self.assertIs(warning.category, RuntimeWarning)
2151
2152 def testOldTestResult(self):
2153 class Test(unittest.TestCase):
2154 def testSkip(self):
2155 self.skipTest('foobar')
2156 @unittest.expectedFailure
2157 def testExpectedFail(self):
2158 raise TypeError
2159 @unittest.expectedFailure
2160 def testUnexpectedSuccess(self):
2161 pass
2162
2163 for test_name, should_pass in (('testSkip', True),
2164 ('testExpectedFail', True),
2165 ('testUnexpectedSuccess', False)):
2166 test = Test(test_name)
2167 self.assertOldResultWarning(test, int(not should_pass))
2168
2169 def testOldTestTesultSetup(self):
2170 class Test(unittest.TestCase):
2171 def setUp(self):
2172 self.skipTest('no reason')
2173 def testFoo(self):
2174 pass
2175 self.assertOldResultWarning(Test('testFoo'), 0)
2176
2177 def testOldTestResultClass(self):
2178 @unittest.skip('no reason')
2179 class Test(unittest.TestCase):
2180 def testFoo(self):
2181 pass
2182 self.assertOldResultWarning(Test('testFoo'), 0)
2183
Michael Foordd99ef9a2010-02-23 17:00:53 +00002184 def testOldResultWithRunner(self):
2185 class Test(unittest.TestCase):
2186 def testFoo(self):
2187 pass
2188 runner = unittest.TextTestRunner(resultclass=OldResult,
2189 stream=StringIO())
2190 # This will raise an exception if TextTestRunner can't handle old
2191 # test result objects
2192 runner.run(Test('testFoo'))
Michael Foorddb43b5a2010-02-10 14:25:12 +00002193
Georg Brandl15c5ce92007-03-07 09:09:40 +00002194### Support code for Test_TestCase
2195################################################################
2196
2197class Foo(unittest.TestCase):
2198 def runTest(self): pass
Michael Foorddb003cb2010-03-22 01:02:23 +00002199 def test1(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002200
Georg Brandl15c5ce92007-03-07 09:09:40 +00002201class Bar(Foo):
2202 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002203
Michael Foord1b9e9532010-03-22 01:01:34 +00002204def getLoggingTestCase():
2205 class LoggingTestCase(unittest.TestCase):
2206 """A test case which logs its calls."""
Michael Foord07ef4872009-05-02 22:43:34 +00002207
Michael Foord1b9e9532010-03-22 01:01:34 +00002208 def __init__(self, events):
2209 super(LoggingTestCase, self).__init__('test')
2210 self.events = events
Michael Foord07ef4872009-05-02 22:43:34 +00002211
Michael Foord1b9e9532010-03-22 01:01:34 +00002212 def setUp(self):
2213 self.events.append('setUp')
Michael Foord07ef4872009-05-02 22:43:34 +00002214
Michael Foord1b9e9532010-03-22 01:01:34 +00002215 def test(self):
2216 self.events.append('test')
Michael Foord07ef4872009-05-02 22:43:34 +00002217
Michael Foord1b9e9532010-03-22 01:01:34 +00002218 def tearDown(self):
2219 self.events.append('tearDown')
2220 return LoggingTestCase
Michael Foord07ef4872009-05-02 22:43:34 +00002221
2222class ResultWithNoStartTestRunStopTestRun(object):
2223 """An object honouring TestResult before startTestRun/stopTestRun."""
2224
2225 def __init__(self):
2226 self.failures = []
2227 self.errors = []
2228 self.testsRun = 0
2229 self.skipped = []
2230 self.expectedFailures = []
2231 self.unexpectedSuccesses = []
2232 self.shouldStop = False
2233
2234 def startTest(self, test):
2235 pass
2236
2237 def stopTest(self, test):
2238 pass
2239
2240 def addError(self, test):
2241 pass
2242
2243 def addFailure(self, test):
2244 pass
2245
2246 def addSuccess(self, test):
2247 pass
2248
2249 def wasSuccessful(self):
2250 return True
2251
2252
Georg Brandl15c5ce92007-03-07 09:09:40 +00002253################################################################
2254### /Support code for Test_TestCase
2255
2256class Test_TestCase(TestCase, TestEquality, TestHashing):
2257
2258 ### Set up attributes used by inherited tests
2259 ################################################################
2260
2261 # Used by TestHashing.test_hash and TestEquality.test_eq
2262 eq_pairs = [(Foo('test1'), Foo('test1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002263
Georg Brandl15c5ce92007-03-07 09:09:40 +00002264 # Used by TestEquality.test_ne
2265 ne_pairs = [(Foo('test1'), Foo('runTest'))
2266 ,(Foo('test1'), Bar('test1'))
2267 ,(Foo('test1'), Bar('test2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002268
Georg Brandl15c5ce92007-03-07 09:09:40 +00002269 ################################################################
2270 ### /Set up attributes used by inherited tests
Tim Petersea5962f2007-03-12 18:07:52 +00002271
Georg Brandl15c5ce92007-03-07 09:09:40 +00002272
2273 # "class TestCase([methodName])"
2274 # ...
2275 # "Each instance of TestCase will run a single test method: the
2276 # method named methodName."
2277 # ...
2278 # "methodName defaults to "runTest"."
2279 #
2280 # Make sure it really is optional, and that it defaults to the proper
2281 # thing.
2282 def test_init__no_test_name(self):
2283 class Test(unittest.TestCase):
2284 def runTest(self): raise MyException()
2285 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002286
Georg Brandl15c5ce92007-03-07 09:09:40 +00002287 self.assertEqual(Test().id()[-13:], '.Test.runTest')
Tim Petersea5962f2007-03-12 18:07:52 +00002288
Georg Brandl15c5ce92007-03-07 09:09:40 +00002289 # "class TestCase([methodName])"
2290 # ...
2291 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002292 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002293 def test_init__test_name__valid(self):
2294 class Test(unittest.TestCase):
2295 def runTest(self): raise MyException()
2296 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002297
Georg Brandl15c5ce92007-03-07 09:09:40 +00002298 self.assertEqual(Test('test').id()[-10:], '.Test.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002299
Georg Brandl15c5ce92007-03-07 09:09:40 +00002300 # "class TestCase([methodName])"
2301 # ...
2302 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002303 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002304 def test_init__test_name__invalid(self):
2305 class Test(unittest.TestCase):
2306 def runTest(self): raise MyException()
2307 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002308
Georg Brandl15c5ce92007-03-07 09:09:40 +00002309 try:
2310 Test('testfoo')
2311 except ValueError:
2312 pass
2313 else:
2314 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +00002315
Georg Brandl15c5ce92007-03-07 09:09:40 +00002316 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00002317 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00002318 def test_countTestCases(self):
2319 class Foo(unittest.TestCase):
2320 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002321
Georg Brandl15c5ce92007-03-07 09:09:40 +00002322 self.assertEqual(Foo('test').countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00002323
Georg Brandl15c5ce92007-03-07 09:09:40 +00002324 # "Return the default type of test result object to be used to run this
2325 # test. For TestCase instances, this will always be
2326 # unittest.TestResult; subclasses of TestCase should
2327 # override this as necessary."
2328 def test_defaultTestResult(self):
2329 class Foo(unittest.TestCase):
2330 def runTest(self):
2331 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002332
Georg Brandl15c5ce92007-03-07 09:09:40 +00002333 result = Foo().defaultTestResult()
2334 self.assertEqual(type(result), unittest.TestResult)
2335
2336 # "When a setUp() method is defined, the test runner will run that method
2337 # prior to each test. Likewise, if a tearDown() method is defined, the
2338 # test runner will invoke that method after each test. In the example,
2339 # setUp() was used to create a fresh sequence for each test."
2340 #
2341 # Make sure the proper call order is maintained, even if setUp() raises
2342 # an exception.
2343 def test_run_call_order__error_in_setUp(self):
2344 events = []
2345 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002346
Michael Foord1b9e9532010-03-22 01:01:34 +00002347 class Foo(getLoggingTestCase()):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002348 def setUp(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002349 super(Foo, self).setUp()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002350 raise RuntimeError('raised by Foo.setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002351
Michael Foord07ef4872009-05-02 22:43:34 +00002352 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002353 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2354 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002355
Michael Foord07ef4872009-05-02 22:43:34 +00002356 # "With a temporary result stopTestRun is called when setUp errors.
2357 def test_run_call_order__error_in_setUp_default_result(self):
2358 events = []
2359
Michael Foord1b9e9532010-03-22 01:01:34 +00002360 class Foo(getLoggingTestCase()):
Michael Foord07ef4872009-05-02 22:43:34 +00002361 def defaultTestResult(self):
2362 return LoggingResult(self.events)
2363
2364 def setUp(self):
2365 super(Foo, self).setUp()
2366 raise RuntimeError('raised by Foo.setUp')
2367
2368 Foo(events).run()
2369 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2370 'stopTest', 'stopTestRun']
2371 self.assertEqual(events, expected)
2372
Georg Brandl15c5ce92007-03-07 09:09:40 +00002373 # "When a setUp() method is defined, the test runner will run that method
2374 # prior to each test. Likewise, if a tearDown() method is defined, the
2375 # test runner will invoke that method after each test. In the example,
2376 # setUp() was used to create a fresh sequence for each test."
2377 #
2378 # Make sure the proper call order is maintained, even if the test raises
2379 # an error (as opposed to a failure).
2380 def test_run_call_order__error_in_test(self):
2381 events = []
2382 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002383
Michael Foord1b9e9532010-03-22 01:01:34 +00002384 class Foo(getLoggingTestCase()):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002385 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002386 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002387 raise RuntimeError('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002388
Georg Brandl15c5ce92007-03-07 09:09:40 +00002389 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2390 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002391 Foo(events).run(result)
2392 self.assertEqual(events, expected)
2393
2394 # "With a default result, an error in the test still results in stopTestRun
2395 # being called."
2396 def test_run_call_order__error_in_test_default_result(self):
2397 events = []
2398
Michael Foord1b9e9532010-03-22 01:01:34 +00002399 class Foo(getLoggingTestCase()):
Michael Foord07ef4872009-05-02 22:43:34 +00002400 def defaultTestResult(self):
2401 return LoggingResult(self.events)
2402
2403 def test(self):
2404 super(Foo, self).test()
2405 raise RuntimeError('raised by Foo.test')
2406
2407 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2408 'tearDown', 'stopTest', 'stopTestRun']
2409 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002410 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002411
Georg Brandl15c5ce92007-03-07 09:09:40 +00002412 # "When a setUp() method is defined, the test runner will run that method
2413 # prior to each test. Likewise, if a tearDown() method is defined, the
2414 # test runner will invoke that method after each test. In the example,
2415 # setUp() was used to create a fresh sequence for each test."
2416 #
2417 # Make sure the proper call order is maintained, even if the test signals
2418 # a failure (as opposed to an error).
2419 def test_run_call_order__failure_in_test(self):
2420 events = []
2421 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002422
Michael Foord1b9e9532010-03-22 01:01:34 +00002423 class Foo(getLoggingTestCase()):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002424 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002425 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002426 self.fail('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002427
Georg Brandl15c5ce92007-03-07 09:09:40 +00002428 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2429 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002430 Foo(events).run(result)
2431 self.assertEqual(events, expected)
2432
2433 # "When a test fails with a default result stopTestRun is still called."
2434 def test_run_call_order__failure_in_test_default_result(self):
2435
Michael Foord1b9e9532010-03-22 01:01:34 +00002436 class Foo(getLoggingTestCase()):
Michael Foord07ef4872009-05-02 22:43:34 +00002437 def defaultTestResult(self):
2438 return LoggingResult(self.events)
2439 def test(self):
2440 super(Foo, self).test()
2441 self.fail('raised by Foo.test')
2442
2443 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2444 'tearDown', 'stopTest', 'stopTestRun']
2445 events = []
2446 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002447 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002448
Georg Brandl15c5ce92007-03-07 09:09:40 +00002449 # "When a setUp() method is defined, the test runner will run that method
2450 # prior to each test. Likewise, if a tearDown() method is defined, the
2451 # test runner will invoke that method after each test. In the example,
2452 # setUp() was used to create a fresh sequence for each test."
2453 #
2454 # Make sure the proper call order is maintained, even if tearDown() raises
2455 # an exception.
2456 def test_run_call_order__error_in_tearDown(self):
2457 events = []
2458 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002459
Michael Foord1b9e9532010-03-22 01:01:34 +00002460 class Foo(getLoggingTestCase()):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002461 def tearDown(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002462 super(Foo, self).tearDown()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002463 raise RuntimeError('raised by Foo.tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002464
Michael Foord07ef4872009-05-02 22:43:34 +00002465 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002466 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2467 'stopTest']
2468 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002469
Michael Foord07ef4872009-05-02 22:43:34 +00002470 # "When tearDown errors with a default result stopTestRun is still called."
2471 def test_run_call_order__error_in_tearDown_default_result(self):
2472
Michael Foord1b9e9532010-03-22 01:01:34 +00002473 class Foo(getLoggingTestCase()):
Michael Foord07ef4872009-05-02 22:43:34 +00002474 def defaultTestResult(self):
2475 return LoggingResult(self.events)
2476 def tearDown(self):
2477 super(Foo, self).tearDown()
2478 raise RuntimeError('raised by Foo.tearDown')
2479
2480 events = []
2481 Foo(events).run()
2482 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2483 'addError', 'stopTest', 'stopTestRun']
2484 self.assertEqual(events, expected)
2485
2486 # "TestCase.run() still works when the defaultTestResult is a TestResult
2487 # that does not support startTestRun and stopTestRun.
2488 def test_run_call_order_default_result(self):
2489
2490 class Foo(unittest.TestCase):
2491 def defaultTestResult(self):
2492 return ResultWithNoStartTestRunStopTestRun()
2493 def test(self):
2494 pass
2495
2496 Foo('test').run()
2497
Georg Brandl15c5ce92007-03-07 09:09:40 +00002498 # "This class attribute gives the exception raised by the test() method.
2499 # If a test framework needs to use a specialized exception, possibly to
2500 # carry additional information, it must subclass this exception in
2501 # order to ``play fair'' with the framework. The initial value of this
2502 # attribute is AssertionError"
2503 def test_failureException__default(self):
2504 class Foo(unittest.TestCase):
2505 def test(self):
2506 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002507
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002508 self.assertTrue(Foo('test').failureException is AssertionError)
Tim Petersea5962f2007-03-12 18:07:52 +00002509
Georg Brandl15c5ce92007-03-07 09:09:40 +00002510 # "This class attribute gives the exception raised by the test() method.
2511 # If a test framework needs to use a specialized exception, possibly to
2512 # carry additional information, it must subclass this exception in
2513 # order to ``play fair'' with the framework."
2514 #
2515 # Make sure TestCase.run() respects the designated failureException
2516 def test_failureException__subclassing__explicit_raise(self):
2517 events = []
2518 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002519
Georg Brandl15c5ce92007-03-07 09:09:40 +00002520 class Foo(unittest.TestCase):
2521 def test(self):
2522 raise RuntimeError()
Tim Petersea5962f2007-03-12 18:07:52 +00002523
Georg Brandl15c5ce92007-03-07 09:09:40 +00002524 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002525
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002526 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002527
2528
Georg Brandl15c5ce92007-03-07 09:09:40 +00002529 Foo('test').run(result)
2530 expected = ['startTest', 'addFailure', 'stopTest']
2531 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002532
Georg Brandl15c5ce92007-03-07 09:09:40 +00002533 # "This class attribute gives the exception raised by the test() method.
2534 # If a test framework needs to use a specialized exception, possibly to
2535 # carry additional information, it must subclass this exception in
2536 # order to ``play fair'' with the framework."
2537 #
2538 # Make sure TestCase.run() respects the designated failureException
2539 def test_failureException__subclassing__implicit_raise(self):
2540 events = []
2541 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002542
Georg Brandl15c5ce92007-03-07 09:09:40 +00002543 class Foo(unittest.TestCase):
2544 def test(self):
2545 self.fail("foo")
Tim Petersea5962f2007-03-12 18:07:52 +00002546
Georg Brandl15c5ce92007-03-07 09:09:40 +00002547 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002548
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002549 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002550
2551
Georg Brandl15c5ce92007-03-07 09:09:40 +00002552 Foo('test').run(result)
2553 expected = ['startTest', 'addFailure', 'stopTest']
2554 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002555
2556 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002557 def test_setUp(self):
2558 class Foo(unittest.TestCase):
2559 def runTest(self):
2560 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002561
Georg Brandl15c5ce92007-03-07 09:09:40 +00002562 # ... and nothing should happen
2563 Foo().setUp()
Tim Petersea5962f2007-03-12 18:07:52 +00002564
2565 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002566 def test_tearDown(self):
2567 class Foo(unittest.TestCase):
2568 def runTest(self):
2569 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002570
Georg Brandl15c5ce92007-03-07 09:09:40 +00002571 # ... and nothing should happen
2572 Foo().tearDown()
Tim Petersea5962f2007-03-12 18:07:52 +00002573
Georg Brandl15c5ce92007-03-07 09:09:40 +00002574 # "Return a string identifying the specific test case."
2575 #
2576 # Because of the vague nature of the docs, I'm not going to lock this
2577 # test down too much. Really all that can be asserted is that the id()
2578 # will be a string (either 8-byte or unicode -- again, because the docs
2579 # just say "string")
2580 def test_id(self):
2581 class Foo(unittest.TestCase):
2582 def runTest(self):
2583 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002584
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002585 self.assertIsInstance(Foo().id(), basestring)
Tim Petersea5962f2007-03-12 18:07:52 +00002586
Georg Brandl15c5ce92007-03-07 09:09:40 +00002587 # "If result is omitted or None, a temporary result object is created
Michael Foord07ef4872009-05-02 22:43:34 +00002588 # and used, but is not made available to the caller. As TestCase owns the
2589 # temporary result startTestRun and stopTestRun are called.
2590
Georg Brandl15c5ce92007-03-07 09:09:40 +00002591 def test_run__uses_defaultTestResult(self):
2592 events = []
Tim Petersea5962f2007-03-12 18:07:52 +00002593
Georg Brandl15c5ce92007-03-07 09:09:40 +00002594 class Foo(unittest.TestCase):
2595 def test(self):
2596 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002597
Georg Brandl15c5ce92007-03-07 09:09:40 +00002598 def defaultTestResult(self):
2599 return LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002600
2601 # Make run() find a result object on its own
Georg Brandl15c5ce92007-03-07 09:09:40 +00002602 Foo('test').run()
Tim Petersea5962f2007-03-12 18:07:52 +00002603
Michael Foord07ef4872009-05-02 22:43:34 +00002604 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2605 'stopTest', 'stopTestRun']
Georg Brandl15c5ce92007-03-07 09:09:40 +00002606 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002607
Gregory P. Smith28399852009-03-31 16:54:10 +00002608 def testShortDescriptionWithoutDocstring(self):
Michael Foorddb43b5a2010-02-10 14:25:12 +00002609 self.assertIsNone(self.shortDescription())
Gregory P. Smith28399852009-03-31 16:54:10 +00002610
R. David Murrayf28fd242010-02-23 00:24:49 +00002611 @unittest.skipIf(sys.flags.optimize >= 2,
2612 "Docstrings are omitted with -O2 and above")
Gregory P. Smith28399852009-03-31 16:54:10 +00002613 def testShortDescriptionWithOneLineDocstring(self):
2614 """Tests shortDescription() for a method with a docstring."""
2615 self.assertEqual(
2616 self.shortDescription(),
Michael Foorddb43b5a2010-02-10 14:25:12 +00002617 'Tests shortDescription() for a method with a docstring.')
Gregory P. Smith28399852009-03-31 16:54:10 +00002618
R. David Murrayf28fd242010-02-23 00:24:49 +00002619 @unittest.skipIf(sys.flags.optimize >= 2,
2620 "Docstrings are omitted with -O2 and above")
Gregory P. Smith28399852009-03-31 16:54:10 +00002621 def testShortDescriptionWithMultiLineDocstring(self):
2622 """Tests shortDescription() for a method with a longer docstring.
2623
2624 This method ensures that only the first line of a docstring is
2625 returned used in the short description, no matter how long the
2626 whole thing is.
2627 """
2628 self.assertEqual(
2629 self.shortDescription(),
Gregory P. Smith28399852009-03-31 16:54:10 +00002630 'Tests shortDescription() for a method with a longer '
Michael Foorddb43b5a2010-02-10 14:25:12 +00002631 'docstring.')
Gregory P. Smith28399852009-03-31 16:54:10 +00002632
Gregory P. Smith28399852009-03-31 16:54:10 +00002633 def testAddTypeEqualityFunc(self):
2634 class SadSnake(object):
2635 """Dummy class for test_addTypeEqualityFunc."""
2636 s1, s2 = SadSnake(), SadSnake()
Michael Foord98e7b762010-03-20 03:00:34 +00002637 self.assertNotEqual(s1, s2)
Gregory P. Smith28399852009-03-31 16:54:10 +00002638 def AllSnakesCreatedEqual(a, b, msg=None):
Michael Foord98e7b762010-03-20 03:00:34 +00002639 return type(a) is type(b) is SadSnake
Gregory P. Smith28399852009-03-31 16:54:10 +00002640 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2641 self.assertEqual(s1, s2)
2642 # No this doesn't clean up and remove the SadSnake equality func
2643 # from this TestCase instance but since its a local nothing else
2644 # will ever notice that.
2645
Michael Foordf2dfef12009-04-05 19:19:28 +00002646 def testAssertIs(self):
2647 thing = object()
2648 self.assertIs(thing, thing)
2649 self.assertRaises(self.failureException, self.assertIs, thing, object())
2650
2651 def testAssertIsNot(self):
2652 thing = object()
2653 self.assertIsNot(thing, object())
2654 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2655
Georg Brandlf895cf52009-10-01 20:59:31 +00002656 def testAssertIsInstance(self):
2657 thing = []
2658 self.assertIsInstance(thing, list)
2659 self.assertRaises(self.failureException, self.assertIsInstance,
2660 thing, dict)
2661
2662 def testAssertNotIsInstance(self):
2663 thing = []
2664 self.assertNotIsInstance(thing, dict)
2665 self.assertRaises(self.failureException, self.assertNotIsInstance,
2666 thing, list)
2667
Gregory P. Smith28399852009-03-31 16:54:10 +00002668 def testAssertIn(self):
2669 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2670
2671 self.assertIn('a', 'abc')
2672 self.assertIn(2, [1, 2, 3])
2673 self.assertIn('monkey', animals)
2674
2675 self.assertNotIn('d', 'abc')
2676 self.assertNotIn(0, [1, 2, 3])
2677 self.assertNotIn('otter', animals)
2678
2679 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2680 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2681 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2682 animals)
2683
2684 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2685 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2686 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2687 animals)
2688
2689 def testAssertDictContainsSubset(self):
2690 self.assertDictContainsSubset({}, {})
2691 self.assertDictContainsSubset({}, {'a': 1})
2692 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2693 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2694 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2695
Michael Foord225a0992010-02-18 20:30:09 +00002696 with self.assertRaises(self.failureException):
2697 self.assertDictContainsSubset({1: "one"}, {})
Gregory P. Smith28399852009-03-31 16:54:10 +00002698
Michael Foord225a0992010-02-18 20:30:09 +00002699 with self.assertRaises(self.failureException):
2700 self.assertDictContainsSubset({'a': 2}, {'a': 1})
Gregory P. Smith28399852009-03-31 16:54:10 +00002701
Michael Foord225a0992010-02-18 20:30:09 +00002702 with self.assertRaises(self.failureException):
2703 self.assertDictContainsSubset({'c': 1}, {'a': 1})
Gregory P. Smith28399852009-03-31 16:54:10 +00002704
Michael Foord225a0992010-02-18 20:30:09 +00002705 with self.assertRaises(self.failureException):
2706 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2707
2708 with self.assertRaises(self.failureException):
2709 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2710
Michael Foord2f677562010-02-21 14:48:59 +00002711 with warnings.catch_warnings(record=True):
2712 # silence the UnicodeWarning
2713 one = ''.join(chr(i) for i in range(255))
2714 # this used to cause a UnicodeDecodeError constructing the failure msg
2715 with self.assertRaises(self.failureException):
2716 self.assertDictContainsSubset({'foo': one}, {'foo': u'\uFFFD'})
Gregory P. Smith28399852009-03-31 16:54:10 +00002717
2718 def testAssertEqual(self):
2719 equal_pairs = [
2720 ((), ()),
2721 ({}, {}),
2722 ([], []),
2723 (set(), set()),
2724 (frozenset(), frozenset())]
2725 for a, b in equal_pairs:
2726 # This mess of try excepts is to test the assertEqual behavior
2727 # itself.
2728 try:
2729 self.assertEqual(a, b)
2730 except self.failureException:
2731 self.fail('assertEqual(%r, %r) failed' % (a, b))
2732 try:
2733 self.assertEqual(a, b, msg='foo')
2734 except self.failureException:
2735 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2736 try:
2737 self.assertEqual(a, b, 'foo')
2738 except self.failureException:
2739 self.fail('assertEqual(%r, %r) with third parameter failed' %
2740 (a, b))
2741
2742 unequal_pairs = [
2743 ((), []),
2744 ({}, set()),
2745 (set([4,1]), frozenset([4,2])),
2746 (frozenset([4,5]), set([2,3])),
2747 (set([3,4]), set([5,4]))]
2748 for a, b in unequal_pairs:
2749 self.assertRaises(self.failureException, self.assertEqual, a, b)
2750 self.assertRaises(self.failureException, self.assertEqual, a, b,
2751 'foo')
2752 self.assertRaises(self.failureException, self.assertEqual, a, b,
2753 msg='foo')
2754
2755 def testEquality(self):
2756 self.assertListEqual([], [])
2757 self.assertTupleEqual((), ())
2758 self.assertSequenceEqual([], ())
2759
2760 a = [0, 'a', []]
2761 b = []
2762 self.assertRaises(unittest.TestCase.failureException,
2763 self.assertListEqual, a, b)
2764 self.assertRaises(unittest.TestCase.failureException,
2765 self.assertListEqual, tuple(a), tuple(b))
2766 self.assertRaises(unittest.TestCase.failureException,
2767 self.assertSequenceEqual, a, tuple(b))
2768
2769 b.extend(a)
2770 self.assertListEqual(a, b)
2771 self.assertTupleEqual(tuple(a), tuple(b))
2772 self.assertSequenceEqual(a, tuple(b))
2773 self.assertSequenceEqual(tuple(a), b)
2774
2775 self.assertRaises(self.failureException, self.assertListEqual,
2776 a, tuple(b))
2777 self.assertRaises(self.failureException, self.assertTupleEqual,
2778 tuple(a), b)
2779 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2780 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2781 tuple(b))
2782 self.assertRaises(self.failureException, self.assertSequenceEqual,
2783 None, tuple(b))
2784 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2785 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2786 self.assertRaises(self.failureException, self.assertSequenceEqual,
2787 1, 1)
2788
2789 self.assertDictEqual({}, {})
2790
2791 c = { 'x': 1 }
2792 d = {}
2793 self.assertRaises(unittest.TestCase.failureException,
2794 self.assertDictEqual, c, d)
2795
2796 d.update(c)
2797 self.assertDictEqual(c, d)
2798
2799 d['x'] = 0
2800 self.assertRaises(unittest.TestCase.failureException,
2801 self.assertDictEqual, c, d, 'These are unequal')
2802
2803 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2804 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2805 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2806
Michael Foord98e7b762010-03-20 03:00:34 +00002807 def testAssertItemsEqual(self):
2808 a = object()
2809 self.assertItemsEqual([1, 2, 3], [3, 2, 1])
2810 self.assertItemsEqual(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2811 self.assertItemsEqual([a, a, 2, 2, 3], (a, 2, 3, a, 2))
2812 self.assertItemsEqual([1, "2", "a", "a"], ["a", "2", True, "a"])
2813 self.assertRaises(self.failureException, self.assertItemsEqual,
2814 [1, 2] + [3] * 100, [1] * 100 + [2, 3])
2815 self.assertRaises(self.failureException, self.assertItemsEqual,
2816 [1, "2", "a", "a"], ["a", "2", True, 1])
2817 self.assertRaises(self.failureException, self.assertItemsEqual,
Gregory P. Smith28399852009-03-31 16:54:10 +00002818 [10], [10, 11])
Michael Foord98e7b762010-03-20 03:00:34 +00002819 self.assertRaises(self.failureException, self.assertItemsEqual,
Gregory P. Smith28399852009-03-31 16:54:10 +00002820 [10, 11], [10])
Michael Foord98e7b762010-03-20 03:00:34 +00002821 self.assertRaises(self.failureException, self.assertItemsEqual,
2822 [10, 11, 10], [10, 11])
Gregory P. Smith28399852009-03-31 16:54:10 +00002823
2824 # Test that sequences of unhashable objects can be tested for sameness:
Michael Foord98e7b762010-03-20 03:00:34 +00002825 self.assertItemsEqual([[1, 2], [3, 4], 0], [False, [3, 4], [1, 2]])
2826 with test_support.check_warnings(quiet=True) as w:
2827 # hashable types, but not orderable
2828 self.assertRaises(self.failureException, self.assertItemsEqual,
2829 [], [divmod, 'x', 1, 5j, 2j, frozenset()])
2830 # comparing dicts raises a py3k warning
2831 self.assertItemsEqual([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2832 # comparing heterogenous non-hashable sequences raises a py3k warning
2833 self.assertItemsEqual([1, 'x', divmod, []], [divmod, [], 'x', 1])
2834 self.assertRaises(self.failureException, self.assertItemsEqual,
2835 [], [divmod, [], 'x', 1, 5j, 2j, set()])
2836 # fail the test if warnings are not silenced
2837 if w.warnings:
2838 self.fail('assertItemsEqual raised a warning: ' +
2839 str(w.warnings[0]))
2840 self.assertRaises(self.failureException, self.assertItemsEqual,
Gregory P. Smith28399852009-03-31 16:54:10 +00002841 [[1]], [[2]])
2842
Michael Foord98e7b762010-03-20 03:00:34 +00002843 # Same elements, but not same sequence length
2844 self.assertRaises(self.failureException, self.assertItemsEqual,
2845 [1, 1, 2], [2, 1])
2846 self.assertRaises(self.failureException, self.assertItemsEqual,
2847 [1, 1, "2", "a", "a"], ["2", "2", True, "a"])
2848 self.assertRaises(self.failureException, self.assertItemsEqual,
2849 [1, {'b': 2}, None, True], [{'b': 2}, True, None])
2850
2851
Gregory P. Smith28399852009-03-31 16:54:10 +00002852 def testAssertSetEqual(self):
2853 set1 = set()
2854 set2 = set()
2855 self.assertSetEqual(set1, set2)
2856
2857 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2858 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2859 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2860 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2861
2862 set1 = set(['a'])
2863 set2 = set()
2864 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2865
2866 set1 = set(['a'])
2867 set2 = set(['a'])
2868 self.assertSetEqual(set1, set2)
2869
2870 set1 = set(['a'])
2871 set2 = set(['a', 'b'])
2872 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2873
2874 set1 = set(['a'])
2875 set2 = frozenset(['a', 'b'])
2876 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2877
2878 set1 = set(['a', 'b'])
2879 set2 = frozenset(['a', 'b'])
2880 self.assertSetEqual(set1, set2)
2881
2882 set1 = set()
2883 set2 = "foo"
2884 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2885 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2886
2887 # make sure any string formatting is tuple-safe
2888 set1 = set([(0, 1), (2, 3)])
2889 set2 = set([(4, 5)])
2890 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2891
2892 def testInequality(self):
2893 # Try ints
2894 self.assertGreater(2, 1)
2895 self.assertGreaterEqual(2, 1)
2896 self.assertGreaterEqual(1, 1)
2897 self.assertLess(1, 2)
2898 self.assertLessEqual(1, 2)
2899 self.assertLessEqual(1, 1)
2900 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2901 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2902 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2903 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2904 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2905 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2906
2907 # Try Floats
2908 self.assertGreater(1.1, 1.0)
2909 self.assertGreaterEqual(1.1, 1.0)
2910 self.assertGreaterEqual(1.0, 1.0)
2911 self.assertLess(1.0, 1.1)
2912 self.assertLessEqual(1.0, 1.1)
2913 self.assertLessEqual(1.0, 1.0)
2914 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2915 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2916 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2917 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2918 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2919 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2920
2921 # Try Strings
2922 self.assertGreater('bug', 'ant')
2923 self.assertGreaterEqual('bug', 'ant')
2924 self.assertGreaterEqual('ant', 'ant')
2925 self.assertLess('ant', 'bug')
2926 self.assertLessEqual('ant', 'bug')
2927 self.assertLessEqual('ant', 'ant')
2928 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2929 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2930 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2931 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2932 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2933 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2934
2935 # Try Unicode
2936 self.assertGreater(u'bug', u'ant')
2937 self.assertGreaterEqual(u'bug', u'ant')
2938 self.assertGreaterEqual(u'ant', u'ant')
2939 self.assertLess(u'ant', u'bug')
2940 self.assertLessEqual(u'ant', u'bug')
2941 self.assertLessEqual(u'ant', u'ant')
2942 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug')
2943 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant')
2944 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2945 u'bug')
2946 self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant')
2947 self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant')
2948 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant')
2949
2950 # Try Mixed String/Unicode
2951 self.assertGreater('bug', u'ant')
2952 self.assertGreater(u'bug', 'ant')
2953 self.assertGreaterEqual('bug', u'ant')
2954 self.assertGreaterEqual(u'bug', 'ant')
2955 self.assertGreaterEqual('ant', u'ant')
2956 self.assertGreaterEqual(u'ant', 'ant')
2957 self.assertLess('ant', u'bug')
2958 self.assertLess(u'ant', 'bug')
2959 self.assertLessEqual('ant', u'bug')
2960 self.assertLessEqual(u'ant', 'bug')
2961 self.assertLessEqual('ant', u'ant')
2962 self.assertLessEqual(u'ant', 'ant')
2963 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug')
2964 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug')
2965 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant')
2966 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant')
2967 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant',
2968 u'bug')
2969 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2970 'bug')
2971 self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant')
2972 self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant')
2973 self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant')
2974 self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant')
2975 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant')
2976 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant')
2977
2978 def testAssertMultiLineEqual(self):
2979 sample_text = b"""\
2980http://www.python.org/doc/2.3/lib/module-unittest.html
2981test case
2982 A test case is the smallest unit of testing. [...]
2983"""
2984 revised_sample_text = b"""\
2985http://www.python.org/doc/2.4.1/lib/module-unittest.html
2986test case
2987 A test case is the smallest unit of testing. [...] You may provide your
2988 own implementation that does not subclass from TestCase, of course.
2989"""
2990 sample_text_error = b"""
2991- http://www.python.org/doc/2.3/lib/module-unittest.html
2992? ^
2993+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2994? ^^^
2995 test case
2996- A test case is the smallest unit of testing. [...]
2997+ A test case is the smallest unit of testing. [...] You may provide your
2998? +++++++++++++++++++++
2999+ own implementation that does not subclass from TestCase, of course.
3000"""
3001
3002 for type_changer in (lambda x: x, lambda x: x.decode('utf8')):
3003 try:
3004 self.assertMultiLineEqual(type_changer(sample_text),
3005 type_changer(revised_sample_text))
3006 except self.failureException, e:
Michael Foordfe6349c2010-02-08 22:41:16 +00003007 # assertMultiLineEqual is hooked up as the default for
3008 # unicode strings - so we can't use it for this check
3009 self.assertTrue(sample_text_error == str(e).encode('utf8'))
Gregory P. Smith28399852009-03-31 16:54:10 +00003010
3011 def testAssertIsNone(self):
3012 self.assertIsNone(None)
3013 self.assertRaises(self.failureException, self.assertIsNone, False)
3014 self.assertIsNotNone('DjZoPloGears on Rails')
3015 self.assertRaises(self.failureException, self.assertIsNotNone, None)
3016
3017 def testAssertRegexpMatches(self):
3018 self.assertRegexpMatches('asdfabasdf', r'ab+')
3019 self.assertRaises(self.failureException, self.assertRegexpMatches,
3020 'saaas', r'aaaa')
3021
3022 def testAssertRaisesRegexp(self):
3023 class ExceptionMock(Exception):
3024 pass
3025
3026 def Stub():
3027 raise ExceptionMock('We expect')
3028
3029 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
3030 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
3031 self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
3032
3033 def testAssertNotRaisesRegexp(self):
3034 self.assertRaisesRegexp(
3035 self.failureException, '^Exception not raised$',
3036 self.assertRaisesRegexp, Exception, re.compile('x'),
3037 lambda: None)
3038 self.assertRaisesRegexp(
3039 self.failureException, '^Exception not raised$',
3040 self.assertRaisesRegexp, Exception, 'x',
3041 lambda: None)
3042 self.assertRaisesRegexp(
3043 self.failureException, '^Exception not raised$',
3044 self.assertRaisesRegexp, Exception, u'x',
3045 lambda: None)
3046
3047 def testAssertRaisesRegexpMismatch(self):
3048 def Stub():
3049 raise Exception('Unexpected')
3050
3051 self.assertRaisesRegexp(
3052 self.failureException,
3053 r'"\^Expected\$" does not match "Unexpected"',
3054 self.assertRaisesRegexp, Exception, '^Expected$',
3055 Stub)
3056 self.assertRaisesRegexp(
3057 self.failureException,
3058 r'"\^Expected\$" does not match "Unexpected"',
3059 self.assertRaisesRegexp, Exception, u'^Expected$',
3060 Stub)
3061 self.assertRaisesRegexp(
3062 self.failureException,
3063 r'"\^Expected\$" does not match "Unexpected"',
3064 self.assertRaisesRegexp, Exception,
3065 re.compile('^Expected$'), Stub)
3066
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00003067 def testAssertRaisesExcValue(self):
3068 class ExceptionMock(Exception):
3069 pass
3070
3071 def Stub(foo):
3072 raise ExceptionMock(foo)
3073 v = "particular value"
3074
3075 ctx = self.assertRaises(ExceptionMock)
3076 with ctx:
3077 Stub(v)
Georg Brandldc3694b2010-02-07 17:02:22 +00003078 e = ctx.exception
Ezio Melottib0f5adc2010-01-24 16:58:36 +00003079 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00003080 self.assertEqual(e.args[0], v)
3081
Gregory P. Smith7558d572009-03-31 19:03:28 +00003082 def testSynonymAssertMethodNames(self):
3083 """Test undocumented method name synonyms.
3084
3085 Please do not use these methods names in your own code.
3086
3087 This test confirms their continued existence and functionality
3088 in order to avoid breaking existing code.
3089 """
3090 self.assertNotEquals(3, 5)
3091 self.assertEquals(3, 3)
3092 self.assertAlmostEquals(2.0, 2.0)
3093 self.assertNotAlmostEquals(3.0, 5.0)
3094 self.assert_(True)
3095
3096 def testPendingDeprecationMethodNames(self):
3097 """Test fail* methods pending deprecation, they will warn in 3.2.
3098
3099 Do not use these methods. They will go away in 3.3.
3100 """
Michael Foord98e7b762010-03-20 03:00:34 +00003101 with test_support.check_warnings():
3102 self.failIfEqual(3, 5)
3103 self.failUnlessEqual(3, 3)
3104 self.failUnlessAlmostEqual(2.0, 2.0)
3105 self.failIfAlmostEqual(3.0, 5.0)
3106 self.failUnless(True)
3107 self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam')
3108 self.failIf(False)
Gregory P. Smith7558d572009-03-31 19:03:28 +00003109
Michael Foorde2942d02009-04-02 05:51:54 +00003110 def testDeepcopy(self):
3111 # Issue: 5660
3112 class TestableTest(TestCase):
3113 def testNothing(self):
3114 pass
3115
3116 test = TestableTest('testNothing')
3117
3118 # This shouldn't blow up
3119 deepcopy(test)
3120
Benjamin Peterson692428e2009-03-23 21:50:21 +00003121
3122class Test_TestSkipping(TestCase):
3123
3124 def test_skipping(self):
3125 class Foo(unittest.TestCase):
3126 def test_skip_me(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00003127 self.skipTest("skip")
Benjamin Peterson692428e2009-03-23 21:50:21 +00003128 events = []
3129 result = LoggingResult(events)
3130 test = Foo("test_skip_me")
3131 test.run(result)
3132 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3133 self.assertEqual(result.skipped, [(test, "skip")])
3134
3135 # Try letting setUp skip the test now.
3136 class Foo(unittest.TestCase):
3137 def setUp(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00003138 self.skipTest("testing")
Benjamin Peterson692428e2009-03-23 21:50:21 +00003139 def test_nothing(self): pass
3140 events = []
3141 result = LoggingResult(events)
3142 test = Foo("test_nothing")
3143 test.run(result)
3144 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3145 self.assertEqual(result.skipped, [(test, "testing")])
3146 self.assertEqual(result.testsRun, 1)
3147
3148 def test_skipping_decorators(self):
3149 op_table = ((unittest.skipUnless, False, True),
3150 (unittest.skipIf, True, False))
3151 for deco, do_skip, dont_skip in op_table:
3152 class Foo(unittest.TestCase):
3153 @deco(do_skip, "testing")
3154 def test_skip(self): pass
3155
3156 @deco(dont_skip, "testing")
3157 def test_dont_skip(self): pass
3158 test_do_skip = Foo("test_skip")
3159 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003160 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003161 events = []
3162 result = LoggingResult(events)
3163 suite.run(result)
3164 self.assertEqual(len(result.skipped), 1)
3165 expected = ['startTest', 'addSkip', 'stopTest',
3166 'startTest', 'addSuccess', 'stopTest']
3167 self.assertEqual(events, expected)
3168 self.assertEqual(result.testsRun, 2)
3169 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
3170 self.assertTrue(result.wasSuccessful())
3171
3172 def test_skip_class(self):
3173 @unittest.skip("testing")
3174 class Foo(unittest.TestCase):
3175 def test_1(self):
3176 record.append(1)
3177 record = []
3178 result = unittest.TestResult()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003179 test = Foo("test_1")
3180 suite = unittest.TestSuite([test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003181 suite.run(result)
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003182 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003183 self.assertEqual(record, [])
3184
3185 def test_expected_failure(self):
3186 class Foo(unittest.TestCase):
3187 @unittest.expectedFailure
3188 def test_die(self):
3189 self.fail("help me!")
3190 events = []
3191 result = LoggingResult(events)
3192 test = Foo("test_die")
3193 test.run(result)
3194 self.assertEqual(events,
3195 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003196 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00003197 self.assertTrue(result.wasSuccessful())
3198
3199 def test_unexpected_success(self):
3200 class Foo(unittest.TestCase):
3201 @unittest.expectedFailure
3202 def test_die(self):
3203 pass
3204 events = []
3205 result = LoggingResult(events)
3206 test = Foo("test_die")
3207 test.run(result)
3208 self.assertEqual(events,
3209 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3210 self.assertFalse(result.failures)
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003211 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003212 self.assertTrue(result.wasSuccessful())
3213
Michael Foord53e8eea2010-03-07 20:22:12 +00003214 def test_skip_doesnt_run_setup(self):
3215 class Foo(unittest.TestCase):
3216 wasSetUp = False
3217 wasTornDown = False
3218 def setUp(self):
3219 Foo.wasSetUp = True
3220 def tornDown(self):
3221 Foo.wasTornDown = True
3222 @unittest.skip('testing')
3223 def test_1(self):
3224 pass
3225
3226 result = unittest.TestResult()
3227 test = Foo("test_1")
3228 suite = unittest.TestSuite([test])
3229 suite.run(result)
3230 self.assertEqual(result.skipped, [(test, "testing")])
3231 self.assertFalse(Foo.wasSetUp)
3232 self.assertFalse(Foo.wasTornDown)
3233
3234 def test_decorated_skip(self):
3235 def decorator(func):
3236 def inner(*a):
3237 return func(*a)
3238 return inner
3239
3240 class Foo(unittest.TestCase):
3241 @decorator
3242 @unittest.skip('testing')
3243 def test_1(self):
3244 pass
3245
3246 result = unittest.TestResult()
3247 test = Foo("test_1")
3248 suite = unittest.TestSuite([test])
3249 suite.run(result)
3250 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003251
3252
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003253class Test_Assertions(TestCase):
3254 def test_AlmostEqual(self):
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003255 self.assertAlmostEqual(1.00000001, 1.0)
3256 self.assertNotAlmostEqual(1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003257 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003258 self.assertAlmostEqual, 1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003259 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003260 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003261
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003262 self.assertAlmostEqual(1.1, 1.0, places=0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003263 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003264 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003265
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003266 self.assertAlmostEqual(0, .1+.1j, places=0)
3267 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003268 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003269 self.assertAlmostEqual, 0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003270 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003271 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003272
Michael Foordc3f79372009-09-13 16:40:02 +00003273 self.assertAlmostEqual(float('inf'), float('inf'))
3274 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3275 float('inf'), float('inf'))
3276
3277
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003278 def test_assertRaises(self):
3279 def _raise(e):
3280 raise e
3281 self.assertRaises(KeyError, _raise, KeyError)
3282 self.assertRaises(KeyError, _raise, KeyError("key"))
3283 try:
3284 self.assertRaises(KeyError, lambda: None)
Gregory P. Smith28399852009-03-31 16:54:10 +00003285 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003286 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003287 else:
3288 self.fail("assertRaises() didn't fail")
3289 try:
3290 self.assertRaises(KeyError, _raise, ValueError)
3291 except ValueError:
3292 pass
3293 else:
3294 self.fail("assertRaises() didn't let exception pass through")
Michael Foord2bd52dc2010-02-07 18:44:12 +00003295 with self.assertRaises(KeyError) as cm:
3296 try:
3297 raise KeyError
3298 except Exception, e:
3299 raise
3300 self.assertIs(cm.exception, e)
3301
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003302 with self.assertRaises(KeyError):
3303 raise KeyError("key")
3304 try:
3305 with self.assertRaises(KeyError):
3306 pass
Gregory P. Smith28399852009-03-31 16:54:10 +00003307 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003308 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003309 else:
3310 self.fail("assertRaises() didn't fail")
3311 try:
3312 with self.assertRaises(KeyError):
3313 raise ValueError
3314 except ValueError:
3315 pass
3316 else:
3317 self.fail("assertRaises() didn't let exception pass through")
3318
3319
Michael Foord345b2fe2009-04-02 03:20:38 +00003320class TestLongMessage(TestCase):
3321 """Test that the individual asserts honour longMessage.
3322 This actually tests all the message behaviour for
3323 asserts that use longMessage."""
3324
3325 def setUp(self):
3326 class TestableTestFalse(TestCase):
3327 longMessage = False
3328 failureException = self.failureException
3329
3330 def testTest(self):
3331 pass
3332
3333 class TestableTestTrue(TestCase):
3334 longMessage = True
3335 failureException = self.failureException
3336
3337 def testTest(self):
3338 pass
3339
3340 self.testableTrue = TestableTestTrue('testTest')
3341 self.testableFalse = TestableTestFalse('testTest')
3342
3343 def testDefault(self):
3344 self.assertFalse(TestCase.longMessage)
3345
3346 def test_formatMsg(self):
3347 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3348 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3349
3350 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3351 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3352
Michael Foord53e8eea2010-03-07 20:22:12 +00003353 # This blows up if _formatMessage uses string concatenation
3354 self.testableTrue._formatMessage(object(), 'foo')
3355
3356 def test_formatMessage_unicode_error(self):
3357 with warnings.catch_warnings(record=True):
3358 # This causes a UnicodeWarning due to its craziness
3359 one = ''.join(chr(i) for i in range(255))
3360 # this used to cause a UnicodeDecodeError constructing msg
3361 self.testableTrue._formatMessage(one, u'\uFFFD')
3362
Michael Foord345b2fe2009-04-02 03:20:38 +00003363 def assertMessages(self, methodName, args, errors):
3364 def getMethod(i):
3365 useTestableFalse = i < 2
3366 if useTestableFalse:
3367 test = self.testableFalse
3368 else:
3369 test = self.testableTrue
3370 return getattr(test, methodName)
3371
3372 for i, expected_regexp in enumerate(errors):
3373 testMethod = getMethod(i)
3374 kwargs = {}
3375 withMsg = i % 2
3376 if withMsg:
3377 kwargs = {"msg": "oops"}
3378
3379 with self.assertRaisesRegexp(self.failureException,
3380 expected_regexp=expected_regexp):
3381 testMethod(*args, **kwargs)
3382
3383 def testAssertTrue(self):
3384 self.assertMessages('assertTrue', (False,),
3385 ["^False is not True$", "^oops$", "^False is not True$",
3386 "^False is not True : oops$"])
3387
3388 def testAssertFalse(self):
3389 self.assertMessages('assertFalse', (True,),
3390 ["^True is not False$", "^oops$", "^True is not False$",
3391 "^True is not False : oops$"])
3392
3393 def testNotEqual(self):
3394 self.assertMessages('assertNotEqual', (1, 1),
3395 ["^1 == 1$", "^oops$", "^1 == 1$",
3396 "^1 == 1 : oops$"])
3397
3398 def testAlmostEqual(self):
3399 self.assertMessages('assertAlmostEqual', (1, 2),
3400 ["^1 != 2 within 7 places$", "^oops$",
3401 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3402
3403 def testNotAlmostEqual(self):
3404 self.assertMessages('assertNotAlmostEqual', (1, 1),
3405 ["^1 == 1 within 7 places$", "^oops$",
3406 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3407
3408 def test_baseAssertEqual(self):
3409 self.assertMessages('_baseAssertEqual', (1, 2),
3410 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3411
3412 def testAssertSequenceEqual(self):
3413 # Error messages are multiline so not testing on full message
3414 # assertTupleEqual and assertListEqual delegate to this method
3415 self.assertMessages('assertSequenceEqual', ([], [None]),
3416 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3417 r"\+ \[None\] : oops$"])
3418
3419 def testAssertSetEqual(self):
3420 self.assertMessages('assertSetEqual', (set(), set([None])),
3421 ["None$", "^oops$", "None$",
3422 "None : oops$"])
3423
3424 def testAssertIn(self):
3425 self.assertMessages('assertIn', (None, []),
3426 ['^None not found in \[\]$', "^oops$",
3427 '^None not found in \[\]$',
3428 '^None not found in \[\] : oops$'])
3429
3430 def testAssertNotIn(self):
3431 self.assertMessages('assertNotIn', (None, [None]),
3432 ['^None unexpectedly found in \[None\]$', "^oops$",
3433 '^None unexpectedly found in \[None\]$',
3434 '^None unexpectedly found in \[None\] : oops$'])
3435
3436 def testAssertDictEqual(self):
3437 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3438 [r"\+ \{'key': 'value'\}$", "^oops$",
3439 "\+ \{'key': 'value'\}$",
3440 "\+ \{'key': 'value'\} : oops$"])
3441
3442 def testAssertDictContainsSubset(self):
3443 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3444 ["^Missing: 'key'$", "^oops$",
3445 "^Missing: 'key'$",
3446 "^Missing: 'key' : oops$"])
3447
Michael Foord98e7b762010-03-20 03:00:34 +00003448 def testAssertItemsEqual(self):
3449 self.assertMessages('assertItemsEqual', ([], [None]),
Michael Foord345b2fe2009-04-02 03:20:38 +00003450 [r"\[None\]$", "^oops$",
3451 r"\[None\]$",
3452 r"\[None\] : oops$"])
3453
3454 def testAssertMultiLineEqual(self):
3455 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3456 [r"\+ foo$", "^oops$",
3457 r"\+ foo$",
3458 r"\+ foo : oops$"])
3459
3460 def testAssertLess(self):
3461 self.assertMessages('assertLess', (2, 1),
3462 ["^2 not less than 1$", "^oops$",
3463 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3464
3465 def testAssertLessEqual(self):
3466 self.assertMessages('assertLessEqual', (2, 1),
3467 ["^2 not less than or equal to 1$", "^oops$",
3468 "^2 not less than or equal to 1$",
3469 "^2 not less than or equal to 1 : oops$"])
3470
3471 def testAssertGreater(self):
3472 self.assertMessages('assertGreater', (1, 2),
3473 ["^1 not greater than 2$", "^oops$",
3474 "^1 not greater than 2$",
3475 "^1 not greater than 2 : oops$"])
3476
3477 def testAssertGreaterEqual(self):
3478 self.assertMessages('assertGreaterEqual', (1, 2),
3479 ["^1 not greater than or equal to 2$", "^oops$",
3480 "^1 not greater than or equal to 2$",
3481 "^1 not greater than or equal to 2 : oops$"])
3482
3483 def testAssertIsNone(self):
3484 self.assertMessages('assertIsNone', ('not None',),
3485 ["^'not None' is not None$", "^oops$",
3486 "^'not None' is not None$",
3487 "^'not None' is not None : oops$"])
3488
3489 def testAssertIsNotNone(self):
3490 self.assertMessages('assertIsNotNone', (None,),
3491 ["^unexpectedly None$", "^oops$",
3492 "^unexpectedly None$",
3493 "^unexpectedly None : oops$"])
3494
Michael Foordf2dfef12009-04-05 19:19:28 +00003495 def testAssertIs(self):
3496 self.assertMessages('assertIs', (None, 'foo'),
3497 ["^None is not 'foo'$", "^oops$",
3498 "^None is not 'foo'$",
3499 "^None is not 'foo' : oops$"])
3500
3501 def testAssertIsNot(self):
3502 self.assertMessages('assertIsNot', (None, None),
3503 ["^unexpectedly identical: None$", "^oops$",
3504 "^unexpectedly identical: None$",
3505 "^unexpectedly identical: None : oops$"])
3506
Michael Foord345b2fe2009-04-02 03:20:38 +00003507
Michael Foorde2fb98f2009-05-02 20:15:05 +00003508class TestCleanUp(TestCase):
3509
3510 def testCleanUp(self):
3511 class TestableTest(TestCase):
3512 def testNothing(self):
3513 pass
3514
3515 test = TestableTest('testNothing')
3516 self.assertEqual(test._cleanups, [])
3517
3518 cleanups = []
3519
3520 def cleanup1(*args, **kwargs):
3521 cleanups.append((1, args, kwargs))
3522
3523 def cleanup2(*args, **kwargs):
3524 cleanups.append((2, args, kwargs))
3525
3526 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3527 test.addCleanup(cleanup2)
3528
3529 self.assertEqual(test._cleanups,
3530 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3531 (cleanup2, (), {})])
3532
3533 result = test.doCleanups()
3534 self.assertTrue(result)
3535
3536 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3537
3538 def testCleanUpWithErrors(self):
3539 class TestableTest(TestCase):
3540 def testNothing(self):
3541 pass
3542
3543 class MockResult(object):
3544 errors = []
3545 def addError(self, test, exc_info):
3546 self.errors.append((test, exc_info))
3547
3548 result = MockResult()
3549 test = TestableTest('testNothing')
Michael Foorda50af062009-05-21 22:57:02 +00003550 test._resultForDoCleanups = result
Michael Foorde2fb98f2009-05-02 20:15:05 +00003551
3552 exc1 = Exception('foo')
3553 exc2 = Exception('bar')
3554 def cleanup1():
3555 raise exc1
3556
3557 def cleanup2():
3558 raise exc2
3559
3560 test.addCleanup(cleanup1)
3561 test.addCleanup(cleanup2)
3562
3563 self.assertFalse(test.doCleanups())
3564
3565 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3566 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3567 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3568
3569 def testCleanupInRun(self):
3570 blowUp = False
3571 ordering = []
3572
3573 class TestableTest(TestCase):
3574 def setUp(self):
3575 ordering.append('setUp')
3576 if blowUp:
3577 raise Exception('foo')
3578
3579 def testNothing(self):
3580 ordering.append('test')
3581
3582 def tearDown(self):
3583 ordering.append('tearDown')
3584
3585 test = TestableTest('testNothing')
3586
3587 def cleanup1():
3588 ordering.append('cleanup1')
3589 def cleanup2():
3590 ordering.append('cleanup2')
3591 test.addCleanup(cleanup1)
3592 test.addCleanup(cleanup2)
3593
3594 def success(some_test):
3595 self.assertEqual(some_test, test)
3596 ordering.append('success')
3597
3598 result = unittest.TestResult()
3599 result.addSuccess = success
3600
3601 test.run(result)
3602 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3603 'cleanup2', 'cleanup1', 'success'])
3604
3605 blowUp = True
3606 ordering = []
3607 test = TestableTest('testNothing')
3608 test.addCleanup(cleanup1)
3609 test.run(result)
3610 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3611
3612
Michael Foord829f6b82009-05-02 11:43:06 +00003613class Test_TestProgram(TestCase):
3614
3615 # Horrible white box test
3616 def testNoExit(self):
3617 result = object()
3618 test = object()
3619
3620 class FakeRunner(object):
3621 def run(self, test):
3622 self.test = test
3623 return result
3624
3625 runner = FakeRunner()
3626
Michael Foord5d31e052009-05-11 17:59:43 +00003627 oldParseArgs = TestProgram.parseArgs
3628 def restoreParseArgs():
Michael Foord829f6b82009-05-02 11:43:06 +00003629 TestProgram.parseArgs = oldParseArgs
Michael Foord5d31e052009-05-11 17:59:43 +00003630 TestProgram.parseArgs = lambda *args: None
3631 self.addCleanup(restoreParseArgs)
3632
3633 def removeTest():
Michael Foord829f6b82009-05-02 11:43:06 +00003634 del TestProgram.test
Michael Foord5d31e052009-05-11 17:59:43 +00003635 TestProgram.test = test
3636 self.addCleanup(removeTest)
3637
3638 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3639
3640 self.assertEqual(program.result, result)
3641 self.assertEqual(runner.test, test)
3642 self.assertEqual(program.verbosity, 2)
Michael Foord829f6b82009-05-02 11:43:06 +00003643
Michael Foord829f6b82009-05-02 11:43:06 +00003644 class FooBar(unittest.TestCase):
3645 def testPass(self):
3646 assert True
3647 def testFail(self):
3648 assert False
3649
3650 class FooBarLoader(unittest.TestLoader):
3651 """Test loader that returns a suite containing FooBar."""
3652 def loadTestsFromModule(self, module):
3653 return self.suiteClass(
3654 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3655
3656
3657 def test_NonExit(self):
3658 program = unittest.main(exit=False,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003659 argv=["foobar"],
3660 testRunner=unittest.TextTestRunner(stream=StringIO()),
3661 testLoader=self.FooBarLoader())
Michael Foord829f6b82009-05-02 11:43:06 +00003662 self.assertTrue(hasattr(program, 'result'))
3663
3664
3665 def test_Exit(self):
3666 self.assertRaises(
3667 SystemExit,
3668 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003669 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003670 testRunner=unittest.TextTestRunner(stream=StringIO()),
3671 exit=True,
3672 testLoader=self.FooBarLoader())
3673
3674
3675 def test_ExitAsDefault(self):
3676 self.assertRaises(
3677 SystemExit,
3678 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003679 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003680 testRunner=unittest.TextTestRunner(stream=StringIO()),
3681 testLoader=self.FooBarLoader())
3682
3683
Michael Foord07ef4872009-05-02 22:43:34 +00003684class Test_TextTestRunner(TestCase):
3685 """Tests for TextTestRunner."""
3686
3687 def test_works_with_result_without_startTestRun_stopTestRun(self):
3688 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3689 separator2 = ''
3690 def printErrors(self):
3691 pass
3692
3693 class Runner(unittest.TextTestRunner):
3694 def __init__(self):
3695 super(Runner, self).__init__(StringIO())
3696
3697 def _makeResult(self):
3698 return OldTextResult()
3699
3700 runner = Runner()
3701 runner.run(unittest.TestSuite())
3702
3703 def test_startTestRun_stopTestRun_called(self):
3704 class LoggingTextResult(LoggingResult):
3705 separator2 = ''
3706 def printErrors(self):
3707 pass
3708
3709 class LoggingRunner(unittest.TextTestRunner):
3710 def __init__(self, events):
3711 super(LoggingRunner, self).__init__(StringIO())
3712 self._events = events
3713
3714 def _makeResult(self):
3715 return LoggingTextResult(self._events)
3716
3717 events = []
3718 runner = LoggingRunner(events)
3719 runner.run(unittest.TestSuite())
3720 expected = ['startTestRun', 'stopTestRun']
3721 self.assertEqual(events, expected)
3722
Antoine Pitrou0734c632009-11-10 20:49:30 +00003723 def test_pickle_unpickle(self):
3724 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3725 # required by test_multiprocessing under Windows (in verbose mode).
3726 import StringIO
3727 # cStringIO objects are not pickleable, but StringIO objects are.
3728 stream = StringIO.StringIO("foo")
3729 runner = unittest.TextTestRunner(stream)
3730 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
3731 s = pickle.dumps(runner, protocol=protocol)
3732 obj = pickle.loads(s)
3733 # StringIO objects never compare equal, a cheap test instead.
3734 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3735
Michael Foorddb43b5a2010-02-10 14:25:12 +00003736 def test_resultclass(self):
3737 def MockResultClass(*args):
3738 return args
3739 STREAM = object()
3740 DESCRIPTIONS = object()
3741 VERBOSITY = object()
3742 runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY,
3743 resultclass=MockResultClass)
3744 self.assertEqual(runner.resultclass, MockResultClass)
3745
3746 expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY)
3747 self.assertEqual(runner._makeResult(), expectedresult)
3748
Michael Foord07ef4872009-05-02 22:43:34 +00003749
Michael Foordb4a81c82009-05-29 20:33:46 +00003750class TestDiscovery(TestCase):
3751
3752 # Heavily mocked tests so I can avoid hitting the filesystem
Michael Foorde91ea562009-09-13 19:07:03 +00003753 def test_get_name_from_path(self):
Michael Foordb4a81c82009-05-29 20:33:46 +00003754 loader = unittest.TestLoader()
3755
Michael Foordb4a81c82009-05-29 20:33:46 +00003756 loader._top_level_dir = '/foo'
Michael Foorde91ea562009-09-13 19:07:03 +00003757 name = loader._get_name_from_path('/foo/bar/baz.py')
3758 self.assertEqual(name, 'bar.baz')
Michael Foordb4a81c82009-05-29 20:33:46 +00003759
3760 if not __debug__:
3761 # asserts are off
3762 return
3763
3764 with self.assertRaises(AssertionError):
Michael Foorde91ea562009-09-13 19:07:03 +00003765 loader._get_name_from_path('/bar/baz.py')
Michael Foordb4a81c82009-05-29 20:33:46 +00003766
3767 def test_find_tests(self):
3768 loader = unittest.TestLoader()
3769
3770 original_listdir = os.listdir
3771 def restore_listdir():
3772 os.listdir = original_listdir
3773 original_isfile = os.path.isfile
3774 def restore_isfile():
3775 os.path.isfile = original_isfile
3776 original_isdir = os.path.isdir
3777 def restore_isdir():
3778 os.path.isdir = original_isdir
3779
3780 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Michael Foorde91ea562009-09-13 19:07:03 +00003781 'test.foo', 'test-not-a-module.py', 'another_dir'],
Michael Foordb4a81c82009-05-29 20:33:46 +00003782 ['test3.py', 'test4.py', ]]
3783 os.listdir = lambda path: path_lists.pop(0)
3784 self.addCleanup(restore_listdir)
3785
3786 def isdir(path):
3787 return path.endswith('dir')
3788 os.path.isdir = isdir
3789 self.addCleanup(restore_isdir)
3790
3791 def isfile(path):
3792 # another_dir is not a package and so shouldn't be recursed into
3793 return not path.endswith('dir') and not 'another_dir' in path
3794 os.path.isfile = isfile
3795 self.addCleanup(restore_isfile)
3796
Michael Foorde91ea562009-09-13 19:07:03 +00003797 loader._get_module_from_name = lambda path: path + ' module'
Michael Foordb4a81c82009-05-29 20:33:46 +00003798 loader.loadTestsFromModule = lambda module: module + ' tests'
3799
3800 loader._top_level_dir = '/foo'
3801 suite = list(loader._find_tests('/foo', 'test*.py'))
3802
Michael Foorde91ea562009-09-13 19:07:03 +00003803 expected = [name + ' module tests' for name in
3804 ('test1', 'test2')]
3805 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3806 ('test3', 'test4')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003807 self.assertEqual(suite, expected)
3808
3809 def test_find_tests_with_package(self):
3810 loader = unittest.TestLoader()
3811
3812 original_listdir = os.listdir
3813 def restore_listdir():
3814 os.listdir = original_listdir
3815 original_isfile = os.path.isfile
3816 def restore_isfile():
3817 os.path.isfile = original_isfile
3818 original_isdir = os.path.isdir
3819 def restore_isdir():
3820 os.path.isdir = original_isdir
3821
3822 directories = ['a_directory', 'test_directory', 'test_directory2']
3823 path_lists = [directories, [], [], []]
3824 os.listdir = lambda path: path_lists.pop(0)
3825 self.addCleanup(restore_listdir)
3826
3827 os.path.isdir = lambda path: True
3828 self.addCleanup(restore_isdir)
3829
3830 os.path.isfile = lambda path: os.path.basename(path) not in directories
3831 self.addCleanup(restore_isfile)
3832
3833 class Module(object):
3834 paths = []
3835 load_tests_args = []
3836
3837 def __init__(self, path):
3838 self.path = path
3839 self.paths.append(path)
3840 if os.path.basename(path) == 'test_directory':
3841 def load_tests(loader, tests, pattern):
3842 self.load_tests_args.append((loader, tests, pattern))
3843 return 'load_tests'
3844 self.load_tests = load_tests
3845
3846 def __eq__(self, other):
3847 return self.path == other.path
3848
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003849 # Silence py3k warning
3850 __hash__ = None
3851
Michael Foorde91ea562009-09-13 19:07:03 +00003852 loader._get_module_from_name = lambda name: Module(name)
Michael Foordb4a81c82009-05-29 20:33:46 +00003853 def loadTestsFromModule(module, use_load_tests):
3854 if use_load_tests:
3855 raise self.failureException('use_load_tests should be False for packages')
3856 return module.path + ' module tests'
3857 loader.loadTestsFromModule = loadTestsFromModule
3858
3859 loader._top_level_dir = '/foo'
3860 # this time no '.py' on the pattern so that it can match
3861 # a test package
3862 suite = list(loader._find_tests('/foo', 'test*'))
3863
3864 # We should have loaded tests from the test_directory package by calling load_tests
3865 # and directly from the test_directory2 package
Michael Foordd53d0852009-06-05 14:14:34 +00003866 self.assertEqual(suite,
Michael Foorde91ea562009-09-13 19:07:03 +00003867 ['load_tests', 'test_directory2' + ' module tests'])
3868 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Michael Foordb4a81c82009-05-29 20:33:46 +00003869
3870 # load_tests should have been called once with loader, tests and pattern
3871 self.assertEqual(Module.load_tests_args,
Michael Foorde91ea562009-09-13 19:07:03 +00003872 [(loader, 'test_directory' + ' module tests', 'test*')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003873
3874 def test_discover(self):
3875 loader = unittest.TestLoader()
3876
3877 original_isfile = os.path.isfile
3878 def restore_isfile():
3879 os.path.isfile = original_isfile
3880
3881 os.path.isfile = lambda path: False
3882 self.addCleanup(restore_isfile)
3883
Nick Coghlanb6edf192009-10-17 08:21:21 +00003884 orig_sys_path = sys.path[:]
3885 def restore_path():
3886 sys.path[:] = orig_sys_path
3887 self.addCleanup(restore_path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003888
Nick Coghlanb6edf192009-10-17 08:21:21 +00003889 full_path = os.path.abspath(os.path.normpath('/foo'))
Michael Foordb4a81c82009-05-29 20:33:46 +00003890 with self.assertRaises(ImportError):
3891 loader.discover('/foo/bar', top_level_dir='/foo')
3892
3893 self.assertEqual(loader._top_level_dir, full_path)
3894 self.assertIn(full_path, sys.path)
3895
3896 os.path.isfile = lambda path: True
3897 _find_tests_args = []
3898 def _find_tests(start_dir, pattern):
3899 _find_tests_args.append((start_dir, pattern))
3900 return ['tests']
3901 loader._find_tests = _find_tests
3902 loader.suiteClass = str
3903
3904 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3905
3906 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3907 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3908 self.assertEqual(suite, "['tests']")
3909 self.assertEqual(loader._top_level_dir, top_level_dir)
3910 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlanb6edf192009-10-17 08:21:21 +00003911 self.assertIn(top_level_dir, sys.path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003912
Michael Foorde91ea562009-09-13 19:07:03 +00003913 def test_discover_with_modules_that_fail_to_import(self):
3914 loader = unittest.TestLoader()
3915
3916 listdir = os.listdir
3917 os.listdir = lambda _: ['test_this_does_not_exist.py']
3918 isfile = os.path.isfile
3919 os.path.isfile = lambda _: True
Nick Coghlanb6edf192009-10-17 08:21:21 +00003920 orig_sys_path = sys.path[:]
Michael Foorde91ea562009-09-13 19:07:03 +00003921 def restore():
3922 os.path.isfile = isfile
3923 os.listdir = listdir
Nick Coghlanb6edf192009-10-17 08:21:21 +00003924 sys.path[:] = orig_sys_path
Michael Foorde91ea562009-09-13 19:07:03 +00003925 self.addCleanup(restore)
3926
3927 suite = loader.discover('.')
Nick Coghlanb6edf192009-10-17 08:21:21 +00003928 self.assertIn(os.getcwd(), sys.path)
Michael Foorde91ea562009-09-13 19:07:03 +00003929 self.assertEqual(suite.countTestCases(), 1)
3930 test = list(list(suite)[0])[0] # extract test from suite
3931
3932 with self.assertRaises(ImportError):
3933 test.test_this_does_not_exist()
3934
Michael Foordb4a81c82009-05-29 20:33:46 +00003935 def test_command_line_handling_parseArgs(self):
3936 # Haha - take that uninstantiable class
3937 program = object.__new__(TestProgram)
3938
3939 args = []
3940 def do_discovery(argv):
3941 args.extend(argv)
3942 program._do_discovery = do_discovery
3943 program.parseArgs(['something', 'discover'])
3944 self.assertEqual(args, [])
3945
3946 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3947 self.assertEqual(args, ['foo', 'bar'])
3948
3949 def test_command_line_handling_do_discovery_too_many_arguments(self):
3950 class Stop(Exception):
3951 pass
3952 def usageExit():
3953 raise Stop
3954
3955 program = object.__new__(TestProgram)
3956 program.usageExit = usageExit
3957
3958 with self.assertRaises(Stop):
3959 # too many args
3960 program._do_discovery(['one', 'two', 'three', 'four'])
3961
3962
3963 def test_command_line_handling_do_discovery_calls_loader(self):
3964 program = object.__new__(TestProgram)
3965
3966 class Loader(object):
3967 args = []
3968 def discover(self, start_dir, pattern, top_level_dir):
3969 self.args.append((start_dir, pattern, top_level_dir))
3970 return 'tests'
3971
3972 program._do_discovery(['-v'], Loader=Loader)
3973 self.assertEqual(program.verbosity, 2)
3974 self.assertEqual(program.test, 'tests')
3975 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3976
3977 Loader.args = []
3978 program = object.__new__(TestProgram)
3979 program._do_discovery(['--verbose'], Loader=Loader)
3980 self.assertEqual(program.test, 'tests')
3981 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3982
3983 Loader.args = []
3984 program = object.__new__(TestProgram)
3985 program._do_discovery([], Loader=Loader)
3986 self.assertEqual(program.test, 'tests')
3987 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3988
3989 Loader.args = []
3990 program = object.__new__(TestProgram)
3991 program._do_discovery(['fish'], Loader=Loader)
3992 self.assertEqual(program.test, 'tests')
3993 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3994
3995 Loader.args = []
3996 program = object.__new__(TestProgram)
3997 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3998 self.assertEqual(program.test, 'tests')
3999 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
4000
4001 Loader.args = []
4002 program = object.__new__(TestProgram)
4003 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
4004 self.assertEqual(program.test, 'tests')
4005 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
4006
4007 Loader.args = []
4008 program = object.__new__(TestProgram)
4009 program._do_discovery(['-s', 'fish'], Loader=Loader)
4010 self.assertEqual(program.test, 'tests')
4011 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
4012
4013 Loader.args = []
4014 program = object.__new__(TestProgram)
4015 program._do_discovery(['-t', 'fish'], Loader=Loader)
4016 self.assertEqual(program.test, 'tests')
4017 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
4018
4019 Loader.args = []
4020 program = object.__new__(TestProgram)
4021 program._do_discovery(['-p', 'fish'], Loader=Loader)
4022 self.assertEqual(program.test, 'tests')
4023 self.assertEqual(Loader.args, [('.', 'fish', None)])
4024
4025 Loader.args = []
4026 program = object.__new__(TestProgram)
4027 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
4028 self.assertEqual(program.test, 'tests')
4029 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
4030 self.assertEqual(program.verbosity, 2)
4031
4032
Michael Foord5ffa3252010-03-07 22:04:55 +00004033class TestSetups(unittest.TestCase):
4034
4035 def getRunner(self):
4036 return unittest.TextTestRunner(resultclass=resultFactory,
4037 stream=StringIO())
4038 def runTests(self, *cases):
4039 suite = unittest.TestSuite()
4040 for case in cases:
4041 tests = unittest.defaultTestLoader.loadTestsFromTestCase(case)
4042 suite.addTests(tests)
4043
4044 runner = self.getRunner()
4045
4046 # creating a nested suite exposes some potential bugs
4047 realSuite = unittest.TestSuite()
4048 realSuite.addTest(suite)
4049 # adding empty suites to the end exposes potential bugs
4050 suite.addTest(unittest.TestSuite())
4051 realSuite.addTest(unittest.TestSuite())
4052 return runner.run(realSuite)
4053
4054 def test_setup_class(self):
4055 class Test(unittest.TestCase):
4056 setUpCalled = 0
4057 @classmethod
4058 def setUpClass(cls):
4059 Test.setUpCalled += 1
4060 unittest.TestCase.setUpClass()
4061 def test_one(self):
4062 pass
4063 def test_two(self):
4064 pass
4065
4066 result = self.runTests(Test)
4067
4068 self.assertEqual(Test.setUpCalled, 1)
4069 self.assertEqual(result.testsRun, 2)
4070 self.assertEqual(len(result.errors), 0)
4071
4072 def test_teardown_class(self):
4073 class Test(unittest.TestCase):
4074 tearDownCalled = 0
4075 @classmethod
4076 def tearDownClass(cls):
4077 Test.tearDownCalled += 1
4078 unittest.TestCase.tearDownClass()
4079 def test_one(self):
4080 pass
4081 def test_two(self):
4082 pass
4083
4084 result = self.runTests(Test)
4085
4086 self.assertEqual(Test.tearDownCalled, 1)
4087 self.assertEqual(result.testsRun, 2)
4088 self.assertEqual(len(result.errors), 0)
4089
4090 def test_teardown_class_two_classes(self):
4091 class Test(unittest.TestCase):
4092 tearDownCalled = 0
4093 @classmethod
4094 def tearDownClass(cls):
4095 Test.tearDownCalled += 1
4096 unittest.TestCase.tearDownClass()
4097 def test_one(self):
4098 pass
4099 def test_two(self):
4100 pass
4101
4102 class Test2(unittest.TestCase):
4103 tearDownCalled = 0
4104 @classmethod
4105 def tearDownClass(cls):
4106 Test2.tearDownCalled += 1
4107 unittest.TestCase.tearDownClass()
4108 def test_one(self):
4109 pass
4110 def test_two(self):
4111 pass
4112
4113 result = self.runTests(Test, Test2)
4114
4115 self.assertEqual(Test.tearDownCalled, 1)
4116 self.assertEqual(Test2.tearDownCalled, 1)
4117 self.assertEqual(result.testsRun, 4)
4118 self.assertEqual(len(result.errors), 0)
4119
4120 def test_error_in_setupclass(self):
4121 class BrokenTest(unittest.TestCase):
4122 @classmethod
4123 def setUpClass(cls):
4124 raise TypeError('foo')
4125 def test_one(self):
4126 pass
4127 def test_two(self):
4128 pass
4129
4130 result = self.runTests(BrokenTest)
4131
4132 self.assertEqual(result.testsRun, 0)
4133 self.assertEqual(len(result.errors), 1)
4134 error, _ = result.errors[0]
4135 self.assertEqual(str(error),
4136 'classSetUp (%s.BrokenTest)' % __name__)
4137
4138 def test_error_in_teardown_class(self):
4139 class Test(unittest.TestCase):
4140 tornDown = 0
4141 @classmethod
4142 def tearDownClass(cls):
4143 Test.tornDown += 1
4144 raise TypeError('foo')
4145 def test_one(self):
4146 pass
4147 def test_two(self):
4148 pass
4149
4150 class Test2(unittest.TestCase):
4151 tornDown = 0
4152 @classmethod
4153 def tearDownClass(cls):
4154 Test2.tornDown += 1
4155 raise TypeError('foo')
4156 def test_one(self):
4157 pass
4158 def test_two(self):
4159 pass
4160
4161 result = self.runTests(Test, Test2)
4162 self.assertEqual(result.testsRun, 4)
4163 self.assertEqual(len(result.errors), 2)
4164 self.assertEqual(Test.tornDown, 1)
4165 self.assertEqual(Test2.tornDown, 1)
4166
4167 error, _ = result.errors[0]
4168 self.assertEqual(str(error),
4169 'classTearDown (%s.Test)' % __name__)
4170
4171 def test_class_not_torndown_when_setup_fails(self):
4172 class Test(unittest.TestCase):
4173 tornDown = False
4174 @classmethod
4175 def setUpClass(cls):
4176 raise TypeError
4177 @classmethod
4178 def tearDownClass(cls):
4179 Test.tornDown = True
4180 raise TypeError('foo')
4181 def test_one(self):
4182 pass
4183
4184 self.runTests(Test)
4185 self.assertFalse(Test.tornDown)
4186
4187 def test_class_not_setup_or_torndown_when_skipped(self):
4188 class Test(unittest.TestCase):
4189 classSetUp = False
4190 tornDown = False
4191 @classmethod
4192 def setUpClass(cls):
4193 Test.classSetUp = True
4194 @classmethod
4195 def tearDownClass(cls):
4196 Test.tornDown = True
4197 def test_one(self):
4198 pass
4199
4200 Test = unittest.skip("hop")(Test)
4201 self.runTests(Test)
4202 self.assertFalse(Test.classSetUp)
4203 self.assertFalse(Test.tornDown)
4204
4205 def test_setup_teardown_order_with_pathological_suite(self):
4206 results = []
4207
4208 class Module1(object):
4209 @staticmethod
4210 def setUpModule():
4211 results.append('Module1.setUpModule')
4212 @staticmethod
4213 def tearDownModule():
4214 results.append('Module1.tearDownModule')
4215
4216 class Module2(object):
4217 @staticmethod
4218 def setUpModule():
4219 results.append('Module2.setUpModule')
4220 @staticmethod
4221 def tearDownModule():
4222 results.append('Module2.tearDownModule')
4223
4224 class Test1(unittest.TestCase):
4225 @classmethod
4226 def setUpClass(cls):
4227 results.append('setup 1')
4228 @classmethod
4229 def tearDownClass(cls):
4230 results.append('teardown 1')
4231 def testOne(self):
4232 results.append('Test1.testOne')
4233 def testTwo(self):
4234 results.append('Test1.testTwo')
4235
4236 class Test2(unittest.TestCase):
4237 @classmethod
4238 def setUpClass(cls):
4239 results.append('setup 2')
4240 @classmethod
4241 def tearDownClass(cls):
4242 results.append('teardown 2')
4243 def testOne(self):
4244 results.append('Test2.testOne')
4245 def testTwo(self):
4246 results.append('Test2.testTwo')
4247
4248 class Test3(unittest.TestCase):
4249 @classmethod
4250 def setUpClass(cls):
4251 results.append('setup 3')
4252 @classmethod
4253 def tearDownClass(cls):
4254 results.append('teardown 3')
4255 def testOne(self):
4256 results.append('Test3.testOne')
4257 def testTwo(self):
4258 results.append('Test3.testTwo')
4259
4260 Test1.__module__ = Test2.__module__ = 'Module'
4261 Test3.__module__ = 'Module2'
4262 sys.modules['Module'] = Module1
4263 sys.modules['Module2'] = Module2
4264
4265 first = unittest.TestSuite((Test1('testOne'),))
4266 second = unittest.TestSuite((Test1('testTwo'),))
4267 third = unittest.TestSuite((Test2('testOne'),))
4268 fourth = unittest.TestSuite((Test2('testTwo'),))
4269 fifth = unittest.TestSuite((Test3('testOne'),))
4270 sixth = unittest.TestSuite((Test3('testTwo'),))
4271 suite = unittest.TestSuite((first, second, third, fourth, fifth, sixth))
4272
4273 runner = self.getRunner()
4274 result = runner.run(suite)
4275 self.assertEqual(result.testsRun, 6)
4276 self.assertEqual(len(result.errors), 0)
4277
4278 self.assertEqual(results,
4279 ['Module1.setUpModule', 'setup 1',
4280 'Test1.testOne', 'Test1.testTwo', 'teardown 1',
4281 'setup 2', 'Test2.testOne', 'Test2.testTwo',
4282 'teardown 2', 'Module1.tearDownModule',
4283 'Module2.setUpModule', 'setup 3',
4284 'Test3.testOne', 'Test3.testTwo',
4285 'teardown 3', 'Module2.tearDownModule'])
4286
4287 def test_setup_module(self):
4288 class Module(object):
4289 moduleSetup = 0
4290 @staticmethod
4291 def setUpModule():
4292 Module.moduleSetup += 1
4293
4294 class Test(unittest.TestCase):
4295 def test_one(self):
4296 pass
4297 def test_two(self):
4298 pass
4299 Test.__module__ = 'Module'
4300 sys.modules['Module'] = Module
4301
4302 result = self.runTests(Test)
4303 self.assertEqual(Module.moduleSetup, 1)
4304 self.assertEqual(result.testsRun, 2)
4305 self.assertEqual(len(result.errors), 0)
4306
4307 def test_error_in_setup_module(self):
4308 class Module(object):
4309 moduleSetup = 0
4310 moduleTornDown = 0
4311 @staticmethod
4312 def setUpModule():
4313 Module.moduleSetup += 1
4314 raise TypeError('foo')
4315 @staticmethod
4316 def tearDownModule():
4317 Module.moduleTornDown += 1
4318
4319 class Test(unittest.TestCase):
4320 classSetUp = False
4321 classTornDown = False
4322 @classmethod
4323 def setUpClass(cls):
4324 Test.classSetUp = True
4325 @classmethod
4326 def tearDownClass(cls):
4327 Test.classTornDown = True
4328 def test_one(self):
4329 pass
4330 def test_two(self):
4331 pass
4332
4333 class Test2(unittest.TestCase):
4334 def test_one(self):
4335 pass
4336 def test_two(self):
4337 pass
4338 Test.__module__ = 'Module'
4339 Test2.__module__ = 'Module'
4340 sys.modules['Module'] = Module
4341
4342 result = self.runTests(Test, Test2)
4343 self.assertEqual(Module.moduleSetup, 1)
4344 self.assertEqual(Module.moduleTornDown, 0)
4345 self.assertEqual(result.testsRun, 0)
4346 self.assertFalse(Test.classSetUp)
4347 self.assertFalse(Test.classTornDown)
4348 self.assertEqual(len(result.errors), 1)
4349 error, _ = result.errors[0]
4350 self.assertEqual(str(error), 'setUpModule (Module)')
4351
4352 def test_testcase_with_missing_module(self):
4353 class Test(unittest.TestCase):
4354 def test_one(self):
4355 pass
4356 def test_two(self):
4357 pass
4358 Test.__module__ = 'Module'
4359 sys.modules.pop('Module', None)
4360
4361 result = self.runTests(Test)
4362 self.assertEqual(result.testsRun, 2)
4363
4364 def test_teardown_module(self):
4365 class Module(object):
4366 moduleTornDown = 0
4367 @staticmethod
4368 def tearDownModule():
4369 Module.moduleTornDown += 1
4370
4371 class Test(unittest.TestCase):
4372 def test_one(self):
4373 pass
4374 def test_two(self):
4375 pass
4376 Test.__module__ = 'Module'
4377 sys.modules['Module'] = Module
4378
4379 result = self.runTests(Test)
4380 self.assertEqual(Module.moduleTornDown, 1)
4381 self.assertEqual(result.testsRun, 2)
4382 self.assertEqual(len(result.errors), 0)
4383
4384 def test_error_in_teardown_module(self):
4385 class Module(object):
4386 moduleTornDown = 0
4387 @staticmethod
4388 def tearDownModule():
4389 Module.moduleTornDown += 1
4390 raise TypeError('foo')
4391
4392 class Test(unittest.TestCase):
4393 classSetUp = False
4394 classTornDown = False
4395 @classmethod
4396 def setUpClass(cls):
4397 Test.classSetUp = True
4398 @classmethod
4399 def tearDownClass(cls):
4400 Test.classTornDown = True
4401 def test_one(self):
4402 pass
4403 def test_two(self):
4404 pass
4405
4406 class Test2(unittest.TestCase):
4407 def test_one(self):
4408 pass
4409 def test_two(self):
4410 pass
4411 Test.__module__ = 'Module'
4412 Test2.__module__ = 'Module'
4413 sys.modules['Module'] = Module
4414
4415 result = self.runTests(Test, Test2)
4416 self.assertEqual(Module.moduleTornDown, 1)
4417 self.assertEqual(result.testsRun, 4)
4418 self.assertTrue(Test.classSetUp)
4419 self.assertTrue(Test.classTornDown)
4420 self.assertEqual(len(result.errors), 1)
4421 error, _ = result.errors[0]
4422 self.assertEqual(str(error), 'tearDownModule (Module)')
4423
Jim Fultonfafd8742004-08-28 15:22:12 +00004424######################################################################
4425## Main
4426######################################################################
4427
4428def test_main():
Georg Brandl15c5ce92007-03-07 09:09:40 +00004429 test_support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004430 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Michael Foord829f6b82009-05-02 11:43:06 +00004431 Test_TestSkipping, Test_Assertions, TestLongMessage,
Michael Foordae3db0a2010-02-22 23:28:32 +00004432 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner,
Michael Foord5ffa3252010-03-07 22:04:55 +00004433 Test_OldTestResult, TestSetups)
Jim Fultonfafd8742004-08-28 15:22:12 +00004434
Georg Brandl15c5ce92007-03-07 09:09:40 +00004435if __name__ == "__main__":
Tim Petersea5962f2007-03-12 18:07:52 +00004436 test_main()