blob: e094923cd3f82788e95fe0a278b80b9390ad885c [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 Foordae3db0a2010-02-22 23:28:32 +00002087classDict = dict(unittest.TestResult.__dict__)
Michael Foordd99ef9a2010-02-23 17:00:53 +00002088for m in ('addSkip', 'addExpectedFailure', 'addUnexpectedSuccess',
2089 '__init__'):
Michael Foordae3db0a2010-02-22 23:28:32 +00002090 del classDict[m]
Michael Foordd99ef9a2010-02-23 17:00:53 +00002091
2092def __init__(self, stream=None, descriptions=None, verbosity=None):
2093 self.failures = []
2094 self.errors = []
2095 self.testsRun = 0
2096 self.shouldStop = False
2097classDict['__init__'] = __init__
Michael Foordae3db0a2010-02-22 23:28:32 +00002098OldResult = type('OldResult', (object,), classDict)
2099
2100class Test_OldTestResult(unittest.TestCase):
2101
2102 def assertOldResultWarning(self, test, failures):
2103 with warnings.catch_warnings(record=True) as log:
2104 result = OldResult()
2105 test.run(result)
2106 self.assertEqual(len(result.failures), failures)
2107 warning, = log
2108 self.assertIs(warning.category, RuntimeWarning)
2109
2110 def testOldTestResult(self):
2111 class Test(unittest.TestCase):
2112 def testSkip(self):
2113 self.skipTest('foobar')
2114 @unittest.expectedFailure
2115 def testExpectedFail(self):
2116 raise TypeError
2117 @unittest.expectedFailure
2118 def testUnexpectedSuccess(self):
2119 pass
2120
2121 for test_name, should_pass in (('testSkip', True),
2122 ('testExpectedFail', True),
2123 ('testUnexpectedSuccess', False)):
2124 test = Test(test_name)
2125 self.assertOldResultWarning(test, int(not should_pass))
2126
2127 def testOldTestTesultSetup(self):
2128 class Test(unittest.TestCase):
2129 def setUp(self):
2130 self.skipTest('no reason')
2131 def testFoo(self):
2132 pass
2133 self.assertOldResultWarning(Test('testFoo'), 0)
2134
2135 def testOldTestResultClass(self):
2136 @unittest.skip('no reason')
2137 class Test(unittest.TestCase):
2138 def testFoo(self):
2139 pass
2140 self.assertOldResultWarning(Test('testFoo'), 0)
2141
Michael Foordd99ef9a2010-02-23 17:00:53 +00002142 def testOldResultWithRunner(self):
2143 class Test(unittest.TestCase):
2144 def testFoo(self):
2145 pass
2146 runner = unittest.TextTestRunner(resultclass=OldResult,
2147 stream=StringIO())
2148 # This will raise an exception if TextTestRunner can't handle old
2149 # test result objects
2150 runner.run(Test('testFoo'))
Michael Foorddb43b5a2010-02-10 14:25:12 +00002151
Georg Brandl15c5ce92007-03-07 09:09:40 +00002152### Support code for Test_TestCase
2153################################################################
2154
2155class Foo(unittest.TestCase):
2156 def runTest(self): pass
2157 def test1(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002158
Georg Brandl15c5ce92007-03-07 09:09:40 +00002159class Bar(Foo):
2160 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002161
Michael Foord07ef4872009-05-02 22:43:34 +00002162class LoggingTestCase(unittest.TestCase):
2163 """A test case which logs its calls."""
2164
2165 def __init__(self, events):
2166 super(LoggingTestCase, self).__init__('test')
2167 self.events = events
2168
2169 def setUp(self):
2170 self.events.append('setUp')
2171
2172 def test(self):
2173 self.events.append('test')
2174
2175 def tearDown(self):
2176 self.events.append('tearDown')
2177
2178class ResultWithNoStartTestRunStopTestRun(object):
2179 """An object honouring TestResult before startTestRun/stopTestRun."""
2180
2181 def __init__(self):
2182 self.failures = []
2183 self.errors = []
2184 self.testsRun = 0
2185 self.skipped = []
2186 self.expectedFailures = []
2187 self.unexpectedSuccesses = []
2188 self.shouldStop = False
2189
2190 def startTest(self, test):
2191 pass
2192
2193 def stopTest(self, test):
2194 pass
2195
2196 def addError(self, test):
2197 pass
2198
2199 def addFailure(self, test):
2200 pass
2201
2202 def addSuccess(self, test):
2203 pass
2204
2205 def wasSuccessful(self):
2206 return True
2207
2208
Georg Brandl15c5ce92007-03-07 09:09:40 +00002209################################################################
2210### /Support code for Test_TestCase
2211
2212class Test_TestCase(TestCase, TestEquality, TestHashing):
2213
2214 ### Set up attributes used by inherited tests
2215 ################################################################
2216
2217 # Used by TestHashing.test_hash and TestEquality.test_eq
2218 eq_pairs = [(Foo('test1'), Foo('test1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002219
Georg Brandl15c5ce92007-03-07 09:09:40 +00002220 # Used by TestEquality.test_ne
2221 ne_pairs = [(Foo('test1'), Foo('runTest'))
2222 ,(Foo('test1'), Bar('test1'))
2223 ,(Foo('test1'), Bar('test2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002224
Georg Brandl15c5ce92007-03-07 09:09:40 +00002225 ################################################################
2226 ### /Set up attributes used by inherited tests
Tim Petersea5962f2007-03-12 18:07:52 +00002227
Georg Brandl15c5ce92007-03-07 09:09:40 +00002228
2229 # "class TestCase([methodName])"
2230 # ...
2231 # "Each instance of TestCase will run a single test method: the
2232 # method named methodName."
2233 # ...
2234 # "methodName defaults to "runTest"."
2235 #
2236 # Make sure it really is optional, and that it defaults to the proper
2237 # thing.
2238 def test_init__no_test_name(self):
2239 class Test(unittest.TestCase):
2240 def runTest(self): raise MyException()
2241 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002242
Georg Brandl15c5ce92007-03-07 09:09:40 +00002243 self.assertEqual(Test().id()[-13:], '.Test.runTest')
Tim Petersea5962f2007-03-12 18:07:52 +00002244
Georg Brandl15c5ce92007-03-07 09:09:40 +00002245 # "class TestCase([methodName])"
2246 # ...
2247 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002248 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002249 def test_init__test_name__valid(self):
2250 class Test(unittest.TestCase):
2251 def runTest(self): raise MyException()
2252 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002253
Georg Brandl15c5ce92007-03-07 09:09:40 +00002254 self.assertEqual(Test('test').id()[-10:], '.Test.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002255
Georg Brandl15c5ce92007-03-07 09:09:40 +00002256 # "class TestCase([methodName])"
2257 # ...
2258 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002259 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002260 def test_init__test_name__invalid(self):
2261 class Test(unittest.TestCase):
2262 def runTest(self): raise MyException()
2263 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002264
Georg Brandl15c5ce92007-03-07 09:09:40 +00002265 try:
2266 Test('testfoo')
2267 except ValueError:
2268 pass
2269 else:
2270 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +00002271
Georg Brandl15c5ce92007-03-07 09:09:40 +00002272 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00002273 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00002274 def test_countTestCases(self):
2275 class Foo(unittest.TestCase):
2276 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002277
Georg Brandl15c5ce92007-03-07 09:09:40 +00002278 self.assertEqual(Foo('test').countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00002279
Georg Brandl15c5ce92007-03-07 09:09:40 +00002280 # "Return the default type of test result object to be used to run this
2281 # test. For TestCase instances, this will always be
2282 # unittest.TestResult; subclasses of TestCase should
2283 # override this as necessary."
2284 def test_defaultTestResult(self):
2285 class Foo(unittest.TestCase):
2286 def runTest(self):
2287 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002288
Georg Brandl15c5ce92007-03-07 09:09:40 +00002289 result = Foo().defaultTestResult()
2290 self.assertEqual(type(result), unittest.TestResult)
2291
2292 # "When a setUp() method is defined, the test runner will run that method
2293 # prior to each test. Likewise, if a tearDown() method is defined, the
2294 # test runner will invoke that method after each test. In the example,
2295 # setUp() was used to create a fresh sequence for each test."
2296 #
2297 # Make sure the proper call order is maintained, even if setUp() raises
2298 # an exception.
2299 def test_run_call_order__error_in_setUp(self):
2300 events = []
2301 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002302
Michael Foord07ef4872009-05-02 22:43:34 +00002303 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002304 def setUp(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002305 super(Foo, self).setUp()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002306 raise RuntimeError('raised by Foo.setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002307
Michael Foord07ef4872009-05-02 22:43:34 +00002308 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002309 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2310 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002311
Michael Foord07ef4872009-05-02 22:43:34 +00002312 # "With a temporary result stopTestRun is called when setUp errors.
2313 def test_run_call_order__error_in_setUp_default_result(self):
2314 events = []
2315
2316 class Foo(LoggingTestCase):
2317 def defaultTestResult(self):
2318 return LoggingResult(self.events)
2319
2320 def setUp(self):
2321 super(Foo, self).setUp()
2322 raise RuntimeError('raised by Foo.setUp')
2323
2324 Foo(events).run()
2325 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2326 'stopTest', 'stopTestRun']
2327 self.assertEqual(events, expected)
2328
Georg Brandl15c5ce92007-03-07 09:09:40 +00002329 # "When a setUp() method is defined, the test runner will run that method
2330 # prior to each test. Likewise, if a tearDown() method is defined, the
2331 # test runner will invoke that method after each test. In the example,
2332 # setUp() was used to create a fresh sequence for each test."
2333 #
2334 # Make sure the proper call order is maintained, even if the test raises
2335 # an error (as opposed to a failure).
2336 def test_run_call_order__error_in_test(self):
2337 events = []
2338 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002339
Michael Foord07ef4872009-05-02 22:43:34 +00002340 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002341 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002342 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002343 raise RuntimeError('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002344
Georg Brandl15c5ce92007-03-07 09:09:40 +00002345 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2346 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002347 Foo(events).run(result)
2348 self.assertEqual(events, expected)
2349
2350 # "With a default result, an error in the test still results in stopTestRun
2351 # being called."
2352 def test_run_call_order__error_in_test_default_result(self):
2353 events = []
2354
2355 class Foo(LoggingTestCase):
2356 def defaultTestResult(self):
2357 return LoggingResult(self.events)
2358
2359 def test(self):
2360 super(Foo, self).test()
2361 raise RuntimeError('raised by Foo.test')
2362
2363 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2364 'tearDown', 'stopTest', 'stopTestRun']
2365 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002366 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002367
Georg Brandl15c5ce92007-03-07 09:09:40 +00002368 # "When a setUp() method is defined, the test runner will run that method
2369 # prior to each test. Likewise, if a tearDown() method is defined, the
2370 # test runner will invoke that method after each test. In the example,
2371 # setUp() was used to create a fresh sequence for each test."
2372 #
2373 # Make sure the proper call order is maintained, even if the test signals
2374 # a failure (as opposed to an error).
2375 def test_run_call_order__failure_in_test(self):
2376 events = []
2377 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002378
Michael Foord07ef4872009-05-02 22:43:34 +00002379 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002380 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002381 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002382 self.fail('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002383
Georg Brandl15c5ce92007-03-07 09:09:40 +00002384 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2385 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002386 Foo(events).run(result)
2387 self.assertEqual(events, expected)
2388
2389 # "When a test fails with a default result stopTestRun is still called."
2390 def test_run_call_order__failure_in_test_default_result(self):
2391
2392 class Foo(LoggingTestCase):
2393 def defaultTestResult(self):
2394 return LoggingResult(self.events)
2395 def test(self):
2396 super(Foo, self).test()
2397 self.fail('raised by Foo.test')
2398
2399 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2400 'tearDown', 'stopTest', 'stopTestRun']
2401 events = []
2402 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002403 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002404
Georg Brandl15c5ce92007-03-07 09:09:40 +00002405 # "When a setUp() method is defined, the test runner will run that method
2406 # prior to each test. Likewise, if a tearDown() method is defined, the
2407 # test runner will invoke that method after each test. In the example,
2408 # setUp() was used to create a fresh sequence for each test."
2409 #
2410 # Make sure the proper call order is maintained, even if tearDown() raises
2411 # an exception.
2412 def test_run_call_order__error_in_tearDown(self):
2413 events = []
2414 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002415
Michael Foord07ef4872009-05-02 22:43:34 +00002416 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002417 def tearDown(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002418 super(Foo, self).tearDown()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002419 raise RuntimeError('raised by Foo.tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002420
Michael Foord07ef4872009-05-02 22:43:34 +00002421 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002422 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2423 'stopTest']
2424 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002425
Michael Foord07ef4872009-05-02 22:43:34 +00002426 # "When tearDown errors with a default result stopTestRun is still called."
2427 def test_run_call_order__error_in_tearDown_default_result(self):
2428
2429 class Foo(LoggingTestCase):
2430 def defaultTestResult(self):
2431 return LoggingResult(self.events)
2432 def tearDown(self):
2433 super(Foo, self).tearDown()
2434 raise RuntimeError('raised by Foo.tearDown')
2435
2436 events = []
2437 Foo(events).run()
2438 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2439 'addError', 'stopTest', 'stopTestRun']
2440 self.assertEqual(events, expected)
2441
2442 # "TestCase.run() still works when the defaultTestResult is a TestResult
2443 # that does not support startTestRun and stopTestRun.
2444 def test_run_call_order_default_result(self):
2445
2446 class Foo(unittest.TestCase):
2447 def defaultTestResult(self):
2448 return ResultWithNoStartTestRunStopTestRun()
2449 def test(self):
2450 pass
2451
2452 Foo('test').run()
2453
Georg Brandl15c5ce92007-03-07 09:09:40 +00002454 # "This class attribute gives the exception raised by the test() method.
2455 # If a test framework needs to use a specialized exception, possibly to
2456 # carry additional information, it must subclass this exception in
2457 # order to ``play fair'' with the framework. The initial value of this
2458 # attribute is AssertionError"
2459 def test_failureException__default(self):
2460 class Foo(unittest.TestCase):
2461 def test(self):
2462 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002463
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002464 self.assertTrue(Foo('test').failureException is AssertionError)
Tim Petersea5962f2007-03-12 18:07:52 +00002465
Georg Brandl15c5ce92007-03-07 09:09:40 +00002466 # "This class attribute gives the exception raised by the test() method.
2467 # If a test framework needs to use a specialized exception, possibly to
2468 # carry additional information, it must subclass this exception in
2469 # order to ``play fair'' with the framework."
2470 #
2471 # Make sure TestCase.run() respects the designated failureException
2472 def test_failureException__subclassing__explicit_raise(self):
2473 events = []
2474 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002475
Georg Brandl15c5ce92007-03-07 09:09:40 +00002476 class Foo(unittest.TestCase):
2477 def test(self):
2478 raise RuntimeError()
Tim Petersea5962f2007-03-12 18:07:52 +00002479
Georg Brandl15c5ce92007-03-07 09:09:40 +00002480 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002481
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002482 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002483
2484
Georg Brandl15c5ce92007-03-07 09:09:40 +00002485 Foo('test').run(result)
2486 expected = ['startTest', 'addFailure', 'stopTest']
2487 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002488
Georg Brandl15c5ce92007-03-07 09:09:40 +00002489 # "This class attribute gives the exception raised by the test() method.
2490 # If a test framework needs to use a specialized exception, possibly to
2491 # carry additional information, it must subclass this exception in
2492 # order to ``play fair'' with the framework."
2493 #
2494 # Make sure TestCase.run() respects the designated failureException
2495 def test_failureException__subclassing__implicit_raise(self):
2496 events = []
2497 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002498
Georg Brandl15c5ce92007-03-07 09:09:40 +00002499 class Foo(unittest.TestCase):
2500 def test(self):
2501 self.fail("foo")
Tim Petersea5962f2007-03-12 18:07:52 +00002502
Georg Brandl15c5ce92007-03-07 09:09:40 +00002503 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002504
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002505 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002506
2507
Georg Brandl15c5ce92007-03-07 09:09:40 +00002508 Foo('test').run(result)
2509 expected = ['startTest', 'addFailure', 'stopTest']
2510 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002511
2512 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002513 def test_setUp(self):
2514 class Foo(unittest.TestCase):
2515 def runTest(self):
2516 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002517
Georg Brandl15c5ce92007-03-07 09:09:40 +00002518 # ... and nothing should happen
2519 Foo().setUp()
Tim Petersea5962f2007-03-12 18:07:52 +00002520
2521 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002522 def test_tearDown(self):
2523 class Foo(unittest.TestCase):
2524 def runTest(self):
2525 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002526
Georg Brandl15c5ce92007-03-07 09:09:40 +00002527 # ... and nothing should happen
2528 Foo().tearDown()
Tim Petersea5962f2007-03-12 18:07:52 +00002529
Georg Brandl15c5ce92007-03-07 09:09:40 +00002530 # "Return a string identifying the specific test case."
2531 #
2532 # Because of the vague nature of the docs, I'm not going to lock this
2533 # test down too much. Really all that can be asserted is that the id()
2534 # will be a string (either 8-byte or unicode -- again, because the docs
2535 # just say "string")
2536 def test_id(self):
2537 class Foo(unittest.TestCase):
2538 def runTest(self):
2539 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002540
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002541 self.assertIsInstance(Foo().id(), basestring)
Tim Petersea5962f2007-03-12 18:07:52 +00002542
Georg Brandl15c5ce92007-03-07 09:09:40 +00002543 # "If result is omitted or None, a temporary result object is created
Michael Foord07ef4872009-05-02 22:43:34 +00002544 # and used, but is not made available to the caller. As TestCase owns the
2545 # temporary result startTestRun and stopTestRun are called.
2546
Georg Brandl15c5ce92007-03-07 09:09:40 +00002547 def test_run__uses_defaultTestResult(self):
2548 events = []
Tim Petersea5962f2007-03-12 18:07:52 +00002549
Georg Brandl15c5ce92007-03-07 09:09:40 +00002550 class Foo(unittest.TestCase):
2551 def test(self):
2552 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002553
Georg Brandl15c5ce92007-03-07 09:09:40 +00002554 def defaultTestResult(self):
2555 return LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002556
2557 # Make run() find a result object on its own
Georg Brandl15c5ce92007-03-07 09:09:40 +00002558 Foo('test').run()
Tim Petersea5962f2007-03-12 18:07:52 +00002559
Michael Foord07ef4872009-05-02 22:43:34 +00002560 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2561 'stopTest', 'stopTestRun']
Georg Brandl15c5ce92007-03-07 09:09:40 +00002562 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002563
Gregory P. Smith28399852009-03-31 16:54:10 +00002564 def testShortDescriptionWithoutDocstring(self):
Michael Foorddb43b5a2010-02-10 14:25:12 +00002565 self.assertIsNone(self.shortDescription())
Gregory P. Smith28399852009-03-31 16:54:10 +00002566
R. David Murrayf28fd242010-02-23 00:24:49 +00002567 @unittest.skipIf(sys.flags.optimize >= 2,
2568 "Docstrings are omitted with -O2 and above")
Gregory P. Smith28399852009-03-31 16:54:10 +00002569 def testShortDescriptionWithOneLineDocstring(self):
2570 """Tests shortDescription() for a method with a docstring."""
2571 self.assertEqual(
2572 self.shortDescription(),
Michael Foorddb43b5a2010-02-10 14:25:12 +00002573 'Tests shortDescription() for a method with a docstring.')
Gregory P. Smith28399852009-03-31 16:54:10 +00002574
R. David Murrayf28fd242010-02-23 00:24:49 +00002575 @unittest.skipIf(sys.flags.optimize >= 2,
2576 "Docstrings are omitted with -O2 and above")
Gregory P. Smith28399852009-03-31 16:54:10 +00002577 def testShortDescriptionWithMultiLineDocstring(self):
2578 """Tests shortDescription() for a method with a longer docstring.
2579
2580 This method ensures that only the first line of a docstring is
2581 returned used in the short description, no matter how long the
2582 whole thing is.
2583 """
2584 self.assertEqual(
2585 self.shortDescription(),
Gregory P. Smith28399852009-03-31 16:54:10 +00002586 'Tests shortDescription() for a method with a longer '
Michael Foorddb43b5a2010-02-10 14:25:12 +00002587 'docstring.')
Gregory P. Smith28399852009-03-31 16:54:10 +00002588
Gregory P. Smith28399852009-03-31 16:54:10 +00002589 def testAddTypeEqualityFunc(self):
2590 class SadSnake(object):
2591 """Dummy class for test_addTypeEqualityFunc."""
2592 s1, s2 = SadSnake(), SadSnake()
Michael Foord98e7b762010-03-20 03:00:34 +00002593 self.assertNotEqual(s1, s2)
Gregory P. Smith28399852009-03-31 16:54:10 +00002594 def AllSnakesCreatedEqual(a, b, msg=None):
Michael Foord98e7b762010-03-20 03:00:34 +00002595 return type(a) is type(b) is SadSnake
Gregory P. Smith28399852009-03-31 16:54:10 +00002596 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2597 self.assertEqual(s1, s2)
2598 # No this doesn't clean up and remove the SadSnake equality func
2599 # from this TestCase instance but since its a local nothing else
2600 # will ever notice that.
2601
Michael Foordf2dfef12009-04-05 19:19:28 +00002602 def testAssertIs(self):
2603 thing = object()
2604 self.assertIs(thing, thing)
2605 self.assertRaises(self.failureException, self.assertIs, thing, object())
2606
2607 def testAssertIsNot(self):
2608 thing = object()
2609 self.assertIsNot(thing, object())
2610 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2611
Georg Brandlf895cf52009-10-01 20:59:31 +00002612 def testAssertIsInstance(self):
2613 thing = []
2614 self.assertIsInstance(thing, list)
2615 self.assertRaises(self.failureException, self.assertIsInstance,
2616 thing, dict)
2617
2618 def testAssertNotIsInstance(self):
2619 thing = []
2620 self.assertNotIsInstance(thing, dict)
2621 self.assertRaises(self.failureException, self.assertNotIsInstance,
2622 thing, list)
2623
Gregory P. Smith28399852009-03-31 16:54:10 +00002624 def testAssertIn(self):
2625 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2626
2627 self.assertIn('a', 'abc')
2628 self.assertIn(2, [1, 2, 3])
2629 self.assertIn('monkey', animals)
2630
2631 self.assertNotIn('d', 'abc')
2632 self.assertNotIn(0, [1, 2, 3])
2633 self.assertNotIn('otter', animals)
2634
2635 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2636 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2637 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2638 animals)
2639
2640 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2641 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2642 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2643 animals)
2644
2645 def testAssertDictContainsSubset(self):
2646 self.assertDictContainsSubset({}, {})
2647 self.assertDictContainsSubset({}, {'a': 1})
2648 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2649 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2650 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2651
Michael Foord225a0992010-02-18 20:30:09 +00002652 with self.assertRaises(self.failureException):
2653 self.assertDictContainsSubset({1: "one"}, {})
Gregory P. Smith28399852009-03-31 16:54:10 +00002654
Michael Foord225a0992010-02-18 20:30:09 +00002655 with self.assertRaises(self.failureException):
2656 self.assertDictContainsSubset({'a': 2}, {'a': 1})
Gregory P. Smith28399852009-03-31 16:54:10 +00002657
Michael Foord225a0992010-02-18 20:30:09 +00002658 with self.assertRaises(self.failureException):
2659 self.assertDictContainsSubset({'c': 1}, {'a': 1})
Gregory P. Smith28399852009-03-31 16:54:10 +00002660
Michael Foord225a0992010-02-18 20:30:09 +00002661 with self.assertRaises(self.failureException):
2662 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2663
2664 with self.assertRaises(self.failureException):
2665 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2666
Michael Foord2f677562010-02-21 14:48:59 +00002667 with warnings.catch_warnings(record=True):
2668 # silence the UnicodeWarning
2669 one = ''.join(chr(i) for i in range(255))
2670 # this used to cause a UnicodeDecodeError constructing the failure msg
2671 with self.assertRaises(self.failureException):
2672 self.assertDictContainsSubset({'foo': one}, {'foo': u'\uFFFD'})
Gregory P. Smith28399852009-03-31 16:54:10 +00002673
2674 def testAssertEqual(self):
2675 equal_pairs = [
2676 ((), ()),
2677 ({}, {}),
2678 ([], []),
2679 (set(), set()),
2680 (frozenset(), frozenset())]
2681 for a, b in equal_pairs:
2682 # This mess of try excepts is to test the assertEqual behavior
2683 # itself.
2684 try:
2685 self.assertEqual(a, b)
2686 except self.failureException:
2687 self.fail('assertEqual(%r, %r) failed' % (a, b))
2688 try:
2689 self.assertEqual(a, b, msg='foo')
2690 except self.failureException:
2691 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2692 try:
2693 self.assertEqual(a, b, 'foo')
2694 except self.failureException:
2695 self.fail('assertEqual(%r, %r) with third parameter failed' %
2696 (a, b))
2697
2698 unequal_pairs = [
2699 ((), []),
2700 ({}, set()),
2701 (set([4,1]), frozenset([4,2])),
2702 (frozenset([4,5]), set([2,3])),
2703 (set([3,4]), set([5,4]))]
2704 for a, b in unequal_pairs:
2705 self.assertRaises(self.failureException, self.assertEqual, a, b)
2706 self.assertRaises(self.failureException, self.assertEqual, a, b,
2707 'foo')
2708 self.assertRaises(self.failureException, self.assertEqual, a, b,
2709 msg='foo')
2710
2711 def testEquality(self):
2712 self.assertListEqual([], [])
2713 self.assertTupleEqual((), ())
2714 self.assertSequenceEqual([], ())
2715
2716 a = [0, 'a', []]
2717 b = []
2718 self.assertRaises(unittest.TestCase.failureException,
2719 self.assertListEqual, a, b)
2720 self.assertRaises(unittest.TestCase.failureException,
2721 self.assertListEqual, tuple(a), tuple(b))
2722 self.assertRaises(unittest.TestCase.failureException,
2723 self.assertSequenceEqual, a, tuple(b))
2724
2725 b.extend(a)
2726 self.assertListEqual(a, b)
2727 self.assertTupleEqual(tuple(a), tuple(b))
2728 self.assertSequenceEqual(a, tuple(b))
2729 self.assertSequenceEqual(tuple(a), b)
2730
2731 self.assertRaises(self.failureException, self.assertListEqual,
2732 a, tuple(b))
2733 self.assertRaises(self.failureException, self.assertTupleEqual,
2734 tuple(a), b)
2735 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2736 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2737 tuple(b))
2738 self.assertRaises(self.failureException, self.assertSequenceEqual,
2739 None, tuple(b))
2740 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2741 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2742 self.assertRaises(self.failureException, self.assertSequenceEqual,
2743 1, 1)
2744
2745 self.assertDictEqual({}, {})
2746
2747 c = { 'x': 1 }
2748 d = {}
2749 self.assertRaises(unittest.TestCase.failureException,
2750 self.assertDictEqual, c, d)
2751
2752 d.update(c)
2753 self.assertDictEqual(c, d)
2754
2755 d['x'] = 0
2756 self.assertRaises(unittest.TestCase.failureException,
2757 self.assertDictEqual, c, d, 'These are unequal')
2758
2759 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2760 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2761 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2762
Michael Foord98e7b762010-03-20 03:00:34 +00002763 def testAssertItemsEqual(self):
2764 a = object()
2765 self.assertItemsEqual([1, 2, 3], [3, 2, 1])
2766 self.assertItemsEqual(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2767 self.assertItemsEqual([a, a, 2, 2, 3], (a, 2, 3, a, 2))
2768 self.assertItemsEqual([1, "2", "a", "a"], ["a", "2", True, "a"])
2769 self.assertRaises(self.failureException, self.assertItemsEqual,
2770 [1, 2] + [3] * 100, [1] * 100 + [2, 3])
2771 self.assertRaises(self.failureException, self.assertItemsEqual,
2772 [1, "2", "a", "a"], ["a", "2", True, 1])
2773 self.assertRaises(self.failureException, self.assertItemsEqual,
Gregory P. Smith28399852009-03-31 16:54:10 +00002774 [10], [10, 11])
Michael Foord98e7b762010-03-20 03:00:34 +00002775 self.assertRaises(self.failureException, self.assertItemsEqual,
Gregory P. Smith28399852009-03-31 16:54:10 +00002776 [10, 11], [10])
Michael Foord98e7b762010-03-20 03:00:34 +00002777 self.assertRaises(self.failureException, self.assertItemsEqual,
2778 [10, 11, 10], [10, 11])
Gregory P. Smith28399852009-03-31 16:54:10 +00002779
2780 # Test that sequences of unhashable objects can be tested for sameness:
Michael Foord98e7b762010-03-20 03:00:34 +00002781 self.assertItemsEqual([[1, 2], [3, 4], 0], [False, [3, 4], [1, 2]])
2782 with test_support.check_warnings(quiet=True) as w:
2783 # hashable types, but not orderable
2784 self.assertRaises(self.failureException, self.assertItemsEqual,
2785 [], [divmod, 'x', 1, 5j, 2j, frozenset()])
2786 # comparing dicts raises a py3k warning
2787 self.assertItemsEqual([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2788 # comparing heterogenous non-hashable sequences raises a py3k warning
2789 self.assertItemsEqual([1, 'x', divmod, []], [divmod, [], 'x', 1])
2790 self.assertRaises(self.failureException, self.assertItemsEqual,
2791 [], [divmod, [], 'x', 1, 5j, 2j, set()])
2792 # fail the test if warnings are not silenced
2793 if w.warnings:
2794 self.fail('assertItemsEqual raised a warning: ' +
2795 str(w.warnings[0]))
2796 self.assertRaises(self.failureException, self.assertItemsEqual,
Gregory P. Smith28399852009-03-31 16:54:10 +00002797 [[1]], [[2]])
2798
Michael Foord98e7b762010-03-20 03:00:34 +00002799 # Same elements, but not same sequence length
2800 self.assertRaises(self.failureException, self.assertItemsEqual,
2801 [1, 1, 2], [2, 1])
2802 self.assertRaises(self.failureException, self.assertItemsEqual,
2803 [1, 1, "2", "a", "a"], ["2", "2", True, "a"])
2804 self.assertRaises(self.failureException, self.assertItemsEqual,
2805 [1, {'b': 2}, None, True], [{'b': 2}, True, None])
2806
2807
Gregory P. Smith28399852009-03-31 16:54:10 +00002808 def testAssertSetEqual(self):
2809 set1 = set()
2810 set2 = set()
2811 self.assertSetEqual(set1, set2)
2812
2813 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2814 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2815 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2816 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2817
2818 set1 = set(['a'])
2819 set2 = set()
2820 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2821
2822 set1 = set(['a'])
2823 set2 = set(['a'])
2824 self.assertSetEqual(set1, set2)
2825
2826 set1 = set(['a'])
2827 set2 = set(['a', 'b'])
2828 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2829
2830 set1 = set(['a'])
2831 set2 = frozenset(['a', 'b'])
2832 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2833
2834 set1 = set(['a', 'b'])
2835 set2 = frozenset(['a', 'b'])
2836 self.assertSetEqual(set1, set2)
2837
2838 set1 = set()
2839 set2 = "foo"
2840 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2841 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2842
2843 # make sure any string formatting is tuple-safe
2844 set1 = set([(0, 1), (2, 3)])
2845 set2 = set([(4, 5)])
2846 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2847
2848 def testInequality(self):
2849 # Try ints
2850 self.assertGreater(2, 1)
2851 self.assertGreaterEqual(2, 1)
2852 self.assertGreaterEqual(1, 1)
2853 self.assertLess(1, 2)
2854 self.assertLessEqual(1, 2)
2855 self.assertLessEqual(1, 1)
2856 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2857 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2858 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2859 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2860 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2861 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2862
2863 # Try Floats
2864 self.assertGreater(1.1, 1.0)
2865 self.assertGreaterEqual(1.1, 1.0)
2866 self.assertGreaterEqual(1.0, 1.0)
2867 self.assertLess(1.0, 1.1)
2868 self.assertLessEqual(1.0, 1.1)
2869 self.assertLessEqual(1.0, 1.0)
2870 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2871 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2872 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2873 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2874 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2875 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2876
2877 # Try Strings
2878 self.assertGreater('bug', 'ant')
2879 self.assertGreaterEqual('bug', 'ant')
2880 self.assertGreaterEqual('ant', 'ant')
2881 self.assertLess('ant', 'bug')
2882 self.assertLessEqual('ant', 'bug')
2883 self.assertLessEqual('ant', 'ant')
2884 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2885 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2886 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2887 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2888 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2889 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2890
2891 # Try Unicode
2892 self.assertGreater(u'bug', u'ant')
2893 self.assertGreaterEqual(u'bug', u'ant')
2894 self.assertGreaterEqual(u'ant', u'ant')
2895 self.assertLess(u'ant', u'bug')
2896 self.assertLessEqual(u'ant', u'bug')
2897 self.assertLessEqual(u'ant', u'ant')
2898 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug')
2899 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant')
2900 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2901 u'bug')
2902 self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant')
2903 self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant')
2904 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant')
2905
2906 # Try Mixed String/Unicode
2907 self.assertGreater('bug', u'ant')
2908 self.assertGreater(u'bug', 'ant')
2909 self.assertGreaterEqual('bug', u'ant')
2910 self.assertGreaterEqual(u'bug', 'ant')
2911 self.assertGreaterEqual('ant', u'ant')
2912 self.assertGreaterEqual(u'ant', 'ant')
2913 self.assertLess('ant', u'bug')
2914 self.assertLess(u'ant', 'bug')
2915 self.assertLessEqual('ant', u'bug')
2916 self.assertLessEqual(u'ant', 'bug')
2917 self.assertLessEqual('ant', u'ant')
2918 self.assertLessEqual(u'ant', 'ant')
2919 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug')
2920 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug')
2921 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant')
2922 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant')
2923 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant',
2924 u'bug')
2925 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2926 'bug')
2927 self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant')
2928 self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant')
2929 self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant')
2930 self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant')
2931 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant')
2932 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant')
2933
2934 def testAssertMultiLineEqual(self):
2935 sample_text = b"""\
2936http://www.python.org/doc/2.3/lib/module-unittest.html
2937test case
2938 A test case is the smallest unit of testing. [...]
2939"""
2940 revised_sample_text = b"""\
2941http://www.python.org/doc/2.4.1/lib/module-unittest.html
2942test case
2943 A test case is the smallest unit of testing. [...] You may provide your
2944 own implementation that does not subclass from TestCase, of course.
2945"""
2946 sample_text_error = b"""
2947- http://www.python.org/doc/2.3/lib/module-unittest.html
2948? ^
2949+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2950? ^^^
2951 test case
2952- A test case is the smallest unit of testing. [...]
2953+ A test case is the smallest unit of testing. [...] You may provide your
2954? +++++++++++++++++++++
2955+ own implementation that does not subclass from TestCase, of course.
2956"""
2957
2958 for type_changer in (lambda x: x, lambda x: x.decode('utf8')):
2959 try:
2960 self.assertMultiLineEqual(type_changer(sample_text),
2961 type_changer(revised_sample_text))
2962 except self.failureException, e:
Michael Foordfe6349c2010-02-08 22:41:16 +00002963 # assertMultiLineEqual is hooked up as the default for
2964 # unicode strings - so we can't use it for this check
2965 self.assertTrue(sample_text_error == str(e).encode('utf8'))
Gregory P. Smith28399852009-03-31 16:54:10 +00002966
2967 def testAssertIsNone(self):
2968 self.assertIsNone(None)
2969 self.assertRaises(self.failureException, self.assertIsNone, False)
2970 self.assertIsNotNone('DjZoPloGears on Rails')
2971 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2972
2973 def testAssertRegexpMatches(self):
2974 self.assertRegexpMatches('asdfabasdf', r'ab+')
2975 self.assertRaises(self.failureException, self.assertRegexpMatches,
2976 'saaas', r'aaaa')
2977
2978 def testAssertRaisesRegexp(self):
2979 class ExceptionMock(Exception):
2980 pass
2981
2982 def Stub():
2983 raise ExceptionMock('We expect')
2984
2985 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2986 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2987 self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
2988
2989 def testAssertNotRaisesRegexp(self):
2990 self.assertRaisesRegexp(
2991 self.failureException, '^Exception not raised$',
2992 self.assertRaisesRegexp, Exception, re.compile('x'),
2993 lambda: None)
2994 self.assertRaisesRegexp(
2995 self.failureException, '^Exception not raised$',
2996 self.assertRaisesRegexp, Exception, 'x',
2997 lambda: None)
2998 self.assertRaisesRegexp(
2999 self.failureException, '^Exception not raised$',
3000 self.assertRaisesRegexp, Exception, u'x',
3001 lambda: None)
3002
3003 def testAssertRaisesRegexpMismatch(self):
3004 def Stub():
3005 raise Exception('Unexpected')
3006
3007 self.assertRaisesRegexp(
3008 self.failureException,
3009 r'"\^Expected\$" does not match "Unexpected"',
3010 self.assertRaisesRegexp, Exception, '^Expected$',
3011 Stub)
3012 self.assertRaisesRegexp(
3013 self.failureException,
3014 r'"\^Expected\$" does not match "Unexpected"',
3015 self.assertRaisesRegexp, Exception, u'^Expected$',
3016 Stub)
3017 self.assertRaisesRegexp(
3018 self.failureException,
3019 r'"\^Expected\$" does not match "Unexpected"',
3020 self.assertRaisesRegexp, Exception,
3021 re.compile('^Expected$'), Stub)
3022
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00003023 def testAssertRaisesExcValue(self):
3024 class ExceptionMock(Exception):
3025 pass
3026
3027 def Stub(foo):
3028 raise ExceptionMock(foo)
3029 v = "particular value"
3030
3031 ctx = self.assertRaises(ExceptionMock)
3032 with ctx:
3033 Stub(v)
Georg Brandldc3694b2010-02-07 17:02:22 +00003034 e = ctx.exception
Ezio Melottib0f5adc2010-01-24 16:58:36 +00003035 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00003036 self.assertEqual(e.args[0], v)
3037
Gregory P. Smith7558d572009-03-31 19:03:28 +00003038 def testSynonymAssertMethodNames(self):
3039 """Test undocumented method name synonyms.
3040
3041 Please do not use these methods names in your own code.
3042
3043 This test confirms their continued existence and functionality
3044 in order to avoid breaking existing code.
3045 """
3046 self.assertNotEquals(3, 5)
3047 self.assertEquals(3, 3)
3048 self.assertAlmostEquals(2.0, 2.0)
3049 self.assertNotAlmostEquals(3.0, 5.0)
3050 self.assert_(True)
3051
3052 def testPendingDeprecationMethodNames(self):
3053 """Test fail* methods pending deprecation, they will warn in 3.2.
3054
3055 Do not use these methods. They will go away in 3.3.
3056 """
Michael Foord98e7b762010-03-20 03:00:34 +00003057 with test_support.check_warnings():
3058 self.failIfEqual(3, 5)
3059 self.failUnlessEqual(3, 3)
3060 self.failUnlessAlmostEqual(2.0, 2.0)
3061 self.failIfAlmostEqual(3.0, 5.0)
3062 self.failUnless(True)
3063 self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam')
3064 self.failIf(False)
Gregory P. Smith7558d572009-03-31 19:03:28 +00003065
Michael Foorde2942d02009-04-02 05:51:54 +00003066 def testDeepcopy(self):
3067 # Issue: 5660
3068 class TestableTest(TestCase):
3069 def testNothing(self):
3070 pass
3071
3072 test = TestableTest('testNothing')
3073
3074 # This shouldn't blow up
3075 deepcopy(test)
3076
Benjamin Peterson692428e2009-03-23 21:50:21 +00003077
3078class Test_TestSkipping(TestCase):
3079
3080 def test_skipping(self):
3081 class Foo(unittest.TestCase):
3082 def test_skip_me(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00003083 self.skipTest("skip")
Benjamin Peterson692428e2009-03-23 21:50:21 +00003084 events = []
3085 result = LoggingResult(events)
3086 test = Foo("test_skip_me")
3087 test.run(result)
3088 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3089 self.assertEqual(result.skipped, [(test, "skip")])
3090
3091 # Try letting setUp skip the test now.
3092 class Foo(unittest.TestCase):
3093 def setUp(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00003094 self.skipTest("testing")
Benjamin Peterson692428e2009-03-23 21:50:21 +00003095 def test_nothing(self): pass
3096 events = []
3097 result = LoggingResult(events)
3098 test = Foo("test_nothing")
3099 test.run(result)
3100 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3101 self.assertEqual(result.skipped, [(test, "testing")])
3102 self.assertEqual(result.testsRun, 1)
3103
3104 def test_skipping_decorators(self):
3105 op_table = ((unittest.skipUnless, False, True),
3106 (unittest.skipIf, True, False))
3107 for deco, do_skip, dont_skip in op_table:
3108 class Foo(unittest.TestCase):
3109 @deco(do_skip, "testing")
3110 def test_skip(self): pass
3111
3112 @deco(dont_skip, "testing")
3113 def test_dont_skip(self): pass
3114 test_do_skip = Foo("test_skip")
3115 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003116 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003117 events = []
3118 result = LoggingResult(events)
3119 suite.run(result)
3120 self.assertEqual(len(result.skipped), 1)
3121 expected = ['startTest', 'addSkip', 'stopTest',
3122 'startTest', 'addSuccess', 'stopTest']
3123 self.assertEqual(events, expected)
3124 self.assertEqual(result.testsRun, 2)
3125 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
3126 self.assertTrue(result.wasSuccessful())
3127
3128 def test_skip_class(self):
3129 @unittest.skip("testing")
3130 class Foo(unittest.TestCase):
3131 def test_1(self):
3132 record.append(1)
3133 record = []
3134 result = unittest.TestResult()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003135 test = Foo("test_1")
3136 suite = unittest.TestSuite([test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003137 suite.run(result)
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003138 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003139 self.assertEqual(record, [])
3140
3141 def test_expected_failure(self):
3142 class Foo(unittest.TestCase):
3143 @unittest.expectedFailure
3144 def test_die(self):
3145 self.fail("help me!")
3146 events = []
3147 result = LoggingResult(events)
3148 test = Foo("test_die")
3149 test.run(result)
3150 self.assertEqual(events,
3151 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003152 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00003153 self.assertTrue(result.wasSuccessful())
3154
3155 def test_unexpected_success(self):
3156 class Foo(unittest.TestCase):
3157 @unittest.expectedFailure
3158 def test_die(self):
3159 pass
3160 events = []
3161 result = LoggingResult(events)
3162 test = Foo("test_die")
3163 test.run(result)
3164 self.assertEqual(events,
3165 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3166 self.assertFalse(result.failures)
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003167 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003168 self.assertTrue(result.wasSuccessful())
3169
Michael Foord53e8eea2010-03-07 20:22:12 +00003170 def test_skip_doesnt_run_setup(self):
3171 class Foo(unittest.TestCase):
3172 wasSetUp = False
3173 wasTornDown = False
3174 def setUp(self):
3175 Foo.wasSetUp = True
3176 def tornDown(self):
3177 Foo.wasTornDown = True
3178 @unittest.skip('testing')
3179 def test_1(self):
3180 pass
3181
3182 result = unittest.TestResult()
3183 test = Foo("test_1")
3184 suite = unittest.TestSuite([test])
3185 suite.run(result)
3186 self.assertEqual(result.skipped, [(test, "testing")])
3187 self.assertFalse(Foo.wasSetUp)
3188 self.assertFalse(Foo.wasTornDown)
3189
3190 def test_decorated_skip(self):
3191 def decorator(func):
3192 def inner(*a):
3193 return func(*a)
3194 return inner
3195
3196 class Foo(unittest.TestCase):
3197 @decorator
3198 @unittest.skip('testing')
3199 def test_1(self):
3200 pass
3201
3202 result = unittest.TestResult()
3203 test = Foo("test_1")
3204 suite = unittest.TestSuite([test])
3205 suite.run(result)
3206 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003207
3208
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003209class Test_Assertions(TestCase):
3210 def test_AlmostEqual(self):
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003211 self.assertAlmostEqual(1.00000001, 1.0)
3212 self.assertNotAlmostEqual(1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003213 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003214 self.assertAlmostEqual, 1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003215 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003216 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003217
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003218 self.assertAlmostEqual(1.1, 1.0, places=0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003219 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003220 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003221
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003222 self.assertAlmostEqual(0, .1+.1j, places=0)
3223 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003224 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003225 self.assertAlmostEqual, 0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003226 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003227 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003228
Michael Foordc3f79372009-09-13 16:40:02 +00003229 self.assertAlmostEqual(float('inf'), float('inf'))
3230 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3231 float('inf'), float('inf'))
3232
3233
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003234 def test_assertRaises(self):
3235 def _raise(e):
3236 raise e
3237 self.assertRaises(KeyError, _raise, KeyError)
3238 self.assertRaises(KeyError, _raise, KeyError("key"))
3239 try:
3240 self.assertRaises(KeyError, lambda: None)
Gregory P. Smith28399852009-03-31 16:54:10 +00003241 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003242 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003243 else:
3244 self.fail("assertRaises() didn't fail")
3245 try:
3246 self.assertRaises(KeyError, _raise, ValueError)
3247 except ValueError:
3248 pass
3249 else:
3250 self.fail("assertRaises() didn't let exception pass through")
Michael Foord2bd52dc2010-02-07 18:44:12 +00003251 with self.assertRaises(KeyError) as cm:
3252 try:
3253 raise KeyError
3254 except Exception, e:
3255 raise
3256 self.assertIs(cm.exception, e)
3257
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003258 with self.assertRaises(KeyError):
3259 raise KeyError("key")
3260 try:
3261 with self.assertRaises(KeyError):
3262 pass
Gregory P. Smith28399852009-03-31 16:54:10 +00003263 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003264 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003265 else:
3266 self.fail("assertRaises() didn't fail")
3267 try:
3268 with self.assertRaises(KeyError):
3269 raise ValueError
3270 except ValueError:
3271 pass
3272 else:
3273 self.fail("assertRaises() didn't let exception pass through")
3274
3275
Michael Foord345b2fe2009-04-02 03:20:38 +00003276class TestLongMessage(TestCase):
3277 """Test that the individual asserts honour longMessage.
3278 This actually tests all the message behaviour for
3279 asserts that use longMessage."""
3280
3281 def setUp(self):
3282 class TestableTestFalse(TestCase):
3283 longMessage = False
3284 failureException = self.failureException
3285
3286 def testTest(self):
3287 pass
3288
3289 class TestableTestTrue(TestCase):
3290 longMessage = True
3291 failureException = self.failureException
3292
3293 def testTest(self):
3294 pass
3295
3296 self.testableTrue = TestableTestTrue('testTest')
3297 self.testableFalse = TestableTestFalse('testTest')
3298
3299 def testDefault(self):
3300 self.assertFalse(TestCase.longMessage)
3301
3302 def test_formatMsg(self):
3303 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3304 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3305
3306 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3307 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3308
Michael Foord53e8eea2010-03-07 20:22:12 +00003309 # This blows up if _formatMessage uses string concatenation
3310 self.testableTrue._formatMessage(object(), 'foo')
3311
3312 def test_formatMessage_unicode_error(self):
3313 with warnings.catch_warnings(record=True):
3314 # This causes a UnicodeWarning due to its craziness
3315 one = ''.join(chr(i) for i in range(255))
3316 # this used to cause a UnicodeDecodeError constructing msg
3317 self.testableTrue._formatMessage(one, u'\uFFFD')
3318
Michael Foord345b2fe2009-04-02 03:20:38 +00003319 def assertMessages(self, methodName, args, errors):
3320 def getMethod(i):
3321 useTestableFalse = i < 2
3322 if useTestableFalse:
3323 test = self.testableFalse
3324 else:
3325 test = self.testableTrue
3326 return getattr(test, methodName)
3327
3328 for i, expected_regexp in enumerate(errors):
3329 testMethod = getMethod(i)
3330 kwargs = {}
3331 withMsg = i % 2
3332 if withMsg:
3333 kwargs = {"msg": "oops"}
3334
3335 with self.assertRaisesRegexp(self.failureException,
3336 expected_regexp=expected_regexp):
3337 testMethod(*args, **kwargs)
3338
3339 def testAssertTrue(self):
3340 self.assertMessages('assertTrue', (False,),
3341 ["^False is not True$", "^oops$", "^False is not True$",
3342 "^False is not True : oops$"])
3343
3344 def testAssertFalse(self):
3345 self.assertMessages('assertFalse', (True,),
3346 ["^True is not False$", "^oops$", "^True is not False$",
3347 "^True is not False : oops$"])
3348
3349 def testNotEqual(self):
3350 self.assertMessages('assertNotEqual', (1, 1),
3351 ["^1 == 1$", "^oops$", "^1 == 1$",
3352 "^1 == 1 : oops$"])
3353
3354 def testAlmostEqual(self):
3355 self.assertMessages('assertAlmostEqual', (1, 2),
3356 ["^1 != 2 within 7 places$", "^oops$",
3357 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3358
3359 def testNotAlmostEqual(self):
3360 self.assertMessages('assertNotAlmostEqual', (1, 1),
3361 ["^1 == 1 within 7 places$", "^oops$",
3362 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3363
3364 def test_baseAssertEqual(self):
3365 self.assertMessages('_baseAssertEqual', (1, 2),
3366 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3367
3368 def testAssertSequenceEqual(self):
3369 # Error messages are multiline so not testing on full message
3370 # assertTupleEqual and assertListEqual delegate to this method
3371 self.assertMessages('assertSequenceEqual', ([], [None]),
3372 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3373 r"\+ \[None\] : oops$"])
3374
3375 def testAssertSetEqual(self):
3376 self.assertMessages('assertSetEqual', (set(), set([None])),
3377 ["None$", "^oops$", "None$",
3378 "None : oops$"])
3379
3380 def testAssertIn(self):
3381 self.assertMessages('assertIn', (None, []),
3382 ['^None not found in \[\]$', "^oops$",
3383 '^None not found in \[\]$',
3384 '^None not found in \[\] : oops$'])
3385
3386 def testAssertNotIn(self):
3387 self.assertMessages('assertNotIn', (None, [None]),
3388 ['^None unexpectedly found in \[None\]$', "^oops$",
3389 '^None unexpectedly found in \[None\]$',
3390 '^None unexpectedly found in \[None\] : oops$'])
3391
3392 def testAssertDictEqual(self):
3393 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3394 [r"\+ \{'key': 'value'\}$", "^oops$",
3395 "\+ \{'key': 'value'\}$",
3396 "\+ \{'key': 'value'\} : oops$"])
3397
3398 def testAssertDictContainsSubset(self):
3399 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3400 ["^Missing: 'key'$", "^oops$",
3401 "^Missing: 'key'$",
3402 "^Missing: 'key' : oops$"])
3403
Michael Foord98e7b762010-03-20 03:00:34 +00003404 def testAssertItemsEqual(self):
3405 self.assertMessages('assertItemsEqual', ([], [None]),
Michael Foord345b2fe2009-04-02 03:20:38 +00003406 [r"\[None\]$", "^oops$",
3407 r"\[None\]$",
3408 r"\[None\] : oops$"])
3409
3410 def testAssertMultiLineEqual(self):
3411 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3412 [r"\+ foo$", "^oops$",
3413 r"\+ foo$",
3414 r"\+ foo : oops$"])
3415
3416 def testAssertLess(self):
3417 self.assertMessages('assertLess', (2, 1),
3418 ["^2 not less than 1$", "^oops$",
3419 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3420
3421 def testAssertLessEqual(self):
3422 self.assertMessages('assertLessEqual', (2, 1),
3423 ["^2 not less than or equal to 1$", "^oops$",
3424 "^2 not less than or equal to 1$",
3425 "^2 not less than or equal to 1 : oops$"])
3426
3427 def testAssertGreater(self):
3428 self.assertMessages('assertGreater', (1, 2),
3429 ["^1 not greater than 2$", "^oops$",
3430 "^1 not greater than 2$",
3431 "^1 not greater than 2 : oops$"])
3432
3433 def testAssertGreaterEqual(self):
3434 self.assertMessages('assertGreaterEqual', (1, 2),
3435 ["^1 not greater than or equal to 2$", "^oops$",
3436 "^1 not greater than or equal to 2$",
3437 "^1 not greater than or equal to 2 : oops$"])
3438
3439 def testAssertIsNone(self):
3440 self.assertMessages('assertIsNone', ('not None',),
3441 ["^'not None' is not None$", "^oops$",
3442 "^'not None' is not None$",
3443 "^'not None' is not None : oops$"])
3444
3445 def testAssertIsNotNone(self):
3446 self.assertMessages('assertIsNotNone', (None,),
3447 ["^unexpectedly None$", "^oops$",
3448 "^unexpectedly None$",
3449 "^unexpectedly None : oops$"])
3450
Michael Foordf2dfef12009-04-05 19:19:28 +00003451 def testAssertIs(self):
3452 self.assertMessages('assertIs', (None, 'foo'),
3453 ["^None is not 'foo'$", "^oops$",
3454 "^None is not 'foo'$",
3455 "^None is not 'foo' : oops$"])
3456
3457 def testAssertIsNot(self):
3458 self.assertMessages('assertIsNot', (None, None),
3459 ["^unexpectedly identical: None$", "^oops$",
3460 "^unexpectedly identical: None$",
3461 "^unexpectedly identical: None : oops$"])
3462
Michael Foord345b2fe2009-04-02 03:20:38 +00003463
Michael Foorde2fb98f2009-05-02 20:15:05 +00003464class TestCleanUp(TestCase):
3465
3466 def testCleanUp(self):
3467 class TestableTest(TestCase):
3468 def testNothing(self):
3469 pass
3470
3471 test = TestableTest('testNothing')
3472 self.assertEqual(test._cleanups, [])
3473
3474 cleanups = []
3475
3476 def cleanup1(*args, **kwargs):
3477 cleanups.append((1, args, kwargs))
3478
3479 def cleanup2(*args, **kwargs):
3480 cleanups.append((2, args, kwargs))
3481
3482 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3483 test.addCleanup(cleanup2)
3484
3485 self.assertEqual(test._cleanups,
3486 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3487 (cleanup2, (), {})])
3488
3489 result = test.doCleanups()
3490 self.assertTrue(result)
3491
3492 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3493
3494 def testCleanUpWithErrors(self):
3495 class TestableTest(TestCase):
3496 def testNothing(self):
3497 pass
3498
3499 class MockResult(object):
3500 errors = []
3501 def addError(self, test, exc_info):
3502 self.errors.append((test, exc_info))
3503
3504 result = MockResult()
3505 test = TestableTest('testNothing')
Michael Foorda50af062009-05-21 22:57:02 +00003506 test._resultForDoCleanups = result
Michael Foorde2fb98f2009-05-02 20:15:05 +00003507
3508 exc1 = Exception('foo')
3509 exc2 = Exception('bar')
3510 def cleanup1():
3511 raise exc1
3512
3513 def cleanup2():
3514 raise exc2
3515
3516 test.addCleanup(cleanup1)
3517 test.addCleanup(cleanup2)
3518
3519 self.assertFalse(test.doCleanups())
3520
3521 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3522 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3523 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3524
3525 def testCleanupInRun(self):
3526 blowUp = False
3527 ordering = []
3528
3529 class TestableTest(TestCase):
3530 def setUp(self):
3531 ordering.append('setUp')
3532 if blowUp:
3533 raise Exception('foo')
3534
3535 def testNothing(self):
3536 ordering.append('test')
3537
3538 def tearDown(self):
3539 ordering.append('tearDown')
3540
3541 test = TestableTest('testNothing')
3542
3543 def cleanup1():
3544 ordering.append('cleanup1')
3545 def cleanup2():
3546 ordering.append('cleanup2')
3547 test.addCleanup(cleanup1)
3548 test.addCleanup(cleanup2)
3549
3550 def success(some_test):
3551 self.assertEqual(some_test, test)
3552 ordering.append('success')
3553
3554 result = unittest.TestResult()
3555 result.addSuccess = success
3556
3557 test.run(result)
3558 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3559 'cleanup2', 'cleanup1', 'success'])
3560
3561 blowUp = True
3562 ordering = []
3563 test = TestableTest('testNothing')
3564 test.addCleanup(cleanup1)
3565 test.run(result)
3566 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3567
3568
Michael Foord829f6b82009-05-02 11:43:06 +00003569class Test_TestProgram(TestCase):
3570
3571 # Horrible white box test
3572 def testNoExit(self):
3573 result = object()
3574 test = object()
3575
3576 class FakeRunner(object):
3577 def run(self, test):
3578 self.test = test
3579 return result
3580
3581 runner = FakeRunner()
3582
Michael Foord5d31e052009-05-11 17:59:43 +00003583 oldParseArgs = TestProgram.parseArgs
3584 def restoreParseArgs():
Michael Foord829f6b82009-05-02 11:43:06 +00003585 TestProgram.parseArgs = oldParseArgs
Michael Foord5d31e052009-05-11 17:59:43 +00003586 TestProgram.parseArgs = lambda *args: None
3587 self.addCleanup(restoreParseArgs)
3588
3589 def removeTest():
Michael Foord829f6b82009-05-02 11:43:06 +00003590 del TestProgram.test
Michael Foord5d31e052009-05-11 17:59:43 +00003591 TestProgram.test = test
3592 self.addCleanup(removeTest)
3593
3594 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3595
3596 self.assertEqual(program.result, result)
3597 self.assertEqual(runner.test, test)
3598 self.assertEqual(program.verbosity, 2)
Michael Foord829f6b82009-05-02 11:43:06 +00003599
Michael Foord829f6b82009-05-02 11:43:06 +00003600 class FooBar(unittest.TestCase):
3601 def testPass(self):
3602 assert True
3603 def testFail(self):
3604 assert False
3605
3606 class FooBarLoader(unittest.TestLoader):
3607 """Test loader that returns a suite containing FooBar."""
3608 def loadTestsFromModule(self, module):
3609 return self.suiteClass(
3610 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3611
3612
3613 def test_NonExit(self):
3614 program = unittest.main(exit=False,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003615 argv=["foobar"],
3616 testRunner=unittest.TextTestRunner(stream=StringIO()),
3617 testLoader=self.FooBarLoader())
Michael Foord829f6b82009-05-02 11:43:06 +00003618 self.assertTrue(hasattr(program, 'result'))
3619
3620
3621 def test_Exit(self):
3622 self.assertRaises(
3623 SystemExit,
3624 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003625 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003626 testRunner=unittest.TextTestRunner(stream=StringIO()),
3627 exit=True,
3628 testLoader=self.FooBarLoader())
3629
3630
3631 def test_ExitAsDefault(self):
3632 self.assertRaises(
3633 SystemExit,
3634 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003635 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003636 testRunner=unittest.TextTestRunner(stream=StringIO()),
3637 testLoader=self.FooBarLoader())
3638
3639
Michael Foord07ef4872009-05-02 22:43:34 +00003640class Test_TextTestRunner(TestCase):
3641 """Tests for TextTestRunner."""
3642
3643 def test_works_with_result_without_startTestRun_stopTestRun(self):
3644 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3645 separator2 = ''
3646 def printErrors(self):
3647 pass
3648
3649 class Runner(unittest.TextTestRunner):
3650 def __init__(self):
3651 super(Runner, self).__init__(StringIO())
3652
3653 def _makeResult(self):
3654 return OldTextResult()
3655
3656 runner = Runner()
3657 runner.run(unittest.TestSuite())
3658
3659 def test_startTestRun_stopTestRun_called(self):
3660 class LoggingTextResult(LoggingResult):
3661 separator2 = ''
3662 def printErrors(self):
3663 pass
3664
3665 class LoggingRunner(unittest.TextTestRunner):
3666 def __init__(self, events):
3667 super(LoggingRunner, self).__init__(StringIO())
3668 self._events = events
3669
3670 def _makeResult(self):
3671 return LoggingTextResult(self._events)
3672
3673 events = []
3674 runner = LoggingRunner(events)
3675 runner.run(unittest.TestSuite())
3676 expected = ['startTestRun', 'stopTestRun']
3677 self.assertEqual(events, expected)
3678
Antoine Pitrou0734c632009-11-10 20:49:30 +00003679 def test_pickle_unpickle(self):
3680 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3681 # required by test_multiprocessing under Windows (in verbose mode).
3682 import StringIO
3683 # cStringIO objects are not pickleable, but StringIO objects are.
3684 stream = StringIO.StringIO("foo")
3685 runner = unittest.TextTestRunner(stream)
3686 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
3687 s = pickle.dumps(runner, protocol=protocol)
3688 obj = pickle.loads(s)
3689 # StringIO objects never compare equal, a cheap test instead.
3690 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3691
Michael Foorddb43b5a2010-02-10 14:25:12 +00003692 def test_resultclass(self):
3693 def MockResultClass(*args):
3694 return args
3695 STREAM = object()
3696 DESCRIPTIONS = object()
3697 VERBOSITY = object()
3698 runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY,
3699 resultclass=MockResultClass)
3700 self.assertEqual(runner.resultclass, MockResultClass)
3701
3702 expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY)
3703 self.assertEqual(runner._makeResult(), expectedresult)
3704
Michael Foord07ef4872009-05-02 22:43:34 +00003705
Michael Foordb4a81c82009-05-29 20:33:46 +00003706class TestDiscovery(TestCase):
3707
3708 # Heavily mocked tests so I can avoid hitting the filesystem
Michael Foorde91ea562009-09-13 19:07:03 +00003709 def test_get_name_from_path(self):
Michael Foordb4a81c82009-05-29 20:33:46 +00003710 loader = unittest.TestLoader()
3711
Michael Foordb4a81c82009-05-29 20:33:46 +00003712 loader._top_level_dir = '/foo'
Michael Foorde91ea562009-09-13 19:07:03 +00003713 name = loader._get_name_from_path('/foo/bar/baz.py')
3714 self.assertEqual(name, 'bar.baz')
Michael Foordb4a81c82009-05-29 20:33:46 +00003715
3716 if not __debug__:
3717 # asserts are off
3718 return
3719
3720 with self.assertRaises(AssertionError):
Michael Foorde91ea562009-09-13 19:07:03 +00003721 loader._get_name_from_path('/bar/baz.py')
Michael Foordb4a81c82009-05-29 20:33:46 +00003722
3723 def test_find_tests(self):
3724 loader = unittest.TestLoader()
3725
3726 original_listdir = os.listdir
3727 def restore_listdir():
3728 os.listdir = original_listdir
3729 original_isfile = os.path.isfile
3730 def restore_isfile():
3731 os.path.isfile = original_isfile
3732 original_isdir = os.path.isdir
3733 def restore_isdir():
3734 os.path.isdir = original_isdir
3735
3736 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Michael Foorde91ea562009-09-13 19:07:03 +00003737 'test.foo', 'test-not-a-module.py', 'another_dir'],
Michael Foordb4a81c82009-05-29 20:33:46 +00003738 ['test3.py', 'test4.py', ]]
3739 os.listdir = lambda path: path_lists.pop(0)
3740 self.addCleanup(restore_listdir)
3741
3742 def isdir(path):
3743 return path.endswith('dir')
3744 os.path.isdir = isdir
3745 self.addCleanup(restore_isdir)
3746
3747 def isfile(path):
3748 # another_dir is not a package and so shouldn't be recursed into
3749 return not path.endswith('dir') and not 'another_dir' in path
3750 os.path.isfile = isfile
3751 self.addCleanup(restore_isfile)
3752
Michael Foorde91ea562009-09-13 19:07:03 +00003753 loader._get_module_from_name = lambda path: path + ' module'
Michael Foordb4a81c82009-05-29 20:33:46 +00003754 loader.loadTestsFromModule = lambda module: module + ' tests'
3755
3756 loader._top_level_dir = '/foo'
3757 suite = list(loader._find_tests('/foo', 'test*.py'))
3758
Michael Foorde91ea562009-09-13 19:07:03 +00003759 expected = [name + ' module tests' for name in
3760 ('test1', 'test2')]
3761 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3762 ('test3', 'test4')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003763 self.assertEqual(suite, expected)
3764
3765 def test_find_tests_with_package(self):
3766 loader = unittest.TestLoader()
3767
3768 original_listdir = os.listdir
3769 def restore_listdir():
3770 os.listdir = original_listdir
3771 original_isfile = os.path.isfile
3772 def restore_isfile():
3773 os.path.isfile = original_isfile
3774 original_isdir = os.path.isdir
3775 def restore_isdir():
3776 os.path.isdir = original_isdir
3777
3778 directories = ['a_directory', 'test_directory', 'test_directory2']
3779 path_lists = [directories, [], [], []]
3780 os.listdir = lambda path: path_lists.pop(0)
3781 self.addCleanup(restore_listdir)
3782
3783 os.path.isdir = lambda path: True
3784 self.addCleanup(restore_isdir)
3785
3786 os.path.isfile = lambda path: os.path.basename(path) not in directories
3787 self.addCleanup(restore_isfile)
3788
3789 class Module(object):
3790 paths = []
3791 load_tests_args = []
3792
3793 def __init__(self, path):
3794 self.path = path
3795 self.paths.append(path)
3796 if os.path.basename(path) == 'test_directory':
3797 def load_tests(loader, tests, pattern):
3798 self.load_tests_args.append((loader, tests, pattern))
3799 return 'load_tests'
3800 self.load_tests = load_tests
3801
3802 def __eq__(self, other):
3803 return self.path == other.path
3804
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003805 # Silence py3k warning
3806 __hash__ = None
3807
Michael Foorde91ea562009-09-13 19:07:03 +00003808 loader._get_module_from_name = lambda name: Module(name)
Michael Foordb4a81c82009-05-29 20:33:46 +00003809 def loadTestsFromModule(module, use_load_tests):
3810 if use_load_tests:
3811 raise self.failureException('use_load_tests should be False for packages')
3812 return module.path + ' module tests'
3813 loader.loadTestsFromModule = loadTestsFromModule
3814
3815 loader._top_level_dir = '/foo'
3816 # this time no '.py' on the pattern so that it can match
3817 # a test package
3818 suite = list(loader._find_tests('/foo', 'test*'))
3819
3820 # We should have loaded tests from the test_directory package by calling load_tests
3821 # and directly from the test_directory2 package
Michael Foordd53d0852009-06-05 14:14:34 +00003822 self.assertEqual(suite,
Michael Foorde91ea562009-09-13 19:07:03 +00003823 ['load_tests', 'test_directory2' + ' module tests'])
3824 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Michael Foordb4a81c82009-05-29 20:33:46 +00003825
3826 # load_tests should have been called once with loader, tests and pattern
3827 self.assertEqual(Module.load_tests_args,
Michael Foorde91ea562009-09-13 19:07:03 +00003828 [(loader, 'test_directory' + ' module tests', 'test*')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003829
3830 def test_discover(self):
3831 loader = unittest.TestLoader()
3832
3833 original_isfile = os.path.isfile
3834 def restore_isfile():
3835 os.path.isfile = original_isfile
3836
3837 os.path.isfile = lambda path: False
3838 self.addCleanup(restore_isfile)
3839
Nick Coghlanb6edf192009-10-17 08:21:21 +00003840 orig_sys_path = sys.path[:]
3841 def restore_path():
3842 sys.path[:] = orig_sys_path
3843 self.addCleanup(restore_path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003844
Nick Coghlanb6edf192009-10-17 08:21:21 +00003845 full_path = os.path.abspath(os.path.normpath('/foo'))
Michael Foordb4a81c82009-05-29 20:33:46 +00003846 with self.assertRaises(ImportError):
3847 loader.discover('/foo/bar', top_level_dir='/foo')
3848
3849 self.assertEqual(loader._top_level_dir, full_path)
3850 self.assertIn(full_path, sys.path)
3851
3852 os.path.isfile = lambda path: True
3853 _find_tests_args = []
3854 def _find_tests(start_dir, pattern):
3855 _find_tests_args.append((start_dir, pattern))
3856 return ['tests']
3857 loader._find_tests = _find_tests
3858 loader.suiteClass = str
3859
3860 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3861
3862 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3863 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3864 self.assertEqual(suite, "['tests']")
3865 self.assertEqual(loader._top_level_dir, top_level_dir)
3866 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlanb6edf192009-10-17 08:21:21 +00003867 self.assertIn(top_level_dir, sys.path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003868
Michael Foorde91ea562009-09-13 19:07:03 +00003869 def test_discover_with_modules_that_fail_to_import(self):
3870 loader = unittest.TestLoader()
3871
3872 listdir = os.listdir
3873 os.listdir = lambda _: ['test_this_does_not_exist.py']
3874 isfile = os.path.isfile
3875 os.path.isfile = lambda _: True
Nick Coghlanb6edf192009-10-17 08:21:21 +00003876 orig_sys_path = sys.path[:]
Michael Foorde91ea562009-09-13 19:07:03 +00003877 def restore():
3878 os.path.isfile = isfile
3879 os.listdir = listdir
Nick Coghlanb6edf192009-10-17 08:21:21 +00003880 sys.path[:] = orig_sys_path
Michael Foorde91ea562009-09-13 19:07:03 +00003881 self.addCleanup(restore)
3882
3883 suite = loader.discover('.')
Nick Coghlanb6edf192009-10-17 08:21:21 +00003884 self.assertIn(os.getcwd(), sys.path)
Michael Foorde91ea562009-09-13 19:07:03 +00003885 self.assertEqual(suite.countTestCases(), 1)
3886 test = list(list(suite)[0])[0] # extract test from suite
3887
3888 with self.assertRaises(ImportError):
3889 test.test_this_does_not_exist()
3890
Michael Foordb4a81c82009-05-29 20:33:46 +00003891 def test_command_line_handling_parseArgs(self):
3892 # Haha - take that uninstantiable class
3893 program = object.__new__(TestProgram)
3894
3895 args = []
3896 def do_discovery(argv):
3897 args.extend(argv)
3898 program._do_discovery = do_discovery
3899 program.parseArgs(['something', 'discover'])
3900 self.assertEqual(args, [])
3901
3902 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3903 self.assertEqual(args, ['foo', 'bar'])
3904
3905 def test_command_line_handling_do_discovery_too_many_arguments(self):
3906 class Stop(Exception):
3907 pass
3908 def usageExit():
3909 raise Stop
3910
3911 program = object.__new__(TestProgram)
3912 program.usageExit = usageExit
3913
3914 with self.assertRaises(Stop):
3915 # too many args
3916 program._do_discovery(['one', 'two', 'three', 'four'])
3917
3918
3919 def test_command_line_handling_do_discovery_calls_loader(self):
3920 program = object.__new__(TestProgram)
3921
3922 class Loader(object):
3923 args = []
3924 def discover(self, start_dir, pattern, top_level_dir):
3925 self.args.append((start_dir, pattern, top_level_dir))
3926 return 'tests'
3927
3928 program._do_discovery(['-v'], Loader=Loader)
3929 self.assertEqual(program.verbosity, 2)
3930 self.assertEqual(program.test, 'tests')
3931 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3932
3933 Loader.args = []
3934 program = object.__new__(TestProgram)
3935 program._do_discovery(['--verbose'], Loader=Loader)
3936 self.assertEqual(program.test, 'tests')
3937 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3938
3939 Loader.args = []
3940 program = object.__new__(TestProgram)
3941 program._do_discovery([], Loader=Loader)
3942 self.assertEqual(program.test, 'tests')
3943 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3944
3945 Loader.args = []
3946 program = object.__new__(TestProgram)
3947 program._do_discovery(['fish'], Loader=Loader)
3948 self.assertEqual(program.test, 'tests')
3949 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3950
3951 Loader.args = []
3952 program = object.__new__(TestProgram)
3953 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3954 self.assertEqual(program.test, 'tests')
3955 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3956
3957 Loader.args = []
3958 program = object.__new__(TestProgram)
3959 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3960 self.assertEqual(program.test, 'tests')
3961 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3962
3963 Loader.args = []
3964 program = object.__new__(TestProgram)
3965 program._do_discovery(['-s', 'fish'], Loader=Loader)
3966 self.assertEqual(program.test, 'tests')
3967 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3968
3969 Loader.args = []
3970 program = object.__new__(TestProgram)
3971 program._do_discovery(['-t', 'fish'], Loader=Loader)
3972 self.assertEqual(program.test, 'tests')
3973 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3974
3975 Loader.args = []
3976 program = object.__new__(TestProgram)
3977 program._do_discovery(['-p', 'fish'], Loader=Loader)
3978 self.assertEqual(program.test, 'tests')
3979 self.assertEqual(Loader.args, [('.', 'fish', None)])
3980
3981 Loader.args = []
3982 program = object.__new__(TestProgram)
3983 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3984 self.assertEqual(program.test, 'tests')
3985 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3986 self.assertEqual(program.verbosity, 2)
3987
3988
Michael Foord5ffa3252010-03-07 22:04:55 +00003989class TestSetups(unittest.TestCase):
3990
3991 def getRunner(self):
3992 return unittest.TextTestRunner(resultclass=resultFactory,
3993 stream=StringIO())
3994 def runTests(self, *cases):
3995 suite = unittest.TestSuite()
3996 for case in cases:
3997 tests = unittest.defaultTestLoader.loadTestsFromTestCase(case)
3998 suite.addTests(tests)
3999
4000 runner = self.getRunner()
4001
4002 # creating a nested suite exposes some potential bugs
4003 realSuite = unittest.TestSuite()
4004 realSuite.addTest(suite)
4005 # adding empty suites to the end exposes potential bugs
4006 suite.addTest(unittest.TestSuite())
4007 realSuite.addTest(unittest.TestSuite())
4008 return runner.run(realSuite)
4009
4010 def test_setup_class(self):
4011 class Test(unittest.TestCase):
4012 setUpCalled = 0
4013 @classmethod
4014 def setUpClass(cls):
4015 Test.setUpCalled += 1
4016 unittest.TestCase.setUpClass()
4017 def test_one(self):
4018 pass
4019 def test_two(self):
4020 pass
4021
4022 result = self.runTests(Test)
4023
4024 self.assertEqual(Test.setUpCalled, 1)
4025 self.assertEqual(result.testsRun, 2)
4026 self.assertEqual(len(result.errors), 0)
4027
4028 def test_teardown_class(self):
4029 class Test(unittest.TestCase):
4030 tearDownCalled = 0
4031 @classmethod
4032 def tearDownClass(cls):
4033 Test.tearDownCalled += 1
4034 unittest.TestCase.tearDownClass()
4035 def test_one(self):
4036 pass
4037 def test_two(self):
4038 pass
4039
4040 result = self.runTests(Test)
4041
4042 self.assertEqual(Test.tearDownCalled, 1)
4043 self.assertEqual(result.testsRun, 2)
4044 self.assertEqual(len(result.errors), 0)
4045
4046 def test_teardown_class_two_classes(self):
4047 class Test(unittest.TestCase):
4048 tearDownCalled = 0
4049 @classmethod
4050 def tearDownClass(cls):
4051 Test.tearDownCalled += 1
4052 unittest.TestCase.tearDownClass()
4053 def test_one(self):
4054 pass
4055 def test_two(self):
4056 pass
4057
4058 class Test2(unittest.TestCase):
4059 tearDownCalled = 0
4060 @classmethod
4061 def tearDownClass(cls):
4062 Test2.tearDownCalled += 1
4063 unittest.TestCase.tearDownClass()
4064 def test_one(self):
4065 pass
4066 def test_two(self):
4067 pass
4068
4069 result = self.runTests(Test, Test2)
4070
4071 self.assertEqual(Test.tearDownCalled, 1)
4072 self.assertEqual(Test2.tearDownCalled, 1)
4073 self.assertEqual(result.testsRun, 4)
4074 self.assertEqual(len(result.errors), 0)
4075
4076 def test_error_in_setupclass(self):
4077 class BrokenTest(unittest.TestCase):
4078 @classmethod
4079 def setUpClass(cls):
4080 raise TypeError('foo')
4081 def test_one(self):
4082 pass
4083 def test_two(self):
4084 pass
4085
4086 result = self.runTests(BrokenTest)
4087
4088 self.assertEqual(result.testsRun, 0)
4089 self.assertEqual(len(result.errors), 1)
4090 error, _ = result.errors[0]
4091 self.assertEqual(str(error),
4092 'classSetUp (%s.BrokenTest)' % __name__)
4093
4094 def test_error_in_teardown_class(self):
4095 class Test(unittest.TestCase):
4096 tornDown = 0
4097 @classmethod
4098 def tearDownClass(cls):
4099 Test.tornDown += 1
4100 raise TypeError('foo')
4101 def test_one(self):
4102 pass
4103 def test_two(self):
4104 pass
4105
4106 class Test2(unittest.TestCase):
4107 tornDown = 0
4108 @classmethod
4109 def tearDownClass(cls):
4110 Test2.tornDown += 1
4111 raise TypeError('foo')
4112 def test_one(self):
4113 pass
4114 def test_two(self):
4115 pass
4116
4117 result = self.runTests(Test, Test2)
4118 self.assertEqual(result.testsRun, 4)
4119 self.assertEqual(len(result.errors), 2)
4120 self.assertEqual(Test.tornDown, 1)
4121 self.assertEqual(Test2.tornDown, 1)
4122
4123 error, _ = result.errors[0]
4124 self.assertEqual(str(error),
4125 'classTearDown (%s.Test)' % __name__)
4126
4127 def test_class_not_torndown_when_setup_fails(self):
4128 class Test(unittest.TestCase):
4129 tornDown = False
4130 @classmethod
4131 def setUpClass(cls):
4132 raise TypeError
4133 @classmethod
4134 def tearDownClass(cls):
4135 Test.tornDown = True
4136 raise TypeError('foo')
4137 def test_one(self):
4138 pass
4139
4140 self.runTests(Test)
4141 self.assertFalse(Test.tornDown)
4142
4143 def test_class_not_setup_or_torndown_when_skipped(self):
4144 class Test(unittest.TestCase):
4145 classSetUp = False
4146 tornDown = False
4147 @classmethod
4148 def setUpClass(cls):
4149 Test.classSetUp = True
4150 @classmethod
4151 def tearDownClass(cls):
4152 Test.tornDown = True
4153 def test_one(self):
4154 pass
4155
4156 Test = unittest.skip("hop")(Test)
4157 self.runTests(Test)
4158 self.assertFalse(Test.classSetUp)
4159 self.assertFalse(Test.tornDown)
4160
4161 def test_setup_teardown_order_with_pathological_suite(self):
4162 results = []
4163
4164 class Module1(object):
4165 @staticmethod
4166 def setUpModule():
4167 results.append('Module1.setUpModule')
4168 @staticmethod
4169 def tearDownModule():
4170 results.append('Module1.tearDownModule')
4171
4172 class Module2(object):
4173 @staticmethod
4174 def setUpModule():
4175 results.append('Module2.setUpModule')
4176 @staticmethod
4177 def tearDownModule():
4178 results.append('Module2.tearDownModule')
4179
4180 class Test1(unittest.TestCase):
4181 @classmethod
4182 def setUpClass(cls):
4183 results.append('setup 1')
4184 @classmethod
4185 def tearDownClass(cls):
4186 results.append('teardown 1')
4187 def testOne(self):
4188 results.append('Test1.testOne')
4189 def testTwo(self):
4190 results.append('Test1.testTwo')
4191
4192 class Test2(unittest.TestCase):
4193 @classmethod
4194 def setUpClass(cls):
4195 results.append('setup 2')
4196 @classmethod
4197 def tearDownClass(cls):
4198 results.append('teardown 2')
4199 def testOne(self):
4200 results.append('Test2.testOne')
4201 def testTwo(self):
4202 results.append('Test2.testTwo')
4203
4204 class Test3(unittest.TestCase):
4205 @classmethod
4206 def setUpClass(cls):
4207 results.append('setup 3')
4208 @classmethod
4209 def tearDownClass(cls):
4210 results.append('teardown 3')
4211 def testOne(self):
4212 results.append('Test3.testOne')
4213 def testTwo(self):
4214 results.append('Test3.testTwo')
4215
4216 Test1.__module__ = Test2.__module__ = 'Module'
4217 Test3.__module__ = 'Module2'
4218 sys.modules['Module'] = Module1
4219 sys.modules['Module2'] = Module2
4220
4221 first = unittest.TestSuite((Test1('testOne'),))
4222 second = unittest.TestSuite((Test1('testTwo'),))
4223 third = unittest.TestSuite((Test2('testOne'),))
4224 fourth = unittest.TestSuite((Test2('testTwo'),))
4225 fifth = unittest.TestSuite((Test3('testOne'),))
4226 sixth = unittest.TestSuite((Test3('testTwo'),))
4227 suite = unittest.TestSuite((first, second, third, fourth, fifth, sixth))
4228
4229 runner = self.getRunner()
4230 result = runner.run(suite)
4231 self.assertEqual(result.testsRun, 6)
4232 self.assertEqual(len(result.errors), 0)
4233
4234 self.assertEqual(results,
4235 ['Module1.setUpModule', 'setup 1',
4236 'Test1.testOne', 'Test1.testTwo', 'teardown 1',
4237 'setup 2', 'Test2.testOne', 'Test2.testTwo',
4238 'teardown 2', 'Module1.tearDownModule',
4239 'Module2.setUpModule', 'setup 3',
4240 'Test3.testOne', 'Test3.testTwo',
4241 'teardown 3', 'Module2.tearDownModule'])
4242
4243 def test_setup_module(self):
4244 class Module(object):
4245 moduleSetup = 0
4246 @staticmethod
4247 def setUpModule():
4248 Module.moduleSetup += 1
4249
4250 class Test(unittest.TestCase):
4251 def test_one(self):
4252 pass
4253 def test_two(self):
4254 pass
4255 Test.__module__ = 'Module'
4256 sys.modules['Module'] = Module
4257
4258 result = self.runTests(Test)
4259 self.assertEqual(Module.moduleSetup, 1)
4260 self.assertEqual(result.testsRun, 2)
4261 self.assertEqual(len(result.errors), 0)
4262
4263 def test_error_in_setup_module(self):
4264 class Module(object):
4265 moduleSetup = 0
4266 moduleTornDown = 0
4267 @staticmethod
4268 def setUpModule():
4269 Module.moduleSetup += 1
4270 raise TypeError('foo')
4271 @staticmethod
4272 def tearDownModule():
4273 Module.moduleTornDown += 1
4274
4275 class Test(unittest.TestCase):
4276 classSetUp = False
4277 classTornDown = False
4278 @classmethod
4279 def setUpClass(cls):
4280 Test.classSetUp = True
4281 @classmethod
4282 def tearDownClass(cls):
4283 Test.classTornDown = True
4284 def test_one(self):
4285 pass
4286 def test_two(self):
4287 pass
4288
4289 class Test2(unittest.TestCase):
4290 def test_one(self):
4291 pass
4292 def test_two(self):
4293 pass
4294 Test.__module__ = 'Module'
4295 Test2.__module__ = 'Module'
4296 sys.modules['Module'] = Module
4297
4298 result = self.runTests(Test, Test2)
4299 self.assertEqual(Module.moduleSetup, 1)
4300 self.assertEqual(Module.moduleTornDown, 0)
4301 self.assertEqual(result.testsRun, 0)
4302 self.assertFalse(Test.classSetUp)
4303 self.assertFalse(Test.classTornDown)
4304 self.assertEqual(len(result.errors), 1)
4305 error, _ = result.errors[0]
4306 self.assertEqual(str(error), 'setUpModule (Module)')
4307
4308 def test_testcase_with_missing_module(self):
4309 class Test(unittest.TestCase):
4310 def test_one(self):
4311 pass
4312 def test_two(self):
4313 pass
4314 Test.__module__ = 'Module'
4315 sys.modules.pop('Module', None)
4316
4317 result = self.runTests(Test)
4318 self.assertEqual(result.testsRun, 2)
4319
4320 def test_teardown_module(self):
4321 class Module(object):
4322 moduleTornDown = 0
4323 @staticmethod
4324 def tearDownModule():
4325 Module.moduleTornDown += 1
4326
4327 class Test(unittest.TestCase):
4328 def test_one(self):
4329 pass
4330 def test_two(self):
4331 pass
4332 Test.__module__ = 'Module'
4333 sys.modules['Module'] = Module
4334
4335 result = self.runTests(Test)
4336 self.assertEqual(Module.moduleTornDown, 1)
4337 self.assertEqual(result.testsRun, 2)
4338 self.assertEqual(len(result.errors), 0)
4339
4340 def test_error_in_teardown_module(self):
4341 class Module(object):
4342 moduleTornDown = 0
4343 @staticmethod
4344 def tearDownModule():
4345 Module.moduleTornDown += 1
4346 raise TypeError('foo')
4347
4348 class Test(unittest.TestCase):
4349 classSetUp = False
4350 classTornDown = False
4351 @classmethod
4352 def setUpClass(cls):
4353 Test.classSetUp = True
4354 @classmethod
4355 def tearDownClass(cls):
4356 Test.classTornDown = True
4357 def test_one(self):
4358 pass
4359 def test_two(self):
4360 pass
4361
4362 class Test2(unittest.TestCase):
4363 def test_one(self):
4364 pass
4365 def test_two(self):
4366 pass
4367 Test.__module__ = 'Module'
4368 Test2.__module__ = 'Module'
4369 sys.modules['Module'] = Module
4370
4371 result = self.runTests(Test, Test2)
4372 self.assertEqual(Module.moduleTornDown, 1)
4373 self.assertEqual(result.testsRun, 4)
4374 self.assertTrue(Test.classSetUp)
4375 self.assertTrue(Test.classTornDown)
4376 self.assertEqual(len(result.errors), 1)
4377 error, _ = result.errors[0]
4378 self.assertEqual(str(error), 'tearDownModule (Module)')
4379
Jim Fultonfafd8742004-08-28 15:22:12 +00004380######################################################################
4381## Main
4382######################################################################
4383
4384def test_main():
Georg Brandl15c5ce92007-03-07 09:09:40 +00004385 test_support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004386 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Michael Foord829f6b82009-05-02 11:43:06 +00004387 Test_TestSkipping, Test_Assertions, TestLongMessage,
Michael Foordae3db0a2010-02-22 23:28:32 +00004388 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner,
Michael Foord5ffa3252010-03-07 22:04:55 +00004389 Test_OldTestResult, TestSetups)
Jim Fultonfafd8742004-08-28 15:22:12 +00004390
Georg Brandl15c5ce92007-03-07 09:09:40 +00004391if __name__ == "__main__":
Tim Petersea5962f2007-03-12 18:07:52 +00004392 test_main()