blob: 048f67b0971f7509a41170119f030c9249799806 [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
Georg Brandl15c5ce92007-03-07 09:09:40 +000025class LoggingResult(unittest.TestResult):
26 def __init__(self, log):
27 self._events = log
28 super(LoggingResult, self).__init__()
29
30 def startTest(self, test):
31 self._events.append('startTest')
32 super(LoggingResult, self).startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +000033
Michael Foord07ef4872009-05-02 22:43:34 +000034 def startTestRun(self):
35 self._events.append('startTestRun')
36 super(LoggingResult, self).startTestRun()
37
Georg Brandl15c5ce92007-03-07 09:09:40 +000038 def stopTest(self, test):
39 self._events.append('stopTest')
40 super(LoggingResult, self).stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +000041
Michael Foord07ef4872009-05-02 22:43:34 +000042 def stopTestRun(self):
43 self._events.append('stopTestRun')
44 super(LoggingResult, self).stopTestRun()
45
Georg Brandl15c5ce92007-03-07 09:09:40 +000046 def addFailure(self, *args):
47 self._events.append('addFailure')
48 super(LoggingResult, self).addFailure(*args)
Tim Petersea5962f2007-03-12 18:07:52 +000049
Benjamin Peterson692428e2009-03-23 21:50:21 +000050 def addSuccess(self, *args):
51 self._events.append('addSuccess')
52 super(LoggingResult, self).addSuccess(*args)
53
Georg Brandl15c5ce92007-03-07 09:09:40 +000054 def addError(self, *args):
55 self._events.append('addError')
56 super(LoggingResult, self).addError(*args)
57
Benjamin Peterson692428e2009-03-23 21:50:21 +000058 def addSkip(self, *args):
59 self._events.append('addSkip')
60 super(LoggingResult, self).addSkip(*args)
61
62 def addExpectedFailure(self, *args):
63 self._events.append('addExpectedFailure')
64 super(LoggingResult, self).addExpectedFailure(*args)
65
66 def addUnexpectedSuccess(self, *args):
67 self._events.append('addUnexpectedSuccess')
68 super(LoggingResult, self).addUnexpectedSuccess(*args)
69
70
Georg Brandl15c5ce92007-03-07 09:09:40 +000071class TestEquality(object):
Michael Foord345b2fe2009-04-02 03:20:38 +000072 """Used as a mixin for TestCase"""
73
Tim Petersea5962f2007-03-12 18:07:52 +000074 # Check for a valid __eq__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000075 def test_eq(self):
76 for obj_1, obj_2 in self.eq_pairs:
77 self.assertEqual(obj_1, obj_2)
78 self.assertEqual(obj_2, obj_1)
Tim Petersea5962f2007-03-12 18:07:52 +000079
80 # Check for a valid __ne__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000081 def test_ne(self):
82 for obj_1, obj_2 in self.ne_pairs:
Benjamin Peterson6b0032f2009-06-30 23:30:12 +000083 self.assertNotEqual(obj_1, obj_2)
84 self.assertNotEqual(obj_2, obj_1)
Tim Petersea5962f2007-03-12 18:07:52 +000085
Georg Brandl15c5ce92007-03-07 09:09:40 +000086class TestHashing(object):
Michael Foord345b2fe2009-04-02 03:20:38 +000087 """Used as a mixin for TestCase"""
88
Tim Petersea5962f2007-03-12 18:07:52 +000089 # Check for a valid __hash__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000090 def test_hash(self):
91 for obj_1, obj_2 in self.eq_pairs:
92 try:
Gregory P. Smith28399852009-03-31 16:54:10 +000093 if not hash(obj_1) == hash(obj_2):
94 self.fail("%r and %r do not hash equal" % (obj_1, obj_2))
Georg Brandl15c5ce92007-03-07 09:09:40 +000095 except KeyboardInterrupt:
96 raise
Georg Brandl15c5ce92007-03-07 09:09:40 +000097 except Exception, e:
Gregory P. Smith28399852009-03-31 16:54:10 +000098 self.fail("Problem hashing %r and %r: %s" % (obj_1, obj_2, e))
Tim Petersea5962f2007-03-12 18:07:52 +000099
Georg Brandl15c5ce92007-03-07 09:09:40 +0000100 for obj_1, obj_2 in self.ne_pairs:
101 try:
Gregory P. Smith28399852009-03-31 16:54:10 +0000102 if hash(obj_1) == hash(obj_2):
103 self.fail("%s and %s hash equal, but shouldn't" %
104 (obj_1, obj_2))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000105 except KeyboardInterrupt:
106 raise
Georg Brandl15c5ce92007-03-07 09:09:40 +0000107 except Exception, e:
108 self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e))
Tim Petersea5962f2007-03-12 18:07:52 +0000109
Georg Brandl15c5ce92007-03-07 09:09:40 +0000110
Benjamin Peterson692428e2009-03-23 21:50:21 +0000111# List subclass we can add attributes to.
112class MyClassSuite(list):
113
Benjamin Peterson176a56c2009-05-25 00:48:58 +0000114 def __init__(self, tests):
Benjamin Peterson692428e2009-03-23 21:50:21 +0000115 super(MyClassSuite, self).__init__(tests)
116
117
Georg Brandl15c5ce92007-03-07 09:09:40 +0000118################################################################
119### /Support code
120
121class Test_TestLoader(TestCase):
122
123 ### Tests for TestLoader.loadTestsFromTestCase
124 ################################################################
125
126 # "Return a suite of all tests cases contained in the TestCase-derived
127 # class testCaseClass"
128 def test_loadTestsFromTestCase(self):
129 class Foo(unittest.TestCase):
130 def test_1(self): pass
131 def test_2(self): pass
132 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000133
Georg Brandl15c5ce92007-03-07 09:09:40 +0000134 tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +0000135
Georg Brandl15c5ce92007-03-07 09:09:40 +0000136 loader = unittest.TestLoader()
137 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +0000138
Georg Brandl15c5ce92007-03-07 09:09:40 +0000139 # "Return a suite of all tests cases contained in the TestCase-derived
140 # class testCaseClass"
141 #
Tim Petersea5962f2007-03-12 18:07:52 +0000142 # Make sure it does the right thing even if no tests were found
Georg Brandl15c5ce92007-03-07 09:09:40 +0000143 def test_loadTestsFromTestCase__no_matches(self):
144 class Foo(unittest.TestCase):
145 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000146
Georg Brandl15c5ce92007-03-07 09:09:40 +0000147 empty_suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +0000148
Georg Brandl15c5ce92007-03-07 09:09:40 +0000149 loader = unittest.TestLoader()
150 self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite)
Tim Petersea5962f2007-03-12 18:07:52 +0000151
Georg Brandl15c5ce92007-03-07 09:09:40 +0000152 # "Return a suite of all tests cases contained in the TestCase-derived
153 # class testCaseClass"
154 #
155 # What happens if loadTestsFromTestCase() is given an object
156 # that isn't a subclass of TestCase? Specifically, what happens
157 # if testCaseClass is a subclass of TestSuite?
158 #
159 # This is checked for specifically in the code, so we better add a
160 # test for it.
161 def test_loadTestsFromTestCase__TestSuite_subclass(self):
162 class NotATestCase(unittest.TestSuite):
163 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000164
Georg Brandl15c5ce92007-03-07 09:09:40 +0000165 loader = unittest.TestLoader()
166 try:
167 loader.loadTestsFromTestCase(NotATestCase)
168 except TypeError:
169 pass
170 else:
171 self.fail('Should raise TypeError')
Tim Petersea5962f2007-03-12 18:07:52 +0000172
Georg Brandl15c5ce92007-03-07 09:09:40 +0000173 # "Return a suite of all tests cases contained in the TestCase-derived
174 # class testCaseClass"
175 #
176 # Make sure loadTestsFromTestCase() picks up the default test method
177 # name (as specified by TestCase), even though the method name does
178 # not match the default TestLoader.testMethodPrefix string
179 def test_loadTestsFromTestCase__default_method_name(self):
180 class Foo(unittest.TestCase):
181 def runTest(self):
182 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000183
Georg Brandl15c5ce92007-03-07 09:09:40 +0000184 loader = unittest.TestLoader()
185 # This has to be false for the test to succeed
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000186 self.assertFalse('runTest'.startswith(loader.testMethodPrefix))
Tim Petersea5962f2007-03-12 18:07:52 +0000187
Georg Brandl15c5ce92007-03-07 09:09:40 +0000188 suite = loader.loadTestsFromTestCase(Foo)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000189 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000190 self.assertEqual(list(suite), [Foo('runTest')])
191
192 ################################################################
193 ### /Tests for TestLoader.loadTestsFromTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000194
Georg Brandl15c5ce92007-03-07 09:09:40 +0000195 ### Tests for TestLoader.loadTestsFromModule
196 ################################################################
197
198 # "This method searches `module` for classes derived from TestCase"
199 def test_loadTestsFromModule__TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000200 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000201 class MyTestCase(unittest.TestCase):
202 def test(self):
203 pass
204 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000205
Georg Brandl15c5ce92007-03-07 09:09:40 +0000206 loader = unittest.TestLoader()
207 suite = loader.loadTestsFromModule(m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000208 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000209
Georg Brandl15c5ce92007-03-07 09:09:40 +0000210 expected = [loader.suiteClass([MyTestCase('test')])]
211 self.assertEqual(list(suite), expected)
Tim Petersea5962f2007-03-12 18:07:52 +0000212
Georg Brandl15c5ce92007-03-07 09:09:40 +0000213 # "This method searches `module` for classes derived from TestCase"
Tim Petersea5962f2007-03-12 18:07:52 +0000214 #
Georg Brandl15c5ce92007-03-07 09:09:40 +0000215 # What happens if no tests are found (no TestCase instances)?
216 def test_loadTestsFromModule__no_TestCase_instances(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000217 m = types.ModuleType('m')
Tim Petersea5962f2007-03-12 18:07:52 +0000218
Georg Brandl15c5ce92007-03-07 09:09:40 +0000219 loader = unittest.TestLoader()
220 suite = loader.loadTestsFromModule(m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000221 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000222 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000223
Georg Brandl15c5ce92007-03-07 09:09:40 +0000224 # "This method searches `module` for classes derived from TestCase"
225 #
Tim Petersea5962f2007-03-12 18:07:52 +0000226 # What happens if no tests are found (TestCases instances, but no tests)?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000227 def test_loadTestsFromModule__no_TestCase_tests(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000228 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000229 class MyTestCase(unittest.TestCase):
230 pass
231 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000232
Georg Brandl15c5ce92007-03-07 09:09:40 +0000233 loader = unittest.TestLoader()
234 suite = loader.loadTestsFromModule(m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000235 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000236
Georg Brandl15c5ce92007-03-07 09:09:40 +0000237 self.assertEqual(list(suite), [loader.suiteClass()])
Tim Petersea5962f2007-03-12 18:07:52 +0000238
Georg Brandl15c5ce92007-03-07 09:09:40 +0000239 # "This method searches `module` for classes derived from TestCase"s
240 #
241 # What happens if loadTestsFromModule() is given something other
242 # than a module?
243 #
244 # XXX Currently, it succeeds anyway. This flexibility
245 # should either be documented or loadTestsFromModule() should
246 # raise a TypeError
247 #
248 # XXX Certain people are using this behaviour. We'll add a test for it
249 def test_loadTestsFromModule__not_a_module(self):
250 class MyTestCase(unittest.TestCase):
251 def test(self):
252 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000253
Georg Brandl15c5ce92007-03-07 09:09:40 +0000254 class NotAModule(object):
255 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000256
Georg Brandl15c5ce92007-03-07 09:09:40 +0000257 loader = unittest.TestLoader()
258 suite = loader.loadTestsFromModule(NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000259
Georg Brandl15c5ce92007-03-07 09:09:40 +0000260 reference = [unittest.TestSuite([MyTestCase('test')])]
261 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000262
Michael Foordb4a81c82009-05-29 20:33:46 +0000263
264 # Check that loadTestsFromModule honors (or not) a module
265 # with a load_tests function.
266 def test_loadTestsFromModule__load_tests(self):
267 m = types.ModuleType('m')
268 class MyTestCase(unittest.TestCase):
269 def test(self):
270 pass
271 m.testcase_1 = MyTestCase
272
273 load_tests_args = []
274 def load_tests(loader, tests, pattern):
Michael Foord08770602010-02-06 00:22:26 +0000275 self.assertIsInstance(tests, unittest.TestSuite)
Michael Foordb4a81c82009-05-29 20:33:46 +0000276 load_tests_args.extend((loader, tests, pattern))
277 return tests
278 m.load_tests = load_tests
279
280 loader = unittest.TestLoader()
281 suite = loader.loadTestsFromModule(m)
Michael Foord08770602010-02-06 00:22:26 +0000282 self.assertIsInstance(suite, unittest.TestSuite)
Michael Foordb4a81c82009-05-29 20:33:46 +0000283 self.assertEquals(load_tests_args, [loader, suite, None])
284
285 load_tests_args = []
286 suite = loader.loadTestsFromModule(m, use_load_tests=False)
287 self.assertEquals(load_tests_args, [])
288
Georg Brandl15c5ce92007-03-07 09:09:40 +0000289 ################################################################
290 ### /Tests for TestLoader.loadTestsFromModule()
Tim Petersea5962f2007-03-12 18:07:52 +0000291
Georg Brandl15c5ce92007-03-07 09:09:40 +0000292 ### Tests for TestLoader.loadTestsFromName()
293 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000294
Georg Brandl15c5ce92007-03-07 09:09:40 +0000295 # "The specifier name is a ``dotted name'' that may resolve either to
296 # a module, a test case class, a TestSuite instance, a test method
297 # within a test case class, or a callable object which returns a
298 # TestCase or TestSuite instance."
299 #
300 # Is ValueError raised in response to an empty name?
301 def test_loadTestsFromName__empty_name(self):
302 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000303
Georg Brandl15c5ce92007-03-07 09:09:40 +0000304 try:
305 loader.loadTestsFromName('')
306 except ValueError, e:
307 self.assertEqual(str(e), "Empty module name")
308 else:
309 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000310
Georg Brandl15c5ce92007-03-07 09:09:40 +0000311 # "The specifier name is a ``dotted name'' that may resolve either to
312 # a module, a test case class, a TestSuite instance, a test method
313 # within a test case class, or a callable object which returns a
314 # TestCase or TestSuite instance."
315 #
Tim Petersea5962f2007-03-12 18:07:52 +0000316 # What happens when the name contains invalid characters?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000317 def test_loadTestsFromName__malformed_name(self):
318 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000319
Georg Brandl15c5ce92007-03-07 09:09:40 +0000320 # XXX Should this raise ValueError or ImportError?
321 try:
322 loader.loadTestsFromName('abc () //')
323 except ValueError:
324 pass
325 except ImportError:
326 pass
327 else:
328 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000329
Georg Brandl15c5ce92007-03-07 09:09:40 +0000330 # "The specifier name is a ``dotted name'' that may resolve ... to a
331 # module"
332 #
Tim Petersea5962f2007-03-12 18:07:52 +0000333 # What happens when a module by that name can't be found?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000334 def test_loadTestsFromName__unknown_module_name(self):
335 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000336
Georg Brandl15c5ce92007-03-07 09:09:40 +0000337 try:
338 loader.loadTestsFromName('sdasfasfasdf')
339 except ImportError, e:
340 self.assertEqual(str(e), "No module named sdasfasfasdf")
341 else:
342 self.fail("TestLoader.loadTestsFromName failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000343
Georg Brandl15c5ce92007-03-07 09:09:40 +0000344 # "The specifier name is a ``dotted name'' that may resolve either to
345 # a module, a test case class, a TestSuite instance, a test method
346 # within a test case class, or a callable object which returns a
347 # TestCase or TestSuite instance."
348 #
Tim Petersea5962f2007-03-12 18:07:52 +0000349 # What happens when the module is found, but the attribute can't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000350 def test_loadTestsFromName__unknown_attr_name(self):
351 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000352
Georg Brandl15c5ce92007-03-07 09:09:40 +0000353 try:
354 loader.loadTestsFromName('unittest.sdasfasfasdf')
355 except AttributeError, e:
356 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
357 else:
358 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000359
Georg Brandl15c5ce92007-03-07 09:09:40 +0000360 # "The specifier name is a ``dotted name'' that may resolve either to
361 # a module, a test case class, a TestSuite instance, a test method
362 # within a test case class, or a callable object which returns a
363 # TestCase or TestSuite instance."
364 #
365 # What happens when we provide the module, but the attribute can't be
366 # found?
367 def test_loadTestsFromName__relative_unknown_name(self):
368 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000369
Georg Brandl15c5ce92007-03-07 09:09:40 +0000370 try:
371 loader.loadTestsFromName('sdasfasfasdf', unittest)
372 except AttributeError, e:
373 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
374 else:
375 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000376
Georg Brandl15c5ce92007-03-07 09:09:40 +0000377 # "The specifier name is a ``dotted name'' that may resolve either to
378 # a module, a test case class, a TestSuite instance, a test method
379 # within a test case class, or a callable object which returns a
380 # TestCase or TestSuite instance."
381 # ...
382 # "The method optionally resolves name relative to the given module"
383 #
384 # Does loadTestsFromName raise ValueError when passed an empty
385 # name relative to a provided module?
386 #
387 # XXX Should probably raise a ValueError instead of an AttributeError
388 def test_loadTestsFromName__relative_empty_name(self):
389 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000390
Georg Brandl15c5ce92007-03-07 09:09:40 +0000391 try:
392 loader.loadTestsFromName('', unittest)
393 except AttributeError, e:
394 pass
395 else:
396 self.fail("Failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000397
Georg Brandl15c5ce92007-03-07 09:09:40 +0000398 # "The specifier name is a ``dotted name'' that may resolve either to
399 # a module, a test case class, a TestSuite instance, a test method
400 # within a test case class, or a callable object which returns a
401 # TestCase or TestSuite instance."
402 # ...
403 # "The method optionally resolves name relative to the given module"
404 #
405 # What happens when an impossible name is given, relative to the provided
406 # `module`?
407 def test_loadTestsFromName__relative_malformed_name(self):
408 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000409
Georg Brandl15c5ce92007-03-07 09:09:40 +0000410 # XXX Should this raise AttributeError or ValueError?
411 try:
412 loader.loadTestsFromName('abc () //', unittest)
413 except ValueError:
414 pass
415 except AttributeError:
416 pass
417 else:
418 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
419
420 # "The method optionally resolves name relative to the given module"
421 #
422 # Does loadTestsFromName raise TypeError when the `module` argument
423 # isn't a module object?
424 #
425 # XXX Accepts the not-a-module object, ignorning the object's type
426 # This should raise an exception or the method name should be changed
427 #
428 # XXX Some people are relying on this, so keep it for now
429 def test_loadTestsFromName__relative_not_a_module(self):
430 class MyTestCase(unittest.TestCase):
431 def test(self):
432 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000433
Georg Brandl15c5ce92007-03-07 09:09:40 +0000434 class NotAModule(object):
435 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000436
Georg Brandl15c5ce92007-03-07 09:09:40 +0000437 loader = unittest.TestLoader()
438 suite = loader.loadTestsFromName('test_2', NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000439
Georg Brandl15c5ce92007-03-07 09:09:40 +0000440 reference = [MyTestCase('test')]
441 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000442
Georg Brandl15c5ce92007-03-07 09:09:40 +0000443 # "The specifier name is a ``dotted name'' that may resolve either to
444 # a module, a test case class, a TestSuite instance, a test method
445 # within a test case class, or a callable object which returns a
446 # TestCase or TestSuite instance."
447 #
448 # Does it raise an exception if the name resolves to an invalid
449 # object?
450 def test_loadTestsFromName__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000451 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000452 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000453
Georg Brandl15c5ce92007-03-07 09:09:40 +0000454 loader = unittest.TestLoader()
455 try:
456 loader.loadTestsFromName('testcase_1', m)
457 except TypeError:
458 pass
459 else:
460 self.fail("Should have raised TypeError")
461
462 # "The specifier name is a ``dotted name'' that may
463 # resolve either to ... a test case class"
464 def test_loadTestsFromName__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000465 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000466 class MyTestCase(unittest.TestCase):
467 def test(self):
468 pass
469 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000470
Georg Brandl15c5ce92007-03-07 09:09:40 +0000471 loader = unittest.TestLoader()
472 suite = loader.loadTestsFromName('testcase_1', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000473 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000474 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000475
Georg Brandl15c5ce92007-03-07 09:09:40 +0000476 # "The specifier name is a ``dotted name'' that may resolve either to
477 # a module, a test case class, a TestSuite instance, a test method
478 # within a test case class, or a callable object which returns a
479 # TestCase or TestSuite instance."
480 def test_loadTestsFromName__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000481 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000482 class MyTestCase(unittest.TestCase):
483 def test(self):
484 pass
485 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000486
Georg Brandl15c5ce92007-03-07 09:09:40 +0000487 loader = unittest.TestLoader()
488 suite = loader.loadTestsFromName('testsuite', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000489 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000490
Georg Brandl15c5ce92007-03-07 09:09:40 +0000491 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000492
Georg Brandl15c5ce92007-03-07 09:09:40 +0000493 # "The specifier name is a ``dotted name'' that may resolve ... to
494 # ... a test method within a test case class"
495 def test_loadTestsFromName__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000496 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000497 class MyTestCase(unittest.TestCase):
498 def test(self):
499 pass
500 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000501
Georg Brandl15c5ce92007-03-07 09:09:40 +0000502 loader = unittest.TestLoader()
503 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000504 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000505
Georg Brandl15c5ce92007-03-07 09:09:40 +0000506 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000507
Georg Brandl15c5ce92007-03-07 09:09:40 +0000508 # "The specifier name is a ``dotted name'' that may resolve either to
509 # a module, a test case class, a TestSuite instance, a test method
510 # within a test case class, or a callable object which returns a
511 # TestCase or TestSuite instance."
512 #
513 # Does loadTestsFromName() raise the proper exception when trying to
514 # resolve "a test method within a test case class" that doesn't exist
515 # for the given name (relative to a provided module)?
516 def test_loadTestsFromName__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000517 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000518 class MyTestCase(unittest.TestCase):
519 def test(self):
520 pass
521 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000522
Georg Brandl15c5ce92007-03-07 09:09:40 +0000523 loader = unittest.TestLoader()
524 try:
525 loader.loadTestsFromName('testcase_1.testfoo', m)
526 except AttributeError, e:
527 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
528 else:
529 self.fail("Failed to raise AttributeError")
530
531 # "The specifier name is a ``dotted name'' that may resolve ... to
532 # ... a callable object which returns a ... TestSuite instance"
533 def test_loadTestsFromName__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000534 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000535 testcase_1 = unittest.FunctionTestCase(lambda: None)
536 testcase_2 = unittest.FunctionTestCase(lambda: None)
537 def return_TestSuite():
538 return unittest.TestSuite([testcase_1, testcase_2])
539 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000540
Georg Brandl15c5ce92007-03-07 09:09:40 +0000541 loader = unittest.TestLoader()
542 suite = loader.loadTestsFromName('return_TestSuite', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000543 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000544 self.assertEqual(list(suite), [testcase_1, testcase_2])
Tim Petersea5962f2007-03-12 18:07:52 +0000545
Georg Brandl15c5ce92007-03-07 09:09:40 +0000546 # "The specifier name is a ``dotted name'' that may resolve ... to
547 # ... a callable object which returns a TestCase ... instance"
548 def test_loadTestsFromName__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000549 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000550 testcase_1 = unittest.FunctionTestCase(lambda: None)
551 def return_TestCase():
552 return testcase_1
553 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000554
Georg Brandl15c5ce92007-03-07 09:09:40 +0000555 loader = unittest.TestLoader()
556 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000557 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000558 self.assertEqual(list(suite), [testcase_1])
Tim Petersea5962f2007-03-12 18:07:52 +0000559
Georg Brandl15c5ce92007-03-07 09:09:40 +0000560 # "The specifier name is a ``dotted name'' that may resolve ... to
Michael Foord5a9719d2009-09-13 17:28:35 +0000561 # ... a callable object which returns a TestCase ... instance"
562 #*****************************************************************
563 #Override the suiteClass attribute to ensure that the suiteClass
564 #attribute is used
565 def test_loadTestsFromName__callable__TestCase_instance_ProperSuiteClass(self):
566 class SubTestSuite(unittest.TestSuite):
567 pass
568 m = types.ModuleType('m')
569 testcase_1 = unittest.FunctionTestCase(lambda: None)
570 def return_TestCase():
571 return testcase_1
572 m.return_TestCase = return_TestCase
573
574 loader = unittest.TestLoader()
575 loader.suiteClass = SubTestSuite
576 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000577 self.assertIsInstance(suite, loader.suiteClass)
Michael Foord5a9719d2009-09-13 17:28:35 +0000578 self.assertEqual(list(suite), [testcase_1])
579
580 # "The specifier name is a ``dotted name'' that may resolve ... to
581 # ... a test method within a test case class"
582 #*****************************************************************
583 #Override the suiteClass attribute to ensure that the suiteClass
584 #attribute is used
585 def test_loadTestsFromName__relative_testmethod_ProperSuiteClass(self):
586 class SubTestSuite(unittest.TestSuite):
587 pass
588 m = types.ModuleType('m')
589 class MyTestCase(unittest.TestCase):
590 def test(self):
591 pass
592 m.testcase_1 = MyTestCase
593
594 loader = unittest.TestLoader()
595 loader.suiteClass=SubTestSuite
596 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000597 self.assertIsInstance(suite, loader.suiteClass)
Michael Foord5a9719d2009-09-13 17:28:35 +0000598
599 self.assertEqual(list(suite), [MyTestCase('test')])
600
601 # "The specifier name is a ``dotted name'' that may resolve ... to
Georg Brandl15c5ce92007-03-07 09:09:40 +0000602 # ... a callable object which returns a TestCase or TestSuite instance"
603 #
604 # What happens if the callable returns something else?
605 def test_loadTestsFromName__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000606 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000607 def return_wrong():
608 return 6
609 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000610
Georg Brandl15c5ce92007-03-07 09:09:40 +0000611 loader = unittest.TestLoader()
612 try:
613 suite = loader.loadTestsFromName('return_wrong', m)
614 except TypeError:
615 pass
616 else:
617 self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000618
Georg Brandl15c5ce92007-03-07 09:09:40 +0000619 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +0000620 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +0000621 def test_loadTestsFromName__module_not_loaded(self):
622 # We're going to try to load this module as a side-effect, so it
623 # better not be loaded before we try.
624 #
625 # Why pick audioop? Google shows it isn't used very often, so there's
626 # a good chance that it won't be imported when this test is run
627 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +0000628
Georg Brandl15c5ce92007-03-07 09:09:40 +0000629 if module_name in sys.modules:
630 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000631
Georg Brandl15c5ce92007-03-07 09:09:40 +0000632 loader = unittest.TestLoader()
633 try:
634 suite = loader.loadTestsFromName(module_name)
635
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000636 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000637 self.assertEqual(list(suite), [])
638
639 # audioop should now be loaded, thanks to loadTestsFromName()
Ezio Melottiaa980582010-01-23 23:04:36 +0000640 self.assertIn(module_name, sys.modules)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000641 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000642 if module_name in sys.modules:
643 del sys.modules[module_name]
Georg Brandl15c5ce92007-03-07 09:09:40 +0000644
645 ################################################################
646 ### Tests for TestLoader.loadTestsFromName()
647
648 ### Tests for TestLoader.loadTestsFromNames()
649 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000650
Georg Brandl15c5ce92007-03-07 09:09:40 +0000651 # "Similar to loadTestsFromName(), but takes a sequence of names rather
652 # than a single name."
653 #
654 # What happens if that sequence of names is empty?
655 def test_loadTestsFromNames__empty_name_list(self):
656 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000657
Georg Brandl15c5ce92007-03-07 09:09:40 +0000658 suite = loader.loadTestsFromNames([])
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000659 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000660 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000661
Georg Brandl15c5ce92007-03-07 09:09:40 +0000662 # "Similar to loadTestsFromName(), but takes a sequence of names rather
663 # than a single name."
664 # ...
665 # "The method optionally resolves name relative to the given module"
666 #
667 # What happens if that sequence of names is empty?
668 #
669 # XXX Should this raise a ValueError or just return an empty TestSuite?
670 def test_loadTestsFromNames__relative_empty_name_list(self):
671 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000672
Georg Brandl15c5ce92007-03-07 09:09:40 +0000673 suite = loader.loadTestsFromNames([], unittest)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000674 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000675 self.assertEqual(list(suite), [])
676
677 # "The specifier name is a ``dotted name'' that may resolve either to
678 # a module, a test case class, a TestSuite instance, a test method
679 # within a test case class, or a callable object which returns a
680 # TestCase or TestSuite instance."
681 #
682 # Is ValueError raised in response to an empty name?
683 def test_loadTestsFromNames__empty_name(self):
684 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000685
Georg Brandl15c5ce92007-03-07 09:09:40 +0000686 try:
687 loader.loadTestsFromNames([''])
688 except ValueError, e:
689 self.assertEqual(str(e), "Empty module name")
690 else:
691 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000692
Georg Brandl15c5ce92007-03-07 09:09:40 +0000693 # "The specifier name is a ``dotted name'' that may resolve either to
694 # a module, a test case class, a TestSuite instance, a test method
695 # within a test case class, or a callable object which returns a
696 # TestCase or TestSuite instance."
697 #
Tim Petersea5962f2007-03-12 18:07:52 +0000698 # What happens when presented with an impossible module name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000699 def test_loadTestsFromNames__malformed_name(self):
700 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000701
Georg Brandl15c5ce92007-03-07 09:09:40 +0000702 # XXX Should this raise ValueError or ImportError?
703 try:
704 loader.loadTestsFromNames(['abc () //'])
705 except ValueError:
706 pass
707 except ImportError:
708 pass
709 else:
710 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000711
Georg Brandl15c5ce92007-03-07 09:09:40 +0000712 # "The specifier name is a ``dotted name'' that may resolve either to
713 # a module, a test case class, a TestSuite instance, a test method
714 # within a test case class, or a callable object which returns a
715 # TestCase or TestSuite instance."
716 #
Tim Petersea5962f2007-03-12 18:07:52 +0000717 # What happens when no module can be found for the given name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000718 def test_loadTestsFromNames__unknown_module_name(self):
719 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000720
Georg Brandl15c5ce92007-03-07 09:09:40 +0000721 try:
722 loader.loadTestsFromNames(['sdasfasfasdf'])
723 except ImportError, e:
724 self.assertEqual(str(e), "No module named sdasfasfasdf")
725 else:
726 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000727
Georg Brandl15c5ce92007-03-07 09:09:40 +0000728 # "The specifier name is a ``dotted name'' that may resolve either to
729 # a module, a test case class, a TestSuite instance, a test method
730 # within a test case class, or a callable object which returns a
731 # TestCase or TestSuite instance."
732 #
Tim Petersea5962f2007-03-12 18:07:52 +0000733 # What happens when the module can be found, but not the attribute?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000734 def test_loadTestsFromNames__unknown_attr_name(self):
735 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000736
Georg Brandl15c5ce92007-03-07 09:09:40 +0000737 try:
738 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
739 except AttributeError, e:
740 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
741 else:
742 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000743
Georg Brandl15c5ce92007-03-07 09:09:40 +0000744 # "The specifier name is a ``dotted name'' that may resolve either to
745 # a module, a test case class, a TestSuite instance, a test method
746 # within a test case class, or a callable object which returns a
747 # TestCase or TestSuite instance."
748 # ...
749 # "The method optionally resolves name relative to the given module"
750 #
751 # What happens when given an unknown attribute on a specified `module`
752 # argument?
753 def test_loadTestsFromNames__unknown_name_relative_1(self):
754 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000755
Georg Brandl15c5ce92007-03-07 09:09:40 +0000756 try:
757 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
758 except AttributeError, e:
759 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
760 else:
761 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000762
Georg Brandl15c5ce92007-03-07 09:09:40 +0000763 # "The specifier name is a ``dotted name'' that may resolve either to
764 # a module, a test case class, a TestSuite instance, a test method
765 # within a test case class, or a callable object which returns a
766 # TestCase or TestSuite instance."
767 # ...
768 # "The method optionally resolves name relative to the given module"
769 #
770 # Do unknown attributes (relative to a provided module) still raise an
Tim Petersea5962f2007-03-12 18:07:52 +0000771 # exception even in the presence of valid attribute names?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000772 def test_loadTestsFromNames__unknown_name_relative_2(self):
773 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000774
Georg Brandl15c5ce92007-03-07 09:09:40 +0000775 try:
776 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
777 except AttributeError, e:
778 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
779 else:
780 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
781
782 # "The specifier name is a ``dotted name'' that may resolve either to
783 # a module, a test case class, a TestSuite instance, a test method
784 # within a test case class, or a callable object which returns a
785 # TestCase or TestSuite instance."
786 # ...
787 # "The method optionally resolves name relative to the given module"
788 #
789 # What happens when faced with the empty string?
790 #
791 # XXX This currently raises AttributeError, though ValueError is probably
792 # more appropriate
793 def test_loadTestsFromNames__relative_empty_name(self):
794 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000795
Georg Brandl15c5ce92007-03-07 09:09:40 +0000796 try:
797 loader.loadTestsFromNames([''], unittest)
798 except AttributeError:
799 pass
800 else:
801 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000802
Georg Brandl15c5ce92007-03-07 09:09:40 +0000803 # "The specifier name is a ``dotted name'' that may resolve either to
804 # a module, a test case class, a TestSuite instance, a test method
805 # within a test case class, or a callable object which returns a
806 # TestCase or TestSuite instance."
807 # ...
808 # "The method optionally resolves name relative to the given module"
809 #
Tim Petersea5962f2007-03-12 18:07:52 +0000810 # What happens when presented with an impossible attribute name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000811 def test_loadTestsFromNames__relative_malformed_name(self):
812 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000813
Georg Brandl15c5ce92007-03-07 09:09:40 +0000814 # XXX Should this raise AttributeError or ValueError?
815 try:
816 loader.loadTestsFromNames(['abc () //'], unittest)
817 except AttributeError:
818 pass
819 except ValueError:
820 pass
821 else:
822 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
823
824 # "The method optionally resolves name relative to the given module"
825 #
826 # Does loadTestsFromNames() make sure the provided `module` is in fact
827 # a module?
828 #
829 # XXX This validation is currently not done. This flexibility should
830 # either be documented or a TypeError should be raised.
831 def test_loadTestsFromNames__relative_not_a_module(self):
832 class MyTestCase(unittest.TestCase):
833 def test(self):
834 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000835
Georg Brandl15c5ce92007-03-07 09:09:40 +0000836 class NotAModule(object):
837 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000838
Georg Brandl15c5ce92007-03-07 09:09:40 +0000839 loader = unittest.TestLoader()
840 suite = loader.loadTestsFromNames(['test_2'], NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000841
Georg Brandl15c5ce92007-03-07 09:09:40 +0000842 reference = [unittest.TestSuite([MyTestCase('test')])]
843 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000844
Georg Brandl15c5ce92007-03-07 09:09:40 +0000845 # "The specifier name is a ``dotted name'' that may resolve either to
846 # a module, a test case class, a TestSuite instance, a test method
847 # within a test case class, or a callable object which returns a
848 # TestCase or TestSuite instance."
849 #
850 # Does it raise an exception if the name resolves to an invalid
851 # object?
852 def test_loadTestsFromNames__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000853 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000854 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000855
Georg Brandl15c5ce92007-03-07 09:09:40 +0000856 loader = unittest.TestLoader()
857 try:
858 loader.loadTestsFromNames(['testcase_1'], m)
859 except TypeError:
860 pass
861 else:
862 self.fail("Should have raised TypeError")
863
864 # "The specifier name is a ``dotted name'' that may resolve ... to
865 # ... a test case class"
866 def test_loadTestsFromNames__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000867 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000868 class MyTestCase(unittest.TestCase):
869 def test(self):
870 pass
871 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000872
Georg Brandl15c5ce92007-03-07 09:09:40 +0000873 loader = unittest.TestLoader()
874 suite = loader.loadTestsFromNames(['testcase_1'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000875 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000876
Georg Brandl15c5ce92007-03-07 09:09:40 +0000877 expected = loader.suiteClass([MyTestCase('test')])
878 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000879
Georg Brandl15c5ce92007-03-07 09:09:40 +0000880 # "The specifier name is a ``dotted name'' that may resolve ... to
881 # ... a TestSuite instance"
882 def test_loadTestsFromNames__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000883 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000884 class MyTestCase(unittest.TestCase):
885 def test(self):
886 pass
887 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000888
Georg Brandl15c5ce92007-03-07 09:09:40 +0000889 loader = unittest.TestLoader()
890 suite = loader.loadTestsFromNames(['testsuite'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000891 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000892
Georg Brandl15c5ce92007-03-07 09:09:40 +0000893 self.assertEqual(list(suite), [m.testsuite])
Tim Petersea5962f2007-03-12 18:07:52 +0000894
Georg Brandl15c5ce92007-03-07 09:09:40 +0000895 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
896 # test method within a test case class"
897 def test_loadTestsFromNames__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000898 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000899 class MyTestCase(unittest.TestCase):
900 def test(self):
901 pass
902 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000903
Georg Brandl15c5ce92007-03-07 09:09:40 +0000904 loader = unittest.TestLoader()
905 suite = loader.loadTestsFromNames(['testcase_1.test'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000906 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000907
Georg Brandl15c5ce92007-03-07 09:09:40 +0000908 ref_suite = unittest.TestSuite([MyTestCase('test')])
909 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000910
Georg Brandl15c5ce92007-03-07 09:09:40 +0000911 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
912 # test method within a test case class"
913 #
914 # Does the method gracefully handle names that initially look like they
Tim Petersea5962f2007-03-12 18:07:52 +0000915 # resolve to "a test method within a test case class" but don't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000916 def test_loadTestsFromNames__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000917 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000918 class MyTestCase(unittest.TestCase):
919 def test(self):
920 pass
921 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000922
Georg Brandl15c5ce92007-03-07 09:09:40 +0000923 loader = unittest.TestLoader()
924 try:
925 loader.loadTestsFromNames(['testcase_1.testfoo'], m)
926 except AttributeError, e:
927 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
928 else:
929 self.fail("Failed to raise AttributeError")
930
931 # "The specifier name is a ``dotted name'' that may resolve ... to
932 # ... a callable object which returns a ... TestSuite instance"
933 def test_loadTestsFromNames__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000934 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000935 testcase_1 = unittest.FunctionTestCase(lambda: None)
936 testcase_2 = unittest.FunctionTestCase(lambda: None)
937 def return_TestSuite():
938 return unittest.TestSuite([testcase_1, testcase_2])
939 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000940
Georg Brandl15c5ce92007-03-07 09:09:40 +0000941 loader = unittest.TestLoader()
942 suite = loader.loadTestsFromNames(['return_TestSuite'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000943 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000944
Georg Brandl15c5ce92007-03-07 09:09:40 +0000945 expected = unittest.TestSuite([testcase_1, testcase_2])
946 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000947
Georg Brandl15c5ce92007-03-07 09:09:40 +0000948 # "The specifier name is a ``dotted name'' that may resolve ... to
949 # ... a callable object which returns a TestCase ... instance"
950 def test_loadTestsFromNames__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000951 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000952 testcase_1 = unittest.FunctionTestCase(lambda: None)
953 def return_TestCase():
954 return testcase_1
955 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000956
Georg Brandl15c5ce92007-03-07 09:09:40 +0000957 loader = unittest.TestLoader()
958 suite = loader.loadTestsFromNames(['return_TestCase'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000959 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000960
Georg Brandl15c5ce92007-03-07 09:09:40 +0000961 ref_suite = unittest.TestSuite([testcase_1])
962 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000963
Georg Brandl15c5ce92007-03-07 09:09:40 +0000964 # "The specifier name is a ``dotted name'' that may resolve ... to
965 # ... a callable object which returns a TestCase or TestSuite instance"
966 #
Tim Petersea5962f2007-03-12 18:07:52 +0000967 # Are staticmethods handled correctly?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000968 def test_loadTestsFromNames__callable__call_staticmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000969 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000970 class Test1(unittest.TestCase):
971 def test(self):
972 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000973
Georg Brandl15c5ce92007-03-07 09:09:40 +0000974 testcase_1 = Test1('test')
975 class Foo(unittest.TestCase):
976 @staticmethod
977 def foo():
978 return testcase_1
979 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +0000980
Georg Brandl15c5ce92007-03-07 09:09:40 +0000981 loader = unittest.TestLoader()
982 suite = loader.loadTestsFromNames(['Foo.foo'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000983 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000984
Georg Brandl15c5ce92007-03-07 09:09:40 +0000985 ref_suite = unittest.TestSuite([testcase_1])
986 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000987
Georg Brandl15c5ce92007-03-07 09:09:40 +0000988 # "The specifier name is a ``dotted name'' that may resolve ... to
989 # ... a callable object which returns a TestCase or TestSuite instance"
990 #
991 # What happens when the callable returns something else?
992 def test_loadTestsFromNames__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000993 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000994 def return_wrong():
995 return 6
996 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000997
Georg Brandl15c5ce92007-03-07 09:09:40 +0000998 loader = unittest.TestLoader()
999 try:
1000 suite = loader.loadTestsFromNames(['return_wrong'], m)
1001 except TypeError:
1002 pass
1003 else:
1004 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +00001005
Georg Brandl15c5ce92007-03-07 09:09:40 +00001006 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +00001007 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001008 def test_loadTestsFromNames__module_not_loaded(self):
1009 # We're going to try to load this module as a side-effect, so it
1010 # better not be loaded before we try.
1011 #
1012 # Why pick audioop? Google shows it isn't used very often, so there's
1013 # a good chance that it won't be imported when this test is run
1014 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +00001015
Georg Brandl15c5ce92007-03-07 09:09:40 +00001016 if module_name in sys.modules:
1017 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +00001018
Georg Brandl15c5ce92007-03-07 09:09:40 +00001019 loader = unittest.TestLoader()
1020 try:
1021 suite = loader.loadTestsFromNames([module_name])
1022
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001023 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +00001024 self.assertEqual(list(suite), [unittest.TestSuite()])
1025
1026 # audioop should now be loaded, thanks to loadTestsFromName()
Ezio Melottiaa980582010-01-23 23:04:36 +00001027 self.assertIn(module_name, sys.modules)
Georg Brandl15c5ce92007-03-07 09:09:40 +00001028 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +00001029 if module_name in sys.modules:
1030 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +00001031
Georg Brandl15c5ce92007-03-07 09:09:40 +00001032 ################################################################
1033 ### /Tests for TestLoader.loadTestsFromNames()
1034
1035 ### Tests for TestLoader.getTestCaseNames()
1036 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001037
Georg Brandl15c5ce92007-03-07 09:09:40 +00001038 # "Return a sorted sequence of method names found within testCaseClass"
1039 #
1040 # Test.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +00001041 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +00001042 def test_getTestCaseNames(self):
1043 class Test(unittest.TestCase):
1044 def test_1(self): pass
1045 def test_2(self): pass
1046 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001047
Georg Brandl15c5ce92007-03-07 09:09:40 +00001048 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001049
Georg Brandl15c5ce92007-03-07 09:09:40 +00001050 self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])
Tim Petersea5962f2007-03-12 18:07:52 +00001051
Georg Brandl15c5ce92007-03-07 09:09:40 +00001052 # "Return a sorted sequence of method names found within testCaseClass"
1053 #
Tim Petersea5962f2007-03-12 18:07:52 +00001054 # Does getTestCaseNames() behave appropriately if no tests are found?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001055 def test_getTestCaseNames__no_tests(self):
1056 class Test(unittest.TestCase):
1057 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001058
Georg Brandl15c5ce92007-03-07 09:09:40 +00001059 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001060
Georg Brandl15c5ce92007-03-07 09:09:40 +00001061 self.assertEqual(loader.getTestCaseNames(Test), [])
Tim Petersea5962f2007-03-12 18:07:52 +00001062
Georg Brandl15c5ce92007-03-07 09:09:40 +00001063 # "Return a sorted sequence of method names found within testCaseClass"
1064 #
1065 # Are not-TestCases handled gracefully?
1066 #
1067 # XXX This should raise a TypeError, not return a list
1068 #
1069 # XXX It's too late in the 2.5 release cycle to fix this, but it should
1070 # probably be revisited for 2.6
1071 def test_getTestCaseNames__not_a_TestCase(self):
1072 class BadCase(int):
1073 def test_foo(self):
1074 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001075
Georg Brandl15c5ce92007-03-07 09:09:40 +00001076 loader = unittest.TestLoader()
1077 names = loader.getTestCaseNames(BadCase)
Tim Petersea5962f2007-03-12 18:07:52 +00001078
Georg Brandl15c5ce92007-03-07 09:09:40 +00001079 self.assertEqual(names, ['test_foo'])
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 # Make sure inherited names are handled.
1084 #
1085 # TestP.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +00001086 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +00001087 def test_getTestCaseNames__inheritance(self):
1088 class TestP(unittest.TestCase):
1089 def test_1(self): pass
1090 def test_2(self): pass
1091 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001092
Georg Brandl15c5ce92007-03-07 09:09:40 +00001093 class TestC(TestP):
1094 def test_1(self): pass
1095 def test_3(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001096
Georg Brandl15c5ce92007-03-07 09:09:40 +00001097 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001098
Georg Brandl15c5ce92007-03-07 09:09:40 +00001099 names = ['test_1', 'test_2', 'test_3']
1100 self.assertEqual(loader.getTestCaseNames(TestC), names)
Tim Petersea5962f2007-03-12 18:07:52 +00001101
1102 ################################################################
Georg Brandl15c5ce92007-03-07 09:09:40 +00001103 ### /Tests for TestLoader.getTestCaseNames()
1104
1105 ### Tests for TestLoader.testMethodPrefix
1106 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001107
Georg Brandl15c5ce92007-03-07 09:09:40 +00001108 # "String giving the prefix of method names which will be interpreted as
1109 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001110 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001111 # Implicit in the documentation is that testMethodPrefix is respected by
1112 # all loadTestsFrom* methods.
1113 def test_testMethodPrefix__loadTestsFromTestCase(self):
1114 class Foo(unittest.TestCase):
1115 def test_1(self): pass
1116 def test_2(self): pass
1117 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001118
Georg Brandl15c5ce92007-03-07 09:09:40 +00001119 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1120 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001121
Georg Brandl15c5ce92007-03-07 09:09:40 +00001122 loader = unittest.TestLoader()
1123 loader.testMethodPrefix = 'foo'
1124 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
1125
1126 loader.testMethodPrefix = 'test'
1127 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001128
Georg Brandl15c5ce92007-03-07 09:09:40 +00001129 # "String giving the prefix of method names which will be interpreted as
1130 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001131 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001132 # Implicit in the documentation is that testMethodPrefix is respected by
1133 # all loadTestsFrom* methods.
1134 def test_testMethodPrefix__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001135 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001136 class Foo(unittest.TestCase):
1137 def test_1(self): pass
1138 def test_2(self): pass
1139 def foo_bar(self): pass
1140 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001141
Georg Brandl15c5ce92007-03-07 09:09:40 +00001142 tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
1143 tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]
Tim Petersea5962f2007-03-12 18:07:52 +00001144
Georg Brandl15c5ce92007-03-07 09:09:40 +00001145 loader = unittest.TestLoader()
1146 loader.testMethodPrefix = 'foo'
1147 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
1148
1149 loader.testMethodPrefix = 'test'
1150 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001151
Georg Brandl15c5ce92007-03-07 09:09:40 +00001152 # "String giving the prefix of method names which will be interpreted as
1153 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001154 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001155 # Implicit in the documentation is that testMethodPrefix is respected by
1156 # all loadTestsFrom* methods.
1157 def test_testMethodPrefix__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001158 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001159 class Foo(unittest.TestCase):
1160 def test_1(self): pass
1161 def test_2(self): pass
1162 def foo_bar(self): pass
1163 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001164
Georg Brandl15c5ce92007-03-07 09:09:40 +00001165 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1166 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001167
Georg Brandl15c5ce92007-03-07 09:09:40 +00001168 loader = unittest.TestLoader()
1169 loader.testMethodPrefix = 'foo'
1170 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
1171
1172 loader.testMethodPrefix = 'test'
1173 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001174
Georg Brandl15c5ce92007-03-07 09:09:40 +00001175 # "String giving the prefix of method names which will be interpreted as
1176 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001177 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001178 # Implicit in the documentation is that testMethodPrefix is respected by
1179 # all loadTestsFrom* methods.
1180 def test_testMethodPrefix__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001181 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001182 class Foo(unittest.TestCase):
1183 def test_1(self): pass
1184 def test_2(self): pass
1185 def foo_bar(self): pass
1186 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001187
Georg Brandl15c5ce92007-03-07 09:09:40 +00001188 tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
1189 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1190 tests_2 = unittest.TestSuite([tests_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001191
Georg Brandl15c5ce92007-03-07 09:09:40 +00001192 loader = unittest.TestLoader()
1193 loader.testMethodPrefix = 'foo'
1194 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)
1195
1196 loader.testMethodPrefix = 'test'
1197 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001198
Georg Brandl15c5ce92007-03-07 09:09:40 +00001199 # "The default value is 'test'"
1200 def test_testMethodPrefix__default_value(self):
1201 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001202 self.assertTrue(loader.testMethodPrefix == 'test')
Tim Petersea5962f2007-03-12 18:07:52 +00001203
Georg Brandl15c5ce92007-03-07 09:09:40 +00001204 ################################################################
1205 ### /Tests for TestLoader.testMethodPrefix
1206
Tim Petersea5962f2007-03-12 18:07:52 +00001207 ### Tests for TestLoader.sortTestMethodsUsing
Georg Brandl15c5ce92007-03-07 09:09:40 +00001208 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001209
Georg Brandl15c5ce92007-03-07 09:09:40 +00001210 # "Function to be used to compare method names when sorting them in
1211 # getTestCaseNames() and all the loadTestsFromX() methods"
1212 def test_sortTestMethodsUsing__loadTestsFromTestCase(self):
1213 def reversed_cmp(x, y):
1214 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001215
Georg Brandl15c5ce92007-03-07 09:09:40 +00001216 class Foo(unittest.TestCase):
1217 def test_1(self): pass
1218 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001219
Georg Brandl15c5ce92007-03-07 09:09:40 +00001220 loader = unittest.TestLoader()
1221 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001222
Georg Brandl15c5ce92007-03-07 09:09:40 +00001223 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1224 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001225
Georg Brandl15c5ce92007-03-07 09:09:40 +00001226 # "Function to be used to compare method names when sorting them in
1227 # getTestCaseNames() and all the loadTestsFromX() methods"
1228 def test_sortTestMethodsUsing__loadTestsFromModule(self):
1229 def reversed_cmp(x, y):
1230 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001231
Christian Heimesc756d002007-11-27 21:34:01 +00001232 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001233 class Foo(unittest.TestCase):
1234 def test_1(self): pass
1235 def test_2(self): pass
1236 m.Foo = Foo
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(list(loader.loadTestsFromModule(m)), 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__loadTestsFromName(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(loader.loadTestsFromName('Foo', 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__loadTestsFromNames(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(list(loader.loadTestsFromNames(['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()"
1282 #
1283 # Does it actually affect getTestCaseNames()?
1284 def test_sortTestMethodsUsing__getTestCaseNames(self):
1285 def reversed_cmp(x, y):
1286 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001287
Georg Brandl15c5ce92007-03-07 09:09:40 +00001288 class Foo(unittest.TestCase):
1289 def test_1(self): pass
1290 def test_2(self): pass
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 test_names = ['test_2', 'test_1']
1296 self.assertEqual(loader.getTestCaseNames(Foo), test_names)
Tim Petersea5962f2007-03-12 18:07:52 +00001297
Georg Brandl15c5ce92007-03-07 09:09:40 +00001298 # "The default value is the built-in cmp() function"
1299 def test_sortTestMethodsUsing__default_value(self):
1300 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001301 self.assertTrue(loader.sortTestMethodsUsing is cmp)
Tim Petersea5962f2007-03-12 18:07:52 +00001302
Georg Brandl15c5ce92007-03-07 09:09:40 +00001303 # "it can be set to None to disable the sort."
1304 #
1305 # XXX How is this different from reassigning cmp? Are the tests returned
1306 # in a random order or something? This behaviour should die
1307 def test_sortTestMethodsUsing__None(self):
1308 class Foo(unittest.TestCase):
1309 def test_1(self): pass
1310 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001311
Georg Brandl15c5ce92007-03-07 09:09:40 +00001312 loader = unittest.TestLoader()
1313 loader.sortTestMethodsUsing = None
Tim Petersea5962f2007-03-12 18:07:52 +00001314
Georg Brandl15c5ce92007-03-07 09:09:40 +00001315 test_names = ['test_2', 'test_1']
1316 self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))
Tim Petersea5962f2007-03-12 18:07:52 +00001317
Georg Brandl15c5ce92007-03-07 09:09:40 +00001318 ################################################################
1319 ### /Tests for TestLoader.sortTestMethodsUsing
Tim Petersea5962f2007-03-12 18:07:52 +00001320
Georg Brandl15c5ce92007-03-07 09:09:40 +00001321 ### Tests for TestLoader.suiteClass
1322 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001323
Georg Brandl15c5ce92007-03-07 09:09:40 +00001324 # "Callable object that constructs a test suite from a list of tests."
1325 def test_suiteClass__loadTestsFromTestCase(self):
1326 class Foo(unittest.TestCase):
1327 def test_1(self): pass
1328 def test_2(self): pass
1329 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001330
Georg Brandl15c5ce92007-03-07 09:09:40 +00001331 tests = [Foo('test_1'), Foo('test_2')]
1332
1333 loader = unittest.TestLoader()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001334 loader.suiteClass = list
Georg Brandl15c5ce92007-03-07 09:09:40 +00001335 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001336
Georg Brandl15c5ce92007-03-07 09:09:40 +00001337 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001338 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001339 def test_suiteClass__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001340 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001341 class Foo(unittest.TestCase):
1342 def test_1(self): pass
1343 def test_2(self): pass
1344 def foo_bar(self): pass
1345 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001346
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001347 tests = [[Foo('test_1'), Foo('test_2')]]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001348
1349 loader = unittest.TestLoader()
1350 loader.suiteClass = list
1351 self.assertEqual(loader.loadTestsFromModule(m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001352
Georg Brandl15c5ce92007-03-07 09:09:40 +00001353 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001354 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001355 def test_suiteClass__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001356 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001357 class Foo(unittest.TestCase):
1358 def test_1(self): pass
1359 def test_2(self): pass
1360 def foo_bar(self): pass
1361 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001362
Georg Brandl15c5ce92007-03-07 09:09:40 +00001363 tests = [Foo('test_1'), Foo('test_2')]
1364
1365 loader = unittest.TestLoader()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001366 loader.suiteClass = list
Georg Brandl15c5ce92007-03-07 09:09:40 +00001367 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001368
Georg Brandl15c5ce92007-03-07 09:09:40 +00001369 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001370 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001371 def test_suiteClass__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001372 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001373 class Foo(unittest.TestCase):
1374 def test_1(self): pass
1375 def test_2(self): pass
1376 def foo_bar(self): pass
1377 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001378
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001379 tests = [[Foo('test_1'), Foo('test_2')]]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001380
1381 loader = unittest.TestLoader()
1382 loader.suiteClass = list
1383 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001384
Georg Brandl15c5ce92007-03-07 09:09:40 +00001385 # "The default value is the TestSuite class"
1386 def test_suiteClass__default_value(self):
1387 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001388 self.assertTrue(loader.suiteClass is unittest.TestSuite)
Tim Petersea5962f2007-03-12 18:07:52 +00001389
Georg Brandl15c5ce92007-03-07 09:09:40 +00001390 ################################################################
1391 ### /Tests for TestLoader.suiteClass
1392
1393### Support code for Test_TestSuite
1394################################################################
1395
1396class Foo(unittest.TestCase):
1397 def test_1(self): pass
1398 def test_2(self): pass
1399 def test_3(self): pass
1400 def runTest(self): pass
1401
1402def _mk_TestSuite(*names):
1403 return unittest.TestSuite(Foo(n) for n in names)
Tim Petersea5962f2007-03-12 18:07:52 +00001404
Georg Brandl15c5ce92007-03-07 09:09:40 +00001405################################################################
1406### /Support code for Test_TestSuite
1407
1408class Test_TestSuite(TestCase, TestEquality):
1409
1410 ### Set up attributes needed by inherited tests
1411 ################################################################
1412
1413 # Used by TestEquality.test_eq
1414 eq_pairs = [(unittest.TestSuite(), unittest.TestSuite())
1415 ,(unittest.TestSuite(), unittest.TestSuite([]))
1416 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001417
1418 # Used by TestEquality.test_ne
Georg Brandl15c5ce92007-03-07 09:09:40 +00001419 ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1'))
1420 ,(unittest.TestSuite([]), _mk_TestSuite('test_1'))
1421 ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3'))
1422 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001423
Georg Brandl15c5ce92007-03-07 09:09:40 +00001424 ################################################################
1425 ### /Set up attributes needed by inherited tests
1426
1427 ### Tests for TestSuite.__init__
1428 ################################################################
1429
1430 # "class TestSuite([tests])"
1431 #
1432 # The tests iterable should be optional
1433 def test_init__tests_optional(self):
1434 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001435
Georg Brandl15c5ce92007-03-07 09:09:40 +00001436 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001437
Georg Brandl15c5ce92007-03-07 09:09:40 +00001438 # "class TestSuite([tests])"
1439 # ...
1440 # "If tests is given, it must be an iterable of individual test cases
1441 # or other test suites that will be used to build the suite initially"
1442 #
1443 # TestSuite should deal with empty tests iterables by allowing the
Tim Petersea5962f2007-03-12 18:07:52 +00001444 # creation of an empty suite
Georg Brandl15c5ce92007-03-07 09:09:40 +00001445 def test_init__empty_tests(self):
1446 suite = unittest.TestSuite([])
Tim Petersea5962f2007-03-12 18:07:52 +00001447
Georg Brandl15c5ce92007-03-07 09:09:40 +00001448 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001449
Georg Brandl15c5ce92007-03-07 09:09:40 +00001450 # "class TestSuite([tests])"
1451 # ...
1452 # "If tests is given, it must be an iterable of individual test cases
1453 # or other test suites that will be used to build the suite initially"
1454 #
Tim Petersea5962f2007-03-12 18:07:52 +00001455 # TestSuite should allow any iterable to provide tests
Georg Brandl15c5ce92007-03-07 09:09:40 +00001456 def test_init__tests_from_any_iterable(self):
1457 def tests():
1458 yield unittest.FunctionTestCase(lambda: None)
1459 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001460
Georg Brandl15c5ce92007-03-07 09:09:40 +00001461 suite_1 = unittest.TestSuite(tests())
1462 self.assertEqual(suite_1.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001463
Georg Brandl15c5ce92007-03-07 09:09:40 +00001464 suite_2 = unittest.TestSuite(suite_1)
1465 self.assertEqual(suite_2.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001466
Georg Brandl15c5ce92007-03-07 09:09:40 +00001467 suite_3 = unittest.TestSuite(set(suite_1))
1468 self.assertEqual(suite_3.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001469
Georg Brandl15c5ce92007-03-07 09:09:40 +00001470 # "class TestSuite([tests])"
1471 # ...
1472 # "If tests is given, it must be an iterable of individual test cases
1473 # or other test suites that will be used to build the suite initially"
1474 #
1475 # Does TestSuite() also allow other TestSuite() instances to be present
1476 # in the tests iterable?
1477 def test_init__TestSuite_instances_in_tests(self):
1478 def tests():
1479 ftc = unittest.FunctionTestCase(lambda: None)
1480 yield unittest.TestSuite([ftc])
1481 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001482
Georg Brandl15c5ce92007-03-07 09:09:40 +00001483 suite = unittest.TestSuite(tests())
1484 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001485
Georg Brandl15c5ce92007-03-07 09:09:40 +00001486 ################################################################
1487 ### /Tests for TestSuite.__init__
1488
1489 # Container types should support the iter protocol
1490 def test_iter(self):
1491 test1 = unittest.FunctionTestCase(lambda: None)
1492 test2 = unittest.FunctionTestCase(lambda: None)
1493 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001494
Georg Brandl15c5ce92007-03-07 09:09:40 +00001495 self.assertEqual(list(suite), [test1, test2])
Tim Petersea5962f2007-03-12 18:07:52 +00001496
Georg Brandl15c5ce92007-03-07 09:09:40 +00001497 # "Return the number of tests represented by the this test object.
1498 # ...this method is also implemented by the TestSuite class, which can
1499 # return larger [greater than 1] values"
1500 #
Tim Petersea5962f2007-03-12 18:07:52 +00001501 # Presumably an empty TestSuite returns 0?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001502 def test_countTestCases_zero_simple(self):
1503 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001504
Georg Brandl15c5ce92007-03-07 09:09:40 +00001505 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001506
Georg Brandl15c5ce92007-03-07 09:09:40 +00001507 # "Return the number of tests represented by the this test object.
1508 # ...this method is also implemented by the TestSuite class, which can
1509 # return larger [greater than 1] values"
1510 #
1511 # Presumably an empty TestSuite (even if it contains other empty
1512 # TestSuite instances) returns 0?
1513 def test_countTestCases_zero_nested(self):
1514 class Test1(unittest.TestCase):
1515 def test(self):
1516 pass
1517
1518 suite = unittest.TestSuite([unittest.TestSuite()])
Tim Petersea5962f2007-03-12 18:07:52 +00001519
Georg Brandl15c5ce92007-03-07 09:09:40 +00001520 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001521
Georg Brandl15c5ce92007-03-07 09:09:40 +00001522 # "Return the number of tests represented by the this test object.
1523 # ...this method is also implemented by the TestSuite class, which can
1524 # return larger [greater than 1] values"
1525 def test_countTestCases_simple(self):
1526 test1 = unittest.FunctionTestCase(lambda: None)
1527 test2 = unittest.FunctionTestCase(lambda: None)
1528 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001529
Georg Brandl15c5ce92007-03-07 09:09:40 +00001530 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001531
Georg Brandl15c5ce92007-03-07 09:09:40 +00001532 # "Return the number of tests represented by the this test object.
1533 # ...this method is also implemented by the TestSuite class, which can
1534 # return larger [greater than 1] values"
1535 #
1536 # Make sure this holds for nested TestSuite instances, too
1537 def test_countTestCases_nested(self):
1538 class Test1(unittest.TestCase):
1539 def test1(self): pass
1540 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001541
Georg Brandl15c5ce92007-03-07 09:09:40 +00001542 test2 = unittest.FunctionTestCase(lambda: None)
1543 test3 = unittest.FunctionTestCase(lambda: None)
1544 child = unittest.TestSuite((Test1('test2'), test2))
1545 parent = unittest.TestSuite((test3, child, Test1('test1')))
Tim Petersea5962f2007-03-12 18:07:52 +00001546
Georg Brandl15c5ce92007-03-07 09:09:40 +00001547 self.assertEqual(parent.countTestCases(), 4)
Tim Petersea5962f2007-03-12 18:07:52 +00001548
Georg Brandl15c5ce92007-03-07 09:09:40 +00001549 # "Run the tests associated with this suite, collecting the result into
1550 # the test result object passed as result."
1551 #
1552 # And if there are no tests? What then?
1553 def test_run__empty_suite(self):
1554 events = []
1555 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001556
Georg Brandl15c5ce92007-03-07 09:09:40 +00001557 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001558
Georg Brandl15c5ce92007-03-07 09:09:40 +00001559 suite.run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001560
Georg Brandl15c5ce92007-03-07 09:09:40 +00001561 self.assertEqual(events, [])
Tim Petersea5962f2007-03-12 18:07:52 +00001562
Georg Brandl15c5ce92007-03-07 09:09:40 +00001563 # "Note that unlike TestCase.run(), TestSuite.run() requires the
1564 # "result object to be passed in."
1565 def test_run__requires_result(self):
1566 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001567
Georg Brandl15c5ce92007-03-07 09:09:40 +00001568 try:
1569 suite.run()
1570 except TypeError:
1571 pass
1572 else:
1573 self.fail("Failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +00001574
Georg Brandl15c5ce92007-03-07 09:09:40 +00001575 # "Run the tests associated with this suite, collecting the result into
Tim Petersea5962f2007-03-12 18:07:52 +00001576 # the test result object passed as result."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001577 def test_run(self):
1578 events = []
1579 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001580
Georg Brandl15c5ce92007-03-07 09:09:40 +00001581 class LoggingCase(unittest.TestCase):
1582 def run(self, result):
1583 events.append('run %s' % self._testMethodName)
Tim Petersea5962f2007-03-12 18:07:52 +00001584
Georg Brandl15c5ce92007-03-07 09:09:40 +00001585 def test1(self): pass
1586 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001587
1588 tests = [LoggingCase('test1'), LoggingCase('test2')]
1589
Georg Brandl15c5ce92007-03-07 09:09:40 +00001590 unittest.TestSuite(tests).run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001591
Georg Brandl15c5ce92007-03-07 09:09:40 +00001592 self.assertEqual(events, ['run test1', 'run test2'])
Tim Petersea5962f2007-03-12 18:07:52 +00001593
1594 # "Add a TestCase ... to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001595 def test_addTest__TestCase(self):
1596 class Foo(unittest.TestCase):
1597 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001598
Georg Brandl15c5ce92007-03-07 09:09:40 +00001599 test = Foo('test')
1600 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001601
Georg Brandl15c5ce92007-03-07 09:09:40 +00001602 suite.addTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001603
Georg Brandl15c5ce92007-03-07 09:09:40 +00001604 self.assertEqual(suite.countTestCases(), 1)
1605 self.assertEqual(list(suite), [test])
Tim Petersea5962f2007-03-12 18:07:52 +00001606
1607 # "Add a ... TestSuite to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001608 def test_addTest__TestSuite(self):
1609 class Foo(unittest.TestCase):
1610 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001611
Georg Brandl15c5ce92007-03-07 09:09:40 +00001612 suite_2 = unittest.TestSuite([Foo('test')])
Tim Petersea5962f2007-03-12 18:07:52 +00001613
Georg Brandl15c5ce92007-03-07 09:09:40 +00001614 suite = unittest.TestSuite()
1615 suite.addTest(suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001616
Georg Brandl15c5ce92007-03-07 09:09:40 +00001617 self.assertEqual(suite.countTestCases(), 1)
1618 self.assertEqual(list(suite), [suite_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001619
Georg Brandl15c5ce92007-03-07 09:09:40 +00001620 # "Add all the tests from an iterable of TestCase and TestSuite
1621 # instances to this test suite."
Tim Petersea5962f2007-03-12 18:07:52 +00001622 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001623 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001624 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001625 def test_addTests(self):
1626 class Foo(unittest.TestCase):
1627 def test_1(self): pass
1628 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001629
Georg Brandl15c5ce92007-03-07 09:09:40 +00001630 test_1 = Foo('test_1')
1631 test_2 = Foo('test_2')
1632 inner_suite = unittest.TestSuite([test_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001633
Georg Brandl15c5ce92007-03-07 09:09:40 +00001634 def gen():
1635 yield test_1
1636 yield test_2
1637 yield inner_suite
Tim Petersea5962f2007-03-12 18:07:52 +00001638
Georg Brandl15c5ce92007-03-07 09:09:40 +00001639 suite_1 = unittest.TestSuite()
1640 suite_1.addTests(gen())
Tim Petersea5962f2007-03-12 18:07:52 +00001641
Georg Brandl15c5ce92007-03-07 09:09:40 +00001642 self.assertEqual(list(suite_1), list(gen()))
Tim Petersea5962f2007-03-12 18:07:52 +00001643
Georg Brandl15c5ce92007-03-07 09:09:40 +00001644 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001645 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001646 suite_2 = unittest.TestSuite()
1647 for t in gen():
1648 suite_2.addTest(t)
Tim Petersea5962f2007-03-12 18:07:52 +00001649
Georg Brandl15c5ce92007-03-07 09:09:40 +00001650 self.assertEqual(suite_1, suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001651
Georg Brandl15c5ce92007-03-07 09:09:40 +00001652 # "Add all the tests from an iterable of TestCase and TestSuite
1653 # instances to this test suite."
1654 #
Tim Petersea5962f2007-03-12 18:07:52 +00001655 # What happens if it doesn't get an iterable?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001656 def test_addTest__noniterable(self):
1657 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001658
Georg Brandl15c5ce92007-03-07 09:09:40 +00001659 try:
1660 suite.addTests(5)
1661 except TypeError:
1662 pass
1663 else:
1664 self.fail("Failed to raise TypeError")
Georg Brandld9e50262007-03-07 11:54:49 +00001665
1666 def test_addTest__noncallable(self):
1667 suite = unittest.TestSuite()
1668 self.assertRaises(TypeError, suite.addTest, 5)
1669
1670 def test_addTest__casesuiteclass(self):
1671 suite = unittest.TestSuite()
1672 self.assertRaises(TypeError, suite.addTest, Test_TestSuite)
1673 self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)
1674
1675 def test_addTests__string(self):
1676 suite = unittest.TestSuite()
1677 self.assertRaises(TypeError, suite.addTests, "foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001678
1679
Georg Brandl15c5ce92007-03-07 09:09:40 +00001680class Test_FunctionTestCase(TestCase):
Tim Petersea5962f2007-03-12 18:07:52 +00001681
Georg Brandl15c5ce92007-03-07 09:09:40 +00001682 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00001683 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001684 def test_countTestCases(self):
1685 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001686
Georg Brandl15c5ce92007-03-07 09:09:40 +00001687 self.assertEqual(test.countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00001688
Georg Brandl15c5ce92007-03-07 09:09:40 +00001689 # "When a setUp() method is defined, the test runner will run that method
1690 # prior to each test. Likewise, if a tearDown() method is defined, the
1691 # test runner will invoke that method after each test. In the example,
1692 # setUp() was used to create a fresh sequence for each test."
1693 #
1694 # Make sure the proper call order is maintained, even if setUp() raises
1695 # an exception.
1696 def test_run_call_order__error_in_setUp(self):
1697 events = []
1698 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001699
Georg Brandl15c5ce92007-03-07 09:09:40 +00001700 def setUp():
1701 events.append('setUp')
1702 raise RuntimeError('raised by setUp')
1703
1704 def test():
1705 events.append('test')
1706
1707 def tearDown():
1708 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001709
1710 expected = ['startTest', 'setUp', 'addError', 'stopTest']
Georg Brandl15c5ce92007-03-07 09:09:40 +00001711 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1712 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001713
Georg Brandl15c5ce92007-03-07 09:09:40 +00001714 # "When a setUp() method is defined, the test runner will run that method
1715 # prior to each test. Likewise, if a tearDown() method is defined, the
1716 # test runner will invoke that method after each test. In the example,
1717 # setUp() was used to create a fresh sequence for each test."
1718 #
1719 # Make sure the proper call order is maintained, even if the test raises
1720 # an error (as opposed to a failure).
1721 def test_run_call_order__error_in_test(self):
1722 events = []
1723 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001724
Georg Brandl15c5ce92007-03-07 09:09:40 +00001725 def setUp():
1726 events.append('setUp')
1727
1728 def test():
1729 events.append('test')
1730 raise RuntimeError('raised by test')
1731
1732 def tearDown():
1733 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001734
Georg Brandl15c5ce92007-03-07 09:09:40 +00001735 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
1736 'stopTest']
1737 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1738 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001739
Georg Brandl15c5ce92007-03-07 09:09:40 +00001740 # "When a setUp() method is defined, the test runner will run that method
1741 # prior to each test. Likewise, if a tearDown() method is defined, the
1742 # test runner will invoke that method after each test. In the example,
1743 # setUp() was used to create a fresh sequence for each test."
1744 #
1745 # Make sure the proper call order is maintained, even if the test signals
1746 # a failure (as opposed to an error).
1747 def test_run_call_order__failure_in_test(self):
1748 events = []
1749 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001750
Georg Brandl15c5ce92007-03-07 09:09:40 +00001751 def setUp():
1752 events.append('setUp')
1753
1754 def test():
1755 events.append('test')
1756 self.fail('raised by test')
1757
1758 def tearDown():
1759 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001760
Georg Brandl15c5ce92007-03-07 09:09:40 +00001761 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
1762 'stopTest']
1763 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1764 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001765
Georg Brandl15c5ce92007-03-07 09:09:40 +00001766 # "When a setUp() method is defined, the test runner will run that method
1767 # prior to each test. Likewise, if a tearDown() method is defined, the
1768 # test runner will invoke that method after each test. In the example,
1769 # setUp() was used to create a fresh sequence for each test."
1770 #
1771 # Make sure the proper call order is maintained, even if tearDown() raises
1772 # an exception.
1773 def test_run_call_order__error_in_tearDown(self):
1774 events = []
1775 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001776
Georg Brandl15c5ce92007-03-07 09:09:40 +00001777 def setUp():
1778 events.append('setUp')
1779
1780 def test():
1781 events.append('test')
1782
1783 def tearDown():
1784 events.append('tearDown')
1785 raise RuntimeError('raised by tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001786
Georg Brandl15c5ce92007-03-07 09:09:40 +00001787 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
1788 'stopTest']
1789 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1790 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001791
Georg Brandl15c5ce92007-03-07 09:09:40 +00001792 # "Return a string identifying the specific test case."
1793 #
1794 # Because of the vague nature of the docs, I'm not going to lock this
1795 # test down too much. Really all that can be asserted is that the id()
1796 # will be a string (either 8-byte or unicode -- again, because the docs
1797 # just say "string")
1798 def test_id(self):
1799 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001800
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001801 self.assertIsInstance(test.id(), basestring)
Tim Petersea5962f2007-03-12 18:07:52 +00001802
Georg Brandl15c5ce92007-03-07 09:09:40 +00001803 # "Returns a one-line description of the test, or None if no description
1804 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001805 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001806 def test_shortDescription__no_docstring(self):
1807 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001808
Georg Brandl15c5ce92007-03-07 09:09:40 +00001809 self.assertEqual(test.shortDescription(), None)
Tim Petersea5962f2007-03-12 18:07:52 +00001810
Georg Brandl15c5ce92007-03-07 09:09:40 +00001811 # "Returns a one-line description of the test, or None if no description
1812 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001813 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001814 def test_shortDescription__singleline_docstring(self):
1815 desc = "this tests foo"
1816 test = unittest.FunctionTestCase(lambda: None, description=desc)
Tim Petersea5962f2007-03-12 18:07:52 +00001817
Georg Brandl15c5ce92007-03-07 09:09:40 +00001818 self.assertEqual(test.shortDescription(), "this tests foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001819
Georg Brandl15c5ce92007-03-07 09:09:40 +00001820class Test_TestResult(TestCase):
1821 # Note: there are not separate tests for TestResult.wasSuccessful(),
1822 # TestResult.errors, TestResult.failures, TestResult.testsRun or
1823 # TestResult.shouldStop because these only have meaning in terms of
1824 # other TestResult methods.
1825 #
1826 # Accordingly, tests for the aforenamed attributes are incorporated
1827 # in with the tests for the defining methods.
1828 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001829
Georg Brandl15c5ce92007-03-07 09:09:40 +00001830 def test_init(self):
1831 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001832
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001833 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001834 self.assertEqual(len(result.errors), 0)
1835 self.assertEqual(len(result.failures), 0)
1836 self.assertEqual(result.testsRun, 0)
1837 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001838
Georg Brandl15c5ce92007-03-07 09:09:40 +00001839 # "This method can be called to signal that the set of tests being
1840 # run should be aborted by setting the TestResult's shouldStop
Tim Petersea5962f2007-03-12 18:07:52 +00001841 # attribute to True."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001842 def test_stop(self):
1843 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001844
Georg Brandl15c5ce92007-03-07 09:09:40 +00001845 result.stop()
Tim Petersea5962f2007-03-12 18:07:52 +00001846
Georg Brandl15c5ce92007-03-07 09:09:40 +00001847 self.assertEqual(result.shouldStop, True)
Tim Petersea5962f2007-03-12 18:07:52 +00001848
Georg Brandl15c5ce92007-03-07 09:09:40 +00001849 # "Called when the test case test is about to be run. The default
1850 # implementation simply increments the instance's testsRun counter."
1851 def test_startTest(self):
1852 class Foo(unittest.TestCase):
1853 def test_1(self):
1854 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001855
Georg Brandl15c5ce92007-03-07 09:09:40 +00001856 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001857
Georg Brandl15c5ce92007-03-07 09:09:40 +00001858 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001859
Georg Brandl15c5ce92007-03-07 09:09:40 +00001860 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001861
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001862 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001863 self.assertEqual(len(result.errors), 0)
1864 self.assertEqual(len(result.failures), 0)
1865 self.assertEqual(result.testsRun, 1)
1866 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001867
Georg Brandl15c5ce92007-03-07 09:09:40 +00001868 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001869
Georg Brandl15c5ce92007-03-07 09:09:40 +00001870 # "Called after the test case test has been executed, regardless of
1871 # the outcome. The default implementation does nothing."
1872 def test_stopTest(self):
1873 class Foo(unittest.TestCase):
1874 def test_1(self):
1875 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001876
Georg Brandl15c5ce92007-03-07 09:09:40 +00001877 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001878
Georg Brandl15c5ce92007-03-07 09:09:40 +00001879 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001880
Georg Brandl15c5ce92007-03-07 09:09:40 +00001881 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001882
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001883 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001884 self.assertEqual(len(result.errors), 0)
1885 self.assertEqual(len(result.failures), 0)
1886 self.assertEqual(result.testsRun, 1)
1887 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001888
Georg Brandl15c5ce92007-03-07 09:09:40 +00001889 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001890
Georg Brandl15c5ce92007-03-07 09:09:40 +00001891 # Same tests as above; make sure nothing has changed
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001892 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001893 self.assertEqual(len(result.errors), 0)
1894 self.assertEqual(len(result.failures), 0)
1895 self.assertEqual(result.testsRun, 1)
1896 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001897
Michael Foord07ef4872009-05-02 22:43:34 +00001898 # "Called before and after tests are run. The default implementation does nothing."
1899 def test_startTestRun_stopTestRun(self):
1900 result = unittest.TestResult()
1901 result.startTestRun()
1902 result.stopTestRun()
1903
Georg Brandl15c5ce92007-03-07 09:09:40 +00001904 # "addSuccess(test)"
1905 # ...
1906 # "Called when the test case test succeeds"
1907 # ...
1908 # "wasSuccessful() - Returns True if all tests run so far have passed,
1909 # otherwise returns False"
1910 # ...
1911 # "testsRun - The total number of tests run so far."
1912 # ...
1913 # "errors - A list containing 2-tuples of TestCase instances and
1914 # formatted tracebacks. Each tuple represents a test which raised an
1915 # unexpected exception. Contains formatted
1916 # tracebacks instead of sys.exc_info() results."
1917 # ...
1918 # "failures - A list containing 2-tuples of TestCase instances and
1919 # formatted tracebacks. Each tuple represents a test where a failure was
1920 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1921 # methods. Contains formatted tracebacks instead
1922 # of sys.exc_info() results."
1923 def test_addSuccess(self):
1924 class Foo(unittest.TestCase):
1925 def test_1(self):
1926 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001927
Georg Brandl15c5ce92007-03-07 09:09:40 +00001928 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001929
Georg Brandl15c5ce92007-03-07 09:09:40 +00001930 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001931
Georg Brandl15c5ce92007-03-07 09:09:40 +00001932 result.startTest(test)
1933 result.addSuccess(test)
1934 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001935
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001936 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001937 self.assertEqual(len(result.errors), 0)
1938 self.assertEqual(len(result.failures), 0)
1939 self.assertEqual(result.testsRun, 1)
1940 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001941
Georg Brandl15c5ce92007-03-07 09:09:40 +00001942 # "addFailure(test, err)"
1943 # ...
1944 # "Called when the test case test signals a failure. err is a tuple of
1945 # the form returned by sys.exc_info(): (type, value, traceback)"
1946 # ...
1947 # "wasSuccessful() - Returns True if all tests run so far have passed,
1948 # otherwise returns False"
1949 # ...
1950 # "testsRun - The total number of tests run so far."
1951 # ...
1952 # "errors - A list containing 2-tuples of TestCase instances and
1953 # formatted tracebacks. Each tuple represents a test which raised an
1954 # unexpected exception. Contains formatted
1955 # tracebacks instead of sys.exc_info() results."
1956 # ...
1957 # "failures - A list containing 2-tuples of TestCase instances and
1958 # formatted tracebacks. Each tuple represents a test where a failure was
1959 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1960 # methods. Contains formatted tracebacks instead
1961 # of sys.exc_info() results."
1962 def test_addFailure(self):
Georg Brandl15c5ce92007-03-07 09:09:40 +00001963 class Foo(unittest.TestCase):
1964 def test_1(self):
1965 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001966
Georg Brandl15c5ce92007-03-07 09:09:40 +00001967 test = Foo('test_1')
1968 try:
1969 test.fail("foo")
1970 except:
1971 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00001972
Georg Brandl15c5ce92007-03-07 09:09:40 +00001973 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001974
Georg Brandl15c5ce92007-03-07 09:09:40 +00001975 result.startTest(test)
1976 result.addFailure(test, exc_info_tuple)
1977 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001978
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001979 self.assertFalse(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001980 self.assertEqual(len(result.errors), 0)
1981 self.assertEqual(len(result.failures), 1)
1982 self.assertEqual(result.testsRun, 1)
1983 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001984
Georg Brandl15c5ce92007-03-07 09:09:40 +00001985 test_case, formatted_exc = result.failures[0]
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001986 self.assertTrue(test_case is test)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001987 self.assertIsInstance(formatted_exc, str)
Tim Petersea5962f2007-03-12 18:07:52 +00001988
Georg Brandl15c5ce92007-03-07 09:09:40 +00001989 # "addError(test, err)"
1990 # ...
1991 # "Called when the test case test raises an unexpected exception err
1992 # is a tuple of the form returned by sys.exc_info():
1993 # (type, value, traceback)"
1994 # ...
1995 # "wasSuccessful() - Returns True if all tests run so far have passed,
1996 # otherwise returns False"
1997 # ...
1998 # "testsRun - The total number of tests run so far."
1999 # ...
2000 # "errors - A list containing 2-tuples of TestCase instances and
2001 # formatted tracebacks. Each tuple represents a test which raised an
2002 # unexpected exception. Contains formatted
2003 # tracebacks instead of sys.exc_info() results."
2004 # ...
2005 # "failures - A list containing 2-tuples of TestCase instances and
2006 # formatted tracebacks. Each tuple represents a test where a failure was
2007 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
2008 # methods. Contains formatted tracebacks instead
2009 # of sys.exc_info() results."
2010 def test_addError(self):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002011 class Foo(unittest.TestCase):
2012 def test_1(self):
2013 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002014
Georg Brandl15c5ce92007-03-07 09:09:40 +00002015 test = Foo('test_1')
2016 try:
2017 raise TypeError()
2018 except:
2019 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00002020
Georg Brandl15c5ce92007-03-07 09:09:40 +00002021 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00002022
Georg Brandl15c5ce92007-03-07 09:09:40 +00002023 result.startTest(test)
2024 result.addError(test, exc_info_tuple)
2025 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00002026
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002027 self.assertFalse(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00002028 self.assertEqual(len(result.errors), 1)
2029 self.assertEqual(len(result.failures), 0)
2030 self.assertEqual(result.testsRun, 1)
2031 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00002032
Georg Brandl15c5ce92007-03-07 09:09:40 +00002033 test_case, formatted_exc = result.errors[0]
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002034 self.assertTrue(test_case is test)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002035 self.assertIsInstance(formatted_exc, str)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002036
Michael Foorddb43b5a2010-02-10 14:25:12 +00002037 def testGetDescriptionWithoutDocstring(self):
Michael Foord1c3abf42010-02-10 15:50:58 +00002038 result = unittest.TextTestResult(None, True, 1)
Michael Foorddb43b5a2010-02-10 14:25:12 +00002039 self.assertEqual(
2040 result.getDescription(self),
2041 'testGetDescriptionWithoutDocstring (' + __name__ +
2042 '.Test_TestResult)')
2043
R. David Murrayf28fd242010-02-23 00:24:49 +00002044 @unittest.skipIf(sys.flags.optimize >= 2,
2045 "Docstrings are omitted with -O2 and above")
Michael Foorddb43b5a2010-02-10 14:25:12 +00002046 def testGetDescriptionWithOneLineDocstring(self):
2047 """Tests getDescription() for a method with a docstring."""
Michael Foord1c3abf42010-02-10 15:50:58 +00002048 result = unittest.TextTestResult(None, True, 1)
Michael Foorddb43b5a2010-02-10 14:25:12 +00002049 self.assertEqual(
2050 result.getDescription(self),
2051 ('testGetDescriptionWithOneLineDocstring '
2052 '(' + __name__ + '.Test_TestResult)\n'
2053 'Tests getDescription() for a method with a docstring.'))
2054
R. David Murrayf28fd242010-02-23 00:24:49 +00002055 @unittest.skipIf(sys.flags.optimize >= 2,
2056 "Docstrings are omitted with -O2 and above")
Michael Foorddb43b5a2010-02-10 14:25:12 +00002057 def testGetDescriptionWithMultiLineDocstring(self):
2058 """Tests getDescription() for a method with a longer docstring.
2059 The second line of the docstring.
2060 """
Michael Foord1c3abf42010-02-10 15:50:58 +00002061 result = unittest.TextTestResult(None, True, 1)
Michael Foorddb43b5a2010-02-10 14:25:12 +00002062 self.assertEqual(
2063 result.getDescription(self),
2064 ('testGetDescriptionWithMultiLineDocstring '
2065 '(' + __name__ + '.Test_TestResult)\n'
2066 'Tests getDescription() for a method with a longer '
2067 'docstring.'))
2068
Michael Foordae3db0a2010-02-22 23:28:32 +00002069classDict = dict(unittest.TestResult.__dict__)
Michael Foordd99ef9a2010-02-23 17:00:53 +00002070for m in ('addSkip', 'addExpectedFailure', 'addUnexpectedSuccess',
2071 '__init__'):
Michael Foordae3db0a2010-02-22 23:28:32 +00002072 del classDict[m]
Michael Foordd99ef9a2010-02-23 17:00:53 +00002073
2074def __init__(self, stream=None, descriptions=None, verbosity=None):
2075 self.failures = []
2076 self.errors = []
2077 self.testsRun = 0
2078 self.shouldStop = False
2079classDict['__init__'] = __init__
Michael Foordae3db0a2010-02-22 23:28:32 +00002080OldResult = type('OldResult', (object,), classDict)
2081
2082class Test_OldTestResult(unittest.TestCase):
2083
2084 def assertOldResultWarning(self, test, failures):
2085 with warnings.catch_warnings(record=True) as log:
2086 result = OldResult()
2087 test.run(result)
2088 self.assertEqual(len(result.failures), failures)
2089 warning, = log
2090 self.assertIs(warning.category, RuntimeWarning)
2091
2092 def testOldTestResult(self):
2093 class Test(unittest.TestCase):
2094 def testSkip(self):
2095 self.skipTest('foobar')
2096 @unittest.expectedFailure
2097 def testExpectedFail(self):
2098 raise TypeError
2099 @unittest.expectedFailure
2100 def testUnexpectedSuccess(self):
2101 pass
2102
2103 for test_name, should_pass in (('testSkip', True),
2104 ('testExpectedFail', True),
2105 ('testUnexpectedSuccess', False)):
2106 test = Test(test_name)
2107 self.assertOldResultWarning(test, int(not should_pass))
2108
2109 def testOldTestTesultSetup(self):
2110 class Test(unittest.TestCase):
2111 def setUp(self):
2112 self.skipTest('no reason')
2113 def testFoo(self):
2114 pass
2115 self.assertOldResultWarning(Test('testFoo'), 0)
2116
2117 def testOldTestResultClass(self):
2118 @unittest.skip('no reason')
2119 class Test(unittest.TestCase):
2120 def testFoo(self):
2121 pass
2122 self.assertOldResultWarning(Test('testFoo'), 0)
2123
Michael Foordd99ef9a2010-02-23 17:00:53 +00002124 def testOldResultWithRunner(self):
2125 class Test(unittest.TestCase):
2126 def testFoo(self):
2127 pass
2128 runner = unittest.TextTestRunner(resultclass=OldResult,
2129 stream=StringIO())
2130 # This will raise an exception if TextTestRunner can't handle old
2131 # test result objects
2132 runner.run(Test('testFoo'))
Michael Foorddb43b5a2010-02-10 14:25:12 +00002133
Georg Brandl15c5ce92007-03-07 09:09:40 +00002134### Support code for Test_TestCase
2135################################################################
2136
2137class Foo(unittest.TestCase):
2138 def runTest(self): pass
2139 def test1(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002140
Georg Brandl15c5ce92007-03-07 09:09:40 +00002141class Bar(Foo):
2142 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002143
Michael Foord07ef4872009-05-02 22:43:34 +00002144class LoggingTestCase(unittest.TestCase):
2145 """A test case which logs its calls."""
2146
2147 def __init__(self, events):
2148 super(LoggingTestCase, self).__init__('test')
2149 self.events = events
2150
2151 def setUp(self):
2152 self.events.append('setUp')
2153
2154 def test(self):
2155 self.events.append('test')
2156
2157 def tearDown(self):
2158 self.events.append('tearDown')
2159
2160class ResultWithNoStartTestRunStopTestRun(object):
2161 """An object honouring TestResult before startTestRun/stopTestRun."""
2162
2163 def __init__(self):
2164 self.failures = []
2165 self.errors = []
2166 self.testsRun = 0
2167 self.skipped = []
2168 self.expectedFailures = []
2169 self.unexpectedSuccesses = []
2170 self.shouldStop = False
2171
2172 def startTest(self, test):
2173 pass
2174
2175 def stopTest(self, test):
2176 pass
2177
2178 def addError(self, test):
2179 pass
2180
2181 def addFailure(self, test):
2182 pass
2183
2184 def addSuccess(self, test):
2185 pass
2186
2187 def wasSuccessful(self):
2188 return True
2189
2190
Georg Brandl15c5ce92007-03-07 09:09:40 +00002191################################################################
2192### /Support code for Test_TestCase
2193
2194class Test_TestCase(TestCase, TestEquality, TestHashing):
2195
2196 ### Set up attributes used by inherited tests
2197 ################################################################
2198
2199 # Used by TestHashing.test_hash and TestEquality.test_eq
2200 eq_pairs = [(Foo('test1'), Foo('test1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002201
Georg Brandl15c5ce92007-03-07 09:09:40 +00002202 # Used by TestEquality.test_ne
2203 ne_pairs = [(Foo('test1'), Foo('runTest'))
2204 ,(Foo('test1'), Bar('test1'))
2205 ,(Foo('test1'), Bar('test2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002206
Georg Brandl15c5ce92007-03-07 09:09:40 +00002207 ################################################################
2208 ### /Set up attributes used by inherited tests
Tim Petersea5962f2007-03-12 18:07:52 +00002209
Georg Brandl15c5ce92007-03-07 09:09:40 +00002210
2211 # "class TestCase([methodName])"
2212 # ...
2213 # "Each instance of TestCase will run a single test method: the
2214 # method named methodName."
2215 # ...
2216 # "methodName defaults to "runTest"."
2217 #
2218 # Make sure it really is optional, and that it defaults to the proper
2219 # thing.
2220 def test_init__no_test_name(self):
2221 class Test(unittest.TestCase):
2222 def runTest(self): raise MyException()
2223 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002224
Georg Brandl15c5ce92007-03-07 09:09:40 +00002225 self.assertEqual(Test().id()[-13:], '.Test.runTest')
Tim Petersea5962f2007-03-12 18:07:52 +00002226
Georg Brandl15c5ce92007-03-07 09:09:40 +00002227 # "class TestCase([methodName])"
2228 # ...
2229 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002230 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002231 def test_init__test_name__valid(self):
2232 class Test(unittest.TestCase):
2233 def runTest(self): raise MyException()
2234 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002235
Georg Brandl15c5ce92007-03-07 09:09:40 +00002236 self.assertEqual(Test('test').id()[-10:], '.Test.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002237
Georg Brandl15c5ce92007-03-07 09:09:40 +00002238 # "class TestCase([methodName])"
2239 # ...
2240 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002241 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002242 def test_init__test_name__invalid(self):
2243 class Test(unittest.TestCase):
2244 def runTest(self): raise MyException()
2245 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002246
Georg Brandl15c5ce92007-03-07 09:09:40 +00002247 try:
2248 Test('testfoo')
2249 except ValueError:
2250 pass
2251 else:
2252 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +00002253
Georg Brandl15c5ce92007-03-07 09:09:40 +00002254 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00002255 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00002256 def test_countTestCases(self):
2257 class Foo(unittest.TestCase):
2258 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002259
Georg Brandl15c5ce92007-03-07 09:09:40 +00002260 self.assertEqual(Foo('test').countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00002261
Georg Brandl15c5ce92007-03-07 09:09:40 +00002262 # "Return the default type of test result object to be used to run this
2263 # test. For TestCase instances, this will always be
2264 # unittest.TestResult; subclasses of TestCase should
2265 # override this as necessary."
2266 def test_defaultTestResult(self):
2267 class Foo(unittest.TestCase):
2268 def runTest(self):
2269 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002270
Georg Brandl15c5ce92007-03-07 09:09:40 +00002271 result = Foo().defaultTestResult()
2272 self.assertEqual(type(result), unittest.TestResult)
2273
2274 # "When a setUp() method is defined, the test runner will run that method
2275 # prior to each test. Likewise, if a tearDown() method is defined, the
2276 # test runner will invoke that method after each test. In the example,
2277 # setUp() was used to create a fresh sequence for each test."
2278 #
2279 # Make sure the proper call order is maintained, even if setUp() raises
2280 # an exception.
2281 def test_run_call_order__error_in_setUp(self):
2282 events = []
2283 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002284
Michael Foord07ef4872009-05-02 22:43:34 +00002285 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002286 def setUp(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002287 super(Foo, self).setUp()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002288 raise RuntimeError('raised by Foo.setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002289
Michael Foord07ef4872009-05-02 22:43:34 +00002290 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002291 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2292 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002293
Michael Foord07ef4872009-05-02 22:43:34 +00002294 # "With a temporary result stopTestRun is called when setUp errors.
2295 def test_run_call_order__error_in_setUp_default_result(self):
2296 events = []
2297
2298 class Foo(LoggingTestCase):
2299 def defaultTestResult(self):
2300 return LoggingResult(self.events)
2301
2302 def setUp(self):
2303 super(Foo, self).setUp()
2304 raise RuntimeError('raised by Foo.setUp')
2305
2306 Foo(events).run()
2307 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2308 'stopTest', 'stopTestRun']
2309 self.assertEqual(events, expected)
2310
Georg Brandl15c5ce92007-03-07 09:09:40 +00002311 # "When a setUp() method is defined, the test runner will run that method
2312 # prior to each test. Likewise, if a tearDown() method is defined, the
2313 # test runner will invoke that method after each test. In the example,
2314 # setUp() was used to create a fresh sequence for each test."
2315 #
2316 # Make sure the proper call order is maintained, even if the test raises
2317 # an error (as opposed to a failure).
2318 def test_run_call_order__error_in_test(self):
2319 events = []
2320 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002321
Michael Foord07ef4872009-05-02 22:43:34 +00002322 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002323 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002324 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002325 raise RuntimeError('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002326
Georg Brandl15c5ce92007-03-07 09:09:40 +00002327 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2328 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002329 Foo(events).run(result)
2330 self.assertEqual(events, expected)
2331
2332 # "With a default result, an error in the test still results in stopTestRun
2333 # being called."
2334 def test_run_call_order__error_in_test_default_result(self):
2335 events = []
2336
2337 class Foo(LoggingTestCase):
2338 def defaultTestResult(self):
2339 return LoggingResult(self.events)
2340
2341 def test(self):
2342 super(Foo, self).test()
2343 raise RuntimeError('raised by Foo.test')
2344
2345 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2346 'tearDown', 'stopTest', 'stopTestRun']
2347 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002348 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002349
Georg Brandl15c5ce92007-03-07 09:09:40 +00002350 # "When a setUp() method is defined, the test runner will run that method
2351 # prior to each test. Likewise, if a tearDown() method is defined, the
2352 # test runner will invoke that method after each test. In the example,
2353 # setUp() was used to create a fresh sequence for each test."
2354 #
2355 # Make sure the proper call order is maintained, even if the test signals
2356 # a failure (as opposed to an error).
2357 def test_run_call_order__failure_in_test(self):
2358 events = []
2359 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002360
Michael Foord07ef4872009-05-02 22:43:34 +00002361 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002362 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002363 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002364 self.fail('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002365
Georg Brandl15c5ce92007-03-07 09:09:40 +00002366 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2367 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002368 Foo(events).run(result)
2369 self.assertEqual(events, expected)
2370
2371 # "When a test fails with a default result stopTestRun is still called."
2372 def test_run_call_order__failure_in_test_default_result(self):
2373
2374 class Foo(LoggingTestCase):
2375 def defaultTestResult(self):
2376 return LoggingResult(self.events)
2377 def test(self):
2378 super(Foo, self).test()
2379 self.fail('raised by Foo.test')
2380
2381 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2382 'tearDown', 'stopTest', 'stopTestRun']
2383 events = []
2384 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002385 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002386
Georg Brandl15c5ce92007-03-07 09:09:40 +00002387 # "When a setUp() method is defined, the test runner will run that method
2388 # prior to each test. Likewise, if a tearDown() method is defined, the
2389 # test runner will invoke that method after each test. In the example,
2390 # setUp() was used to create a fresh sequence for each test."
2391 #
2392 # Make sure the proper call order is maintained, even if tearDown() raises
2393 # an exception.
2394 def test_run_call_order__error_in_tearDown(self):
2395 events = []
2396 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002397
Michael Foord07ef4872009-05-02 22:43:34 +00002398 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002399 def tearDown(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002400 super(Foo, self).tearDown()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002401 raise RuntimeError('raised by Foo.tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002402
Michael Foord07ef4872009-05-02 22:43:34 +00002403 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002404 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2405 'stopTest']
2406 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002407
Michael Foord07ef4872009-05-02 22:43:34 +00002408 # "When tearDown errors with a default result stopTestRun is still called."
2409 def test_run_call_order__error_in_tearDown_default_result(self):
2410
2411 class Foo(LoggingTestCase):
2412 def defaultTestResult(self):
2413 return LoggingResult(self.events)
2414 def tearDown(self):
2415 super(Foo, self).tearDown()
2416 raise RuntimeError('raised by Foo.tearDown')
2417
2418 events = []
2419 Foo(events).run()
2420 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2421 'addError', 'stopTest', 'stopTestRun']
2422 self.assertEqual(events, expected)
2423
2424 # "TestCase.run() still works when the defaultTestResult is a TestResult
2425 # that does not support startTestRun and stopTestRun.
2426 def test_run_call_order_default_result(self):
2427
2428 class Foo(unittest.TestCase):
2429 def defaultTestResult(self):
2430 return ResultWithNoStartTestRunStopTestRun()
2431 def test(self):
2432 pass
2433
2434 Foo('test').run()
2435
Georg Brandl15c5ce92007-03-07 09:09:40 +00002436 # "This class attribute gives the exception raised by the test() method.
2437 # If a test framework needs to use a specialized exception, possibly to
2438 # carry additional information, it must subclass this exception in
2439 # order to ``play fair'' with the framework. The initial value of this
2440 # attribute is AssertionError"
2441 def test_failureException__default(self):
2442 class Foo(unittest.TestCase):
2443 def test(self):
2444 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002445
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002446 self.assertTrue(Foo('test').failureException is AssertionError)
Tim Petersea5962f2007-03-12 18:07:52 +00002447
Georg Brandl15c5ce92007-03-07 09:09:40 +00002448 # "This class attribute gives the exception raised by the test() method.
2449 # If a test framework needs to use a specialized exception, possibly to
2450 # carry additional information, it must subclass this exception in
2451 # order to ``play fair'' with the framework."
2452 #
2453 # Make sure TestCase.run() respects the designated failureException
2454 def test_failureException__subclassing__explicit_raise(self):
2455 events = []
2456 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002457
Georg Brandl15c5ce92007-03-07 09:09:40 +00002458 class Foo(unittest.TestCase):
2459 def test(self):
2460 raise RuntimeError()
Tim Petersea5962f2007-03-12 18:07:52 +00002461
Georg Brandl15c5ce92007-03-07 09:09:40 +00002462 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002463
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002464 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002465
2466
Georg Brandl15c5ce92007-03-07 09:09:40 +00002467 Foo('test').run(result)
2468 expected = ['startTest', 'addFailure', 'stopTest']
2469 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002470
Georg Brandl15c5ce92007-03-07 09:09:40 +00002471 # "This class attribute gives the exception raised by the test() method.
2472 # If a test framework needs to use a specialized exception, possibly to
2473 # carry additional information, it must subclass this exception in
2474 # order to ``play fair'' with the framework."
2475 #
2476 # Make sure TestCase.run() respects the designated failureException
2477 def test_failureException__subclassing__implicit_raise(self):
2478 events = []
2479 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002480
Georg Brandl15c5ce92007-03-07 09:09:40 +00002481 class Foo(unittest.TestCase):
2482 def test(self):
2483 self.fail("foo")
Tim Petersea5962f2007-03-12 18:07:52 +00002484
Georg Brandl15c5ce92007-03-07 09:09:40 +00002485 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002486
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002487 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002488
2489
Georg Brandl15c5ce92007-03-07 09:09:40 +00002490 Foo('test').run(result)
2491 expected = ['startTest', 'addFailure', 'stopTest']
2492 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002493
2494 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002495 def test_setUp(self):
2496 class Foo(unittest.TestCase):
2497 def runTest(self):
2498 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002499
Georg Brandl15c5ce92007-03-07 09:09:40 +00002500 # ... and nothing should happen
2501 Foo().setUp()
Tim Petersea5962f2007-03-12 18:07:52 +00002502
2503 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002504 def test_tearDown(self):
2505 class Foo(unittest.TestCase):
2506 def runTest(self):
2507 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002508
Georg Brandl15c5ce92007-03-07 09:09:40 +00002509 # ... and nothing should happen
2510 Foo().tearDown()
Tim Petersea5962f2007-03-12 18:07:52 +00002511
Georg Brandl15c5ce92007-03-07 09:09:40 +00002512 # "Return a string identifying the specific test case."
2513 #
2514 # Because of the vague nature of the docs, I'm not going to lock this
2515 # test down too much. Really all that can be asserted is that the id()
2516 # will be a string (either 8-byte or unicode -- again, because the docs
2517 # just say "string")
2518 def test_id(self):
2519 class Foo(unittest.TestCase):
2520 def runTest(self):
2521 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002522
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002523 self.assertIsInstance(Foo().id(), basestring)
Tim Petersea5962f2007-03-12 18:07:52 +00002524
Georg Brandl15c5ce92007-03-07 09:09:40 +00002525 # "If result is omitted or None, a temporary result object is created
Michael Foord07ef4872009-05-02 22:43:34 +00002526 # and used, but is not made available to the caller. As TestCase owns the
2527 # temporary result startTestRun and stopTestRun are called.
2528
Georg Brandl15c5ce92007-03-07 09:09:40 +00002529 def test_run__uses_defaultTestResult(self):
2530 events = []
Tim Petersea5962f2007-03-12 18:07:52 +00002531
Georg Brandl15c5ce92007-03-07 09:09:40 +00002532 class Foo(unittest.TestCase):
2533 def test(self):
2534 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002535
Georg Brandl15c5ce92007-03-07 09:09:40 +00002536 def defaultTestResult(self):
2537 return LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002538
2539 # Make run() find a result object on its own
Georg Brandl15c5ce92007-03-07 09:09:40 +00002540 Foo('test').run()
Tim Petersea5962f2007-03-12 18:07:52 +00002541
Michael Foord07ef4872009-05-02 22:43:34 +00002542 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2543 'stopTest', 'stopTestRun']
Georg Brandl15c5ce92007-03-07 09:09:40 +00002544 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002545
Gregory P. Smith28399852009-03-31 16:54:10 +00002546 def testShortDescriptionWithoutDocstring(self):
Michael Foorddb43b5a2010-02-10 14:25:12 +00002547 self.assertIsNone(self.shortDescription())
Gregory P. Smith28399852009-03-31 16:54:10 +00002548
R. David Murrayf28fd242010-02-23 00:24:49 +00002549 @unittest.skipIf(sys.flags.optimize >= 2,
2550 "Docstrings are omitted with -O2 and above")
Gregory P. Smith28399852009-03-31 16:54:10 +00002551 def testShortDescriptionWithOneLineDocstring(self):
2552 """Tests shortDescription() for a method with a docstring."""
2553 self.assertEqual(
2554 self.shortDescription(),
Michael Foorddb43b5a2010-02-10 14:25:12 +00002555 'Tests shortDescription() for a method with a docstring.')
Gregory P. Smith28399852009-03-31 16:54:10 +00002556
R. David Murrayf28fd242010-02-23 00:24:49 +00002557 @unittest.skipIf(sys.flags.optimize >= 2,
2558 "Docstrings are omitted with -O2 and above")
Gregory P. Smith28399852009-03-31 16:54:10 +00002559 def testShortDescriptionWithMultiLineDocstring(self):
2560 """Tests shortDescription() for a method with a longer docstring.
2561
2562 This method ensures that only the first line of a docstring is
2563 returned used in the short description, no matter how long the
2564 whole thing is.
2565 """
2566 self.assertEqual(
2567 self.shortDescription(),
Gregory P. Smith28399852009-03-31 16:54:10 +00002568 'Tests shortDescription() for a method with a longer '
Michael Foorddb43b5a2010-02-10 14:25:12 +00002569 'docstring.')
Gregory P. Smith28399852009-03-31 16:54:10 +00002570
Gregory P. Smith28399852009-03-31 16:54:10 +00002571 def testAddTypeEqualityFunc(self):
2572 class SadSnake(object):
2573 """Dummy class for test_addTypeEqualityFunc."""
2574 s1, s2 = SadSnake(), SadSnake()
2575 self.assertFalse(s1 == s2)
2576 def AllSnakesCreatedEqual(a, b, msg=None):
2577 return type(a) == type(b) == SadSnake
2578 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2579 self.assertEqual(s1, s2)
2580 # No this doesn't clean up and remove the SadSnake equality func
2581 # from this TestCase instance but since its a local nothing else
2582 # will ever notice that.
2583
Michael Foordf2dfef12009-04-05 19:19:28 +00002584 def testAssertIs(self):
2585 thing = object()
2586 self.assertIs(thing, thing)
2587 self.assertRaises(self.failureException, self.assertIs, thing, object())
2588
2589 def testAssertIsNot(self):
2590 thing = object()
2591 self.assertIsNot(thing, object())
2592 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2593
Georg Brandlf895cf52009-10-01 20:59:31 +00002594 def testAssertIsInstance(self):
2595 thing = []
2596 self.assertIsInstance(thing, list)
2597 self.assertRaises(self.failureException, self.assertIsInstance,
2598 thing, dict)
2599
2600 def testAssertNotIsInstance(self):
2601 thing = []
2602 self.assertNotIsInstance(thing, dict)
2603 self.assertRaises(self.failureException, self.assertNotIsInstance,
2604 thing, list)
2605
Gregory P. Smith28399852009-03-31 16:54:10 +00002606 def testAssertIn(self):
2607 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2608
2609 self.assertIn('a', 'abc')
2610 self.assertIn(2, [1, 2, 3])
2611 self.assertIn('monkey', animals)
2612
2613 self.assertNotIn('d', 'abc')
2614 self.assertNotIn(0, [1, 2, 3])
2615 self.assertNotIn('otter', animals)
2616
2617 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2618 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2619 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2620 animals)
2621
2622 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2623 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2624 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2625 animals)
2626
2627 def testAssertDictContainsSubset(self):
2628 self.assertDictContainsSubset({}, {})
2629 self.assertDictContainsSubset({}, {'a': 1})
2630 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2631 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2632 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2633
Michael Foord225a0992010-02-18 20:30:09 +00002634 with self.assertRaises(self.failureException):
2635 self.assertDictContainsSubset({1: "one"}, {})
Gregory P. Smith28399852009-03-31 16:54:10 +00002636
Michael Foord225a0992010-02-18 20:30:09 +00002637 with self.assertRaises(self.failureException):
2638 self.assertDictContainsSubset({'a': 2}, {'a': 1})
Gregory P. Smith28399852009-03-31 16:54:10 +00002639
Michael Foord225a0992010-02-18 20:30:09 +00002640 with self.assertRaises(self.failureException):
2641 self.assertDictContainsSubset({'c': 1}, {'a': 1})
Gregory P. Smith28399852009-03-31 16:54:10 +00002642
Michael Foord225a0992010-02-18 20:30:09 +00002643 with self.assertRaises(self.failureException):
2644 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2645
2646 with self.assertRaises(self.failureException):
2647 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2648
Michael Foord2f677562010-02-21 14:48:59 +00002649 with warnings.catch_warnings(record=True):
2650 # silence the UnicodeWarning
2651 one = ''.join(chr(i) for i in range(255))
2652 # this used to cause a UnicodeDecodeError constructing the failure msg
2653 with self.assertRaises(self.failureException):
2654 self.assertDictContainsSubset({'foo': one}, {'foo': u'\uFFFD'})
Gregory P. Smith28399852009-03-31 16:54:10 +00002655
2656 def testAssertEqual(self):
2657 equal_pairs = [
2658 ((), ()),
2659 ({}, {}),
2660 ([], []),
2661 (set(), set()),
2662 (frozenset(), frozenset())]
2663 for a, b in equal_pairs:
2664 # This mess of try excepts is to test the assertEqual behavior
2665 # itself.
2666 try:
2667 self.assertEqual(a, b)
2668 except self.failureException:
2669 self.fail('assertEqual(%r, %r) failed' % (a, b))
2670 try:
2671 self.assertEqual(a, b, msg='foo')
2672 except self.failureException:
2673 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2674 try:
2675 self.assertEqual(a, b, 'foo')
2676 except self.failureException:
2677 self.fail('assertEqual(%r, %r) with third parameter failed' %
2678 (a, b))
2679
2680 unequal_pairs = [
2681 ((), []),
2682 ({}, set()),
2683 (set([4,1]), frozenset([4,2])),
2684 (frozenset([4,5]), set([2,3])),
2685 (set([3,4]), set([5,4]))]
2686 for a, b in unequal_pairs:
2687 self.assertRaises(self.failureException, self.assertEqual, a, b)
2688 self.assertRaises(self.failureException, self.assertEqual, a, b,
2689 'foo')
2690 self.assertRaises(self.failureException, self.assertEqual, a, b,
2691 msg='foo')
2692
2693 def testEquality(self):
2694 self.assertListEqual([], [])
2695 self.assertTupleEqual((), ())
2696 self.assertSequenceEqual([], ())
2697
2698 a = [0, 'a', []]
2699 b = []
2700 self.assertRaises(unittest.TestCase.failureException,
2701 self.assertListEqual, a, b)
2702 self.assertRaises(unittest.TestCase.failureException,
2703 self.assertListEqual, tuple(a), tuple(b))
2704 self.assertRaises(unittest.TestCase.failureException,
2705 self.assertSequenceEqual, a, tuple(b))
2706
2707 b.extend(a)
2708 self.assertListEqual(a, b)
2709 self.assertTupleEqual(tuple(a), tuple(b))
2710 self.assertSequenceEqual(a, tuple(b))
2711 self.assertSequenceEqual(tuple(a), b)
2712
2713 self.assertRaises(self.failureException, self.assertListEqual,
2714 a, tuple(b))
2715 self.assertRaises(self.failureException, self.assertTupleEqual,
2716 tuple(a), b)
2717 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2718 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2719 tuple(b))
2720 self.assertRaises(self.failureException, self.assertSequenceEqual,
2721 None, tuple(b))
2722 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2723 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2724 self.assertRaises(self.failureException, self.assertSequenceEqual,
2725 1, 1)
2726
2727 self.assertDictEqual({}, {})
2728
2729 c = { 'x': 1 }
2730 d = {}
2731 self.assertRaises(unittest.TestCase.failureException,
2732 self.assertDictEqual, c, d)
2733
2734 d.update(c)
2735 self.assertDictEqual(c, d)
2736
2737 d['x'] = 0
2738 self.assertRaises(unittest.TestCase.failureException,
2739 self.assertDictEqual, c, d, 'These are unequal')
2740
2741 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2742 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2743 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2744
2745 self.assertSameElements([1, 2, 3], [3, 2, 1])
2746 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2747 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2748 self.assertRaises(self.failureException, self.assertSameElements,
2749 [10], [10, 11])
2750 self.assertRaises(self.failureException, self.assertSameElements,
2751 [10, 11], [10])
2752
2753 # Test that sequences of unhashable objects can be tested for sameness:
2754 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Michael Foordf2dfef12009-04-05 19:19:28 +00002755
Gregory P. Smith28399852009-03-31 16:54:10 +00002756 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2757 self.assertRaises(self.failureException, self.assertSameElements,
2758 [[1]], [[2]])
2759
2760 def testAssertSetEqual(self):
2761 set1 = set()
2762 set2 = set()
2763 self.assertSetEqual(set1, set2)
2764
2765 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2766 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2767 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2768 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2769
2770 set1 = set(['a'])
2771 set2 = set()
2772 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2773
2774 set1 = set(['a'])
2775 set2 = set(['a'])
2776 self.assertSetEqual(set1, set2)
2777
2778 set1 = set(['a'])
2779 set2 = set(['a', 'b'])
2780 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2781
2782 set1 = set(['a'])
2783 set2 = frozenset(['a', 'b'])
2784 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2785
2786 set1 = set(['a', 'b'])
2787 set2 = frozenset(['a', 'b'])
2788 self.assertSetEqual(set1, set2)
2789
2790 set1 = set()
2791 set2 = "foo"
2792 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2793 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2794
2795 # make sure any string formatting is tuple-safe
2796 set1 = set([(0, 1), (2, 3)])
2797 set2 = set([(4, 5)])
2798 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2799
2800 def testInequality(self):
2801 # Try ints
2802 self.assertGreater(2, 1)
2803 self.assertGreaterEqual(2, 1)
2804 self.assertGreaterEqual(1, 1)
2805 self.assertLess(1, 2)
2806 self.assertLessEqual(1, 2)
2807 self.assertLessEqual(1, 1)
2808 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2809 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2810 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2811 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2812 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2813 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2814
2815 # Try Floats
2816 self.assertGreater(1.1, 1.0)
2817 self.assertGreaterEqual(1.1, 1.0)
2818 self.assertGreaterEqual(1.0, 1.0)
2819 self.assertLess(1.0, 1.1)
2820 self.assertLessEqual(1.0, 1.1)
2821 self.assertLessEqual(1.0, 1.0)
2822 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2823 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2824 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2825 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2826 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2827 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2828
2829 # Try Strings
2830 self.assertGreater('bug', 'ant')
2831 self.assertGreaterEqual('bug', 'ant')
2832 self.assertGreaterEqual('ant', 'ant')
2833 self.assertLess('ant', 'bug')
2834 self.assertLessEqual('ant', 'bug')
2835 self.assertLessEqual('ant', 'ant')
2836 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2837 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2838 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2839 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2840 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2841 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2842
2843 # Try Unicode
2844 self.assertGreater(u'bug', u'ant')
2845 self.assertGreaterEqual(u'bug', u'ant')
2846 self.assertGreaterEqual(u'ant', u'ant')
2847 self.assertLess(u'ant', u'bug')
2848 self.assertLessEqual(u'ant', u'bug')
2849 self.assertLessEqual(u'ant', u'ant')
2850 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug')
2851 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant')
2852 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2853 u'bug')
2854 self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant')
2855 self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant')
2856 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant')
2857
2858 # Try Mixed String/Unicode
2859 self.assertGreater('bug', u'ant')
2860 self.assertGreater(u'bug', 'ant')
2861 self.assertGreaterEqual('bug', u'ant')
2862 self.assertGreaterEqual(u'bug', 'ant')
2863 self.assertGreaterEqual('ant', u'ant')
2864 self.assertGreaterEqual(u'ant', 'ant')
2865 self.assertLess('ant', u'bug')
2866 self.assertLess(u'ant', 'bug')
2867 self.assertLessEqual('ant', u'bug')
2868 self.assertLessEqual(u'ant', 'bug')
2869 self.assertLessEqual('ant', u'ant')
2870 self.assertLessEqual(u'ant', 'ant')
2871 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug')
2872 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug')
2873 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant')
2874 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant')
2875 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant',
2876 u'bug')
2877 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2878 'bug')
2879 self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant')
2880 self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant')
2881 self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant')
2882 self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant')
2883 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant')
2884 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant')
2885
2886 def testAssertMultiLineEqual(self):
2887 sample_text = b"""\
2888http://www.python.org/doc/2.3/lib/module-unittest.html
2889test case
2890 A test case is the smallest unit of testing. [...]
2891"""
2892 revised_sample_text = b"""\
2893http://www.python.org/doc/2.4.1/lib/module-unittest.html
2894test case
2895 A test case is the smallest unit of testing. [...] You may provide your
2896 own implementation that does not subclass from TestCase, of course.
2897"""
2898 sample_text_error = b"""
2899- http://www.python.org/doc/2.3/lib/module-unittest.html
2900? ^
2901+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2902? ^^^
2903 test case
2904- A test case is the smallest unit of testing. [...]
2905+ A test case is the smallest unit of testing. [...] You may provide your
2906? +++++++++++++++++++++
2907+ own implementation that does not subclass from TestCase, of course.
2908"""
2909
2910 for type_changer in (lambda x: x, lambda x: x.decode('utf8')):
2911 try:
2912 self.assertMultiLineEqual(type_changer(sample_text),
2913 type_changer(revised_sample_text))
2914 except self.failureException, e:
Michael Foordfe6349c2010-02-08 22:41:16 +00002915 # assertMultiLineEqual is hooked up as the default for
2916 # unicode strings - so we can't use it for this check
2917 self.assertTrue(sample_text_error == str(e).encode('utf8'))
Gregory P. Smith28399852009-03-31 16:54:10 +00002918
2919 def testAssertIsNone(self):
2920 self.assertIsNone(None)
2921 self.assertRaises(self.failureException, self.assertIsNone, False)
2922 self.assertIsNotNone('DjZoPloGears on Rails')
2923 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2924
2925 def testAssertRegexpMatches(self):
2926 self.assertRegexpMatches('asdfabasdf', r'ab+')
2927 self.assertRaises(self.failureException, self.assertRegexpMatches,
2928 'saaas', r'aaaa')
2929
2930 def testAssertRaisesRegexp(self):
2931 class ExceptionMock(Exception):
2932 pass
2933
2934 def Stub():
2935 raise ExceptionMock('We expect')
2936
2937 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2938 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2939 self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
2940
2941 def testAssertNotRaisesRegexp(self):
2942 self.assertRaisesRegexp(
2943 self.failureException, '^Exception not raised$',
2944 self.assertRaisesRegexp, Exception, re.compile('x'),
2945 lambda: None)
2946 self.assertRaisesRegexp(
2947 self.failureException, '^Exception not raised$',
2948 self.assertRaisesRegexp, Exception, 'x',
2949 lambda: None)
2950 self.assertRaisesRegexp(
2951 self.failureException, '^Exception not raised$',
2952 self.assertRaisesRegexp, Exception, u'x',
2953 lambda: None)
2954
2955 def testAssertRaisesRegexpMismatch(self):
2956 def Stub():
2957 raise Exception('Unexpected')
2958
2959 self.assertRaisesRegexp(
2960 self.failureException,
2961 r'"\^Expected\$" does not match "Unexpected"',
2962 self.assertRaisesRegexp, Exception, '^Expected$',
2963 Stub)
2964 self.assertRaisesRegexp(
2965 self.failureException,
2966 r'"\^Expected\$" does not match "Unexpected"',
2967 self.assertRaisesRegexp, Exception, u'^Expected$',
2968 Stub)
2969 self.assertRaisesRegexp(
2970 self.failureException,
2971 r'"\^Expected\$" does not match "Unexpected"',
2972 self.assertRaisesRegexp, Exception,
2973 re.compile('^Expected$'), Stub)
2974
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00002975 def testAssertRaisesExcValue(self):
2976 class ExceptionMock(Exception):
2977 pass
2978
2979 def Stub(foo):
2980 raise ExceptionMock(foo)
2981 v = "particular value"
2982
2983 ctx = self.assertRaises(ExceptionMock)
2984 with ctx:
2985 Stub(v)
Georg Brandldc3694b2010-02-07 17:02:22 +00002986 e = ctx.exception
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002987 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00002988 self.assertEqual(e.args[0], v)
2989
Gregory P. Smith7558d572009-03-31 19:03:28 +00002990 def testSynonymAssertMethodNames(self):
2991 """Test undocumented method name synonyms.
2992
2993 Please do not use these methods names in your own code.
2994
2995 This test confirms their continued existence and functionality
2996 in order to avoid breaking existing code.
2997 """
2998 self.assertNotEquals(3, 5)
2999 self.assertEquals(3, 3)
3000 self.assertAlmostEquals(2.0, 2.0)
3001 self.assertNotAlmostEquals(3.0, 5.0)
3002 self.assert_(True)
3003
3004 def testPendingDeprecationMethodNames(self):
3005 """Test fail* methods pending deprecation, they will warn in 3.2.
3006
3007 Do not use these methods. They will go away in 3.3.
3008 """
3009 self.failIfEqual(3, 5)
3010 self.failUnlessEqual(3, 3)
3011 self.failUnlessAlmostEqual(2.0, 2.0)
3012 self.failIfAlmostEqual(3.0, 5.0)
3013 self.failUnless(True)
3014 self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam')
3015 self.failIf(False)
3016
Michael Foorde2942d02009-04-02 05:51:54 +00003017 def testDeepcopy(self):
3018 # Issue: 5660
3019 class TestableTest(TestCase):
3020 def testNothing(self):
3021 pass
3022
3023 test = TestableTest('testNothing')
3024
3025 # This shouldn't blow up
3026 deepcopy(test)
3027
Benjamin Peterson692428e2009-03-23 21:50:21 +00003028
3029class Test_TestSkipping(TestCase):
3030
3031 def test_skipping(self):
3032 class Foo(unittest.TestCase):
3033 def test_skip_me(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00003034 self.skipTest("skip")
Benjamin Peterson692428e2009-03-23 21:50:21 +00003035 events = []
3036 result = LoggingResult(events)
3037 test = Foo("test_skip_me")
3038 test.run(result)
3039 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3040 self.assertEqual(result.skipped, [(test, "skip")])
3041
3042 # Try letting setUp skip the test now.
3043 class Foo(unittest.TestCase):
3044 def setUp(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00003045 self.skipTest("testing")
Benjamin Peterson692428e2009-03-23 21:50:21 +00003046 def test_nothing(self): pass
3047 events = []
3048 result = LoggingResult(events)
3049 test = Foo("test_nothing")
3050 test.run(result)
3051 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3052 self.assertEqual(result.skipped, [(test, "testing")])
3053 self.assertEqual(result.testsRun, 1)
3054
3055 def test_skipping_decorators(self):
3056 op_table = ((unittest.skipUnless, False, True),
3057 (unittest.skipIf, True, False))
3058 for deco, do_skip, dont_skip in op_table:
3059 class Foo(unittest.TestCase):
3060 @deco(do_skip, "testing")
3061 def test_skip(self): pass
3062
3063 @deco(dont_skip, "testing")
3064 def test_dont_skip(self): pass
3065 test_do_skip = Foo("test_skip")
3066 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003067 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003068 events = []
3069 result = LoggingResult(events)
3070 suite.run(result)
3071 self.assertEqual(len(result.skipped), 1)
3072 expected = ['startTest', 'addSkip', 'stopTest',
3073 'startTest', 'addSuccess', 'stopTest']
3074 self.assertEqual(events, expected)
3075 self.assertEqual(result.testsRun, 2)
3076 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
3077 self.assertTrue(result.wasSuccessful())
3078
3079 def test_skip_class(self):
3080 @unittest.skip("testing")
3081 class Foo(unittest.TestCase):
3082 def test_1(self):
3083 record.append(1)
3084 record = []
3085 result = unittest.TestResult()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003086 test = Foo("test_1")
3087 suite = unittest.TestSuite([test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003088 suite.run(result)
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003089 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003090 self.assertEqual(record, [])
3091
3092 def test_expected_failure(self):
3093 class Foo(unittest.TestCase):
3094 @unittest.expectedFailure
3095 def test_die(self):
3096 self.fail("help me!")
3097 events = []
3098 result = LoggingResult(events)
3099 test = Foo("test_die")
3100 test.run(result)
3101 self.assertEqual(events,
3102 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003103 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00003104 self.assertTrue(result.wasSuccessful())
3105
3106 def test_unexpected_success(self):
3107 class Foo(unittest.TestCase):
3108 @unittest.expectedFailure
3109 def test_die(self):
3110 pass
3111 events = []
3112 result = LoggingResult(events)
3113 test = Foo("test_die")
3114 test.run(result)
3115 self.assertEqual(events,
3116 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3117 self.assertFalse(result.failures)
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003118 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003119 self.assertTrue(result.wasSuccessful())
3120
3121
3122
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003123class Test_Assertions(TestCase):
3124 def test_AlmostEqual(self):
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003125 self.assertAlmostEqual(1.00000001, 1.0)
3126 self.assertNotAlmostEqual(1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003127 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003128 self.assertAlmostEqual, 1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003129 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003130 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003131
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003132 self.assertAlmostEqual(1.1, 1.0, places=0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003133 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003134 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003135
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003136 self.assertAlmostEqual(0, .1+.1j, places=0)
3137 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003138 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003139 self.assertAlmostEqual, 0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003140 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003141 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003142
Michael Foordc3f79372009-09-13 16:40:02 +00003143 self.assertAlmostEqual(float('inf'), float('inf'))
3144 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3145 float('inf'), float('inf'))
3146
3147
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003148 def test_assertRaises(self):
3149 def _raise(e):
3150 raise e
3151 self.assertRaises(KeyError, _raise, KeyError)
3152 self.assertRaises(KeyError, _raise, KeyError("key"))
3153 try:
3154 self.assertRaises(KeyError, lambda: None)
Gregory P. Smith28399852009-03-31 16:54:10 +00003155 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003156 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003157 else:
3158 self.fail("assertRaises() didn't fail")
3159 try:
3160 self.assertRaises(KeyError, _raise, ValueError)
3161 except ValueError:
3162 pass
3163 else:
3164 self.fail("assertRaises() didn't let exception pass through")
Michael Foord2bd52dc2010-02-07 18:44:12 +00003165 with self.assertRaises(KeyError) as cm:
3166 try:
3167 raise KeyError
3168 except Exception, e:
3169 raise
3170 self.assertIs(cm.exception, e)
3171
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003172 with self.assertRaises(KeyError):
3173 raise KeyError("key")
3174 try:
3175 with self.assertRaises(KeyError):
3176 pass
Gregory P. Smith28399852009-03-31 16:54:10 +00003177 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003178 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003179 else:
3180 self.fail("assertRaises() didn't fail")
3181 try:
3182 with self.assertRaises(KeyError):
3183 raise ValueError
3184 except ValueError:
3185 pass
3186 else:
3187 self.fail("assertRaises() didn't let exception pass through")
3188
3189
Michael Foord345b2fe2009-04-02 03:20:38 +00003190class TestLongMessage(TestCase):
3191 """Test that the individual asserts honour longMessage.
3192 This actually tests all the message behaviour for
3193 asserts that use longMessage."""
3194
3195 def setUp(self):
3196 class TestableTestFalse(TestCase):
3197 longMessage = False
3198 failureException = self.failureException
3199
3200 def testTest(self):
3201 pass
3202
3203 class TestableTestTrue(TestCase):
3204 longMessage = True
3205 failureException = self.failureException
3206
3207 def testTest(self):
3208 pass
3209
3210 self.testableTrue = TestableTestTrue('testTest')
3211 self.testableFalse = TestableTestFalse('testTest')
3212
3213 def testDefault(self):
3214 self.assertFalse(TestCase.longMessage)
3215
3216 def test_formatMsg(self):
3217 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3218 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3219
3220 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3221 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3222
3223 def assertMessages(self, methodName, args, errors):
3224 def getMethod(i):
3225 useTestableFalse = i < 2
3226 if useTestableFalse:
3227 test = self.testableFalse
3228 else:
3229 test = self.testableTrue
3230 return getattr(test, methodName)
3231
3232 for i, expected_regexp in enumerate(errors):
3233 testMethod = getMethod(i)
3234 kwargs = {}
3235 withMsg = i % 2
3236 if withMsg:
3237 kwargs = {"msg": "oops"}
3238
3239 with self.assertRaisesRegexp(self.failureException,
3240 expected_regexp=expected_regexp):
3241 testMethod(*args, **kwargs)
3242
3243 def testAssertTrue(self):
3244 self.assertMessages('assertTrue', (False,),
3245 ["^False is not True$", "^oops$", "^False is not True$",
3246 "^False is not True : oops$"])
3247
3248 def testAssertFalse(self):
3249 self.assertMessages('assertFalse', (True,),
3250 ["^True is not False$", "^oops$", "^True is not False$",
3251 "^True is not False : oops$"])
3252
3253 def testNotEqual(self):
3254 self.assertMessages('assertNotEqual', (1, 1),
3255 ["^1 == 1$", "^oops$", "^1 == 1$",
3256 "^1 == 1 : oops$"])
3257
3258 def testAlmostEqual(self):
3259 self.assertMessages('assertAlmostEqual', (1, 2),
3260 ["^1 != 2 within 7 places$", "^oops$",
3261 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3262
3263 def testNotAlmostEqual(self):
3264 self.assertMessages('assertNotAlmostEqual', (1, 1),
3265 ["^1 == 1 within 7 places$", "^oops$",
3266 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3267
3268 def test_baseAssertEqual(self):
3269 self.assertMessages('_baseAssertEqual', (1, 2),
3270 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3271
3272 def testAssertSequenceEqual(self):
3273 # Error messages are multiline so not testing on full message
3274 # assertTupleEqual and assertListEqual delegate to this method
3275 self.assertMessages('assertSequenceEqual', ([], [None]),
3276 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3277 r"\+ \[None\] : oops$"])
3278
3279 def testAssertSetEqual(self):
3280 self.assertMessages('assertSetEqual', (set(), set([None])),
3281 ["None$", "^oops$", "None$",
3282 "None : oops$"])
3283
3284 def testAssertIn(self):
3285 self.assertMessages('assertIn', (None, []),
3286 ['^None not found in \[\]$', "^oops$",
3287 '^None not found in \[\]$',
3288 '^None not found in \[\] : oops$'])
3289
3290 def testAssertNotIn(self):
3291 self.assertMessages('assertNotIn', (None, [None]),
3292 ['^None unexpectedly found in \[None\]$', "^oops$",
3293 '^None unexpectedly found in \[None\]$',
3294 '^None unexpectedly found in \[None\] : oops$'])
3295
3296 def testAssertDictEqual(self):
3297 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3298 [r"\+ \{'key': 'value'\}$", "^oops$",
3299 "\+ \{'key': 'value'\}$",
3300 "\+ \{'key': 'value'\} : oops$"])
3301
3302 def testAssertDictContainsSubset(self):
3303 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3304 ["^Missing: 'key'$", "^oops$",
3305 "^Missing: 'key'$",
3306 "^Missing: 'key' : oops$"])
3307
3308 def testAssertSameElements(self):
3309 self.assertMessages('assertSameElements', ([], [None]),
3310 [r"\[None\]$", "^oops$",
3311 r"\[None\]$",
3312 r"\[None\] : oops$"])
3313
3314 def testAssertMultiLineEqual(self):
3315 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3316 [r"\+ foo$", "^oops$",
3317 r"\+ foo$",
3318 r"\+ foo : oops$"])
3319
3320 def testAssertLess(self):
3321 self.assertMessages('assertLess', (2, 1),
3322 ["^2 not less than 1$", "^oops$",
3323 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3324
3325 def testAssertLessEqual(self):
3326 self.assertMessages('assertLessEqual', (2, 1),
3327 ["^2 not less than or equal to 1$", "^oops$",
3328 "^2 not less than or equal to 1$",
3329 "^2 not less than or equal to 1 : oops$"])
3330
3331 def testAssertGreater(self):
3332 self.assertMessages('assertGreater', (1, 2),
3333 ["^1 not greater than 2$", "^oops$",
3334 "^1 not greater than 2$",
3335 "^1 not greater than 2 : oops$"])
3336
3337 def testAssertGreaterEqual(self):
3338 self.assertMessages('assertGreaterEqual', (1, 2),
3339 ["^1 not greater than or equal to 2$", "^oops$",
3340 "^1 not greater than or equal to 2$",
3341 "^1 not greater than or equal to 2 : oops$"])
3342
3343 def testAssertIsNone(self):
3344 self.assertMessages('assertIsNone', ('not None',),
3345 ["^'not None' is not None$", "^oops$",
3346 "^'not None' is not None$",
3347 "^'not None' is not None : oops$"])
3348
3349 def testAssertIsNotNone(self):
3350 self.assertMessages('assertIsNotNone', (None,),
3351 ["^unexpectedly None$", "^oops$",
3352 "^unexpectedly None$",
3353 "^unexpectedly None : oops$"])
3354
Michael Foordf2dfef12009-04-05 19:19:28 +00003355 def testAssertIs(self):
3356 self.assertMessages('assertIs', (None, 'foo'),
3357 ["^None is not 'foo'$", "^oops$",
3358 "^None is not 'foo'$",
3359 "^None is not 'foo' : oops$"])
3360
3361 def testAssertIsNot(self):
3362 self.assertMessages('assertIsNot', (None, None),
3363 ["^unexpectedly identical: None$", "^oops$",
3364 "^unexpectedly identical: None$",
3365 "^unexpectedly identical: None : oops$"])
3366
Michael Foord345b2fe2009-04-02 03:20:38 +00003367
Michael Foorde2fb98f2009-05-02 20:15:05 +00003368class TestCleanUp(TestCase):
3369
3370 def testCleanUp(self):
3371 class TestableTest(TestCase):
3372 def testNothing(self):
3373 pass
3374
3375 test = TestableTest('testNothing')
3376 self.assertEqual(test._cleanups, [])
3377
3378 cleanups = []
3379
3380 def cleanup1(*args, **kwargs):
3381 cleanups.append((1, args, kwargs))
3382
3383 def cleanup2(*args, **kwargs):
3384 cleanups.append((2, args, kwargs))
3385
3386 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3387 test.addCleanup(cleanup2)
3388
3389 self.assertEqual(test._cleanups,
3390 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3391 (cleanup2, (), {})])
3392
3393 result = test.doCleanups()
3394 self.assertTrue(result)
3395
3396 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3397
3398 def testCleanUpWithErrors(self):
3399 class TestableTest(TestCase):
3400 def testNothing(self):
3401 pass
3402
3403 class MockResult(object):
3404 errors = []
3405 def addError(self, test, exc_info):
3406 self.errors.append((test, exc_info))
3407
3408 result = MockResult()
3409 test = TestableTest('testNothing')
Michael Foorda50af062009-05-21 22:57:02 +00003410 test._resultForDoCleanups = result
Michael Foorde2fb98f2009-05-02 20:15:05 +00003411
3412 exc1 = Exception('foo')
3413 exc2 = Exception('bar')
3414 def cleanup1():
3415 raise exc1
3416
3417 def cleanup2():
3418 raise exc2
3419
3420 test.addCleanup(cleanup1)
3421 test.addCleanup(cleanup2)
3422
3423 self.assertFalse(test.doCleanups())
3424
3425 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3426 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3427 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3428
3429 def testCleanupInRun(self):
3430 blowUp = False
3431 ordering = []
3432
3433 class TestableTest(TestCase):
3434 def setUp(self):
3435 ordering.append('setUp')
3436 if blowUp:
3437 raise Exception('foo')
3438
3439 def testNothing(self):
3440 ordering.append('test')
3441
3442 def tearDown(self):
3443 ordering.append('tearDown')
3444
3445 test = TestableTest('testNothing')
3446
3447 def cleanup1():
3448 ordering.append('cleanup1')
3449 def cleanup2():
3450 ordering.append('cleanup2')
3451 test.addCleanup(cleanup1)
3452 test.addCleanup(cleanup2)
3453
3454 def success(some_test):
3455 self.assertEqual(some_test, test)
3456 ordering.append('success')
3457
3458 result = unittest.TestResult()
3459 result.addSuccess = success
3460
3461 test.run(result)
3462 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3463 'cleanup2', 'cleanup1', 'success'])
3464
3465 blowUp = True
3466 ordering = []
3467 test = TestableTest('testNothing')
3468 test.addCleanup(cleanup1)
3469 test.run(result)
3470 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3471
3472
Michael Foord829f6b82009-05-02 11:43:06 +00003473class Test_TestProgram(TestCase):
3474
3475 # Horrible white box test
3476 def testNoExit(self):
3477 result = object()
3478 test = object()
3479
3480 class FakeRunner(object):
3481 def run(self, test):
3482 self.test = test
3483 return result
3484
3485 runner = FakeRunner()
3486
Michael Foord5d31e052009-05-11 17:59:43 +00003487 oldParseArgs = TestProgram.parseArgs
3488 def restoreParseArgs():
Michael Foord829f6b82009-05-02 11:43:06 +00003489 TestProgram.parseArgs = oldParseArgs
Michael Foord5d31e052009-05-11 17:59:43 +00003490 TestProgram.parseArgs = lambda *args: None
3491 self.addCleanup(restoreParseArgs)
3492
3493 def removeTest():
Michael Foord829f6b82009-05-02 11:43:06 +00003494 del TestProgram.test
Michael Foord5d31e052009-05-11 17:59:43 +00003495 TestProgram.test = test
3496 self.addCleanup(removeTest)
3497
3498 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3499
3500 self.assertEqual(program.result, result)
3501 self.assertEqual(runner.test, test)
3502 self.assertEqual(program.verbosity, 2)
Michael Foord829f6b82009-05-02 11:43:06 +00003503
Michael Foord829f6b82009-05-02 11:43:06 +00003504 class FooBar(unittest.TestCase):
3505 def testPass(self):
3506 assert True
3507 def testFail(self):
3508 assert False
3509
3510 class FooBarLoader(unittest.TestLoader):
3511 """Test loader that returns a suite containing FooBar."""
3512 def loadTestsFromModule(self, module):
3513 return self.suiteClass(
3514 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3515
3516
3517 def test_NonExit(self):
3518 program = unittest.main(exit=False,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003519 argv=["foobar"],
3520 testRunner=unittest.TextTestRunner(stream=StringIO()),
3521 testLoader=self.FooBarLoader())
Michael Foord829f6b82009-05-02 11:43:06 +00003522 self.assertTrue(hasattr(program, 'result'))
3523
3524
3525 def test_Exit(self):
3526 self.assertRaises(
3527 SystemExit,
3528 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003529 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003530 testRunner=unittest.TextTestRunner(stream=StringIO()),
3531 exit=True,
3532 testLoader=self.FooBarLoader())
3533
3534
3535 def test_ExitAsDefault(self):
3536 self.assertRaises(
3537 SystemExit,
3538 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003539 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003540 testRunner=unittest.TextTestRunner(stream=StringIO()),
3541 testLoader=self.FooBarLoader())
3542
3543
Michael Foord07ef4872009-05-02 22:43:34 +00003544class Test_TextTestRunner(TestCase):
3545 """Tests for TextTestRunner."""
3546
3547 def test_works_with_result_without_startTestRun_stopTestRun(self):
3548 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3549 separator2 = ''
3550 def printErrors(self):
3551 pass
3552
3553 class Runner(unittest.TextTestRunner):
3554 def __init__(self):
3555 super(Runner, self).__init__(StringIO())
3556
3557 def _makeResult(self):
3558 return OldTextResult()
3559
3560 runner = Runner()
3561 runner.run(unittest.TestSuite())
3562
3563 def test_startTestRun_stopTestRun_called(self):
3564 class LoggingTextResult(LoggingResult):
3565 separator2 = ''
3566 def printErrors(self):
3567 pass
3568
3569 class LoggingRunner(unittest.TextTestRunner):
3570 def __init__(self, events):
3571 super(LoggingRunner, self).__init__(StringIO())
3572 self._events = events
3573
3574 def _makeResult(self):
3575 return LoggingTextResult(self._events)
3576
3577 events = []
3578 runner = LoggingRunner(events)
3579 runner.run(unittest.TestSuite())
3580 expected = ['startTestRun', 'stopTestRun']
3581 self.assertEqual(events, expected)
3582
Antoine Pitrou0734c632009-11-10 20:49:30 +00003583 def test_pickle_unpickle(self):
3584 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3585 # required by test_multiprocessing under Windows (in verbose mode).
3586 import StringIO
3587 # cStringIO objects are not pickleable, but StringIO objects are.
3588 stream = StringIO.StringIO("foo")
3589 runner = unittest.TextTestRunner(stream)
3590 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
3591 s = pickle.dumps(runner, protocol=protocol)
3592 obj = pickle.loads(s)
3593 # StringIO objects never compare equal, a cheap test instead.
3594 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3595
Michael Foorddb43b5a2010-02-10 14:25:12 +00003596 def test_resultclass(self):
3597 def MockResultClass(*args):
3598 return args
3599 STREAM = object()
3600 DESCRIPTIONS = object()
3601 VERBOSITY = object()
3602 runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY,
3603 resultclass=MockResultClass)
3604 self.assertEqual(runner.resultclass, MockResultClass)
3605
3606 expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY)
3607 self.assertEqual(runner._makeResult(), expectedresult)
3608
Michael Foord07ef4872009-05-02 22:43:34 +00003609
Michael Foordb4a81c82009-05-29 20:33:46 +00003610class TestDiscovery(TestCase):
3611
3612 # Heavily mocked tests so I can avoid hitting the filesystem
Michael Foorde91ea562009-09-13 19:07:03 +00003613 def test_get_name_from_path(self):
Michael Foordb4a81c82009-05-29 20:33:46 +00003614 loader = unittest.TestLoader()
3615
Michael Foordb4a81c82009-05-29 20:33:46 +00003616 loader._top_level_dir = '/foo'
Michael Foorde91ea562009-09-13 19:07:03 +00003617 name = loader._get_name_from_path('/foo/bar/baz.py')
3618 self.assertEqual(name, 'bar.baz')
Michael Foordb4a81c82009-05-29 20:33:46 +00003619
3620 if not __debug__:
3621 # asserts are off
3622 return
3623
3624 with self.assertRaises(AssertionError):
Michael Foorde91ea562009-09-13 19:07:03 +00003625 loader._get_name_from_path('/bar/baz.py')
Michael Foordb4a81c82009-05-29 20:33:46 +00003626
3627 def test_find_tests(self):
3628 loader = unittest.TestLoader()
3629
3630 original_listdir = os.listdir
3631 def restore_listdir():
3632 os.listdir = original_listdir
3633 original_isfile = os.path.isfile
3634 def restore_isfile():
3635 os.path.isfile = original_isfile
3636 original_isdir = os.path.isdir
3637 def restore_isdir():
3638 os.path.isdir = original_isdir
3639
3640 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Michael Foorde91ea562009-09-13 19:07:03 +00003641 'test.foo', 'test-not-a-module.py', 'another_dir'],
Michael Foordb4a81c82009-05-29 20:33:46 +00003642 ['test3.py', 'test4.py', ]]
3643 os.listdir = lambda path: path_lists.pop(0)
3644 self.addCleanup(restore_listdir)
3645
3646 def isdir(path):
3647 return path.endswith('dir')
3648 os.path.isdir = isdir
3649 self.addCleanup(restore_isdir)
3650
3651 def isfile(path):
3652 # another_dir is not a package and so shouldn't be recursed into
3653 return not path.endswith('dir') and not 'another_dir' in path
3654 os.path.isfile = isfile
3655 self.addCleanup(restore_isfile)
3656
Michael Foorde91ea562009-09-13 19:07:03 +00003657 loader._get_module_from_name = lambda path: path + ' module'
Michael Foordb4a81c82009-05-29 20:33:46 +00003658 loader.loadTestsFromModule = lambda module: module + ' tests'
3659
3660 loader._top_level_dir = '/foo'
3661 suite = list(loader._find_tests('/foo', 'test*.py'))
3662
Michael Foorde91ea562009-09-13 19:07:03 +00003663 expected = [name + ' module tests' for name in
3664 ('test1', 'test2')]
3665 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3666 ('test3', 'test4')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003667 self.assertEqual(suite, expected)
3668
3669 def test_find_tests_with_package(self):
3670 loader = unittest.TestLoader()
3671
3672 original_listdir = os.listdir
3673 def restore_listdir():
3674 os.listdir = original_listdir
3675 original_isfile = os.path.isfile
3676 def restore_isfile():
3677 os.path.isfile = original_isfile
3678 original_isdir = os.path.isdir
3679 def restore_isdir():
3680 os.path.isdir = original_isdir
3681
3682 directories = ['a_directory', 'test_directory', 'test_directory2']
3683 path_lists = [directories, [], [], []]
3684 os.listdir = lambda path: path_lists.pop(0)
3685 self.addCleanup(restore_listdir)
3686
3687 os.path.isdir = lambda path: True
3688 self.addCleanup(restore_isdir)
3689
3690 os.path.isfile = lambda path: os.path.basename(path) not in directories
3691 self.addCleanup(restore_isfile)
3692
3693 class Module(object):
3694 paths = []
3695 load_tests_args = []
3696
3697 def __init__(self, path):
3698 self.path = path
3699 self.paths.append(path)
3700 if os.path.basename(path) == 'test_directory':
3701 def load_tests(loader, tests, pattern):
3702 self.load_tests_args.append((loader, tests, pattern))
3703 return 'load_tests'
3704 self.load_tests = load_tests
3705
3706 def __eq__(self, other):
3707 return self.path == other.path
3708
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003709 # Silence py3k warning
3710 __hash__ = None
3711
Michael Foorde91ea562009-09-13 19:07:03 +00003712 loader._get_module_from_name = lambda name: Module(name)
Michael Foordb4a81c82009-05-29 20:33:46 +00003713 def loadTestsFromModule(module, use_load_tests):
3714 if use_load_tests:
3715 raise self.failureException('use_load_tests should be False for packages')
3716 return module.path + ' module tests'
3717 loader.loadTestsFromModule = loadTestsFromModule
3718
3719 loader._top_level_dir = '/foo'
3720 # this time no '.py' on the pattern so that it can match
3721 # a test package
3722 suite = list(loader._find_tests('/foo', 'test*'))
3723
3724 # We should have loaded tests from the test_directory package by calling load_tests
3725 # and directly from the test_directory2 package
Michael Foordd53d0852009-06-05 14:14:34 +00003726 self.assertEqual(suite,
Michael Foorde91ea562009-09-13 19:07:03 +00003727 ['load_tests', 'test_directory2' + ' module tests'])
3728 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Michael Foordb4a81c82009-05-29 20:33:46 +00003729
3730 # load_tests should have been called once with loader, tests and pattern
3731 self.assertEqual(Module.load_tests_args,
Michael Foorde91ea562009-09-13 19:07:03 +00003732 [(loader, 'test_directory' + ' module tests', 'test*')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003733
3734 def test_discover(self):
3735 loader = unittest.TestLoader()
3736
3737 original_isfile = os.path.isfile
3738 def restore_isfile():
3739 os.path.isfile = original_isfile
3740
3741 os.path.isfile = lambda path: False
3742 self.addCleanup(restore_isfile)
3743
Nick Coghlanb6edf192009-10-17 08:21:21 +00003744 orig_sys_path = sys.path[:]
3745 def restore_path():
3746 sys.path[:] = orig_sys_path
3747 self.addCleanup(restore_path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003748
Nick Coghlanb6edf192009-10-17 08:21:21 +00003749 full_path = os.path.abspath(os.path.normpath('/foo'))
Michael Foordb4a81c82009-05-29 20:33:46 +00003750 with self.assertRaises(ImportError):
3751 loader.discover('/foo/bar', top_level_dir='/foo')
3752
3753 self.assertEqual(loader._top_level_dir, full_path)
3754 self.assertIn(full_path, sys.path)
3755
3756 os.path.isfile = lambda path: True
3757 _find_tests_args = []
3758 def _find_tests(start_dir, pattern):
3759 _find_tests_args.append((start_dir, pattern))
3760 return ['tests']
3761 loader._find_tests = _find_tests
3762 loader.suiteClass = str
3763
3764 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3765
3766 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3767 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3768 self.assertEqual(suite, "['tests']")
3769 self.assertEqual(loader._top_level_dir, top_level_dir)
3770 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlanb6edf192009-10-17 08:21:21 +00003771 self.assertIn(top_level_dir, sys.path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003772
Michael Foorde91ea562009-09-13 19:07:03 +00003773 def test_discover_with_modules_that_fail_to_import(self):
3774 loader = unittest.TestLoader()
3775
3776 listdir = os.listdir
3777 os.listdir = lambda _: ['test_this_does_not_exist.py']
3778 isfile = os.path.isfile
3779 os.path.isfile = lambda _: True
Nick Coghlanb6edf192009-10-17 08:21:21 +00003780 orig_sys_path = sys.path[:]
Michael Foorde91ea562009-09-13 19:07:03 +00003781 def restore():
3782 os.path.isfile = isfile
3783 os.listdir = listdir
Nick Coghlanb6edf192009-10-17 08:21:21 +00003784 sys.path[:] = orig_sys_path
Michael Foorde91ea562009-09-13 19:07:03 +00003785 self.addCleanup(restore)
3786
3787 suite = loader.discover('.')
Nick Coghlanb6edf192009-10-17 08:21:21 +00003788 self.assertIn(os.getcwd(), sys.path)
Michael Foorde91ea562009-09-13 19:07:03 +00003789 self.assertEqual(suite.countTestCases(), 1)
3790 test = list(list(suite)[0])[0] # extract test from suite
3791
3792 with self.assertRaises(ImportError):
3793 test.test_this_does_not_exist()
3794
Michael Foordb4a81c82009-05-29 20:33:46 +00003795 def test_command_line_handling_parseArgs(self):
3796 # Haha - take that uninstantiable class
3797 program = object.__new__(TestProgram)
3798
3799 args = []
3800 def do_discovery(argv):
3801 args.extend(argv)
3802 program._do_discovery = do_discovery
3803 program.parseArgs(['something', 'discover'])
3804 self.assertEqual(args, [])
3805
3806 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3807 self.assertEqual(args, ['foo', 'bar'])
3808
3809 def test_command_line_handling_do_discovery_too_many_arguments(self):
3810 class Stop(Exception):
3811 pass
3812 def usageExit():
3813 raise Stop
3814
3815 program = object.__new__(TestProgram)
3816 program.usageExit = usageExit
3817
3818 with self.assertRaises(Stop):
3819 # too many args
3820 program._do_discovery(['one', 'two', 'three', 'four'])
3821
3822
3823 def test_command_line_handling_do_discovery_calls_loader(self):
3824 program = object.__new__(TestProgram)
3825
3826 class Loader(object):
3827 args = []
3828 def discover(self, start_dir, pattern, top_level_dir):
3829 self.args.append((start_dir, pattern, top_level_dir))
3830 return 'tests'
3831
3832 program._do_discovery(['-v'], Loader=Loader)
3833 self.assertEqual(program.verbosity, 2)
3834 self.assertEqual(program.test, 'tests')
3835 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3836
3837 Loader.args = []
3838 program = object.__new__(TestProgram)
3839 program._do_discovery(['--verbose'], Loader=Loader)
3840 self.assertEqual(program.test, 'tests')
3841 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3842
3843 Loader.args = []
3844 program = object.__new__(TestProgram)
3845 program._do_discovery([], Loader=Loader)
3846 self.assertEqual(program.test, 'tests')
3847 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3848
3849 Loader.args = []
3850 program = object.__new__(TestProgram)
3851 program._do_discovery(['fish'], Loader=Loader)
3852 self.assertEqual(program.test, 'tests')
3853 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3854
3855 Loader.args = []
3856 program = object.__new__(TestProgram)
3857 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3858 self.assertEqual(program.test, 'tests')
3859 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3860
3861 Loader.args = []
3862 program = object.__new__(TestProgram)
3863 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3864 self.assertEqual(program.test, 'tests')
3865 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3866
3867 Loader.args = []
3868 program = object.__new__(TestProgram)
3869 program._do_discovery(['-s', 'fish'], Loader=Loader)
3870 self.assertEqual(program.test, 'tests')
3871 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3872
3873 Loader.args = []
3874 program = object.__new__(TestProgram)
3875 program._do_discovery(['-t', 'fish'], Loader=Loader)
3876 self.assertEqual(program.test, 'tests')
3877 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3878
3879 Loader.args = []
3880 program = object.__new__(TestProgram)
3881 program._do_discovery(['-p', 'fish'], Loader=Loader)
3882 self.assertEqual(program.test, 'tests')
3883 self.assertEqual(Loader.args, [('.', 'fish', None)])
3884
3885 Loader.args = []
3886 program = object.__new__(TestProgram)
3887 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3888 self.assertEqual(program.test, 'tests')
3889 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3890 self.assertEqual(program.verbosity, 2)
3891
3892
Jim Fultonfafd8742004-08-28 15:22:12 +00003893######################################################################
3894## Main
3895######################################################################
3896
3897def test_main():
Georg Brandl15c5ce92007-03-07 09:09:40 +00003898 test_support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003899 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Michael Foord829f6b82009-05-02 11:43:06 +00003900 Test_TestSkipping, Test_Assertions, TestLongMessage,
Michael Foordae3db0a2010-02-22 23:28:32 +00003901 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner,
3902 Test_OldTestResult)
Jim Fultonfafd8742004-08-28 15:22:12 +00003903
Georg Brandl15c5ce92007-03-07 09:09:40 +00003904if __name__ == "__main__":
Tim Petersea5962f2007-03-12 18:07:52 +00003905 test_main()