blob: 5d51ffc547ce26e57c2d9f4ef7ac38b76476bbb7 [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
Michael Foord1b9e9532010-03-22 01:01:34 +00002116 def testFailFastSetByRunner(self):
2117 runner = unittest.TextTestRunner(stream=StringIO(), failfast=True)
2118 def test(result):
2119 self.assertTrue(result.failfast)
2120 result = runner.run(test)
2121
2122
Michael Foordae3db0a2010-02-22 23:28:32 +00002123classDict = dict(unittest.TestResult.__dict__)
Michael Foordd99ef9a2010-02-23 17:00:53 +00002124for m in ('addSkip', 'addExpectedFailure', 'addUnexpectedSuccess',
2125 '__init__'):
Michael Foordae3db0a2010-02-22 23:28:32 +00002126 del classDict[m]
Michael Foordd99ef9a2010-02-23 17:00:53 +00002127
2128def __init__(self, stream=None, descriptions=None, verbosity=None):
2129 self.failures = []
2130 self.errors = []
2131 self.testsRun = 0
2132 self.shouldStop = False
2133classDict['__init__'] = __init__
Michael Foordae3db0a2010-02-22 23:28:32 +00002134OldResult = type('OldResult', (object,), classDict)
2135
2136class Test_OldTestResult(unittest.TestCase):
2137
2138 def assertOldResultWarning(self, test, failures):
2139 with warnings.catch_warnings(record=True) as log:
2140 result = OldResult()
2141 test.run(result)
2142 self.assertEqual(len(result.failures), failures)
2143 warning, = log
2144 self.assertIs(warning.category, RuntimeWarning)
2145
2146 def testOldTestResult(self):
2147 class Test(unittest.TestCase):
2148 def testSkip(self):
2149 self.skipTest('foobar')
2150 @unittest.expectedFailure
2151 def testExpectedFail(self):
2152 raise TypeError
2153 @unittest.expectedFailure
2154 def testUnexpectedSuccess(self):
2155 pass
2156
2157 for test_name, should_pass in (('testSkip', True),
2158 ('testExpectedFail', True),
2159 ('testUnexpectedSuccess', False)):
2160 test = Test(test_name)
2161 self.assertOldResultWarning(test, int(not should_pass))
2162
2163 def testOldTestTesultSetup(self):
2164 class Test(unittest.TestCase):
2165 def setUp(self):
2166 self.skipTest('no reason')
2167 def testFoo(self):
2168 pass
2169 self.assertOldResultWarning(Test('testFoo'), 0)
2170
2171 def testOldTestResultClass(self):
2172 @unittest.skip('no reason')
2173 class Test(unittest.TestCase):
2174 def testFoo(self):
2175 pass
2176 self.assertOldResultWarning(Test('testFoo'), 0)
2177
Michael Foordd99ef9a2010-02-23 17:00:53 +00002178 def testOldResultWithRunner(self):
2179 class Test(unittest.TestCase):
2180 def testFoo(self):
2181 pass
2182 runner = unittest.TextTestRunner(resultclass=OldResult,
2183 stream=StringIO())
2184 # This will raise an exception if TextTestRunner can't handle old
2185 # test result objects
2186 runner.run(Test('testFoo'))
Michael Foorddb43b5a2010-02-10 14:25:12 +00002187
Georg Brandl15c5ce92007-03-07 09:09:40 +00002188### Support code for Test_TestCase
2189################################################################
2190
2191class Foo(unittest.TestCase):
2192 def runTest(self): pass
Michael Foorddb003cb2010-03-22 01:02:23 +00002193 def test1(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002194
Georg Brandl15c5ce92007-03-07 09:09:40 +00002195class Bar(Foo):
2196 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002197
Michael Foord1b9e9532010-03-22 01:01:34 +00002198def getLoggingTestCase():
2199 class LoggingTestCase(unittest.TestCase):
2200 """A test case which logs its calls."""
Michael Foord07ef4872009-05-02 22:43:34 +00002201
Michael Foord1b9e9532010-03-22 01:01:34 +00002202 def __init__(self, events):
2203 super(LoggingTestCase, self).__init__('test')
2204 self.events = events
Michael Foord07ef4872009-05-02 22:43:34 +00002205
Michael Foord1b9e9532010-03-22 01:01:34 +00002206 def setUp(self):
2207 self.events.append('setUp')
Michael Foord07ef4872009-05-02 22:43:34 +00002208
Michael Foord1b9e9532010-03-22 01:01:34 +00002209 def test(self):
2210 self.events.append('test')
Michael Foord07ef4872009-05-02 22:43:34 +00002211
Michael Foord1b9e9532010-03-22 01:01:34 +00002212 def tearDown(self):
2213 self.events.append('tearDown')
2214 return LoggingTestCase
Michael Foord07ef4872009-05-02 22:43:34 +00002215
2216class ResultWithNoStartTestRunStopTestRun(object):
2217 """An object honouring TestResult before startTestRun/stopTestRun."""
2218
2219 def __init__(self):
2220 self.failures = []
2221 self.errors = []
2222 self.testsRun = 0
2223 self.skipped = []
2224 self.expectedFailures = []
2225 self.unexpectedSuccesses = []
2226 self.shouldStop = False
2227
2228 def startTest(self, test):
2229 pass
2230
2231 def stopTest(self, test):
2232 pass
2233
2234 def addError(self, test):
2235 pass
2236
2237 def addFailure(self, test):
2238 pass
2239
2240 def addSuccess(self, test):
2241 pass
2242
2243 def wasSuccessful(self):
2244 return True
2245
2246
Georg Brandl15c5ce92007-03-07 09:09:40 +00002247################################################################
2248### /Support code for Test_TestCase
2249
2250class Test_TestCase(TestCase, TestEquality, TestHashing):
2251
2252 ### Set up attributes used by inherited tests
2253 ################################################################
2254
2255 # Used by TestHashing.test_hash and TestEquality.test_eq
2256 eq_pairs = [(Foo('test1'), Foo('test1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002257
Georg Brandl15c5ce92007-03-07 09:09:40 +00002258 # Used by TestEquality.test_ne
2259 ne_pairs = [(Foo('test1'), Foo('runTest'))
2260 ,(Foo('test1'), Bar('test1'))
2261 ,(Foo('test1'), Bar('test2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002262
Georg Brandl15c5ce92007-03-07 09:09:40 +00002263 ################################################################
2264 ### /Set up attributes used by inherited tests
Tim Petersea5962f2007-03-12 18:07:52 +00002265
Georg Brandl15c5ce92007-03-07 09:09:40 +00002266
2267 # "class TestCase([methodName])"
2268 # ...
2269 # "Each instance of TestCase will run a single test method: the
2270 # method named methodName."
2271 # ...
2272 # "methodName defaults to "runTest"."
2273 #
2274 # Make sure it really is optional, and that it defaults to the proper
2275 # thing.
2276 def test_init__no_test_name(self):
2277 class Test(unittest.TestCase):
2278 def runTest(self): raise MyException()
2279 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002280
Georg Brandl15c5ce92007-03-07 09:09:40 +00002281 self.assertEqual(Test().id()[-13:], '.Test.runTest')
Tim Petersea5962f2007-03-12 18:07:52 +00002282
Georg Brandl15c5ce92007-03-07 09:09:40 +00002283 # "class TestCase([methodName])"
2284 # ...
2285 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002286 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002287 def test_init__test_name__valid(self):
2288 class Test(unittest.TestCase):
2289 def runTest(self): raise MyException()
2290 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002291
Georg Brandl15c5ce92007-03-07 09:09:40 +00002292 self.assertEqual(Test('test').id()[-10:], '.Test.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002293
Georg Brandl15c5ce92007-03-07 09:09:40 +00002294 # "class TestCase([methodName])"
2295 # ...
2296 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002297 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002298 def test_init__test_name__invalid(self):
2299 class Test(unittest.TestCase):
2300 def runTest(self): raise MyException()
2301 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002302
Georg Brandl15c5ce92007-03-07 09:09:40 +00002303 try:
2304 Test('testfoo')
2305 except ValueError:
2306 pass
2307 else:
2308 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +00002309
Georg Brandl15c5ce92007-03-07 09:09:40 +00002310 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00002311 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00002312 def test_countTestCases(self):
2313 class Foo(unittest.TestCase):
2314 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002315
Georg Brandl15c5ce92007-03-07 09:09:40 +00002316 self.assertEqual(Foo('test').countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00002317
Georg Brandl15c5ce92007-03-07 09:09:40 +00002318 # "Return the default type of test result object to be used to run this
2319 # test. For TestCase instances, this will always be
2320 # unittest.TestResult; subclasses of TestCase should
2321 # override this as necessary."
2322 def test_defaultTestResult(self):
2323 class Foo(unittest.TestCase):
2324 def runTest(self):
2325 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002326
Georg Brandl15c5ce92007-03-07 09:09:40 +00002327 result = Foo().defaultTestResult()
2328 self.assertEqual(type(result), unittest.TestResult)
2329
2330 # "When a setUp() method is defined, the test runner will run that method
2331 # prior to each test. Likewise, if a tearDown() method is defined, the
2332 # test runner will invoke that method after each test. In the example,
2333 # setUp() was used to create a fresh sequence for each test."
2334 #
2335 # Make sure the proper call order is maintained, even if setUp() raises
2336 # an exception.
2337 def test_run_call_order__error_in_setUp(self):
2338 events = []
2339 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002340
Michael Foord1b9e9532010-03-22 01:01:34 +00002341 class Foo(getLoggingTestCase()):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002342 def setUp(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002343 super(Foo, self).setUp()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002344 raise RuntimeError('raised by Foo.setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002345
Michael Foord07ef4872009-05-02 22:43:34 +00002346 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002347 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2348 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002349
Michael Foord07ef4872009-05-02 22:43:34 +00002350 # "With a temporary result stopTestRun is called when setUp errors.
2351 def test_run_call_order__error_in_setUp_default_result(self):
2352 events = []
2353
Michael Foord1b9e9532010-03-22 01:01:34 +00002354 class Foo(getLoggingTestCase()):
Michael Foord07ef4872009-05-02 22:43:34 +00002355 def defaultTestResult(self):
2356 return LoggingResult(self.events)
2357
2358 def setUp(self):
2359 super(Foo, self).setUp()
2360 raise RuntimeError('raised by Foo.setUp')
2361
2362 Foo(events).run()
2363 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2364 'stopTest', 'stopTestRun']
2365 self.assertEqual(events, expected)
2366
Georg Brandl15c5ce92007-03-07 09:09:40 +00002367 # "When a setUp() method is defined, the test runner will run that method
2368 # prior to each test. Likewise, if a tearDown() method is defined, the
2369 # test runner will invoke that method after each test. In the example,
2370 # setUp() was used to create a fresh sequence for each test."
2371 #
2372 # Make sure the proper call order is maintained, even if the test raises
2373 # an error (as opposed to a failure).
2374 def test_run_call_order__error_in_test(self):
2375 events = []
2376 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002377
Michael Foord1b9e9532010-03-22 01:01:34 +00002378 class Foo(getLoggingTestCase()):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002379 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002380 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002381 raise RuntimeError('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002382
Georg Brandl15c5ce92007-03-07 09:09:40 +00002383 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2384 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002385 Foo(events).run(result)
2386 self.assertEqual(events, expected)
2387
2388 # "With a default result, an error in the test still results in stopTestRun
2389 # being called."
2390 def test_run_call_order__error_in_test_default_result(self):
2391 events = []
2392
Michael Foord1b9e9532010-03-22 01:01:34 +00002393 class Foo(getLoggingTestCase()):
Michael Foord07ef4872009-05-02 22:43:34 +00002394 def defaultTestResult(self):
2395 return LoggingResult(self.events)
2396
2397 def test(self):
2398 super(Foo, self).test()
2399 raise RuntimeError('raised by Foo.test')
2400
2401 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2402 'tearDown', 'stopTest', 'stopTestRun']
2403 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002404 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002405
Georg Brandl15c5ce92007-03-07 09:09:40 +00002406 # "When a setUp() method is defined, the test runner will run that method
2407 # prior to each test. Likewise, if a tearDown() method is defined, the
2408 # test runner will invoke that method after each test. In the example,
2409 # setUp() was used to create a fresh sequence for each test."
2410 #
2411 # Make sure the proper call order is maintained, even if the test signals
2412 # a failure (as opposed to an error).
2413 def test_run_call_order__failure_in_test(self):
2414 events = []
2415 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002416
Michael Foord1b9e9532010-03-22 01:01:34 +00002417 class Foo(getLoggingTestCase()):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002418 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002419 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002420 self.fail('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002421
Georg Brandl15c5ce92007-03-07 09:09:40 +00002422 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2423 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002424 Foo(events).run(result)
2425 self.assertEqual(events, expected)
2426
2427 # "When a test fails with a default result stopTestRun is still called."
2428 def test_run_call_order__failure_in_test_default_result(self):
2429
Michael Foord1b9e9532010-03-22 01:01:34 +00002430 class Foo(getLoggingTestCase()):
Michael Foord07ef4872009-05-02 22:43:34 +00002431 def defaultTestResult(self):
2432 return LoggingResult(self.events)
2433 def test(self):
2434 super(Foo, self).test()
2435 self.fail('raised by Foo.test')
2436
2437 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2438 'tearDown', 'stopTest', 'stopTestRun']
2439 events = []
2440 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002441 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002442
Georg Brandl15c5ce92007-03-07 09:09:40 +00002443 # "When a setUp() method is defined, the test runner will run that method
2444 # prior to each test. Likewise, if a tearDown() method is defined, the
2445 # test runner will invoke that method after each test. In the example,
2446 # setUp() was used to create a fresh sequence for each test."
2447 #
2448 # Make sure the proper call order is maintained, even if tearDown() raises
2449 # an exception.
2450 def test_run_call_order__error_in_tearDown(self):
2451 events = []
2452 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002453
Michael Foord1b9e9532010-03-22 01:01:34 +00002454 class Foo(getLoggingTestCase()):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002455 def tearDown(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002456 super(Foo, self).tearDown()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002457 raise RuntimeError('raised by Foo.tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002458
Michael Foord07ef4872009-05-02 22:43:34 +00002459 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002460 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2461 'stopTest']
2462 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002463
Michael Foord07ef4872009-05-02 22:43:34 +00002464 # "When tearDown errors with a default result stopTestRun is still called."
2465 def test_run_call_order__error_in_tearDown_default_result(self):
2466
Michael Foord1b9e9532010-03-22 01:01:34 +00002467 class Foo(getLoggingTestCase()):
Michael Foord07ef4872009-05-02 22:43:34 +00002468 def defaultTestResult(self):
2469 return LoggingResult(self.events)
2470 def tearDown(self):
2471 super(Foo, self).tearDown()
2472 raise RuntimeError('raised by Foo.tearDown')
2473
2474 events = []
2475 Foo(events).run()
2476 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2477 'addError', 'stopTest', 'stopTestRun']
2478 self.assertEqual(events, expected)
2479
2480 # "TestCase.run() still works when the defaultTestResult is a TestResult
2481 # that does not support startTestRun and stopTestRun.
2482 def test_run_call_order_default_result(self):
2483
2484 class Foo(unittest.TestCase):
2485 def defaultTestResult(self):
2486 return ResultWithNoStartTestRunStopTestRun()
2487 def test(self):
2488 pass
2489
2490 Foo('test').run()
2491
Georg Brandl15c5ce92007-03-07 09:09:40 +00002492 # "This class attribute gives the exception raised by the test() method.
2493 # If a test framework needs to use a specialized exception, possibly to
2494 # carry additional information, it must subclass this exception in
2495 # order to ``play fair'' with the framework. The initial value of this
2496 # attribute is AssertionError"
2497 def test_failureException__default(self):
2498 class Foo(unittest.TestCase):
2499 def test(self):
2500 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002501
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002502 self.assertTrue(Foo('test').failureException is AssertionError)
Tim Petersea5962f2007-03-12 18:07:52 +00002503
Georg Brandl15c5ce92007-03-07 09:09:40 +00002504 # "This class attribute gives the exception raised by the test() method.
2505 # If a test framework needs to use a specialized exception, possibly to
2506 # carry additional information, it must subclass this exception in
2507 # order to ``play fair'' with the framework."
2508 #
2509 # Make sure TestCase.run() respects the designated failureException
2510 def test_failureException__subclassing__explicit_raise(self):
2511 events = []
2512 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002513
Georg Brandl15c5ce92007-03-07 09:09:40 +00002514 class Foo(unittest.TestCase):
2515 def test(self):
2516 raise RuntimeError()
Tim Petersea5962f2007-03-12 18:07:52 +00002517
Georg Brandl15c5ce92007-03-07 09:09:40 +00002518 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002519
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002520 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002521
2522
Georg Brandl15c5ce92007-03-07 09:09:40 +00002523 Foo('test').run(result)
2524 expected = ['startTest', 'addFailure', 'stopTest']
2525 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002526
Georg Brandl15c5ce92007-03-07 09:09:40 +00002527 # "This class attribute gives the exception raised by the test() method.
2528 # If a test framework needs to use a specialized exception, possibly to
2529 # carry additional information, it must subclass this exception in
2530 # order to ``play fair'' with the framework."
2531 #
2532 # Make sure TestCase.run() respects the designated failureException
2533 def test_failureException__subclassing__implicit_raise(self):
2534 events = []
2535 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002536
Georg Brandl15c5ce92007-03-07 09:09:40 +00002537 class Foo(unittest.TestCase):
2538 def test(self):
2539 self.fail("foo")
Tim Petersea5962f2007-03-12 18:07:52 +00002540
Georg Brandl15c5ce92007-03-07 09:09:40 +00002541 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002542
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002543 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002544
2545
Georg Brandl15c5ce92007-03-07 09:09:40 +00002546 Foo('test').run(result)
2547 expected = ['startTest', 'addFailure', 'stopTest']
2548 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002549
2550 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002551 def test_setUp(self):
2552 class Foo(unittest.TestCase):
2553 def runTest(self):
2554 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002555
Georg Brandl15c5ce92007-03-07 09:09:40 +00002556 # ... and nothing should happen
2557 Foo().setUp()
Tim Petersea5962f2007-03-12 18:07:52 +00002558
2559 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002560 def test_tearDown(self):
2561 class Foo(unittest.TestCase):
2562 def runTest(self):
2563 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002564
Georg Brandl15c5ce92007-03-07 09:09:40 +00002565 # ... and nothing should happen
2566 Foo().tearDown()
Tim Petersea5962f2007-03-12 18:07:52 +00002567
Georg Brandl15c5ce92007-03-07 09:09:40 +00002568 # "Return a string identifying the specific test case."
2569 #
2570 # Because of the vague nature of the docs, I'm not going to lock this
2571 # test down too much. Really all that can be asserted is that the id()
2572 # will be a string (either 8-byte or unicode -- again, because the docs
2573 # just say "string")
2574 def test_id(self):
2575 class Foo(unittest.TestCase):
2576 def runTest(self):
2577 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002578
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002579 self.assertIsInstance(Foo().id(), basestring)
Tim Petersea5962f2007-03-12 18:07:52 +00002580
Georg Brandl15c5ce92007-03-07 09:09:40 +00002581 # "If result is omitted or None, a temporary result object is created
Michael Foord07ef4872009-05-02 22:43:34 +00002582 # and used, but is not made available to the caller. As TestCase owns the
2583 # temporary result startTestRun and stopTestRun are called.
2584
Georg Brandl15c5ce92007-03-07 09:09:40 +00002585 def test_run__uses_defaultTestResult(self):
2586 events = []
Tim Petersea5962f2007-03-12 18:07:52 +00002587
Georg Brandl15c5ce92007-03-07 09:09:40 +00002588 class Foo(unittest.TestCase):
2589 def test(self):
2590 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002591
Georg Brandl15c5ce92007-03-07 09:09:40 +00002592 def defaultTestResult(self):
2593 return LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002594
2595 # Make run() find a result object on its own
Georg Brandl15c5ce92007-03-07 09:09:40 +00002596 Foo('test').run()
Tim Petersea5962f2007-03-12 18:07:52 +00002597
Michael Foord07ef4872009-05-02 22:43:34 +00002598 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2599 'stopTest', 'stopTestRun']
Georg Brandl15c5ce92007-03-07 09:09:40 +00002600 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002601
Gregory P. Smith28399852009-03-31 16:54:10 +00002602 def testShortDescriptionWithoutDocstring(self):
Michael Foorddb43b5a2010-02-10 14:25:12 +00002603 self.assertIsNone(self.shortDescription())
Gregory P. Smith28399852009-03-31 16:54:10 +00002604
R. David Murrayf28fd242010-02-23 00:24:49 +00002605 @unittest.skipIf(sys.flags.optimize >= 2,
2606 "Docstrings are omitted with -O2 and above")
Gregory P. Smith28399852009-03-31 16:54:10 +00002607 def testShortDescriptionWithOneLineDocstring(self):
2608 """Tests shortDescription() for a method with a docstring."""
2609 self.assertEqual(
2610 self.shortDescription(),
Michael Foorddb43b5a2010-02-10 14:25:12 +00002611 'Tests shortDescription() for a method with a docstring.')
Gregory P. Smith28399852009-03-31 16:54:10 +00002612
R. David Murrayf28fd242010-02-23 00:24:49 +00002613 @unittest.skipIf(sys.flags.optimize >= 2,
2614 "Docstrings are omitted with -O2 and above")
Gregory P. Smith28399852009-03-31 16:54:10 +00002615 def testShortDescriptionWithMultiLineDocstring(self):
2616 """Tests shortDescription() for a method with a longer docstring.
2617
2618 This method ensures that only the first line of a docstring is
2619 returned used in the short description, no matter how long the
2620 whole thing is.
2621 """
2622 self.assertEqual(
2623 self.shortDescription(),
Gregory P. Smith28399852009-03-31 16:54:10 +00002624 'Tests shortDescription() for a method with a longer '
Michael Foorddb43b5a2010-02-10 14:25:12 +00002625 'docstring.')
Gregory P. Smith28399852009-03-31 16:54:10 +00002626
Gregory P. Smith28399852009-03-31 16:54:10 +00002627 def testAddTypeEqualityFunc(self):
2628 class SadSnake(object):
2629 """Dummy class for test_addTypeEqualityFunc."""
2630 s1, s2 = SadSnake(), SadSnake()
Michael Foord98e7b762010-03-20 03:00:34 +00002631 self.assertNotEqual(s1, s2)
Gregory P. Smith28399852009-03-31 16:54:10 +00002632 def AllSnakesCreatedEqual(a, b, msg=None):
Michael Foord98e7b762010-03-20 03:00:34 +00002633 return type(a) is type(b) is SadSnake
Gregory P. Smith28399852009-03-31 16:54:10 +00002634 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2635 self.assertEqual(s1, s2)
2636 # No this doesn't clean up and remove the SadSnake equality func
2637 # from this TestCase instance but since its a local nothing else
2638 # will ever notice that.
2639
Michael Foordf2dfef12009-04-05 19:19:28 +00002640 def testAssertIs(self):
2641 thing = object()
2642 self.assertIs(thing, thing)
2643 self.assertRaises(self.failureException, self.assertIs, thing, object())
2644
2645 def testAssertIsNot(self):
2646 thing = object()
2647 self.assertIsNot(thing, object())
2648 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2649
Georg Brandlf895cf52009-10-01 20:59:31 +00002650 def testAssertIsInstance(self):
2651 thing = []
2652 self.assertIsInstance(thing, list)
2653 self.assertRaises(self.failureException, self.assertIsInstance,
2654 thing, dict)
2655
2656 def testAssertNotIsInstance(self):
2657 thing = []
2658 self.assertNotIsInstance(thing, dict)
2659 self.assertRaises(self.failureException, self.assertNotIsInstance,
2660 thing, list)
2661
Gregory P. Smith28399852009-03-31 16:54:10 +00002662 def testAssertIn(self):
2663 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2664
2665 self.assertIn('a', 'abc')
2666 self.assertIn(2, [1, 2, 3])
2667 self.assertIn('monkey', animals)
2668
2669 self.assertNotIn('d', 'abc')
2670 self.assertNotIn(0, [1, 2, 3])
2671 self.assertNotIn('otter', animals)
2672
2673 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2674 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2675 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2676 animals)
2677
2678 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2679 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2680 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2681 animals)
2682
2683 def testAssertDictContainsSubset(self):
2684 self.assertDictContainsSubset({}, {})
2685 self.assertDictContainsSubset({}, {'a': 1})
2686 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2687 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2688 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2689
Michael Foord225a0992010-02-18 20:30:09 +00002690 with self.assertRaises(self.failureException):
2691 self.assertDictContainsSubset({1: "one"}, {})
Gregory P. Smith28399852009-03-31 16:54:10 +00002692
Michael Foord225a0992010-02-18 20:30:09 +00002693 with self.assertRaises(self.failureException):
2694 self.assertDictContainsSubset({'a': 2}, {'a': 1})
Gregory P. Smith28399852009-03-31 16:54:10 +00002695
Michael Foord225a0992010-02-18 20:30:09 +00002696 with self.assertRaises(self.failureException):
2697 self.assertDictContainsSubset({'c': 1}, {'a': 1})
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': 1, 'c': 1}, {'a': 1})
2701
2702 with self.assertRaises(self.failureException):
2703 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2704
Michael Foord2f677562010-02-21 14:48:59 +00002705 with warnings.catch_warnings(record=True):
2706 # silence the UnicodeWarning
2707 one = ''.join(chr(i) for i in range(255))
2708 # this used to cause a UnicodeDecodeError constructing the failure msg
2709 with self.assertRaises(self.failureException):
2710 self.assertDictContainsSubset({'foo': one}, {'foo': u'\uFFFD'})
Gregory P. Smith28399852009-03-31 16:54:10 +00002711
2712 def testAssertEqual(self):
2713 equal_pairs = [
2714 ((), ()),
2715 ({}, {}),
2716 ([], []),
2717 (set(), set()),
2718 (frozenset(), frozenset())]
2719 for a, b in equal_pairs:
2720 # This mess of try excepts is to test the assertEqual behavior
2721 # itself.
2722 try:
2723 self.assertEqual(a, b)
2724 except self.failureException:
2725 self.fail('assertEqual(%r, %r) failed' % (a, b))
2726 try:
2727 self.assertEqual(a, b, msg='foo')
2728 except self.failureException:
2729 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2730 try:
2731 self.assertEqual(a, b, 'foo')
2732 except self.failureException:
2733 self.fail('assertEqual(%r, %r) with third parameter failed' %
2734 (a, b))
2735
2736 unequal_pairs = [
2737 ((), []),
2738 ({}, set()),
2739 (set([4,1]), frozenset([4,2])),
2740 (frozenset([4,5]), set([2,3])),
2741 (set([3,4]), set([5,4]))]
2742 for a, b in unequal_pairs:
2743 self.assertRaises(self.failureException, self.assertEqual, a, b)
2744 self.assertRaises(self.failureException, self.assertEqual, a, b,
2745 'foo')
2746 self.assertRaises(self.failureException, self.assertEqual, a, b,
2747 msg='foo')
2748
2749 def testEquality(self):
2750 self.assertListEqual([], [])
2751 self.assertTupleEqual((), ())
2752 self.assertSequenceEqual([], ())
2753
2754 a = [0, 'a', []]
2755 b = []
2756 self.assertRaises(unittest.TestCase.failureException,
2757 self.assertListEqual, a, b)
2758 self.assertRaises(unittest.TestCase.failureException,
2759 self.assertListEqual, tuple(a), tuple(b))
2760 self.assertRaises(unittest.TestCase.failureException,
2761 self.assertSequenceEqual, a, tuple(b))
2762
2763 b.extend(a)
2764 self.assertListEqual(a, b)
2765 self.assertTupleEqual(tuple(a), tuple(b))
2766 self.assertSequenceEqual(a, tuple(b))
2767 self.assertSequenceEqual(tuple(a), b)
2768
2769 self.assertRaises(self.failureException, self.assertListEqual,
2770 a, tuple(b))
2771 self.assertRaises(self.failureException, self.assertTupleEqual,
2772 tuple(a), b)
2773 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2774 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2775 tuple(b))
2776 self.assertRaises(self.failureException, self.assertSequenceEqual,
2777 None, tuple(b))
2778 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2779 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2780 self.assertRaises(self.failureException, self.assertSequenceEqual,
2781 1, 1)
2782
2783 self.assertDictEqual({}, {})
2784
2785 c = { 'x': 1 }
2786 d = {}
2787 self.assertRaises(unittest.TestCase.failureException,
2788 self.assertDictEqual, c, d)
2789
2790 d.update(c)
2791 self.assertDictEqual(c, d)
2792
2793 d['x'] = 0
2794 self.assertRaises(unittest.TestCase.failureException,
2795 self.assertDictEqual, c, d, 'These are unequal')
2796
2797 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2798 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2799 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2800
Michael Foord98e7b762010-03-20 03:00:34 +00002801 def testAssertItemsEqual(self):
2802 a = object()
2803 self.assertItemsEqual([1, 2, 3], [3, 2, 1])
2804 self.assertItemsEqual(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2805 self.assertItemsEqual([a, a, 2, 2, 3], (a, 2, 3, a, 2))
2806 self.assertItemsEqual([1, "2", "a", "a"], ["a", "2", True, "a"])
2807 self.assertRaises(self.failureException, self.assertItemsEqual,
2808 [1, 2] + [3] * 100, [1] * 100 + [2, 3])
2809 self.assertRaises(self.failureException, self.assertItemsEqual,
2810 [1, "2", "a", "a"], ["a", "2", True, 1])
2811 self.assertRaises(self.failureException, self.assertItemsEqual,
Gregory P. Smith28399852009-03-31 16:54:10 +00002812 [10], [10, 11])
Michael Foord98e7b762010-03-20 03:00:34 +00002813 self.assertRaises(self.failureException, self.assertItemsEqual,
Gregory P. Smith28399852009-03-31 16:54:10 +00002814 [10, 11], [10])
Michael Foord98e7b762010-03-20 03:00:34 +00002815 self.assertRaises(self.failureException, self.assertItemsEqual,
2816 [10, 11, 10], [10, 11])
Gregory P. Smith28399852009-03-31 16:54:10 +00002817
2818 # Test that sequences of unhashable objects can be tested for sameness:
Michael Foord98e7b762010-03-20 03:00:34 +00002819 self.assertItemsEqual([[1, 2], [3, 4], 0], [False, [3, 4], [1, 2]])
2820 with test_support.check_warnings(quiet=True) as w:
2821 # hashable types, but not orderable
2822 self.assertRaises(self.failureException, self.assertItemsEqual,
2823 [], [divmod, 'x', 1, 5j, 2j, frozenset()])
2824 # comparing dicts raises a py3k warning
2825 self.assertItemsEqual([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2826 # comparing heterogenous non-hashable sequences raises a py3k warning
2827 self.assertItemsEqual([1, 'x', divmod, []], [divmod, [], 'x', 1])
2828 self.assertRaises(self.failureException, self.assertItemsEqual,
2829 [], [divmod, [], 'x', 1, 5j, 2j, set()])
2830 # fail the test if warnings are not silenced
2831 if w.warnings:
2832 self.fail('assertItemsEqual raised a warning: ' +
2833 str(w.warnings[0]))
2834 self.assertRaises(self.failureException, self.assertItemsEqual,
Gregory P. Smith28399852009-03-31 16:54:10 +00002835 [[1]], [[2]])
2836
Michael Foord98e7b762010-03-20 03:00:34 +00002837 # Same elements, but not same sequence length
2838 self.assertRaises(self.failureException, self.assertItemsEqual,
2839 [1, 1, 2], [2, 1])
2840 self.assertRaises(self.failureException, self.assertItemsEqual,
2841 [1, 1, "2", "a", "a"], ["2", "2", True, "a"])
2842 self.assertRaises(self.failureException, self.assertItemsEqual,
2843 [1, {'b': 2}, None, True], [{'b': 2}, True, None])
2844
2845
Gregory P. Smith28399852009-03-31 16:54:10 +00002846 def testAssertSetEqual(self):
2847 set1 = set()
2848 set2 = set()
2849 self.assertSetEqual(set1, set2)
2850
2851 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2852 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2853 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2854 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2855
2856 set1 = set(['a'])
2857 set2 = set()
2858 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2859
2860 set1 = set(['a'])
2861 set2 = set(['a'])
2862 self.assertSetEqual(set1, set2)
2863
2864 set1 = set(['a'])
2865 set2 = set(['a', 'b'])
2866 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2867
2868 set1 = set(['a'])
2869 set2 = frozenset(['a', 'b'])
2870 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2871
2872 set1 = set(['a', 'b'])
2873 set2 = frozenset(['a', 'b'])
2874 self.assertSetEqual(set1, set2)
2875
2876 set1 = set()
2877 set2 = "foo"
2878 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2879 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2880
2881 # make sure any string formatting is tuple-safe
2882 set1 = set([(0, 1), (2, 3)])
2883 set2 = set([(4, 5)])
2884 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2885
2886 def testInequality(self):
2887 # Try ints
2888 self.assertGreater(2, 1)
2889 self.assertGreaterEqual(2, 1)
2890 self.assertGreaterEqual(1, 1)
2891 self.assertLess(1, 2)
2892 self.assertLessEqual(1, 2)
2893 self.assertLessEqual(1, 1)
2894 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2895 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2896 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2897 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2898 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2899 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2900
2901 # Try Floats
2902 self.assertGreater(1.1, 1.0)
2903 self.assertGreaterEqual(1.1, 1.0)
2904 self.assertGreaterEqual(1.0, 1.0)
2905 self.assertLess(1.0, 1.1)
2906 self.assertLessEqual(1.0, 1.1)
2907 self.assertLessEqual(1.0, 1.0)
2908 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2909 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2910 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2911 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2912 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2913 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2914
2915 # Try Strings
2916 self.assertGreater('bug', 'ant')
2917 self.assertGreaterEqual('bug', 'ant')
2918 self.assertGreaterEqual('ant', 'ant')
2919 self.assertLess('ant', 'bug')
2920 self.assertLessEqual('ant', 'bug')
2921 self.assertLessEqual('ant', 'ant')
2922 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2923 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2924 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2925 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2926 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2927 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2928
2929 # Try Unicode
2930 self.assertGreater(u'bug', u'ant')
2931 self.assertGreaterEqual(u'bug', u'ant')
2932 self.assertGreaterEqual(u'ant', u'ant')
2933 self.assertLess(u'ant', u'bug')
2934 self.assertLessEqual(u'ant', u'bug')
2935 self.assertLessEqual(u'ant', u'ant')
2936 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug')
2937 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant')
2938 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2939 u'bug')
2940 self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant')
2941 self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant')
2942 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant')
2943
2944 # Try Mixed String/Unicode
2945 self.assertGreater('bug', u'ant')
2946 self.assertGreater(u'bug', 'ant')
2947 self.assertGreaterEqual('bug', u'ant')
2948 self.assertGreaterEqual(u'bug', 'ant')
2949 self.assertGreaterEqual('ant', u'ant')
2950 self.assertGreaterEqual(u'ant', 'ant')
2951 self.assertLess('ant', u'bug')
2952 self.assertLess(u'ant', 'bug')
2953 self.assertLessEqual('ant', u'bug')
2954 self.assertLessEqual(u'ant', 'bug')
2955 self.assertLessEqual('ant', u'ant')
2956 self.assertLessEqual(u'ant', 'ant')
2957 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug')
2958 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug')
2959 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant')
2960 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant')
2961 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant',
2962 u'bug')
2963 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2964 'bug')
2965 self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant')
2966 self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant')
2967 self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant')
2968 self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant')
2969 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant')
2970 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant')
2971
2972 def testAssertMultiLineEqual(self):
2973 sample_text = b"""\
2974http://www.python.org/doc/2.3/lib/module-unittest.html
2975test case
2976 A test case is the smallest unit of testing. [...]
2977"""
2978 revised_sample_text = b"""\
2979http://www.python.org/doc/2.4.1/lib/module-unittest.html
2980test case
2981 A test case is the smallest unit of testing. [...] You may provide your
2982 own implementation that does not subclass from TestCase, of course.
2983"""
2984 sample_text_error = b"""
2985- http://www.python.org/doc/2.3/lib/module-unittest.html
2986? ^
2987+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2988? ^^^
2989 test case
2990- A test case is the smallest unit of testing. [...]
2991+ A test case is the smallest unit of testing. [...] You may provide your
2992? +++++++++++++++++++++
2993+ own implementation that does not subclass from TestCase, of course.
2994"""
2995
2996 for type_changer in (lambda x: x, lambda x: x.decode('utf8')):
2997 try:
2998 self.assertMultiLineEqual(type_changer(sample_text),
2999 type_changer(revised_sample_text))
3000 except self.failureException, e:
Michael Foordfe6349c2010-02-08 22:41:16 +00003001 # assertMultiLineEqual is hooked up as the default for
3002 # unicode strings - so we can't use it for this check
3003 self.assertTrue(sample_text_error == str(e).encode('utf8'))
Gregory P. Smith28399852009-03-31 16:54:10 +00003004
3005 def testAssertIsNone(self):
3006 self.assertIsNone(None)
3007 self.assertRaises(self.failureException, self.assertIsNone, False)
3008 self.assertIsNotNone('DjZoPloGears on Rails')
3009 self.assertRaises(self.failureException, self.assertIsNotNone, None)
3010
3011 def testAssertRegexpMatches(self):
3012 self.assertRegexpMatches('asdfabasdf', r'ab+')
3013 self.assertRaises(self.failureException, self.assertRegexpMatches,
3014 'saaas', r'aaaa')
3015
3016 def testAssertRaisesRegexp(self):
3017 class ExceptionMock(Exception):
3018 pass
3019
3020 def Stub():
3021 raise ExceptionMock('We expect')
3022
3023 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
3024 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
3025 self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
3026
3027 def testAssertNotRaisesRegexp(self):
3028 self.assertRaisesRegexp(
3029 self.failureException, '^Exception not raised$',
3030 self.assertRaisesRegexp, Exception, re.compile('x'),
3031 lambda: None)
3032 self.assertRaisesRegexp(
3033 self.failureException, '^Exception not raised$',
3034 self.assertRaisesRegexp, Exception, 'x',
3035 lambda: None)
3036 self.assertRaisesRegexp(
3037 self.failureException, '^Exception not raised$',
3038 self.assertRaisesRegexp, Exception, u'x',
3039 lambda: None)
3040
3041 def testAssertRaisesRegexpMismatch(self):
3042 def Stub():
3043 raise Exception('Unexpected')
3044
3045 self.assertRaisesRegexp(
3046 self.failureException,
3047 r'"\^Expected\$" does not match "Unexpected"',
3048 self.assertRaisesRegexp, Exception, '^Expected$',
3049 Stub)
3050 self.assertRaisesRegexp(
3051 self.failureException,
3052 r'"\^Expected\$" does not match "Unexpected"',
3053 self.assertRaisesRegexp, Exception, u'^Expected$',
3054 Stub)
3055 self.assertRaisesRegexp(
3056 self.failureException,
3057 r'"\^Expected\$" does not match "Unexpected"',
3058 self.assertRaisesRegexp, Exception,
3059 re.compile('^Expected$'), Stub)
3060
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00003061 def testAssertRaisesExcValue(self):
3062 class ExceptionMock(Exception):
3063 pass
3064
3065 def Stub(foo):
3066 raise ExceptionMock(foo)
3067 v = "particular value"
3068
3069 ctx = self.assertRaises(ExceptionMock)
3070 with ctx:
3071 Stub(v)
Georg Brandldc3694b2010-02-07 17:02:22 +00003072 e = ctx.exception
Ezio Melottib0f5adc2010-01-24 16:58:36 +00003073 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00003074 self.assertEqual(e.args[0], v)
3075
Gregory P. Smith7558d572009-03-31 19:03:28 +00003076 def testSynonymAssertMethodNames(self):
3077 """Test undocumented method name synonyms.
3078
3079 Please do not use these methods names in your own code.
3080
3081 This test confirms their continued existence and functionality
3082 in order to avoid breaking existing code.
3083 """
3084 self.assertNotEquals(3, 5)
3085 self.assertEquals(3, 3)
3086 self.assertAlmostEquals(2.0, 2.0)
3087 self.assertNotAlmostEquals(3.0, 5.0)
3088 self.assert_(True)
3089
3090 def testPendingDeprecationMethodNames(self):
3091 """Test fail* methods pending deprecation, they will warn in 3.2.
3092
3093 Do not use these methods. They will go away in 3.3.
3094 """
Michael Foord98e7b762010-03-20 03:00:34 +00003095 with test_support.check_warnings():
3096 self.failIfEqual(3, 5)
3097 self.failUnlessEqual(3, 3)
3098 self.failUnlessAlmostEqual(2.0, 2.0)
3099 self.failIfAlmostEqual(3.0, 5.0)
3100 self.failUnless(True)
3101 self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam')
3102 self.failIf(False)
Gregory P. Smith7558d572009-03-31 19:03:28 +00003103
Michael Foorde2942d02009-04-02 05:51:54 +00003104 def testDeepcopy(self):
3105 # Issue: 5660
3106 class TestableTest(TestCase):
3107 def testNothing(self):
3108 pass
3109
3110 test = TestableTest('testNothing')
3111
3112 # This shouldn't blow up
3113 deepcopy(test)
3114
Benjamin Peterson692428e2009-03-23 21:50:21 +00003115
3116class Test_TestSkipping(TestCase):
3117
3118 def test_skipping(self):
3119 class Foo(unittest.TestCase):
3120 def test_skip_me(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00003121 self.skipTest("skip")
Benjamin Peterson692428e2009-03-23 21:50:21 +00003122 events = []
3123 result = LoggingResult(events)
3124 test = Foo("test_skip_me")
3125 test.run(result)
3126 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3127 self.assertEqual(result.skipped, [(test, "skip")])
3128
3129 # Try letting setUp skip the test now.
3130 class Foo(unittest.TestCase):
3131 def setUp(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00003132 self.skipTest("testing")
Benjamin Peterson692428e2009-03-23 21:50:21 +00003133 def test_nothing(self): pass
3134 events = []
3135 result = LoggingResult(events)
3136 test = Foo("test_nothing")
3137 test.run(result)
3138 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3139 self.assertEqual(result.skipped, [(test, "testing")])
3140 self.assertEqual(result.testsRun, 1)
3141
3142 def test_skipping_decorators(self):
3143 op_table = ((unittest.skipUnless, False, True),
3144 (unittest.skipIf, True, False))
3145 for deco, do_skip, dont_skip in op_table:
3146 class Foo(unittest.TestCase):
3147 @deco(do_skip, "testing")
3148 def test_skip(self): pass
3149
3150 @deco(dont_skip, "testing")
3151 def test_dont_skip(self): pass
3152 test_do_skip = Foo("test_skip")
3153 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003154 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003155 events = []
3156 result = LoggingResult(events)
3157 suite.run(result)
3158 self.assertEqual(len(result.skipped), 1)
3159 expected = ['startTest', 'addSkip', 'stopTest',
3160 'startTest', 'addSuccess', 'stopTest']
3161 self.assertEqual(events, expected)
3162 self.assertEqual(result.testsRun, 2)
3163 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
3164 self.assertTrue(result.wasSuccessful())
3165
3166 def test_skip_class(self):
3167 @unittest.skip("testing")
3168 class Foo(unittest.TestCase):
3169 def test_1(self):
3170 record.append(1)
3171 record = []
3172 result = unittest.TestResult()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003173 test = Foo("test_1")
3174 suite = unittest.TestSuite([test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003175 suite.run(result)
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003176 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003177 self.assertEqual(record, [])
3178
3179 def test_expected_failure(self):
3180 class Foo(unittest.TestCase):
3181 @unittest.expectedFailure
3182 def test_die(self):
3183 self.fail("help me!")
3184 events = []
3185 result = LoggingResult(events)
3186 test = Foo("test_die")
3187 test.run(result)
3188 self.assertEqual(events,
3189 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003190 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00003191 self.assertTrue(result.wasSuccessful())
3192
3193 def test_unexpected_success(self):
3194 class Foo(unittest.TestCase):
3195 @unittest.expectedFailure
3196 def test_die(self):
3197 pass
3198 events = []
3199 result = LoggingResult(events)
3200 test = Foo("test_die")
3201 test.run(result)
3202 self.assertEqual(events,
3203 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3204 self.assertFalse(result.failures)
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003205 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003206 self.assertTrue(result.wasSuccessful())
3207
Michael Foord53e8eea2010-03-07 20:22:12 +00003208 def test_skip_doesnt_run_setup(self):
3209 class Foo(unittest.TestCase):
3210 wasSetUp = False
3211 wasTornDown = False
3212 def setUp(self):
3213 Foo.wasSetUp = True
3214 def tornDown(self):
3215 Foo.wasTornDown = True
3216 @unittest.skip('testing')
3217 def test_1(self):
3218 pass
3219
3220 result = unittest.TestResult()
3221 test = Foo("test_1")
3222 suite = unittest.TestSuite([test])
3223 suite.run(result)
3224 self.assertEqual(result.skipped, [(test, "testing")])
3225 self.assertFalse(Foo.wasSetUp)
3226 self.assertFalse(Foo.wasTornDown)
3227
3228 def test_decorated_skip(self):
3229 def decorator(func):
3230 def inner(*a):
3231 return func(*a)
3232 return inner
3233
3234 class Foo(unittest.TestCase):
3235 @decorator
3236 @unittest.skip('testing')
3237 def test_1(self):
3238 pass
3239
3240 result = unittest.TestResult()
3241 test = Foo("test_1")
3242 suite = unittest.TestSuite([test])
3243 suite.run(result)
3244 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003245
3246
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003247class Test_Assertions(TestCase):
3248 def test_AlmostEqual(self):
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003249 self.assertAlmostEqual(1.00000001, 1.0)
3250 self.assertNotAlmostEqual(1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003251 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003252 self.assertAlmostEqual, 1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003253 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003254 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003255
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003256 self.assertAlmostEqual(1.1, 1.0, places=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.1, 1.0, places=1)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003259
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003260 self.assertAlmostEqual(0, .1+.1j, places=0)
3261 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003262 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003263 self.assertAlmostEqual, 0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003264 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003265 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003266
Michael Foordc3f79372009-09-13 16:40:02 +00003267 self.assertAlmostEqual(float('inf'), float('inf'))
3268 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3269 float('inf'), float('inf'))
3270
3271
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003272 def test_assertRaises(self):
3273 def _raise(e):
3274 raise e
3275 self.assertRaises(KeyError, _raise, KeyError)
3276 self.assertRaises(KeyError, _raise, KeyError("key"))
3277 try:
3278 self.assertRaises(KeyError, lambda: None)
Gregory P. Smith28399852009-03-31 16:54:10 +00003279 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003280 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003281 else:
3282 self.fail("assertRaises() didn't fail")
3283 try:
3284 self.assertRaises(KeyError, _raise, ValueError)
3285 except ValueError:
3286 pass
3287 else:
3288 self.fail("assertRaises() didn't let exception pass through")
Michael Foord2bd52dc2010-02-07 18:44:12 +00003289 with self.assertRaises(KeyError) as cm:
3290 try:
3291 raise KeyError
3292 except Exception, e:
3293 raise
3294 self.assertIs(cm.exception, e)
3295
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003296 with self.assertRaises(KeyError):
3297 raise KeyError("key")
3298 try:
3299 with self.assertRaises(KeyError):
3300 pass
Gregory P. Smith28399852009-03-31 16:54:10 +00003301 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003302 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003303 else:
3304 self.fail("assertRaises() didn't fail")
3305 try:
3306 with self.assertRaises(KeyError):
3307 raise ValueError
3308 except ValueError:
3309 pass
3310 else:
3311 self.fail("assertRaises() didn't let exception pass through")
3312
3313
Michael Foord345b2fe2009-04-02 03:20:38 +00003314class TestLongMessage(TestCase):
3315 """Test that the individual asserts honour longMessage.
3316 This actually tests all the message behaviour for
3317 asserts that use longMessage."""
3318
3319 def setUp(self):
3320 class TestableTestFalse(TestCase):
3321 longMessage = False
3322 failureException = self.failureException
3323
3324 def testTest(self):
3325 pass
3326
3327 class TestableTestTrue(TestCase):
3328 longMessage = True
3329 failureException = self.failureException
3330
3331 def testTest(self):
3332 pass
3333
3334 self.testableTrue = TestableTestTrue('testTest')
3335 self.testableFalse = TestableTestFalse('testTest')
3336
3337 def testDefault(self):
3338 self.assertFalse(TestCase.longMessage)
3339
3340 def test_formatMsg(self):
3341 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3342 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3343
3344 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3345 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3346
Michael Foord53e8eea2010-03-07 20:22:12 +00003347 # This blows up if _formatMessage uses string concatenation
3348 self.testableTrue._formatMessage(object(), 'foo')
3349
3350 def test_formatMessage_unicode_error(self):
3351 with warnings.catch_warnings(record=True):
3352 # This causes a UnicodeWarning due to its craziness
3353 one = ''.join(chr(i) for i in range(255))
3354 # this used to cause a UnicodeDecodeError constructing msg
3355 self.testableTrue._formatMessage(one, u'\uFFFD')
3356
Michael Foord345b2fe2009-04-02 03:20:38 +00003357 def assertMessages(self, methodName, args, errors):
3358 def getMethod(i):
3359 useTestableFalse = i < 2
3360 if useTestableFalse:
3361 test = self.testableFalse
3362 else:
3363 test = self.testableTrue
3364 return getattr(test, methodName)
3365
3366 for i, expected_regexp in enumerate(errors):
3367 testMethod = getMethod(i)
3368 kwargs = {}
3369 withMsg = i % 2
3370 if withMsg:
3371 kwargs = {"msg": "oops"}
3372
3373 with self.assertRaisesRegexp(self.failureException,
3374 expected_regexp=expected_regexp):
3375 testMethod(*args, **kwargs)
3376
3377 def testAssertTrue(self):
3378 self.assertMessages('assertTrue', (False,),
3379 ["^False is not True$", "^oops$", "^False is not True$",
3380 "^False is not True : oops$"])
3381
3382 def testAssertFalse(self):
3383 self.assertMessages('assertFalse', (True,),
3384 ["^True is not False$", "^oops$", "^True is not False$",
3385 "^True is not False : oops$"])
3386
3387 def testNotEqual(self):
3388 self.assertMessages('assertNotEqual', (1, 1),
3389 ["^1 == 1$", "^oops$", "^1 == 1$",
3390 "^1 == 1 : oops$"])
3391
3392 def testAlmostEqual(self):
3393 self.assertMessages('assertAlmostEqual', (1, 2),
3394 ["^1 != 2 within 7 places$", "^oops$",
3395 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3396
3397 def testNotAlmostEqual(self):
3398 self.assertMessages('assertNotAlmostEqual', (1, 1),
3399 ["^1 == 1 within 7 places$", "^oops$",
3400 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3401
3402 def test_baseAssertEqual(self):
3403 self.assertMessages('_baseAssertEqual', (1, 2),
3404 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3405
3406 def testAssertSequenceEqual(self):
3407 # Error messages are multiline so not testing on full message
3408 # assertTupleEqual and assertListEqual delegate to this method
3409 self.assertMessages('assertSequenceEqual', ([], [None]),
3410 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3411 r"\+ \[None\] : oops$"])
3412
3413 def testAssertSetEqual(self):
3414 self.assertMessages('assertSetEqual', (set(), set([None])),
3415 ["None$", "^oops$", "None$",
3416 "None : oops$"])
3417
3418 def testAssertIn(self):
3419 self.assertMessages('assertIn', (None, []),
3420 ['^None not found in \[\]$', "^oops$",
3421 '^None not found in \[\]$',
3422 '^None not found in \[\] : oops$'])
3423
3424 def testAssertNotIn(self):
3425 self.assertMessages('assertNotIn', (None, [None]),
3426 ['^None unexpectedly found in \[None\]$', "^oops$",
3427 '^None unexpectedly found in \[None\]$',
3428 '^None unexpectedly found in \[None\] : oops$'])
3429
3430 def testAssertDictEqual(self):
3431 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3432 [r"\+ \{'key': 'value'\}$", "^oops$",
3433 "\+ \{'key': 'value'\}$",
3434 "\+ \{'key': 'value'\} : oops$"])
3435
3436 def testAssertDictContainsSubset(self):
3437 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3438 ["^Missing: 'key'$", "^oops$",
3439 "^Missing: 'key'$",
3440 "^Missing: 'key' : oops$"])
3441
Michael Foord98e7b762010-03-20 03:00:34 +00003442 def testAssertItemsEqual(self):
3443 self.assertMessages('assertItemsEqual', ([], [None]),
Michael Foord345b2fe2009-04-02 03:20:38 +00003444 [r"\[None\]$", "^oops$",
3445 r"\[None\]$",
3446 r"\[None\] : oops$"])
3447
3448 def testAssertMultiLineEqual(self):
3449 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3450 [r"\+ foo$", "^oops$",
3451 r"\+ foo$",
3452 r"\+ foo : oops$"])
3453
3454 def testAssertLess(self):
3455 self.assertMessages('assertLess', (2, 1),
3456 ["^2 not less than 1$", "^oops$",
3457 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3458
3459 def testAssertLessEqual(self):
3460 self.assertMessages('assertLessEqual', (2, 1),
3461 ["^2 not less than or equal to 1$", "^oops$",
3462 "^2 not less than or equal to 1$",
3463 "^2 not less than or equal to 1 : oops$"])
3464
3465 def testAssertGreater(self):
3466 self.assertMessages('assertGreater', (1, 2),
3467 ["^1 not greater than 2$", "^oops$",
3468 "^1 not greater than 2$",
3469 "^1 not greater than 2 : oops$"])
3470
3471 def testAssertGreaterEqual(self):
3472 self.assertMessages('assertGreaterEqual', (1, 2),
3473 ["^1 not greater than or equal to 2$", "^oops$",
3474 "^1 not greater than or equal to 2$",
3475 "^1 not greater than or equal to 2 : oops$"])
3476
3477 def testAssertIsNone(self):
3478 self.assertMessages('assertIsNone', ('not None',),
3479 ["^'not None' is not None$", "^oops$",
3480 "^'not None' is not None$",
3481 "^'not None' is not None : oops$"])
3482
3483 def testAssertIsNotNone(self):
3484 self.assertMessages('assertIsNotNone', (None,),
3485 ["^unexpectedly None$", "^oops$",
3486 "^unexpectedly None$",
3487 "^unexpectedly None : oops$"])
3488
Michael Foordf2dfef12009-04-05 19:19:28 +00003489 def testAssertIs(self):
3490 self.assertMessages('assertIs', (None, 'foo'),
3491 ["^None is not 'foo'$", "^oops$",
3492 "^None is not 'foo'$",
3493 "^None is not 'foo' : oops$"])
3494
3495 def testAssertIsNot(self):
3496 self.assertMessages('assertIsNot', (None, None),
3497 ["^unexpectedly identical: None$", "^oops$",
3498 "^unexpectedly identical: None$",
3499 "^unexpectedly identical: None : oops$"])
3500
Michael Foord345b2fe2009-04-02 03:20:38 +00003501
Michael Foorde2fb98f2009-05-02 20:15:05 +00003502class TestCleanUp(TestCase):
3503
3504 def testCleanUp(self):
3505 class TestableTest(TestCase):
3506 def testNothing(self):
3507 pass
3508
3509 test = TestableTest('testNothing')
3510 self.assertEqual(test._cleanups, [])
3511
3512 cleanups = []
3513
3514 def cleanup1(*args, **kwargs):
3515 cleanups.append((1, args, kwargs))
3516
3517 def cleanup2(*args, **kwargs):
3518 cleanups.append((2, args, kwargs))
3519
3520 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3521 test.addCleanup(cleanup2)
3522
3523 self.assertEqual(test._cleanups,
3524 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3525 (cleanup2, (), {})])
3526
3527 result = test.doCleanups()
3528 self.assertTrue(result)
3529
3530 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3531
3532 def testCleanUpWithErrors(self):
3533 class TestableTest(TestCase):
3534 def testNothing(self):
3535 pass
3536
3537 class MockResult(object):
3538 errors = []
3539 def addError(self, test, exc_info):
3540 self.errors.append((test, exc_info))
3541
3542 result = MockResult()
3543 test = TestableTest('testNothing')
Michael Foorda50af062009-05-21 22:57:02 +00003544 test._resultForDoCleanups = result
Michael Foorde2fb98f2009-05-02 20:15:05 +00003545
3546 exc1 = Exception('foo')
3547 exc2 = Exception('bar')
3548 def cleanup1():
3549 raise exc1
3550
3551 def cleanup2():
3552 raise exc2
3553
3554 test.addCleanup(cleanup1)
3555 test.addCleanup(cleanup2)
3556
3557 self.assertFalse(test.doCleanups())
3558
3559 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3560 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3561 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3562
3563 def testCleanupInRun(self):
3564 blowUp = False
3565 ordering = []
3566
3567 class TestableTest(TestCase):
3568 def setUp(self):
3569 ordering.append('setUp')
3570 if blowUp:
3571 raise Exception('foo')
3572
3573 def testNothing(self):
3574 ordering.append('test')
3575
3576 def tearDown(self):
3577 ordering.append('tearDown')
3578
3579 test = TestableTest('testNothing')
3580
3581 def cleanup1():
3582 ordering.append('cleanup1')
3583 def cleanup2():
3584 ordering.append('cleanup2')
3585 test.addCleanup(cleanup1)
3586 test.addCleanup(cleanup2)
3587
3588 def success(some_test):
3589 self.assertEqual(some_test, test)
3590 ordering.append('success')
3591
3592 result = unittest.TestResult()
3593 result.addSuccess = success
3594
3595 test.run(result)
3596 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3597 'cleanup2', 'cleanup1', 'success'])
3598
3599 blowUp = True
3600 ordering = []
3601 test = TestableTest('testNothing')
3602 test.addCleanup(cleanup1)
3603 test.run(result)
3604 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3605
3606
Michael Foord829f6b82009-05-02 11:43:06 +00003607class Test_TestProgram(TestCase):
3608
3609 # Horrible white box test
3610 def testNoExit(self):
3611 result = object()
3612 test = object()
3613
3614 class FakeRunner(object):
3615 def run(self, test):
3616 self.test = test
3617 return result
3618
3619 runner = FakeRunner()
3620
Michael Foord5d31e052009-05-11 17:59:43 +00003621 oldParseArgs = TestProgram.parseArgs
3622 def restoreParseArgs():
Michael Foord829f6b82009-05-02 11:43:06 +00003623 TestProgram.parseArgs = oldParseArgs
Michael Foord5d31e052009-05-11 17:59:43 +00003624 TestProgram.parseArgs = lambda *args: None
3625 self.addCleanup(restoreParseArgs)
3626
3627 def removeTest():
Michael Foord829f6b82009-05-02 11:43:06 +00003628 del TestProgram.test
Michael Foord5d31e052009-05-11 17:59:43 +00003629 TestProgram.test = test
3630 self.addCleanup(removeTest)
3631
3632 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3633
3634 self.assertEqual(program.result, result)
3635 self.assertEqual(runner.test, test)
3636 self.assertEqual(program.verbosity, 2)
Michael Foord829f6b82009-05-02 11:43:06 +00003637
Michael Foord829f6b82009-05-02 11:43:06 +00003638 class FooBar(unittest.TestCase):
3639 def testPass(self):
3640 assert True
3641 def testFail(self):
3642 assert False
3643
3644 class FooBarLoader(unittest.TestLoader):
3645 """Test loader that returns a suite containing FooBar."""
3646 def loadTestsFromModule(self, module):
3647 return self.suiteClass(
3648 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3649
3650
3651 def test_NonExit(self):
3652 program = unittest.main(exit=False,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003653 argv=["foobar"],
3654 testRunner=unittest.TextTestRunner(stream=StringIO()),
3655 testLoader=self.FooBarLoader())
Michael Foord829f6b82009-05-02 11:43:06 +00003656 self.assertTrue(hasattr(program, 'result'))
3657
3658
3659 def test_Exit(self):
3660 self.assertRaises(
3661 SystemExit,
3662 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003663 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003664 testRunner=unittest.TextTestRunner(stream=StringIO()),
3665 exit=True,
3666 testLoader=self.FooBarLoader())
3667
3668
3669 def test_ExitAsDefault(self):
3670 self.assertRaises(
3671 SystemExit,
3672 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003673 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003674 testRunner=unittest.TextTestRunner(stream=StringIO()),
3675 testLoader=self.FooBarLoader())
3676
3677
Michael Foord07ef4872009-05-02 22:43:34 +00003678class Test_TextTestRunner(TestCase):
3679 """Tests for TextTestRunner."""
3680
3681 def test_works_with_result_without_startTestRun_stopTestRun(self):
3682 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3683 separator2 = ''
3684 def printErrors(self):
3685 pass
3686
3687 class Runner(unittest.TextTestRunner):
3688 def __init__(self):
3689 super(Runner, self).__init__(StringIO())
3690
3691 def _makeResult(self):
3692 return OldTextResult()
3693
3694 runner = Runner()
3695 runner.run(unittest.TestSuite())
3696
3697 def test_startTestRun_stopTestRun_called(self):
3698 class LoggingTextResult(LoggingResult):
3699 separator2 = ''
3700 def printErrors(self):
3701 pass
3702
3703 class LoggingRunner(unittest.TextTestRunner):
3704 def __init__(self, events):
3705 super(LoggingRunner, self).__init__(StringIO())
3706 self._events = events
3707
3708 def _makeResult(self):
3709 return LoggingTextResult(self._events)
3710
3711 events = []
3712 runner = LoggingRunner(events)
3713 runner.run(unittest.TestSuite())
3714 expected = ['startTestRun', 'stopTestRun']
3715 self.assertEqual(events, expected)
3716
Antoine Pitrou0734c632009-11-10 20:49:30 +00003717 def test_pickle_unpickle(self):
3718 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3719 # required by test_multiprocessing under Windows (in verbose mode).
3720 import StringIO
3721 # cStringIO objects are not pickleable, but StringIO objects are.
3722 stream = StringIO.StringIO("foo")
3723 runner = unittest.TextTestRunner(stream)
3724 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
3725 s = pickle.dumps(runner, protocol=protocol)
3726 obj = pickle.loads(s)
3727 # StringIO objects never compare equal, a cheap test instead.
3728 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3729
Michael Foorddb43b5a2010-02-10 14:25:12 +00003730 def test_resultclass(self):
3731 def MockResultClass(*args):
3732 return args
3733 STREAM = object()
3734 DESCRIPTIONS = object()
3735 VERBOSITY = object()
3736 runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY,
3737 resultclass=MockResultClass)
3738 self.assertEqual(runner.resultclass, MockResultClass)
3739
3740 expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY)
3741 self.assertEqual(runner._makeResult(), expectedresult)
3742
Michael Foord07ef4872009-05-02 22:43:34 +00003743
Michael Foordb4a81c82009-05-29 20:33:46 +00003744class TestDiscovery(TestCase):
3745
3746 # Heavily mocked tests so I can avoid hitting the filesystem
Michael Foorde91ea562009-09-13 19:07:03 +00003747 def test_get_name_from_path(self):
Michael Foordb4a81c82009-05-29 20:33:46 +00003748 loader = unittest.TestLoader()
3749
Michael Foordb4a81c82009-05-29 20:33:46 +00003750 loader._top_level_dir = '/foo'
Michael Foorde91ea562009-09-13 19:07:03 +00003751 name = loader._get_name_from_path('/foo/bar/baz.py')
3752 self.assertEqual(name, 'bar.baz')
Michael Foordb4a81c82009-05-29 20:33:46 +00003753
3754 if not __debug__:
3755 # asserts are off
3756 return
3757
3758 with self.assertRaises(AssertionError):
Michael Foorde91ea562009-09-13 19:07:03 +00003759 loader._get_name_from_path('/bar/baz.py')
Michael Foordb4a81c82009-05-29 20:33:46 +00003760
3761 def test_find_tests(self):
3762 loader = unittest.TestLoader()
3763
3764 original_listdir = os.listdir
3765 def restore_listdir():
3766 os.listdir = original_listdir
3767 original_isfile = os.path.isfile
3768 def restore_isfile():
3769 os.path.isfile = original_isfile
3770 original_isdir = os.path.isdir
3771 def restore_isdir():
3772 os.path.isdir = original_isdir
3773
3774 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Michael Foorde91ea562009-09-13 19:07:03 +00003775 'test.foo', 'test-not-a-module.py', 'another_dir'],
Michael Foordb4a81c82009-05-29 20:33:46 +00003776 ['test3.py', 'test4.py', ]]
3777 os.listdir = lambda path: path_lists.pop(0)
3778 self.addCleanup(restore_listdir)
3779
3780 def isdir(path):
3781 return path.endswith('dir')
3782 os.path.isdir = isdir
3783 self.addCleanup(restore_isdir)
3784
3785 def isfile(path):
3786 # another_dir is not a package and so shouldn't be recursed into
3787 return not path.endswith('dir') and not 'another_dir' in path
3788 os.path.isfile = isfile
3789 self.addCleanup(restore_isfile)
3790
Michael Foorde91ea562009-09-13 19:07:03 +00003791 loader._get_module_from_name = lambda path: path + ' module'
Michael Foordb4a81c82009-05-29 20:33:46 +00003792 loader.loadTestsFromModule = lambda module: module + ' tests'
3793
3794 loader._top_level_dir = '/foo'
3795 suite = list(loader._find_tests('/foo', 'test*.py'))
3796
Michael Foorde91ea562009-09-13 19:07:03 +00003797 expected = [name + ' module tests' for name in
3798 ('test1', 'test2')]
3799 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3800 ('test3', 'test4')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003801 self.assertEqual(suite, expected)
3802
3803 def test_find_tests_with_package(self):
3804 loader = unittest.TestLoader()
3805
3806 original_listdir = os.listdir
3807 def restore_listdir():
3808 os.listdir = original_listdir
3809 original_isfile = os.path.isfile
3810 def restore_isfile():
3811 os.path.isfile = original_isfile
3812 original_isdir = os.path.isdir
3813 def restore_isdir():
3814 os.path.isdir = original_isdir
3815
3816 directories = ['a_directory', 'test_directory', 'test_directory2']
3817 path_lists = [directories, [], [], []]
3818 os.listdir = lambda path: path_lists.pop(0)
3819 self.addCleanup(restore_listdir)
3820
3821 os.path.isdir = lambda path: True
3822 self.addCleanup(restore_isdir)
3823
3824 os.path.isfile = lambda path: os.path.basename(path) not in directories
3825 self.addCleanup(restore_isfile)
3826
3827 class Module(object):
3828 paths = []
3829 load_tests_args = []
3830
3831 def __init__(self, path):
3832 self.path = path
3833 self.paths.append(path)
3834 if os.path.basename(path) == 'test_directory':
3835 def load_tests(loader, tests, pattern):
3836 self.load_tests_args.append((loader, tests, pattern))
3837 return 'load_tests'
3838 self.load_tests = load_tests
3839
3840 def __eq__(self, other):
3841 return self.path == other.path
3842
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003843 # Silence py3k warning
3844 __hash__ = None
3845
Michael Foorde91ea562009-09-13 19:07:03 +00003846 loader._get_module_from_name = lambda name: Module(name)
Michael Foordb4a81c82009-05-29 20:33:46 +00003847 def loadTestsFromModule(module, use_load_tests):
3848 if use_load_tests:
3849 raise self.failureException('use_load_tests should be False for packages')
3850 return module.path + ' module tests'
3851 loader.loadTestsFromModule = loadTestsFromModule
3852
3853 loader._top_level_dir = '/foo'
3854 # this time no '.py' on the pattern so that it can match
3855 # a test package
3856 suite = list(loader._find_tests('/foo', 'test*'))
3857
3858 # We should have loaded tests from the test_directory package by calling load_tests
3859 # and directly from the test_directory2 package
Michael Foordd53d0852009-06-05 14:14:34 +00003860 self.assertEqual(suite,
Michael Foorde91ea562009-09-13 19:07:03 +00003861 ['load_tests', 'test_directory2' + ' module tests'])
3862 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Michael Foordb4a81c82009-05-29 20:33:46 +00003863
3864 # load_tests should have been called once with loader, tests and pattern
3865 self.assertEqual(Module.load_tests_args,
Michael Foorde91ea562009-09-13 19:07:03 +00003866 [(loader, 'test_directory' + ' module tests', 'test*')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003867
3868 def test_discover(self):
3869 loader = unittest.TestLoader()
3870
3871 original_isfile = os.path.isfile
3872 def restore_isfile():
3873 os.path.isfile = original_isfile
3874
3875 os.path.isfile = lambda path: False
3876 self.addCleanup(restore_isfile)
3877
Nick Coghlanb6edf192009-10-17 08:21:21 +00003878 orig_sys_path = sys.path[:]
3879 def restore_path():
3880 sys.path[:] = orig_sys_path
3881 self.addCleanup(restore_path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003882
Nick Coghlanb6edf192009-10-17 08:21:21 +00003883 full_path = os.path.abspath(os.path.normpath('/foo'))
Michael Foordb4a81c82009-05-29 20:33:46 +00003884 with self.assertRaises(ImportError):
3885 loader.discover('/foo/bar', top_level_dir='/foo')
3886
3887 self.assertEqual(loader._top_level_dir, full_path)
3888 self.assertIn(full_path, sys.path)
3889
3890 os.path.isfile = lambda path: True
3891 _find_tests_args = []
3892 def _find_tests(start_dir, pattern):
3893 _find_tests_args.append((start_dir, pattern))
3894 return ['tests']
3895 loader._find_tests = _find_tests
3896 loader.suiteClass = str
3897
3898 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3899
3900 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3901 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3902 self.assertEqual(suite, "['tests']")
3903 self.assertEqual(loader._top_level_dir, top_level_dir)
3904 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlanb6edf192009-10-17 08:21:21 +00003905 self.assertIn(top_level_dir, sys.path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003906
Michael Foorde91ea562009-09-13 19:07:03 +00003907 def test_discover_with_modules_that_fail_to_import(self):
3908 loader = unittest.TestLoader()
3909
3910 listdir = os.listdir
3911 os.listdir = lambda _: ['test_this_does_not_exist.py']
3912 isfile = os.path.isfile
3913 os.path.isfile = lambda _: True
Nick Coghlanb6edf192009-10-17 08:21:21 +00003914 orig_sys_path = sys.path[:]
Michael Foorde91ea562009-09-13 19:07:03 +00003915 def restore():
3916 os.path.isfile = isfile
3917 os.listdir = listdir
Nick Coghlanb6edf192009-10-17 08:21:21 +00003918 sys.path[:] = orig_sys_path
Michael Foorde91ea562009-09-13 19:07:03 +00003919 self.addCleanup(restore)
3920
3921 suite = loader.discover('.')
Nick Coghlanb6edf192009-10-17 08:21:21 +00003922 self.assertIn(os.getcwd(), sys.path)
Michael Foorde91ea562009-09-13 19:07:03 +00003923 self.assertEqual(suite.countTestCases(), 1)
3924 test = list(list(suite)[0])[0] # extract test from suite
3925
3926 with self.assertRaises(ImportError):
3927 test.test_this_does_not_exist()
3928
Michael Foordb4a81c82009-05-29 20:33:46 +00003929 def test_command_line_handling_parseArgs(self):
3930 # Haha - take that uninstantiable class
3931 program = object.__new__(TestProgram)
3932
3933 args = []
3934 def do_discovery(argv):
3935 args.extend(argv)
3936 program._do_discovery = do_discovery
3937 program.parseArgs(['something', 'discover'])
3938 self.assertEqual(args, [])
3939
3940 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3941 self.assertEqual(args, ['foo', 'bar'])
3942
3943 def test_command_line_handling_do_discovery_too_many_arguments(self):
3944 class Stop(Exception):
3945 pass
3946 def usageExit():
3947 raise Stop
3948
3949 program = object.__new__(TestProgram)
3950 program.usageExit = usageExit
3951
3952 with self.assertRaises(Stop):
3953 # too many args
3954 program._do_discovery(['one', 'two', 'three', 'four'])
3955
3956
3957 def test_command_line_handling_do_discovery_calls_loader(self):
3958 program = object.__new__(TestProgram)
3959
3960 class Loader(object):
3961 args = []
3962 def discover(self, start_dir, pattern, top_level_dir):
3963 self.args.append((start_dir, pattern, top_level_dir))
3964 return 'tests'
3965
3966 program._do_discovery(['-v'], Loader=Loader)
3967 self.assertEqual(program.verbosity, 2)
3968 self.assertEqual(program.test, 'tests')
3969 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3970
3971 Loader.args = []
3972 program = object.__new__(TestProgram)
3973 program._do_discovery(['--verbose'], Loader=Loader)
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([], 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(['fish'], Loader=Loader)
3986 self.assertEqual(program.test, 'tests')
3987 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3988
3989 Loader.args = []
3990 program = object.__new__(TestProgram)
3991 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3992 self.assertEqual(program.test, 'tests')
3993 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3994
3995 Loader.args = []
3996 program = object.__new__(TestProgram)
3997 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3998 self.assertEqual(program.test, 'tests')
3999 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
4000
4001 Loader.args = []
4002 program = object.__new__(TestProgram)
4003 program._do_discovery(['-s', 'fish'], Loader=Loader)
4004 self.assertEqual(program.test, 'tests')
4005 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
4006
4007 Loader.args = []
4008 program = object.__new__(TestProgram)
4009 program._do_discovery(['-t', 'fish'], Loader=Loader)
4010 self.assertEqual(program.test, 'tests')
4011 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
4012
4013 Loader.args = []
4014 program = object.__new__(TestProgram)
4015 program._do_discovery(['-p', 'fish'], Loader=Loader)
4016 self.assertEqual(program.test, 'tests')
4017 self.assertEqual(Loader.args, [('.', 'fish', None)])
Michael Foord49899692010-03-22 01:41:11 +00004018 self.assertFalse(program.failfast)
Michael Foordb4a81c82009-05-29 20:33:46 +00004019
4020 Loader.args = []
4021 program = object.__new__(TestProgram)
Michael Foord49899692010-03-22 01:41:11 +00004022 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v', '-f'], Loader=Loader)
Michael Foordb4a81c82009-05-29 20:33:46 +00004023 self.assertEqual(program.test, 'tests')
4024 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
4025 self.assertEqual(program.verbosity, 2)
Michael Foord49899692010-03-22 01:41:11 +00004026 self.assertTrue(program.failfast)
Michael Foordb4a81c82009-05-29 20:33:46 +00004027
4028
Michael Foord5ffa3252010-03-07 22:04:55 +00004029class TestSetups(unittest.TestCase):
4030
4031 def getRunner(self):
4032 return unittest.TextTestRunner(resultclass=resultFactory,
4033 stream=StringIO())
4034 def runTests(self, *cases):
4035 suite = unittest.TestSuite()
4036 for case in cases:
4037 tests = unittest.defaultTestLoader.loadTestsFromTestCase(case)
4038 suite.addTests(tests)
4039
4040 runner = self.getRunner()
4041
4042 # creating a nested suite exposes some potential bugs
4043 realSuite = unittest.TestSuite()
4044 realSuite.addTest(suite)
4045 # adding empty suites to the end exposes potential bugs
4046 suite.addTest(unittest.TestSuite())
4047 realSuite.addTest(unittest.TestSuite())
4048 return runner.run(realSuite)
4049
4050 def test_setup_class(self):
4051 class Test(unittest.TestCase):
4052 setUpCalled = 0
4053 @classmethod
4054 def setUpClass(cls):
4055 Test.setUpCalled += 1
4056 unittest.TestCase.setUpClass()
4057 def test_one(self):
4058 pass
4059 def test_two(self):
4060 pass
4061
4062 result = self.runTests(Test)
4063
4064 self.assertEqual(Test.setUpCalled, 1)
4065 self.assertEqual(result.testsRun, 2)
4066 self.assertEqual(len(result.errors), 0)
4067
4068 def test_teardown_class(self):
4069 class Test(unittest.TestCase):
4070 tearDownCalled = 0
4071 @classmethod
4072 def tearDownClass(cls):
4073 Test.tearDownCalled += 1
4074 unittest.TestCase.tearDownClass()
4075 def test_one(self):
4076 pass
4077 def test_two(self):
4078 pass
4079
4080 result = self.runTests(Test)
4081
4082 self.assertEqual(Test.tearDownCalled, 1)
4083 self.assertEqual(result.testsRun, 2)
4084 self.assertEqual(len(result.errors), 0)
4085
4086 def test_teardown_class_two_classes(self):
4087 class Test(unittest.TestCase):
4088 tearDownCalled = 0
4089 @classmethod
4090 def tearDownClass(cls):
4091 Test.tearDownCalled += 1
4092 unittest.TestCase.tearDownClass()
4093 def test_one(self):
4094 pass
4095 def test_two(self):
4096 pass
4097
4098 class Test2(unittest.TestCase):
4099 tearDownCalled = 0
4100 @classmethod
4101 def tearDownClass(cls):
4102 Test2.tearDownCalled += 1
4103 unittest.TestCase.tearDownClass()
4104 def test_one(self):
4105 pass
4106 def test_two(self):
4107 pass
4108
4109 result = self.runTests(Test, Test2)
4110
4111 self.assertEqual(Test.tearDownCalled, 1)
4112 self.assertEqual(Test2.tearDownCalled, 1)
4113 self.assertEqual(result.testsRun, 4)
4114 self.assertEqual(len(result.errors), 0)
4115
4116 def test_error_in_setupclass(self):
4117 class BrokenTest(unittest.TestCase):
4118 @classmethod
4119 def setUpClass(cls):
4120 raise TypeError('foo')
4121 def test_one(self):
4122 pass
4123 def test_two(self):
4124 pass
4125
4126 result = self.runTests(BrokenTest)
4127
4128 self.assertEqual(result.testsRun, 0)
4129 self.assertEqual(len(result.errors), 1)
4130 error, _ = result.errors[0]
4131 self.assertEqual(str(error),
4132 'classSetUp (%s.BrokenTest)' % __name__)
4133
4134 def test_error_in_teardown_class(self):
4135 class Test(unittest.TestCase):
4136 tornDown = 0
4137 @classmethod
4138 def tearDownClass(cls):
4139 Test.tornDown += 1
4140 raise TypeError('foo')
4141 def test_one(self):
4142 pass
4143 def test_two(self):
4144 pass
4145
4146 class Test2(unittest.TestCase):
4147 tornDown = 0
4148 @classmethod
4149 def tearDownClass(cls):
4150 Test2.tornDown += 1
4151 raise TypeError('foo')
4152 def test_one(self):
4153 pass
4154 def test_two(self):
4155 pass
4156
4157 result = self.runTests(Test, Test2)
4158 self.assertEqual(result.testsRun, 4)
4159 self.assertEqual(len(result.errors), 2)
4160 self.assertEqual(Test.tornDown, 1)
4161 self.assertEqual(Test2.tornDown, 1)
4162
4163 error, _ = result.errors[0]
4164 self.assertEqual(str(error),
4165 'classTearDown (%s.Test)' % __name__)
4166
4167 def test_class_not_torndown_when_setup_fails(self):
4168 class Test(unittest.TestCase):
4169 tornDown = False
4170 @classmethod
4171 def setUpClass(cls):
4172 raise TypeError
4173 @classmethod
4174 def tearDownClass(cls):
4175 Test.tornDown = True
4176 raise TypeError('foo')
4177 def test_one(self):
4178 pass
4179
4180 self.runTests(Test)
4181 self.assertFalse(Test.tornDown)
4182
4183 def test_class_not_setup_or_torndown_when_skipped(self):
4184 class Test(unittest.TestCase):
4185 classSetUp = False
4186 tornDown = False
4187 @classmethod
4188 def setUpClass(cls):
4189 Test.classSetUp = True
4190 @classmethod
4191 def tearDownClass(cls):
4192 Test.tornDown = True
4193 def test_one(self):
4194 pass
4195
4196 Test = unittest.skip("hop")(Test)
4197 self.runTests(Test)
4198 self.assertFalse(Test.classSetUp)
4199 self.assertFalse(Test.tornDown)
4200
4201 def test_setup_teardown_order_with_pathological_suite(self):
4202 results = []
4203
4204 class Module1(object):
4205 @staticmethod
4206 def setUpModule():
4207 results.append('Module1.setUpModule')
4208 @staticmethod
4209 def tearDownModule():
4210 results.append('Module1.tearDownModule')
4211
4212 class Module2(object):
4213 @staticmethod
4214 def setUpModule():
4215 results.append('Module2.setUpModule')
4216 @staticmethod
4217 def tearDownModule():
4218 results.append('Module2.tearDownModule')
4219
4220 class Test1(unittest.TestCase):
4221 @classmethod
4222 def setUpClass(cls):
4223 results.append('setup 1')
4224 @classmethod
4225 def tearDownClass(cls):
4226 results.append('teardown 1')
4227 def testOne(self):
4228 results.append('Test1.testOne')
4229 def testTwo(self):
4230 results.append('Test1.testTwo')
4231
4232 class Test2(unittest.TestCase):
4233 @classmethod
4234 def setUpClass(cls):
4235 results.append('setup 2')
4236 @classmethod
4237 def tearDownClass(cls):
4238 results.append('teardown 2')
4239 def testOne(self):
4240 results.append('Test2.testOne')
4241 def testTwo(self):
4242 results.append('Test2.testTwo')
4243
4244 class Test3(unittest.TestCase):
4245 @classmethod
4246 def setUpClass(cls):
4247 results.append('setup 3')
4248 @classmethod
4249 def tearDownClass(cls):
4250 results.append('teardown 3')
4251 def testOne(self):
4252 results.append('Test3.testOne')
4253 def testTwo(self):
4254 results.append('Test3.testTwo')
4255
4256 Test1.__module__ = Test2.__module__ = 'Module'
4257 Test3.__module__ = 'Module2'
4258 sys.modules['Module'] = Module1
4259 sys.modules['Module2'] = Module2
4260
4261 first = unittest.TestSuite((Test1('testOne'),))
4262 second = unittest.TestSuite((Test1('testTwo'),))
4263 third = unittest.TestSuite((Test2('testOne'),))
4264 fourth = unittest.TestSuite((Test2('testTwo'),))
4265 fifth = unittest.TestSuite((Test3('testOne'),))
4266 sixth = unittest.TestSuite((Test3('testTwo'),))
4267 suite = unittest.TestSuite((first, second, third, fourth, fifth, sixth))
4268
4269 runner = self.getRunner()
4270 result = runner.run(suite)
4271 self.assertEqual(result.testsRun, 6)
4272 self.assertEqual(len(result.errors), 0)
4273
4274 self.assertEqual(results,
4275 ['Module1.setUpModule', 'setup 1',
4276 'Test1.testOne', 'Test1.testTwo', 'teardown 1',
4277 'setup 2', 'Test2.testOne', 'Test2.testTwo',
4278 'teardown 2', 'Module1.tearDownModule',
4279 'Module2.setUpModule', 'setup 3',
4280 'Test3.testOne', 'Test3.testTwo',
4281 'teardown 3', 'Module2.tearDownModule'])
4282
4283 def test_setup_module(self):
4284 class Module(object):
4285 moduleSetup = 0
4286 @staticmethod
4287 def setUpModule():
4288 Module.moduleSetup += 1
4289
4290 class Test(unittest.TestCase):
4291 def test_one(self):
4292 pass
4293 def test_two(self):
4294 pass
4295 Test.__module__ = 'Module'
4296 sys.modules['Module'] = Module
4297
4298 result = self.runTests(Test)
4299 self.assertEqual(Module.moduleSetup, 1)
4300 self.assertEqual(result.testsRun, 2)
4301 self.assertEqual(len(result.errors), 0)
4302
4303 def test_error_in_setup_module(self):
4304 class Module(object):
4305 moduleSetup = 0
4306 moduleTornDown = 0
4307 @staticmethod
4308 def setUpModule():
4309 Module.moduleSetup += 1
4310 raise TypeError('foo')
4311 @staticmethod
4312 def tearDownModule():
4313 Module.moduleTornDown += 1
4314
4315 class Test(unittest.TestCase):
4316 classSetUp = False
4317 classTornDown = False
4318 @classmethod
4319 def setUpClass(cls):
4320 Test.classSetUp = True
4321 @classmethod
4322 def tearDownClass(cls):
4323 Test.classTornDown = True
4324 def test_one(self):
4325 pass
4326 def test_two(self):
4327 pass
4328
4329 class Test2(unittest.TestCase):
4330 def test_one(self):
4331 pass
4332 def test_two(self):
4333 pass
4334 Test.__module__ = 'Module'
4335 Test2.__module__ = 'Module'
4336 sys.modules['Module'] = Module
4337
4338 result = self.runTests(Test, Test2)
4339 self.assertEqual(Module.moduleSetup, 1)
4340 self.assertEqual(Module.moduleTornDown, 0)
4341 self.assertEqual(result.testsRun, 0)
4342 self.assertFalse(Test.classSetUp)
4343 self.assertFalse(Test.classTornDown)
4344 self.assertEqual(len(result.errors), 1)
4345 error, _ = result.errors[0]
4346 self.assertEqual(str(error), 'setUpModule (Module)')
4347
4348 def test_testcase_with_missing_module(self):
4349 class Test(unittest.TestCase):
4350 def test_one(self):
4351 pass
4352 def test_two(self):
4353 pass
4354 Test.__module__ = 'Module'
4355 sys.modules.pop('Module', None)
4356
4357 result = self.runTests(Test)
4358 self.assertEqual(result.testsRun, 2)
4359
4360 def test_teardown_module(self):
4361 class Module(object):
4362 moduleTornDown = 0
4363 @staticmethod
4364 def tearDownModule():
4365 Module.moduleTornDown += 1
4366
4367 class Test(unittest.TestCase):
4368 def test_one(self):
4369 pass
4370 def test_two(self):
4371 pass
4372 Test.__module__ = 'Module'
4373 sys.modules['Module'] = Module
4374
4375 result = self.runTests(Test)
4376 self.assertEqual(Module.moduleTornDown, 1)
4377 self.assertEqual(result.testsRun, 2)
4378 self.assertEqual(len(result.errors), 0)
4379
4380 def test_error_in_teardown_module(self):
4381 class Module(object):
4382 moduleTornDown = 0
4383 @staticmethod
4384 def tearDownModule():
4385 Module.moduleTornDown += 1
4386 raise TypeError('foo')
4387
4388 class Test(unittest.TestCase):
4389 classSetUp = False
4390 classTornDown = False
4391 @classmethod
4392 def setUpClass(cls):
4393 Test.classSetUp = True
4394 @classmethod
4395 def tearDownClass(cls):
4396 Test.classTornDown = True
4397 def test_one(self):
4398 pass
4399 def test_two(self):
4400 pass
4401
4402 class Test2(unittest.TestCase):
4403 def test_one(self):
4404 pass
4405 def test_two(self):
4406 pass
4407 Test.__module__ = 'Module'
4408 Test2.__module__ = 'Module'
4409 sys.modules['Module'] = Module
4410
4411 result = self.runTests(Test, Test2)
4412 self.assertEqual(Module.moduleTornDown, 1)
4413 self.assertEqual(result.testsRun, 4)
4414 self.assertTrue(Test.classSetUp)
4415 self.assertTrue(Test.classTornDown)
4416 self.assertEqual(len(result.errors), 1)
4417 error, _ = result.errors[0]
4418 self.assertEqual(str(error), 'tearDownModule (Module)')
4419
Jim Fultonfafd8742004-08-28 15:22:12 +00004420######################################################################
4421## Main
4422######################################################################
4423
4424def test_main():
Georg Brandl15c5ce92007-03-07 09:09:40 +00004425 test_support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004426 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Michael Foord829f6b82009-05-02 11:43:06 +00004427 Test_TestSkipping, Test_Assertions, TestLongMessage,
Michael Foordae3db0a2010-02-22 23:28:32 +00004428 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner,
Michael Foord5ffa3252010-03-07 22:04:55 +00004429 Test_OldTestResult, TestSetups)
Jim Fultonfafd8742004-08-28 15:22:12 +00004430
Georg Brandl15c5ce92007-03-07 09:09:40 +00004431if __name__ == "__main__":
Tim Petersea5962f2007-03-12 18:07:52 +00004432 test_main()