blob: d5f9a5c539df5ad412c3b6c83f0264c610f879c9 [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
2044 def testGetDescriptionWithOneLineDocstring(self):
2045 """Tests getDescription() for a method with a docstring."""
Michael Foord1c3abf42010-02-10 15:50:58 +00002046 result = unittest.TextTestResult(None, True, 1)
Michael Foorddb43b5a2010-02-10 14:25:12 +00002047 self.assertEqual(
2048 result.getDescription(self),
2049 ('testGetDescriptionWithOneLineDocstring '
2050 '(' + __name__ + '.Test_TestResult)\n'
2051 'Tests getDescription() for a method with a docstring.'))
2052
2053 def testGetDescriptionWithMultiLineDocstring(self):
2054 """Tests getDescription() for a method with a longer docstring.
2055 The second line of the docstring.
2056 """
Michael Foord1c3abf42010-02-10 15:50:58 +00002057 result = unittest.TextTestResult(None, True, 1)
Michael Foorddb43b5a2010-02-10 14:25:12 +00002058 self.assertEqual(
2059 result.getDescription(self),
2060 ('testGetDescriptionWithMultiLineDocstring '
2061 '(' + __name__ + '.Test_TestResult)\n'
2062 'Tests getDescription() for a method with a longer '
2063 'docstring.'))
2064
Michael Foordae3db0a2010-02-22 23:28:32 +00002065classDict = dict(unittest.TestResult.__dict__)
2066for m in 'addSkip', 'addExpectedFailure', 'addUnexpectedSuccess':
2067 del classDict[m]
2068OldResult = type('OldResult', (object,), classDict)
2069
2070class Test_OldTestResult(unittest.TestCase):
2071
2072 def assertOldResultWarning(self, test, failures):
2073 with warnings.catch_warnings(record=True) as log:
2074 result = OldResult()
2075 test.run(result)
2076 self.assertEqual(len(result.failures), failures)
2077 warning, = log
2078 self.assertIs(warning.category, RuntimeWarning)
2079
2080 def testOldTestResult(self):
2081 class Test(unittest.TestCase):
2082 def testSkip(self):
2083 self.skipTest('foobar')
2084 @unittest.expectedFailure
2085 def testExpectedFail(self):
2086 raise TypeError
2087 @unittest.expectedFailure
2088 def testUnexpectedSuccess(self):
2089 pass
2090
2091 for test_name, should_pass in (('testSkip', True),
2092 ('testExpectedFail', True),
2093 ('testUnexpectedSuccess', False)):
2094 test = Test(test_name)
2095 self.assertOldResultWarning(test, int(not should_pass))
2096
2097 def testOldTestTesultSetup(self):
2098 class Test(unittest.TestCase):
2099 def setUp(self):
2100 self.skipTest('no reason')
2101 def testFoo(self):
2102 pass
2103 self.assertOldResultWarning(Test('testFoo'), 0)
2104
2105 def testOldTestResultClass(self):
2106 @unittest.skip('no reason')
2107 class Test(unittest.TestCase):
2108 def testFoo(self):
2109 pass
2110 self.assertOldResultWarning(Test('testFoo'), 0)
2111
Michael Foorddb43b5a2010-02-10 14:25:12 +00002112
Georg Brandl15c5ce92007-03-07 09:09:40 +00002113### Support code for Test_TestCase
2114################################################################
2115
2116class Foo(unittest.TestCase):
2117 def runTest(self): pass
2118 def test1(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002119
Georg Brandl15c5ce92007-03-07 09:09:40 +00002120class Bar(Foo):
2121 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002122
Michael Foord07ef4872009-05-02 22:43:34 +00002123class LoggingTestCase(unittest.TestCase):
2124 """A test case which logs its calls."""
2125
2126 def __init__(self, events):
2127 super(LoggingTestCase, self).__init__('test')
2128 self.events = events
2129
2130 def setUp(self):
2131 self.events.append('setUp')
2132
2133 def test(self):
2134 self.events.append('test')
2135
2136 def tearDown(self):
2137 self.events.append('tearDown')
2138
2139class ResultWithNoStartTestRunStopTestRun(object):
2140 """An object honouring TestResult before startTestRun/stopTestRun."""
2141
2142 def __init__(self):
2143 self.failures = []
2144 self.errors = []
2145 self.testsRun = 0
2146 self.skipped = []
2147 self.expectedFailures = []
2148 self.unexpectedSuccesses = []
2149 self.shouldStop = False
2150
2151 def startTest(self, test):
2152 pass
2153
2154 def stopTest(self, test):
2155 pass
2156
2157 def addError(self, test):
2158 pass
2159
2160 def addFailure(self, test):
2161 pass
2162
2163 def addSuccess(self, test):
2164 pass
2165
2166 def wasSuccessful(self):
2167 return True
2168
2169
Georg Brandl15c5ce92007-03-07 09:09:40 +00002170################################################################
2171### /Support code for Test_TestCase
2172
2173class Test_TestCase(TestCase, TestEquality, TestHashing):
2174
2175 ### Set up attributes used by inherited tests
2176 ################################################################
2177
2178 # Used by TestHashing.test_hash and TestEquality.test_eq
2179 eq_pairs = [(Foo('test1'), Foo('test1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002180
Georg Brandl15c5ce92007-03-07 09:09:40 +00002181 # Used by TestEquality.test_ne
2182 ne_pairs = [(Foo('test1'), Foo('runTest'))
2183 ,(Foo('test1'), Bar('test1'))
2184 ,(Foo('test1'), Bar('test2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002185
Georg Brandl15c5ce92007-03-07 09:09:40 +00002186 ################################################################
2187 ### /Set up attributes used by inherited tests
Tim Petersea5962f2007-03-12 18:07:52 +00002188
Georg Brandl15c5ce92007-03-07 09:09:40 +00002189
2190 # "class TestCase([methodName])"
2191 # ...
2192 # "Each instance of TestCase will run a single test method: the
2193 # method named methodName."
2194 # ...
2195 # "methodName defaults to "runTest"."
2196 #
2197 # Make sure it really is optional, and that it defaults to the proper
2198 # thing.
2199 def test_init__no_test_name(self):
2200 class Test(unittest.TestCase):
2201 def runTest(self): raise MyException()
2202 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002203
Georg Brandl15c5ce92007-03-07 09:09:40 +00002204 self.assertEqual(Test().id()[-13:], '.Test.runTest')
Tim Petersea5962f2007-03-12 18:07:52 +00002205
Georg Brandl15c5ce92007-03-07 09:09:40 +00002206 # "class TestCase([methodName])"
2207 # ...
2208 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002209 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002210 def test_init__test_name__valid(self):
2211 class Test(unittest.TestCase):
2212 def runTest(self): raise MyException()
2213 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002214
Georg Brandl15c5ce92007-03-07 09:09:40 +00002215 self.assertEqual(Test('test').id()[-10:], '.Test.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002216
Georg Brandl15c5ce92007-03-07 09:09:40 +00002217 # "class TestCase([methodName])"
2218 # ...
2219 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002220 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002221 def test_init__test_name__invalid(self):
2222 class Test(unittest.TestCase):
2223 def runTest(self): raise MyException()
2224 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002225
Georg Brandl15c5ce92007-03-07 09:09:40 +00002226 try:
2227 Test('testfoo')
2228 except ValueError:
2229 pass
2230 else:
2231 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +00002232
Georg Brandl15c5ce92007-03-07 09:09:40 +00002233 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00002234 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00002235 def test_countTestCases(self):
2236 class Foo(unittest.TestCase):
2237 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002238
Georg Brandl15c5ce92007-03-07 09:09:40 +00002239 self.assertEqual(Foo('test').countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00002240
Georg Brandl15c5ce92007-03-07 09:09:40 +00002241 # "Return the default type of test result object to be used to run this
2242 # test. For TestCase instances, this will always be
2243 # unittest.TestResult; subclasses of TestCase should
2244 # override this as necessary."
2245 def test_defaultTestResult(self):
2246 class Foo(unittest.TestCase):
2247 def runTest(self):
2248 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002249
Georg Brandl15c5ce92007-03-07 09:09:40 +00002250 result = Foo().defaultTestResult()
2251 self.assertEqual(type(result), unittest.TestResult)
2252
2253 # "When a setUp() method is defined, the test runner will run that method
2254 # prior to each test. Likewise, if a tearDown() method is defined, the
2255 # test runner will invoke that method after each test. In the example,
2256 # setUp() was used to create a fresh sequence for each test."
2257 #
2258 # Make sure the proper call order is maintained, even if setUp() raises
2259 # an exception.
2260 def test_run_call_order__error_in_setUp(self):
2261 events = []
2262 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002263
Michael Foord07ef4872009-05-02 22:43:34 +00002264 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002265 def setUp(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002266 super(Foo, self).setUp()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002267 raise RuntimeError('raised by Foo.setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002268
Michael Foord07ef4872009-05-02 22:43:34 +00002269 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002270 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2271 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002272
Michael Foord07ef4872009-05-02 22:43:34 +00002273 # "With a temporary result stopTestRun is called when setUp errors.
2274 def test_run_call_order__error_in_setUp_default_result(self):
2275 events = []
2276
2277 class Foo(LoggingTestCase):
2278 def defaultTestResult(self):
2279 return LoggingResult(self.events)
2280
2281 def setUp(self):
2282 super(Foo, self).setUp()
2283 raise RuntimeError('raised by Foo.setUp')
2284
2285 Foo(events).run()
2286 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2287 'stopTest', 'stopTestRun']
2288 self.assertEqual(events, expected)
2289
Georg Brandl15c5ce92007-03-07 09:09:40 +00002290 # "When a setUp() method is defined, the test runner will run that method
2291 # prior to each test. Likewise, if a tearDown() method is defined, the
2292 # test runner will invoke that method after each test. In the example,
2293 # setUp() was used to create a fresh sequence for each test."
2294 #
2295 # Make sure the proper call order is maintained, even if the test raises
2296 # an error (as opposed to a failure).
2297 def test_run_call_order__error_in_test(self):
2298 events = []
2299 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002300
Michael Foord07ef4872009-05-02 22:43:34 +00002301 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002302 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002303 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002304 raise RuntimeError('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002305
Georg Brandl15c5ce92007-03-07 09:09:40 +00002306 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2307 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002308 Foo(events).run(result)
2309 self.assertEqual(events, expected)
2310
2311 # "With a default result, an error in the test still results in stopTestRun
2312 # being called."
2313 def test_run_call_order__error_in_test_default_result(self):
2314 events = []
2315
2316 class Foo(LoggingTestCase):
2317 def defaultTestResult(self):
2318 return LoggingResult(self.events)
2319
2320 def test(self):
2321 super(Foo, self).test()
2322 raise RuntimeError('raised by Foo.test')
2323
2324 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2325 'tearDown', 'stopTest', 'stopTestRun']
2326 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002327 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002328
Georg Brandl15c5ce92007-03-07 09:09:40 +00002329 # "When a setUp() method is defined, the test runner will run that method
2330 # prior to each test. Likewise, if a tearDown() method is defined, the
2331 # test runner will invoke that method after each test. In the example,
2332 # setUp() was used to create a fresh sequence for each test."
2333 #
2334 # Make sure the proper call order is maintained, even if the test signals
2335 # a failure (as opposed to an error).
2336 def test_run_call_order__failure_in_test(self):
2337 events = []
2338 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002339
Michael Foord07ef4872009-05-02 22:43:34 +00002340 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002341 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002342 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002343 self.fail('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002344
Georg Brandl15c5ce92007-03-07 09:09:40 +00002345 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2346 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002347 Foo(events).run(result)
2348 self.assertEqual(events, expected)
2349
2350 # "When a test fails with a default result stopTestRun is still called."
2351 def test_run_call_order__failure_in_test_default_result(self):
2352
2353 class Foo(LoggingTestCase):
2354 def defaultTestResult(self):
2355 return LoggingResult(self.events)
2356 def test(self):
2357 super(Foo, self).test()
2358 self.fail('raised by Foo.test')
2359
2360 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2361 'tearDown', 'stopTest', 'stopTestRun']
2362 events = []
2363 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002364 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002365
Georg Brandl15c5ce92007-03-07 09:09:40 +00002366 # "When a setUp() method is defined, the test runner will run that method
2367 # prior to each test. Likewise, if a tearDown() method is defined, the
2368 # test runner will invoke that method after each test. In the example,
2369 # setUp() was used to create a fresh sequence for each test."
2370 #
2371 # Make sure the proper call order is maintained, even if tearDown() raises
2372 # an exception.
2373 def test_run_call_order__error_in_tearDown(self):
2374 events = []
2375 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002376
Michael Foord07ef4872009-05-02 22:43:34 +00002377 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002378 def tearDown(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002379 super(Foo, self).tearDown()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002380 raise RuntimeError('raised by Foo.tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002381
Michael Foord07ef4872009-05-02 22:43:34 +00002382 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002383 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2384 'stopTest']
2385 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002386
Michael Foord07ef4872009-05-02 22:43:34 +00002387 # "When tearDown errors with a default result stopTestRun is still called."
2388 def test_run_call_order__error_in_tearDown_default_result(self):
2389
2390 class Foo(LoggingTestCase):
2391 def defaultTestResult(self):
2392 return LoggingResult(self.events)
2393 def tearDown(self):
2394 super(Foo, self).tearDown()
2395 raise RuntimeError('raised by Foo.tearDown')
2396
2397 events = []
2398 Foo(events).run()
2399 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2400 'addError', 'stopTest', 'stopTestRun']
2401 self.assertEqual(events, expected)
2402
2403 # "TestCase.run() still works when the defaultTestResult is a TestResult
2404 # that does not support startTestRun and stopTestRun.
2405 def test_run_call_order_default_result(self):
2406
2407 class Foo(unittest.TestCase):
2408 def defaultTestResult(self):
2409 return ResultWithNoStartTestRunStopTestRun()
2410 def test(self):
2411 pass
2412
2413 Foo('test').run()
2414
Georg Brandl15c5ce92007-03-07 09:09:40 +00002415 # "This class attribute gives the exception raised by the test() method.
2416 # If a test framework needs to use a specialized exception, possibly to
2417 # carry additional information, it must subclass this exception in
2418 # order to ``play fair'' with the framework. The initial value of this
2419 # attribute is AssertionError"
2420 def test_failureException__default(self):
2421 class Foo(unittest.TestCase):
2422 def test(self):
2423 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002424
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002425 self.assertTrue(Foo('test').failureException is AssertionError)
Tim Petersea5962f2007-03-12 18:07:52 +00002426
Georg Brandl15c5ce92007-03-07 09:09:40 +00002427 # "This class attribute gives the exception raised by the test() method.
2428 # If a test framework needs to use a specialized exception, possibly to
2429 # carry additional information, it must subclass this exception in
2430 # order to ``play fair'' with the framework."
2431 #
2432 # Make sure TestCase.run() respects the designated failureException
2433 def test_failureException__subclassing__explicit_raise(self):
2434 events = []
2435 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002436
Georg Brandl15c5ce92007-03-07 09:09:40 +00002437 class Foo(unittest.TestCase):
2438 def test(self):
2439 raise RuntimeError()
Tim Petersea5962f2007-03-12 18:07:52 +00002440
Georg Brandl15c5ce92007-03-07 09:09:40 +00002441 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002442
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002443 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002444
2445
Georg Brandl15c5ce92007-03-07 09:09:40 +00002446 Foo('test').run(result)
2447 expected = ['startTest', 'addFailure', 'stopTest']
2448 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002449
Georg Brandl15c5ce92007-03-07 09:09:40 +00002450 # "This class attribute gives the exception raised by the test() method.
2451 # If a test framework needs to use a specialized exception, possibly to
2452 # carry additional information, it must subclass this exception in
2453 # order to ``play fair'' with the framework."
2454 #
2455 # Make sure TestCase.run() respects the designated failureException
2456 def test_failureException__subclassing__implicit_raise(self):
2457 events = []
2458 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002459
Georg Brandl15c5ce92007-03-07 09:09:40 +00002460 class Foo(unittest.TestCase):
2461 def test(self):
2462 self.fail("foo")
Tim Petersea5962f2007-03-12 18:07:52 +00002463
Georg Brandl15c5ce92007-03-07 09:09:40 +00002464 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002465
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002466 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002467
2468
Georg Brandl15c5ce92007-03-07 09:09:40 +00002469 Foo('test').run(result)
2470 expected = ['startTest', 'addFailure', 'stopTest']
2471 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002472
2473 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002474 def test_setUp(self):
2475 class Foo(unittest.TestCase):
2476 def runTest(self):
2477 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002478
Georg Brandl15c5ce92007-03-07 09:09:40 +00002479 # ... and nothing should happen
2480 Foo().setUp()
Tim Petersea5962f2007-03-12 18:07:52 +00002481
2482 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002483 def test_tearDown(self):
2484 class Foo(unittest.TestCase):
2485 def runTest(self):
2486 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002487
Georg Brandl15c5ce92007-03-07 09:09:40 +00002488 # ... and nothing should happen
2489 Foo().tearDown()
Tim Petersea5962f2007-03-12 18:07:52 +00002490
Georg Brandl15c5ce92007-03-07 09:09:40 +00002491 # "Return a string identifying the specific test case."
2492 #
2493 # Because of the vague nature of the docs, I'm not going to lock this
2494 # test down too much. Really all that can be asserted is that the id()
2495 # will be a string (either 8-byte or unicode -- again, because the docs
2496 # just say "string")
2497 def test_id(self):
2498 class Foo(unittest.TestCase):
2499 def runTest(self):
2500 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002501
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002502 self.assertIsInstance(Foo().id(), basestring)
Tim Petersea5962f2007-03-12 18:07:52 +00002503
Georg Brandl15c5ce92007-03-07 09:09:40 +00002504 # "If result is omitted or None, a temporary result object is created
Michael Foord07ef4872009-05-02 22:43:34 +00002505 # and used, but is not made available to the caller. As TestCase owns the
2506 # temporary result startTestRun and stopTestRun are called.
2507
Georg Brandl15c5ce92007-03-07 09:09:40 +00002508 def test_run__uses_defaultTestResult(self):
2509 events = []
Tim Petersea5962f2007-03-12 18:07:52 +00002510
Georg Brandl15c5ce92007-03-07 09:09:40 +00002511 class Foo(unittest.TestCase):
2512 def test(self):
2513 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002514
Georg Brandl15c5ce92007-03-07 09:09:40 +00002515 def defaultTestResult(self):
2516 return LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002517
2518 # Make run() find a result object on its own
Georg Brandl15c5ce92007-03-07 09:09:40 +00002519 Foo('test').run()
Tim Petersea5962f2007-03-12 18:07:52 +00002520
Michael Foord07ef4872009-05-02 22:43:34 +00002521 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2522 'stopTest', 'stopTestRun']
Georg Brandl15c5ce92007-03-07 09:09:40 +00002523 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002524
Gregory P. Smith28399852009-03-31 16:54:10 +00002525 def testShortDescriptionWithoutDocstring(self):
Michael Foorddb43b5a2010-02-10 14:25:12 +00002526 self.assertIsNone(self.shortDescription())
Gregory P. Smith28399852009-03-31 16:54:10 +00002527
2528 def testShortDescriptionWithOneLineDocstring(self):
2529 """Tests shortDescription() for a method with a docstring."""
2530 self.assertEqual(
2531 self.shortDescription(),
Michael Foorddb43b5a2010-02-10 14:25:12 +00002532 'Tests shortDescription() for a method with a docstring.')
Gregory P. Smith28399852009-03-31 16:54:10 +00002533
2534 def testShortDescriptionWithMultiLineDocstring(self):
2535 """Tests shortDescription() for a method with a longer docstring.
2536
2537 This method ensures that only the first line of a docstring is
2538 returned used in the short description, no matter how long the
2539 whole thing is.
2540 """
2541 self.assertEqual(
2542 self.shortDescription(),
Gregory P. Smith28399852009-03-31 16:54:10 +00002543 'Tests shortDescription() for a method with a longer '
Michael Foorddb43b5a2010-02-10 14:25:12 +00002544 'docstring.')
Gregory P. Smith28399852009-03-31 16:54:10 +00002545
Gregory P. Smith28399852009-03-31 16:54:10 +00002546 def testAddTypeEqualityFunc(self):
2547 class SadSnake(object):
2548 """Dummy class for test_addTypeEqualityFunc."""
2549 s1, s2 = SadSnake(), SadSnake()
2550 self.assertFalse(s1 == s2)
2551 def AllSnakesCreatedEqual(a, b, msg=None):
2552 return type(a) == type(b) == SadSnake
2553 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2554 self.assertEqual(s1, s2)
2555 # No this doesn't clean up and remove the SadSnake equality func
2556 # from this TestCase instance but since its a local nothing else
2557 # will ever notice that.
2558
Michael Foordf2dfef12009-04-05 19:19:28 +00002559 def testAssertIs(self):
2560 thing = object()
2561 self.assertIs(thing, thing)
2562 self.assertRaises(self.failureException, self.assertIs, thing, object())
2563
2564 def testAssertIsNot(self):
2565 thing = object()
2566 self.assertIsNot(thing, object())
2567 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2568
Georg Brandlf895cf52009-10-01 20:59:31 +00002569 def testAssertIsInstance(self):
2570 thing = []
2571 self.assertIsInstance(thing, list)
2572 self.assertRaises(self.failureException, self.assertIsInstance,
2573 thing, dict)
2574
2575 def testAssertNotIsInstance(self):
2576 thing = []
2577 self.assertNotIsInstance(thing, dict)
2578 self.assertRaises(self.failureException, self.assertNotIsInstance,
2579 thing, list)
2580
Gregory P. Smith28399852009-03-31 16:54:10 +00002581 def testAssertIn(self):
2582 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2583
2584 self.assertIn('a', 'abc')
2585 self.assertIn(2, [1, 2, 3])
2586 self.assertIn('monkey', animals)
2587
2588 self.assertNotIn('d', 'abc')
2589 self.assertNotIn(0, [1, 2, 3])
2590 self.assertNotIn('otter', animals)
2591
2592 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2593 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2594 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2595 animals)
2596
2597 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2598 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2599 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2600 animals)
2601
2602 def testAssertDictContainsSubset(self):
2603 self.assertDictContainsSubset({}, {})
2604 self.assertDictContainsSubset({}, {'a': 1})
2605 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2606 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2607 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2608
Michael Foord225a0992010-02-18 20:30:09 +00002609 with self.assertRaises(self.failureException):
2610 self.assertDictContainsSubset({1: "one"}, {})
Gregory P. Smith28399852009-03-31 16:54:10 +00002611
Michael Foord225a0992010-02-18 20:30:09 +00002612 with self.assertRaises(self.failureException):
2613 self.assertDictContainsSubset({'a': 2}, {'a': 1})
Gregory P. Smith28399852009-03-31 16:54:10 +00002614
Michael Foord225a0992010-02-18 20:30:09 +00002615 with self.assertRaises(self.failureException):
2616 self.assertDictContainsSubset({'c': 1}, {'a': 1})
Gregory P. Smith28399852009-03-31 16:54:10 +00002617
Michael Foord225a0992010-02-18 20:30:09 +00002618 with self.assertRaises(self.failureException):
2619 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2620
2621 with self.assertRaises(self.failureException):
2622 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2623
Michael Foord2f677562010-02-21 14:48:59 +00002624 with warnings.catch_warnings(record=True):
2625 # silence the UnicodeWarning
2626 one = ''.join(chr(i) for i in range(255))
2627 # this used to cause a UnicodeDecodeError constructing the failure msg
2628 with self.assertRaises(self.failureException):
2629 self.assertDictContainsSubset({'foo': one}, {'foo': u'\uFFFD'})
Gregory P. Smith28399852009-03-31 16:54:10 +00002630
2631 def testAssertEqual(self):
2632 equal_pairs = [
2633 ((), ()),
2634 ({}, {}),
2635 ([], []),
2636 (set(), set()),
2637 (frozenset(), frozenset())]
2638 for a, b in equal_pairs:
2639 # This mess of try excepts is to test the assertEqual behavior
2640 # itself.
2641 try:
2642 self.assertEqual(a, b)
2643 except self.failureException:
2644 self.fail('assertEqual(%r, %r) failed' % (a, b))
2645 try:
2646 self.assertEqual(a, b, msg='foo')
2647 except self.failureException:
2648 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2649 try:
2650 self.assertEqual(a, b, 'foo')
2651 except self.failureException:
2652 self.fail('assertEqual(%r, %r) with third parameter failed' %
2653 (a, b))
2654
2655 unequal_pairs = [
2656 ((), []),
2657 ({}, set()),
2658 (set([4,1]), frozenset([4,2])),
2659 (frozenset([4,5]), set([2,3])),
2660 (set([3,4]), set([5,4]))]
2661 for a, b in unequal_pairs:
2662 self.assertRaises(self.failureException, self.assertEqual, a, b)
2663 self.assertRaises(self.failureException, self.assertEqual, a, b,
2664 'foo')
2665 self.assertRaises(self.failureException, self.assertEqual, a, b,
2666 msg='foo')
2667
2668 def testEquality(self):
2669 self.assertListEqual([], [])
2670 self.assertTupleEqual((), ())
2671 self.assertSequenceEqual([], ())
2672
2673 a = [0, 'a', []]
2674 b = []
2675 self.assertRaises(unittest.TestCase.failureException,
2676 self.assertListEqual, a, b)
2677 self.assertRaises(unittest.TestCase.failureException,
2678 self.assertListEqual, tuple(a), tuple(b))
2679 self.assertRaises(unittest.TestCase.failureException,
2680 self.assertSequenceEqual, a, tuple(b))
2681
2682 b.extend(a)
2683 self.assertListEqual(a, b)
2684 self.assertTupleEqual(tuple(a), tuple(b))
2685 self.assertSequenceEqual(a, tuple(b))
2686 self.assertSequenceEqual(tuple(a), b)
2687
2688 self.assertRaises(self.failureException, self.assertListEqual,
2689 a, tuple(b))
2690 self.assertRaises(self.failureException, self.assertTupleEqual,
2691 tuple(a), b)
2692 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2693 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2694 tuple(b))
2695 self.assertRaises(self.failureException, self.assertSequenceEqual,
2696 None, tuple(b))
2697 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2698 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2699 self.assertRaises(self.failureException, self.assertSequenceEqual,
2700 1, 1)
2701
2702 self.assertDictEqual({}, {})
2703
2704 c = { 'x': 1 }
2705 d = {}
2706 self.assertRaises(unittest.TestCase.failureException,
2707 self.assertDictEqual, c, d)
2708
2709 d.update(c)
2710 self.assertDictEqual(c, d)
2711
2712 d['x'] = 0
2713 self.assertRaises(unittest.TestCase.failureException,
2714 self.assertDictEqual, c, d, 'These are unequal')
2715
2716 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2717 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2718 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2719
2720 self.assertSameElements([1, 2, 3], [3, 2, 1])
2721 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2722 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2723 self.assertRaises(self.failureException, self.assertSameElements,
2724 [10], [10, 11])
2725 self.assertRaises(self.failureException, self.assertSameElements,
2726 [10, 11], [10])
2727
2728 # Test that sequences of unhashable objects can be tested for sameness:
2729 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Michael Foordf2dfef12009-04-05 19:19:28 +00002730
Gregory P. Smith28399852009-03-31 16:54:10 +00002731 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2732 self.assertRaises(self.failureException, self.assertSameElements,
2733 [[1]], [[2]])
2734
2735 def testAssertSetEqual(self):
2736 set1 = set()
2737 set2 = set()
2738 self.assertSetEqual(set1, set2)
2739
2740 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2741 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2742 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2743 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2744
2745 set1 = set(['a'])
2746 set2 = set()
2747 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2748
2749 set1 = set(['a'])
2750 set2 = set(['a'])
2751 self.assertSetEqual(set1, set2)
2752
2753 set1 = set(['a'])
2754 set2 = set(['a', 'b'])
2755 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2756
2757 set1 = set(['a'])
2758 set2 = frozenset(['a', 'b'])
2759 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2760
2761 set1 = set(['a', 'b'])
2762 set2 = frozenset(['a', 'b'])
2763 self.assertSetEqual(set1, set2)
2764
2765 set1 = set()
2766 set2 = "foo"
2767 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2768 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2769
2770 # make sure any string formatting is tuple-safe
2771 set1 = set([(0, 1), (2, 3)])
2772 set2 = set([(4, 5)])
2773 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2774
2775 def testInequality(self):
2776 # Try ints
2777 self.assertGreater(2, 1)
2778 self.assertGreaterEqual(2, 1)
2779 self.assertGreaterEqual(1, 1)
2780 self.assertLess(1, 2)
2781 self.assertLessEqual(1, 2)
2782 self.assertLessEqual(1, 1)
2783 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2784 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2785 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2786 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2787 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2788 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2789
2790 # Try Floats
2791 self.assertGreater(1.1, 1.0)
2792 self.assertGreaterEqual(1.1, 1.0)
2793 self.assertGreaterEqual(1.0, 1.0)
2794 self.assertLess(1.0, 1.1)
2795 self.assertLessEqual(1.0, 1.1)
2796 self.assertLessEqual(1.0, 1.0)
2797 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2798 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2799 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2800 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2801 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2802 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2803
2804 # Try Strings
2805 self.assertGreater('bug', 'ant')
2806 self.assertGreaterEqual('bug', 'ant')
2807 self.assertGreaterEqual('ant', 'ant')
2808 self.assertLess('ant', 'bug')
2809 self.assertLessEqual('ant', 'bug')
2810 self.assertLessEqual('ant', 'ant')
2811 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2812 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2813 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2814 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2815 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2816 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2817
2818 # Try Unicode
2819 self.assertGreater(u'bug', u'ant')
2820 self.assertGreaterEqual(u'bug', u'ant')
2821 self.assertGreaterEqual(u'ant', u'ant')
2822 self.assertLess(u'ant', u'bug')
2823 self.assertLessEqual(u'ant', u'bug')
2824 self.assertLessEqual(u'ant', u'ant')
2825 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug')
2826 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant')
2827 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2828 u'bug')
2829 self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant')
2830 self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant')
2831 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant')
2832
2833 # Try Mixed String/Unicode
2834 self.assertGreater('bug', u'ant')
2835 self.assertGreater(u'bug', 'ant')
2836 self.assertGreaterEqual('bug', u'ant')
2837 self.assertGreaterEqual(u'bug', 'ant')
2838 self.assertGreaterEqual('ant', u'ant')
2839 self.assertGreaterEqual(u'ant', 'ant')
2840 self.assertLess('ant', u'bug')
2841 self.assertLess(u'ant', 'bug')
2842 self.assertLessEqual('ant', u'bug')
2843 self.assertLessEqual(u'ant', 'bug')
2844 self.assertLessEqual('ant', u'ant')
2845 self.assertLessEqual(u'ant', 'ant')
2846 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug')
2847 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug')
2848 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant')
2849 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant')
2850 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant',
2851 u'bug')
2852 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2853 'bug')
2854 self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant')
2855 self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant')
2856 self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant')
2857 self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant')
2858 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant')
2859 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant')
2860
2861 def testAssertMultiLineEqual(self):
2862 sample_text = b"""\
2863http://www.python.org/doc/2.3/lib/module-unittest.html
2864test case
2865 A test case is the smallest unit of testing. [...]
2866"""
2867 revised_sample_text = b"""\
2868http://www.python.org/doc/2.4.1/lib/module-unittest.html
2869test case
2870 A test case is the smallest unit of testing. [...] You may provide your
2871 own implementation that does not subclass from TestCase, of course.
2872"""
2873 sample_text_error = b"""
2874- http://www.python.org/doc/2.3/lib/module-unittest.html
2875? ^
2876+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2877? ^^^
2878 test case
2879- A test case is the smallest unit of testing. [...]
2880+ A test case is the smallest unit of testing. [...] You may provide your
2881? +++++++++++++++++++++
2882+ own implementation that does not subclass from TestCase, of course.
2883"""
2884
2885 for type_changer in (lambda x: x, lambda x: x.decode('utf8')):
2886 try:
2887 self.assertMultiLineEqual(type_changer(sample_text),
2888 type_changer(revised_sample_text))
2889 except self.failureException, e:
Michael Foordfe6349c2010-02-08 22:41:16 +00002890 # assertMultiLineEqual is hooked up as the default for
2891 # unicode strings - so we can't use it for this check
2892 self.assertTrue(sample_text_error == str(e).encode('utf8'))
Gregory P. Smith28399852009-03-31 16:54:10 +00002893
2894 def testAssertIsNone(self):
2895 self.assertIsNone(None)
2896 self.assertRaises(self.failureException, self.assertIsNone, False)
2897 self.assertIsNotNone('DjZoPloGears on Rails')
2898 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2899
2900 def testAssertRegexpMatches(self):
2901 self.assertRegexpMatches('asdfabasdf', r'ab+')
2902 self.assertRaises(self.failureException, self.assertRegexpMatches,
2903 'saaas', r'aaaa')
2904
2905 def testAssertRaisesRegexp(self):
2906 class ExceptionMock(Exception):
2907 pass
2908
2909 def Stub():
2910 raise ExceptionMock('We expect')
2911
2912 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2913 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2914 self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
2915
2916 def testAssertNotRaisesRegexp(self):
2917 self.assertRaisesRegexp(
2918 self.failureException, '^Exception not raised$',
2919 self.assertRaisesRegexp, Exception, re.compile('x'),
2920 lambda: None)
2921 self.assertRaisesRegexp(
2922 self.failureException, '^Exception not raised$',
2923 self.assertRaisesRegexp, Exception, 'x',
2924 lambda: None)
2925 self.assertRaisesRegexp(
2926 self.failureException, '^Exception not raised$',
2927 self.assertRaisesRegexp, Exception, u'x',
2928 lambda: None)
2929
2930 def testAssertRaisesRegexpMismatch(self):
2931 def Stub():
2932 raise Exception('Unexpected')
2933
2934 self.assertRaisesRegexp(
2935 self.failureException,
2936 r'"\^Expected\$" does not match "Unexpected"',
2937 self.assertRaisesRegexp, Exception, '^Expected$',
2938 Stub)
2939 self.assertRaisesRegexp(
2940 self.failureException,
2941 r'"\^Expected\$" does not match "Unexpected"',
2942 self.assertRaisesRegexp, Exception, u'^Expected$',
2943 Stub)
2944 self.assertRaisesRegexp(
2945 self.failureException,
2946 r'"\^Expected\$" does not match "Unexpected"',
2947 self.assertRaisesRegexp, Exception,
2948 re.compile('^Expected$'), Stub)
2949
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00002950 def testAssertRaisesExcValue(self):
2951 class ExceptionMock(Exception):
2952 pass
2953
2954 def Stub(foo):
2955 raise ExceptionMock(foo)
2956 v = "particular value"
2957
2958 ctx = self.assertRaises(ExceptionMock)
2959 with ctx:
2960 Stub(v)
Georg Brandldc3694b2010-02-07 17:02:22 +00002961 e = ctx.exception
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002962 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00002963 self.assertEqual(e.args[0], v)
2964
Gregory P. Smith7558d572009-03-31 19:03:28 +00002965 def testSynonymAssertMethodNames(self):
2966 """Test undocumented method name synonyms.
2967
2968 Please do not use these methods names in your own code.
2969
2970 This test confirms their continued existence and functionality
2971 in order to avoid breaking existing code.
2972 """
2973 self.assertNotEquals(3, 5)
2974 self.assertEquals(3, 3)
2975 self.assertAlmostEquals(2.0, 2.0)
2976 self.assertNotAlmostEquals(3.0, 5.0)
2977 self.assert_(True)
2978
2979 def testPendingDeprecationMethodNames(self):
2980 """Test fail* methods pending deprecation, they will warn in 3.2.
2981
2982 Do not use these methods. They will go away in 3.3.
2983 """
2984 self.failIfEqual(3, 5)
2985 self.failUnlessEqual(3, 3)
2986 self.failUnlessAlmostEqual(2.0, 2.0)
2987 self.failIfAlmostEqual(3.0, 5.0)
2988 self.failUnless(True)
2989 self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam')
2990 self.failIf(False)
2991
Michael Foorde2942d02009-04-02 05:51:54 +00002992 def testDeepcopy(self):
2993 # Issue: 5660
2994 class TestableTest(TestCase):
2995 def testNothing(self):
2996 pass
2997
2998 test = TestableTest('testNothing')
2999
3000 # This shouldn't blow up
3001 deepcopy(test)
3002
Benjamin Peterson692428e2009-03-23 21:50:21 +00003003
3004class Test_TestSkipping(TestCase):
3005
3006 def test_skipping(self):
3007 class Foo(unittest.TestCase):
3008 def test_skip_me(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00003009 self.skipTest("skip")
Benjamin Peterson692428e2009-03-23 21:50:21 +00003010 events = []
3011 result = LoggingResult(events)
3012 test = Foo("test_skip_me")
3013 test.run(result)
3014 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3015 self.assertEqual(result.skipped, [(test, "skip")])
3016
3017 # Try letting setUp skip the test now.
3018 class Foo(unittest.TestCase):
3019 def setUp(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00003020 self.skipTest("testing")
Benjamin Peterson692428e2009-03-23 21:50:21 +00003021 def test_nothing(self): pass
3022 events = []
3023 result = LoggingResult(events)
3024 test = Foo("test_nothing")
3025 test.run(result)
3026 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3027 self.assertEqual(result.skipped, [(test, "testing")])
3028 self.assertEqual(result.testsRun, 1)
3029
3030 def test_skipping_decorators(self):
3031 op_table = ((unittest.skipUnless, False, True),
3032 (unittest.skipIf, True, False))
3033 for deco, do_skip, dont_skip in op_table:
3034 class Foo(unittest.TestCase):
3035 @deco(do_skip, "testing")
3036 def test_skip(self): pass
3037
3038 @deco(dont_skip, "testing")
3039 def test_dont_skip(self): pass
3040 test_do_skip = Foo("test_skip")
3041 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003042 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003043 events = []
3044 result = LoggingResult(events)
3045 suite.run(result)
3046 self.assertEqual(len(result.skipped), 1)
3047 expected = ['startTest', 'addSkip', 'stopTest',
3048 'startTest', 'addSuccess', 'stopTest']
3049 self.assertEqual(events, expected)
3050 self.assertEqual(result.testsRun, 2)
3051 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
3052 self.assertTrue(result.wasSuccessful())
3053
3054 def test_skip_class(self):
3055 @unittest.skip("testing")
3056 class Foo(unittest.TestCase):
3057 def test_1(self):
3058 record.append(1)
3059 record = []
3060 result = unittest.TestResult()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003061 test = Foo("test_1")
3062 suite = unittest.TestSuite([test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003063 suite.run(result)
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003064 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003065 self.assertEqual(record, [])
3066
3067 def test_expected_failure(self):
3068 class Foo(unittest.TestCase):
3069 @unittest.expectedFailure
3070 def test_die(self):
3071 self.fail("help me!")
3072 events = []
3073 result = LoggingResult(events)
3074 test = Foo("test_die")
3075 test.run(result)
3076 self.assertEqual(events,
3077 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003078 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00003079 self.assertTrue(result.wasSuccessful())
3080
3081 def test_unexpected_success(self):
3082 class Foo(unittest.TestCase):
3083 @unittest.expectedFailure
3084 def test_die(self):
3085 pass
3086 events = []
3087 result = LoggingResult(events)
3088 test = Foo("test_die")
3089 test.run(result)
3090 self.assertEqual(events,
3091 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3092 self.assertFalse(result.failures)
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003093 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003094 self.assertTrue(result.wasSuccessful())
3095
3096
3097
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003098class Test_Assertions(TestCase):
3099 def test_AlmostEqual(self):
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003100 self.assertAlmostEqual(1.00000001, 1.0)
3101 self.assertNotAlmostEqual(1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003102 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003103 self.assertAlmostEqual, 1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003104 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003105 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003106
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003107 self.assertAlmostEqual(1.1, 1.0, places=0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003108 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003109 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003110
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003111 self.assertAlmostEqual(0, .1+.1j, places=0)
3112 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003113 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003114 self.assertAlmostEqual, 0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003115 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003116 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003117
Michael Foordc3f79372009-09-13 16:40:02 +00003118 self.assertAlmostEqual(float('inf'), float('inf'))
3119 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3120 float('inf'), float('inf'))
3121
3122
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003123 def test_assertRaises(self):
3124 def _raise(e):
3125 raise e
3126 self.assertRaises(KeyError, _raise, KeyError)
3127 self.assertRaises(KeyError, _raise, KeyError("key"))
3128 try:
3129 self.assertRaises(KeyError, lambda: None)
Gregory P. Smith28399852009-03-31 16:54:10 +00003130 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003131 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003132 else:
3133 self.fail("assertRaises() didn't fail")
3134 try:
3135 self.assertRaises(KeyError, _raise, ValueError)
3136 except ValueError:
3137 pass
3138 else:
3139 self.fail("assertRaises() didn't let exception pass through")
Michael Foord2bd52dc2010-02-07 18:44:12 +00003140 with self.assertRaises(KeyError) as cm:
3141 try:
3142 raise KeyError
3143 except Exception, e:
3144 raise
3145 self.assertIs(cm.exception, e)
3146
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003147 with self.assertRaises(KeyError):
3148 raise KeyError("key")
3149 try:
3150 with self.assertRaises(KeyError):
3151 pass
Gregory P. Smith28399852009-03-31 16:54:10 +00003152 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003153 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003154 else:
3155 self.fail("assertRaises() didn't fail")
3156 try:
3157 with self.assertRaises(KeyError):
3158 raise ValueError
3159 except ValueError:
3160 pass
3161 else:
3162 self.fail("assertRaises() didn't let exception pass through")
3163
3164
Michael Foord345b2fe2009-04-02 03:20:38 +00003165class TestLongMessage(TestCase):
3166 """Test that the individual asserts honour longMessage.
3167 This actually tests all the message behaviour for
3168 asserts that use longMessage."""
3169
3170 def setUp(self):
3171 class TestableTestFalse(TestCase):
3172 longMessage = False
3173 failureException = self.failureException
3174
3175 def testTest(self):
3176 pass
3177
3178 class TestableTestTrue(TestCase):
3179 longMessage = True
3180 failureException = self.failureException
3181
3182 def testTest(self):
3183 pass
3184
3185 self.testableTrue = TestableTestTrue('testTest')
3186 self.testableFalse = TestableTestFalse('testTest')
3187
3188 def testDefault(self):
3189 self.assertFalse(TestCase.longMessage)
3190
3191 def test_formatMsg(self):
3192 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3193 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3194
3195 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3196 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3197
3198 def assertMessages(self, methodName, args, errors):
3199 def getMethod(i):
3200 useTestableFalse = i < 2
3201 if useTestableFalse:
3202 test = self.testableFalse
3203 else:
3204 test = self.testableTrue
3205 return getattr(test, methodName)
3206
3207 for i, expected_regexp in enumerate(errors):
3208 testMethod = getMethod(i)
3209 kwargs = {}
3210 withMsg = i % 2
3211 if withMsg:
3212 kwargs = {"msg": "oops"}
3213
3214 with self.assertRaisesRegexp(self.failureException,
3215 expected_regexp=expected_regexp):
3216 testMethod(*args, **kwargs)
3217
3218 def testAssertTrue(self):
3219 self.assertMessages('assertTrue', (False,),
3220 ["^False is not True$", "^oops$", "^False is not True$",
3221 "^False is not True : oops$"])
3222
3223 def testAssertFalse(self):
3224 self.assertMessages('assertFalse', (True,),
3225 ["^True is not False$", "^oops$", "^True is not False$",
3226 "^True is not False : oops$"])
3227
3228 def testNotEqual(self):
3229 self.assertMessages('assertNotEqual', (1, 1),
3230 ["^1 == 1$", "^oops$", "^1 == 1$",
3231 "^1 == 1 : oops$"])
3232
3233 def testAlmostEqual(self):
3234 self.assertMessages('assertAlmostEqual', (1, 2),
3235 ["^1 != 2 within 7 places$", "^oops$",
3236 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3237
3238 def testNotAlmostEqual(self):
3239 self.assertMessages('assertNotAlmostEqual', (1, 1),
3240 ["^1 == 1 within 7 places$", "^oops$",
3241 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3242
3243 def test_baseAssertEqual(self):
3244 self.assertMessages('_baseAssertEqual', (1, 2),
3245 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3246
3247 def testAssertSequenceEqual(self):
3248 # Error messages are multiline so not testing on full message
3249 # assertTupleEqual and assertListEqual delegate to this method
3250 self.assertMessages('assertSequenceEqual', ([], [None]),
3251 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3252 r"\+ \[None\] : oops$"])
3253
3254 def testAssertSetEqual(self):
3255 self.assertMessages('assertSetEqual', (set(), set([None])),
3256 ["None$", "^oops$", "None$",
3257 "None : oops$"])
3258
3259 def testAssertIn(self):
3260 self.assertMessages('assertIn', (None, []),
3261 ['^None not found in \[\]$', "^oops$",
3262 '^None not found in \[\]$',
3263 '^None not found in \[\] : oops$'])
3264
3265 def testAssertNotIn(self):
3266 self.assertMessages('assertNotIn', (None, [None]),
3267 ['^None unexpectedly found in \[None\]$', "^oops$",
3268 '^None unexpectedly found in \[None\]$',
3269 '^None unexpectedly found in \[None\] : oops$'])
3270
3271 def testAssertDictEqual(self):
3272 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3273 [r"\+ \{'key': 'value'\}$", "^oops$",
3274 "\+ \{'key': 'value'\}$",
3275 "\+ \{'key': 'value'\} : oops$"])
3276
3277 def testAssertDictContainsSubset(self):
3278 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3279 ["^Missing: 'key'$", "^oops$",
3280 "^Missing: 'key'$",
3281 "^Missing: 'key' : oops$"])
3282
3283 def testAssertSameElements(self):
3284 self.assertMessages('assertSameElements', ([], [None]),
3285 [r"\[None\]$", "^oops$",
3286 r"\[None\]$",
3287 r"\[None\] : oops$"])
3288
3289 def testAssertMultiLineEqual(self):
3290 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3291 [r"\+ foo$", "^oops$",
3292 r"\+ foo$",
3293 r"\+ foo : oops$"])
3294
3295 def testAssertLess(self):
3296 self.assertMessages('assertLess', (2, 1),
3297 ["^2 not less than 1$", "^oops$",
3298 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3299
3300 def testAssertLessEqual(self):
3301 self.assertMessages('assertLessEqual', (2, 1),
3302 ["^2 not less than or equal to 1$", "^oops$",
3303 "^2 not less than or equal to 1$",
3304 "^2 not less than or equal to 1 : oops$"])
3305
3306 def testAssertGreater(self):
3307 self.assertMessages('assertGreater', (1, 2),
3308 ["^1 not greater than 2$", "^oops$",
3309 "^1 not greater than 2$",
3310 "^1 not greater than 2 : oops$"])
3311
3312 def testAssertGreaterEqual(self):
3313 self.assertMessages('assertGreaterEqual', (1, 2),
3314 ["^1 not greater than or equal to 2$", "^oops$",
3315 "^1 not greater than or equal to 2$",
3316 "^1 not greater than or equal to 2 : oops$"])
3317
3318 def testAssertIsNone(self):
3319 self.assertMessages('assertIsNone', ('not None',),
3320 ["^'not None' is not None$", "^oops$",
3321 "^'not None' is not None$",
3322 "^'not None' is not None : oops$"])
3323
3324 def testAssertIsNotNone(self):
3325 self.assertMessages('assertIsNotNone', (None,),
3326 ["^unexpectedly None$", "^oops$",
3327 "^unexpectedly None$",
3328 "^unexpectedly None : oops$"])
3329
Michael Foordf2dfef12009-04-05 19:19:28 +00003330 def testAssertIs(self):
3331 self.assertMessages('assertIs', (None, 'foo'),
3332 ["^None is not 'foo'$", "^oops$",
3333 "^None is not 'foo'$",
3334 "^None is not 'foo' : oops$"])
3335
3336 def testAssertIsNot(self):
3337 self.assertMessages('assertIsNot', (None, None),
3338 ["^unexpectedly identical: None$", "^oops$",
3339 "^unexpectedly identical: None$",
3340 "^unexpectedly identical: None : oops$"])
3341
Michael Foord345b2fe2009-04-02 03:20:38 +00003342
Michael Foorde2fb98f2009-05-02 20:15:05 +00003343class TestCleanUp(TestCase):
3344
3345 def testCleanUp(self):
3346 class TestableTest(TestCase):
3347 def testNothing(self):
3348 pass
3349
3350 test = TestableTest('testNothing')
3351 self.assertEqual(test._cleanups, [])
3352
3353 cleanups = []
3354
3355 def cleanup1(*args, **kwargs):
3356 cleanups.append((1, args, kwargs))
3357
3358 def cleanup2(*args, **kwargs):
3359 cleanups.append((2, args, kwargs))
3360
3361 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3362 test.addCleanup(cleanup2)
3363
3364 self.assertEqual(test._cleanups,
3365 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3366 (cleanup2, (), {})])
3367
3368 result = test.doCleanups()
3369 self.assertTrue(result)
3370
3371 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3372
3373 def testCleanUpWithErrors(self):
3374 class TestableTest(TestCase):
3375 def testNothing(self):
3376 pass
3377
3378 class MockResult(object):
3379 errors = []
3380 def addError(self, test, exc_info):
3381 self.errors.append((test, exc_info))
3382
3383 result = MockResult()
3384 test = TestableTest('testNothing')
Michael Foorda50af062009-05-21 22:57:02 +00003385 test._resultForDoCleanups = result
Michael Foorde2fb98f2009-05-02 20:15:05 +00003386
3387 exc1 = Exception('foo')
3388 exc2 = Exception('bar')
3389 def cleanup1():
3390 raise exc1
3391
3392 def cleanup2():
3393 raise exc2
3394
3395 test.addCleanup(cleanup1)
3396 test.addCleanup(cleanup2)
3397
3398 self.assertFalse(test.doCleanups())
3399
3400 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3401 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3402 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3403
3404 def testCleanupInRun(self):
3405 blowUp = False
3406 ordering = []
3407
3408 class TestableTest(TestCase):
3409 def setUp(self):
3410 ordering.append('setUp')
3411 if blowUp:
3412 raise Exception('foo')
3413
3414 def testNothing(self):
3415 ordering.append('test')
3416
3417 def tearDown(self):
3418 ordering.append('tearDown')
3419
3420 test = TestableTest('testNothing')
3421
3422 def cleanup1():
3423 ordering.append('cleanup1')
3424 def cleanup2():
3425 ordering.append('cleanup2')
3426 test.addCleanup(cleanup1)
3427 test.addCleanup(cleanup2)
3428
3429 def success(some_test):
3430 self.assertEqual(some_test, test)
3431 ordering.append('success')
3432
3433 result = unittest.TestResult()
3434 result.addSuccess = success
3435
3436 test.run(result)
3437 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3438 'cleanup2', 'cleanup1', 'success'])
3439
3440 blowUp = True
3441 ordering = []
3442 test = TestableTest('testNothing')
3443 test.addCleanup(cleanup1)
3444 test.run(result)
3445 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3446
3447
Michael Foord829f6b82009-05-02 11:43:06 +00003448class Test_TestProgram(TestCase):
3449
3450 # Horrible white box test
3451 def testNoExit(self):
3452 result = object()
3453 test = object()
3454
3455 class FakeRunner(object):
3456 def run(self, test):
3457 self.test = test
3458 return result
3459
3460 runner = FakeRunner()
3461
Michael Foord5d31e052009-05-11 17:59:43 +00003462 oldParseArgs = TestProgram.parseArgs
3463 def restoreParseArgs():
Michael Foord829f6b82009-05-02 11:43:06 +00003464 TestProgram.parseArgs = oldParseArgs
Michael Foord5d31e052009-05-11 17:59:43 +00003465 TestProgram.parseArgs = lambda *args: None
3466 self.addCleanup(restoreParseArgs)
3467
3468 def removeTest():
Michael Foord829f6b82009-05-02 11:43:06 +00003469 del TestProgram.test
Michael Foord5d31e052009-05-11 17:59:43 +00003470 TestProgram.test = test
3471 self.addCleanup(removeTest)
3472
3473 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3474
3475 self.assertEqual(program.result, result)
3476 self.assertEqual(runner.test, test)
3477 self.assertEqual(program.verbosity, 2)
Michael Foord829f6b82009-05-02 11:43:06 +00003478
Michael Foord829f6b82009-05-02 11:43:06 +00003479 class FooBar(unittest.TestCase):
3480 def testPass(self):
3481 assert True
3482 def testFail(self):
3483 assert False
3484
3485 class FooBarLoader(unittest.TestLoader):
3486 """Test loader that returns a suite containing FooBar."""
3487 def loadTestsFromModule(self, module):
3488 return self.suiteClass(
3489 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3490
3491
3492 def test_NonExit(self):
3493 program = unittest.main(exit=False,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003494 argv=["foobar"],
3495 testRunner=unittest.TextTestRunner(stream=StringIO()),
3496 testLoader=self.FooBarLoader())
Michael Foord829f6b82009-05-02 11:43:06 +00003497 self.assertTrue(hasattr(program, 'result'))
3498
3499
3500 def test_Exit(self):
3501 self.assertRaises(
3502 SystemExit,
3503 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003504 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003505 testRunner=unittest.TextTestRunner(stream=StringIO()),
3506 exit=True,
3507 testLoader=self.FooBarLoader())
3508
3509
3510 def test_ExitAsDefault(self):
3511 self.assertRaises(
3512 SystemExit,
3513 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003514 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003515 testRunner=unittest.TextTestRunner(stream=StringIO()),
3516 testLoader=self.FooBarLoader())
3517
3518
Michael Foord07ef4872009-05-02 22:43:34 +00003519class Test_TextTestRunner(TestCase):
3520 """Tests for TextTestRunner."""
3521
3522 def test_works_with_result_without_startTestRun_stopTestRun(self):
3523 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3524 separator2 = ''
3525 def printErrors(self):
3526 pass
3527
3528 class Runner(unittest.TextTestRunner):
3529 def __init__(self):
3530 super(Runner, self).__init__(StringIO())
3531
3532 def _makeResult(self):
3533 return OldTextResult()
3534
3535 runner = Runner()
3536 runner.run(unittest.TestSuite())
3537
3538 def test_startTestRun_stopTestRun_called(self):
3539 class LoggingTextResult(LoggingResult):
3540 separator2 = ''
3541 def printErrors(self):
3542 pass
3543
3544 class LoggingRunner(unittest.TextTestRunner):
3545 def __init__(self, events):
3546 super(LoggingRunner, self).__init__(StringIO())
3547 self._events = events
3548
3549 def _makeResult(self):
3550 return LoggingTextResult(self._events)
3551
3552 events = []
3553 runner = LoggingRunner(events)
3554 runner.run(unittest.TestSuite())
3555 expected = ['startTestRun', 'stopTestRun']
3556 self.assertEqual(events, expected)
3557
Antoine Pitrou0734c632009-11-10 20:49:30 +00003558 def test_pickle_unpickle(self):
3559 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3560 # required by test_multiprocessing under Windows (in verbose mode).
3561 import StringIO
3562 # cStringIO objects are not pickleable, but StringIO objects are.
3563 stream = StringIO.StringIO("foo")
3564 runner = unittest.TextTestRunner(stream)
3565 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
3566 s = pickle.dumps(runner, protocol=protocol)
3567 obj = pickle.loads(s)
3568 # StringIO objects never compare equal, a cheap test instead.
3569 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3570
Michael Foorddb43b5a2010-02-10 14:25:12 +00003571 def test_resultclass(self):
3572 def MockResultClass(*args):
3573 return args
3574 STREAM = object()
3575 DESCRIPTIONS = object()
3576 VERBOSITY = object()
3577 runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY,
3578 resultclass=MockResultClass)
3579 self.assertEqual(runner.resultclass, MockResultClass)
3580
3581 expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY)
3582 self.assertEqual(runner._makeResult(), expectedresult)
3583
Michael Foord07ef4872009-05-02 22:43:34 +00003584
Michael Foordb4a81c82009-05-29 20:33:46 +00003585class TestDiscovery(TestCase):
3586
3587 # Heavily mocked tests so I can avoid hitting the filesystem
Michael Foorde91ea562009-09-13 19:07:03 +00003588 def test_get_name_from_path(self):
Michael Foordb4a81c82009-05-29 20:33:46 +00003589 loader = unittest.TestLoader()
3590
Michael Foordb4a81c82009-05-29 20:33:46 +00003591 loader._top_level_dir = '/foo'
Michael Foorde91ea562009-09-13 19:07:03 +00003592 name = loader._get_name_from_path('/foo/bar/baz.py')
3593 self.assertEqual(name, 'bar.baz')
Michael Foordb4a81c82009-05-29 20:33:46 +00003594
3595 if not __debug__:
3596 # asserts are off
3597 return
3598
3599 with self.assertRaises(AssertionError):
Michael Foorde91ea562009-09-13 19:07:03 +00003600 loader._get_name_from_path('/bar/baz.py')
Michael Foordb4a81c82009-05-29 20:33:46 +00003601
3602 def test_find_tests(self):
3603 loader = unittest.TestLoader()
3604
3605 original_listdir = os.listdir
3606 def restore_listdir():
3607 os.listdir = original_listdir
3608 original_isfile = os.path.isfile
3609 def restore_isfile():
3610 os.path.isfile = original_isfile
3611 original_isdir = os.path.isdir
3612 def restore_isdir():
3613 os.path.isdir = original_isdir
3614
3615 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Michael Foorde91ea562009-09-13 19:07:03 +00003616 'test.foo', 'test-not-a-module.py', 'another_dir'],
Michael Foordb4a81c82009-05-29 20:33:46 +00003617 ['test3.py', 'test4.py', ]]
3618 os.listdir = lambda path: path_lists.pop(0)
3619 self.addCleanup(restore_listdir)
3620
3621 def isdir(path):
3622 return path.endswith('dir')
3623 os.path.isdir = isdir
3624 self.addCleanup(restore_isdir)
3625
3626 def isfile(path):
3627 # another_dir is not a package and so shouldn't be recursed into
3628 return not path.endswith('dir') and not 'another_dir' in path
3629 os.path.isfile = isfile
3630 self.addCleanup(restore_isfile)
3631
Michael Foorde91ea562009-09-13 19:07:03 +00003632 loader._get_module_from_name = lambda path: path + ' module'
Michael Foordb4a81c82009-05-29 20:33:46 +00003633 loader.loadTestsFromModule = lambda module: module + ' tests'
3634
3635 loader._top_level_dir = '/foo'
3636 suite = list(loader._find_tests('/foo', 'test*.py'))
3637
Michael Foorde91ea562009-09-13 19:07:03 +00003638 expected = [name + ' module tests' for name in
3639 ('test1', 'test2')]
3640 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3641 ('test3', 'test4')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003642 self.assertEqual(suite, expected)
3643
3644 def test_find_tests_with_package(self):
3645 loader = unittest.TestLoader()
3646
3647 original_listdir = os.listdir
3648 def restore_listdir():
3649 os.listdir = original_listdir
3650 original_isfile = os.path.isfile
3651 def restore_isfile():
3652 os.path.isfile = original_isfile
3653 original_isdir = os.path.isdir
3654 def restore_isdir():
3655 os.path.isdir = original_isdir
3656
3657 directories = ['a_directory', 'test_directory', 'test_directory2']
3658 path_lists = [directories, [], [], []]
3659 os.listdir = lambda path: path_lists.pop(0)
3660 self.addCleanup(restore_listdir)
3661
3662 os.path.isdir = lambda path: True
3663 self.addCleanup(restore_isdir)
3664
3665 os.path.isfile = lambda path: os.path.basename(path) not in directories
3666 self.addCleanup(restore_isfile)
3667
3668 class Module(object):
3669 paths = []
3670 load_tests_args = []
3671
3672 def __init__(self, path):
3673 self.path = path
3674 self.paths.append(path)
3675 if os.path.basename(path) == 'test_directory':
3676 def load_tests(loader, tests, pattern):
3677 self.load_tests_args.append((loader, tests, pattern))
3678 return 'load_tests'
3679 self.load_tests = load_tests
3680
3681 def __eq__(self, other):
3682 return self.path == other.path
3683
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003684 # Silence py3k warning
3685 __hash__ = None
3686
Michael Foorde91ea562009-09-13 19:07:03 +00003687 loader._get_module_from_name = lambda name: Module(name)
Michael Foordb4a81c82009-05-29 20:33:46 +00003688 def loadTestsFromModule(module, use_load_tests):
3689 if use_load_tests:
3690 raise self.failureException('use_load_tests should be False for packages')
3691 return module.path + ' module tests'
3692 loader.loadTestsFromModule = loadTestsFromModule
3693
3694 loader._top_level_dir = '/foo'
3695 # this time no '.py' on the pattern so that it can match
3696 # a test package
3697 suite = list(loader._find_tests('/foo', 'test*'))
3698
3699 # We should have loaded tests from the test_directory package by calling load_tests
3700 # and directly from the test_directory2 package
Michael Foordd53d0852009-06-05 14:14:34 +00003701 self.assertEqual(suite,
Michael Foorde91ea562009-09-13 19:07:03 +00003702 ['load_tests', 'test_directory2' + ' module tests'])
3703 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Michael Foordb4a81c82009-05-29 20:33:46 +00003704
3705 # load_tests should have been called once with loader, tests and pattern
3706 self.assertEqual(Module.load_tests_args,
Michael Foorde91ea562009-09-13 19:07:03 +00003707 [(loader, 'test_directory' + ' module tests', 'test*')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003708
3709 def test_discover(self):
3710 loader = unittest.TestLoader()
3711
3712 original_isfile = os.path.isfile
3713 def restore_isfile():
3714 os.path.isfile = original_isfile
3715
3716 os.path.isfile = lambda path: False
3717 self.addCleanup(restore_isfile)
3718
Nick Coghlanb6edf192009-10-17 08:21:21 +00003719 orig_sys_path = sys.path[:]
3720 def restore_path():
3721 sys.path[:] = orig_sys_path
3722 self.addCleanup(restore_path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003723
Nick Coghlanb6edf192009-10-17 08:21:21 +00003724 full_path = os.path.abspath(os.path.normpath('/foo'))
Michael Foordb4a81c82009-05-29 20:33:46 +00003725 with self.assertRaises(ImportError):
3726 loader.discover('/foo/bar', top_level_dir='/foo')
3727
3728 self.assertEqual(loader._top_level_dir, full_path)
3729 self.assertIn(full_path, sys.path)
3730
3731 os.path.isfile = lambda path: True
3732 _find_tests_args = []
3733 def _find_tests(start_dir, pattern):
3734 _find_tests_args.append((start_dir, pattern))
3735 return ['tests']
3736 loader._find_tests = _find_tests
3737 loader.suiteClass = str
3738
3739 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3740
3741 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3742 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3743 self.assertEqual(suite, "['tests']")
3744 self.assertEqual(loader._top_level_dir, top_level_dir)
3745 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlanb6edf192009-10-17 08:21:21 +00003746 self.assertIn(top_level_dir, sys.path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003747
Michael Foorde91ea562009-09-13 19:07:03 +00003748 def test_discover_with_modules_that_fail_to_import(self):
3749 loader = unittest.TestLoader()
3750
3751 listdir = os.listdir
3752 os.listdir = lambda _: ['test_this_does_not_exist.py']
3753 isfile = os.path.isfile
3754 os.path.isfile = lambda _: True
Nick Coghlanb6edf192009-10-17 08:21:21 +00003755 orig_sys_path = sys.path[:]
Michael Foorde91ea562009-09-13 19:07:03 +00003756 def restore():
3757 os.path.isfile = isfile
3758 os.listdir = listdir
Nick Coghlanb6edf192009-10-17 08:21:21 +00003759 sys.path[:] = orig_sys_path
Michael Foorde91ea562009-09-13 19:07:03 +00003760 self.addCleanup(restore)
3761
3762 suite = loader.discover('.')
Nick Coghlanb6edf192009-10-17 08:21:21 +00003763 self.assertIn(os.getcwd(), sys.path)
Michael Foorde91ea562009-09-13 19:07:03 +00003764 self.assertEqual(suite.countTestCases(), 1)
3765 test = list(list(suite)[0])[0] # extract test from suite
3766
3767 with self.assertRaises(ImportError):
3768 test.test_this_does_not_exist()
3769
Michael Foordb4a81c82009-05-29 20:33:46 +00003770 def test_command_line_handling_parseArgs(self):
3771 # Haha - take that uninstantiable class
3772 program = object.__new__(TestProgram)
3773
3774 args = []
3775 def do_discovery(argv):
3776 args.extend(argv)
3777 program._do_discovery = do_discovery
3778 program.parseArgs(['something', 'discover'])
3779 self.assertEqual(args, [])
3780
3781 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3782 self.assertEqual(args, ['foo', 'bar'])
3783
3784 def test_command_line_handling_do_discovery_too_many_arguments(self):
3785 class Stop(Exception):
3786 pass
3787 def usageExit():
3788 raise Stop
3789
3790 program = object.__new__(TestProgram)
3791 program.usageExit = usageExit
3792
3793 with self.assertRaises(Stop):
3794 # too many args
3795 program._do_discovery(['one', 'two', 'three', 'four'])
3796
3797
3798 def test_command_line_handling_do_discovery_calls_loader(self):
3799 program = object.__new__(TestProgram)
3800
3801 class Loader(object):
3802 args = []
3803 def discover(self, start_dir, pattern, top_level_dir):
3804 self.args.append((start_dir, pattern, top_level_dir))
3805 return 'tests'
3806
3807 program._do_discovery(['-v'], Loader=Loader)
3808 self.assertEqual(program.verbosity, 2)
3809 self.assertEqual(program.test, 'tests')
3810 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3811
3812 Loader.args = []
3813 program = object.__new__(TestProgram)
3814 program._do_discovery(['--verbose'], Loader=Loader)
3815 self.assertEqual(program.test, 'tests')
3816 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3817
3818 Loader.args = []
3819 program = object.__new__(TestProgram)
3820 program._do_discovery([], Loader=Loader)
3821 self.assertEqual(program.test, 'tests')
3822 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3823
3824 Loader.args = []
3825 program = object.__new__(TestProgram)
3826 program._do_discovery(['fish'], Loader=Loader)
3827 self.assertEqual(program.test, 'tests')
3828 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3829
3830 Loader.args = []
3831 program = object.__new__(TestProgram)
3832 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3833 self.assertEqual(program.test, 'tests')
3834 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3835
3836 Loader.args = []
3837 program = object.__new__(TestProgram)
3838 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3839 self.assertEqual(program.test, 'tests')
3840 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3841
3842 Loader.args = []
3843 program = object.__new__(TestProgram)
3844 program._do_discovery(['-s', 'fish'], Loader=Loader)
3845 self.assertEqual(program.test, 'tests')
3846 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3847
3848 Loader.args = []
3849 program = object.__new__(TestProgram)
3850 program._do_discovery(['-t', 'fish'], Loader=Loader)
3851 self.assertEqual(program.test, 'tests')
3852 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3853
3854 Loader.args = []
3855 program = object.__new__(TestProgram)
3856 program._do_discovery(['-p', 'fish'], Loader=Loader)
3857 self.assertEqual(program.test, 'tests')
3858 self.assertEqual(Loader.args, [('.', 'fish', None)])
3859
3860 Loader.args = []
3861 program = object.__new__(TestProgram)
3862 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3863 self.assertEqual(program.test, 'tests')
3864 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3865 self.assertEqual(program.verbosity, 2)
3866
3867
Jim Fultonfafd8742004-08-28 15:22:12 +00003868######################################################################
3869## Main
3870######################################################################
3871
3872def test_main():
Georg Brandl15c5ce92007-03-07 09:09:40 +00003873 test_support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003874 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Michael Foord829f6b82009-05-02 11:43:06 +00003875 Test_TestSkipping, Test_Assertions, TestLongMessage,
Michael Foordae3db0a2010-02-22 23:28:32 +00003876 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner,
3877 Test_OldTestResult)
Jim Fultonfafd8742004-08-28 15:22:12 +00003878
Georg Brandl15c5ce92007-03-07 09:09:40 +00003879if __name__ == "__main__":
Tim Petersea5962f2007-03-12 18:07:52 +00003880 test_main()