blob: 8314262cd96ab9c2ac45d74628c9495f89bce50c [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 Foord07ef4872009-05-02 22:43:34 +00009from StringIO import StringIO
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +000010import __builtin__
Michael Foordb4a81c82009-05-29 20:33:46 +000011import os
Gregory P. Smith28399852009-03-31 16:54:10 +000012import re
Michael Foordb4a81c82009-05-29 20:33:46 +000013import sys
Georg Brandl15c5ce92007-03-07 09:09:40 +000014from test import test_support
Jim Fultonfafd8742004-08-28 15:22:12 +000015import unittest
Michael Foord829f6b82009-05-02 11:43:06 +000016from unittest import TestCase, TestProgram
Christian Heimesc756d002007-11-27 21:34:01 +000017import types
Michael Foorde2942d02009-04-02 05:51:54 +000018from copy import deepcopy
Michael Foord829f6b82009-05-02 11:43:06 +000019from cStringIO import StringIO
Antoine Pitrou0734c632009-11-10 20:49:30 +000020import pickle
Jim Fultonfafd8742004-08-28 15:22:12 +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 import sys
630 if module_name in sys.modules:
631 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000632
Georg Brandl15c5ce92007-03-07 09:09:40 +0000633 loader = unittest.TestLoader()
634 try:
635 suite = loader.loadTestsFromName(module_name)
636
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000637 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000638 self.assertEqual(list(suite), [])
639
640 # audioop should now be loaded, thanks to loadTestsFromName()
Ezio Melottiaa980582010-01-23 23:04:36 +0000641 self.assertIn(module_name, sys.modules)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000642 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000643 if module_name in sys.modules:
644 del sys.modules[module_name]
Georg Brandl15c5ce92007-03-07 09:09:40 +0000645
646 ################################################################
647 ### Tests for TestLoader.loadTestsFromName()
648
649 ### Tests for TestLoader.loadTestsFromNames()
650 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000651
Georg Brandl15c5ce92007-03-07 09:09:40 +0000652 # "Similar to loadTestsFromName(), but takes a sequence of names rather
653 # than a single name."
654 #
655 # What happens if that sequence of names is empty?
656 def test_loadTestsFromNames__empty_name_list(self):
657 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000658
Georg Brandl15c5ce92007-03-07 09:09:40 +0000659 suite = loader.loadTestsFromNames([])
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000660 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000661 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000662
Georg Brandl15c5ce92007-03-07 09:09:40 +0000663 # "Similar to loadTestsFromName(), but takes a sequence of names rather
664 # than a single name."
665 # ...
666 # "The method optionally resolves name relative to the given module"
667 #
668 # What happens if that sequence of names is empty?
669 #
670 # XXX Should this raise a ValueError or just return an empty TestSuite?
671 def test_loadTestsFromNames__relative_empty_name_list(self):
672 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000673
Georg Brandl15c5ce92007-03-07 09:09:40 +0000674 suite = loader.loadTestsFromNames([], unittest)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000675 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000676 self.assertEqual(list(suite), [])
677
678 # "The specifier name is a ``dotted name'' that may resolve either to
679 # a module, a test case class, a TestSuite instance, a test method
680 # within a test case class, or a callable object which returns a
681 # TestCase or TestSuite instance."
682 #
683 # Is ValueError raised in response to an empty name?
684 def test_loadTestsFromNames__empty_name(self):
685 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000686
Georg Brandl15c5ce92007-03-07 09:09:40 +0000687 try:
688 loader.loadTestsFromNames([''])
689 except ValueError, e:
690 self.assertEqual(str(e), "Empty module name")
691 else:
692 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000693
Georg Brandl15c5ce92007-03-07 09:09:40 +0000694 # "The specifier name is a ``dotted name'' that may resolve either to
695 # a module, a test case class, a TestSuite instance, a test method
696 # within a test case class, or a callable object which returns a
697 # TestCase or TestSuite instance."
698 #
Tim Petersea5962f2007-03-12 18:07:52 +0000699 # What happens when presented with an impossible module name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000700 def test_loadTestsFromNames__malformed_name(self):
701 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000702
Georg Brandl15c5ce92007-03-07 09:09:40 +0000703 # XXX Should this raise ValueError or ImportError?
704 try:
705 loader.loadTestsFromNames(['abc () //'])
706 except ValueError:
707 pass
708 except ImportError:
709 pass
710 else:
711 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000712
Georg Brandl15c5ce92007-03-07 09:09:40 +0000713 # "The specifier name is a ``dotted name'' that may resolve either to
714 # a module, a test case class, a TestSuite instance, a test method
715 # within a test case class, or a callable object which returns a
716 # TestCase or TestSuite instance."
717 #
Tim Petersea5962f2007-03-12 18:07:52 +0000718 # What happens when no module can be found for the given name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000719 def test_loadTestsFromNames__unknown_module_name(self):
720 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000721
Georg Brandl15c5ce92007-03-07 09:09:40 +0000722 try:
723 loader.loadTestsFromNames(['sdasfasfasdf'])
724 except ImportError, e:
725 self.assertEqual(str(e), "No module named sdasfasfasdf")
726 else:
727 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000728
Georg Brandl15c5ce92007-03-07 09:09:40 +0000729 # "The specifier name is a ``dotted name'' that may resolve either to
730 # a module, a test case class, a TestSuite instance, a test method
731 # within a test case class, or a callable object which returns a
732 # TestCase or TestSuite instance."
733 #
Tim Petersea5962f2007-03-12 18:07:52 +0000734 # What happens when the module can be found, but not the attribute?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000735 def test_loadTestsFromNames__unknown_attr_name(self):
736 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000737
Georg Brandl15c5ce92007-03-07 09:09:40 +0000738 try:
739 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
740 except AttributeError, e:
741 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
742 else:
743 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000744
Georg Brandl15c5ce92007-03-07 09:09:40 +0000745 # "The specifier name is a ``dotted name'' that may resolve either to
746 # a module, a test case class, a TestSuite instance, a test method
747 # within a test case class, or a callable object which returns a
748 # TestCase or TestSuite instance."
749 # ...
750 # "The method optionally resolves name relative to the given module"
751 #
752 # What happens when given an unknown attribute on a specified `module`
753 # argument?
754 def test_loadTestsFromNames__unknown_name_relative_1(self):
755 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000756
Georg Brandl15c5ce92007-03-07 09:09:40 +0000757 try:
758 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
759 except AttributeError, e:
760 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
761 else:
762 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000763
Georg Brandl15c5ce92007-03-07 09:09:40 +0000764 # "The specifier name is a ``dotted name'' that may resolve either to
765 # a module, a test case class, a TestSuite instance, a test method
766 # within a test case class, or a callable object which returns a
767 # TestCase or TestSuite instance."
768 # ...
769 # "The method optionally resolves name relative to the given module"
770 #
771 # Do unknown attributes (relative to a provided module) still raise an
Tim Petersea5962f2007-03-12 18:07:52 +0000772 # exception even in the presence of valid attribute names?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000773 def test_loadTestsFromNames__unknown_name_relative_2(self):
774 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000775
Georg Brandl15c5ce92007-03-07 09:09:40 +0000776 try:
777 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
778 except AttributeError, e:
779 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
780 else:
781 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
782
783 # "The specifier name is a ``dotted name'' that may resolve either to
784 # a module, a test case class, a TestSuite instance, a test method
785 # within a test case class, or a callable object which returns a
786 # TestCase or TestSuite instance."
787 # ...
788 # "The method optionally resolves name relative to the given module"
789 #
790 # What happens when faced with the empty string?
791 #
792 # XXX This currently raises AttributeError, though ValueError is probably
793 # more appropriate
794 def test_loadTestsFromNames__relative_empty_name(self):
795 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000796
Georg Brandl15c5ce92007-03-07 09:09:40 +0000797 try:
798 loader.loadTestsFromNames([''], unittest)
799 except AttributeError:
800 pass
801 else:
802 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000803
Georg Brandl15c5ce92007-03-07 09:09:40 +0000804 # "The specifier name is a ``dotted name'' that may resolve either to
805 # a module, a test case class, a TestSuite instance, a test method
806 # within a test case class, or a callable object which returns a
807 # TestCase or TestSuite instance."
808 # ...
809 # "The method optionally resolves name relative to the given module"
810 #
Tim Petersea5962f2007-03-12 18:07:52 +0000811 # What happens when presented with an impossible attribute name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000812 def test_loadTestsFromNames__relative_malformed_name(self):
813 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000814
Georg Brandl15c5ce92007-03-07 09:09:40 +0000815 # XXX Should this raise AttributeError or ValueError?
816 try:
817 loader.loadTestsFromNames(['abc () //'], unittest)
818 except AttributeError:
819 pass
820 except ValueError:
821 pass
822 else:
823 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
824
825 # "The method optionally resolves name relative to the given module"
826 #
827 # Does loadTestsFromNames() make sure the provided `module` is in fact
828 # a module?
829 #
830 # XXX This validation is currently not done. This flexibility should
831 # either be documented or a TypeError should be raised.
832 def test_loadTestsFromNames__relative_not_a_module(self):
833 class MyTestCase(unittest.TestCase):
834 def test(self):
835 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000836
Georg Brandl15c5ce92007-03-07 09:09:40 +0000837 class NotAModule(object):
838 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000839
Georg Brandl15c5ce92007-03-07 09:09:40 +0000840 loader = unittest.TestLoader()
841 suite = loader.loadTestsFromNames(['test_2'], NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000842
Georg Brandl15c5ce92007-03-07 09:09:40 +0000843 reference = [unittest.TestSuite([MyTestCase('test')])]
844 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000845
Georg Brandl15c5ce92007-03-07 09:09:40 +0000846 # "The specifier name is a ``dotted name'' that may resolve either to
847 # a module, a test case class, a TestSuite instance, a test method
848 # within a test case class, or a callable object which returns a
849 # TestCase or TestSuite instance."
850 #
851 # Does it raise an exception if the name resolves to an invalid
852 # object?
853 def test_loadTestsFromNames__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000854 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000855 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000856
Georg Brandl15c5ce92007-03-07 09:09:40 +0000857 loader = unittest.TestLoader()
858 try:
859 loader.loadTestsFromNames(['testcase_1'], m)
860 except TypeError:
861 pass
862 else:
863 self.fail("Should have raised TypeError")
864
865 # "The specifier name is a ``dotted name'' that may resolve ... to
866 # ... a test case class"
867 def test_loadTestsFromNames__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000868 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000869 class MyTestCase(unittest.TestCase):
870 def test(self):
871 pass
872 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000873
Georg Brandl15c5ce92007-03-07 09:09:40 +0000874 loader = unittest.TestLoader()
875 suite = loader.loadTestsFromNames(['testcase_1'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000876 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000877
Georg Brandl15c5ce92007-03-07 09:09:40 +0000878 expected = loader.suiteClass([MyTestCase('test')])
879 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000880
Georg Brandl15c5ce92007-03-07 09:09:40 +0000881 # "The specifier name is a ``dotted name'' that may resolve ... to
882 # ... a TestSuite instance"
883 def test_loadTestsFromNames__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000884 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000885 class MyTestCase(unittest.TestCase):
886 def test(self):
887 pass
888 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000889
Georg Brandl15c5ce92007-03-07 09:09:40 +0000890 loader = unittest.TestLoader()
891 suite = loader.loadTestsFromNames(['testsuite'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000892 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000893
Georg Brandl15c5ce92007-03-07 09:09:40 +0000894 self.assertEqual(list(suite), [m.testsuite])
Tim Petersea5962f2007-03-12 18:07:52 +0000895
Georg Brandl15c5ce92007-03-07 09:09:40 +0000896 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
897 # test method within a test case class"
898 def test_loadTestsFromNames__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000899 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000900 class MyTestCase(unittest.TestCase):
901 def test(self):
902 pass
903 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000904
Georg Brandl15c5ce92007-03-07 09:09:40 +0000905 loader = unittest.TestLoader()
906 suite = loader.loadTestsFromNames(['testcase_1.test'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000907 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000908
Georg Brandl15c5ce92007-03-07 09:09:40 +0000909 ref_suite = unittest.TestSuite([MyTestCase('test')])
910 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000911
Georg Brandl15c5ce92007-03-07 09:09:40 +0000912 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
913 # test method within a test case class"
914 #
915 # Does the method gracefully handle names that initially look like they
Tim Petersea5962f2007-03-12 18:07:52 +0000916 # resolve to "a test method within a test case class" but don't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000917 def test_loadTestsFromNames__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000918 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000919 class MyTestCase(unittest.TestCase):
920 def test(self):
921 pass
922 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000923
Georg Brandl15c5ce92007-03-07 09:09:40 +0000924 loader = unittest.TestLoader()
925 try:
926 loader.loadTestsFromNames(['testcase_1.testfoo'], m)
927 except AttributeError, e:
928 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
929 else:
930 self.fail("Failed to raise AttributeError")
931
932 # "The specifier name is a ``dotted name'' that may resolve ... to
933 # ... a callable object which returns a ... TestSuite instance"
934 def test_loadTestsFromNames__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000935 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000936 testcase_1 = unittest.FunctionTestCase(lambda: None)
937 testcase_2 = unittest.FunctionTestCase(lambda: None)
938 def return_TestSuite():
939 return unittest.TestSuite([testcase_1, testcase_2])
940 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000941
Georg Brandl15c5ce92007-03-07 09:09:40 +0000942 loader = unittest.TestLoader()
943 suite = loader.loadTestsFromNames(['return_TestSuite'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000944 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000945
Georg Brandl15c5ce92007-03-07 09:09:40 +0000946 expected = unittest.TestSuite([testcase_1, testcase_2])
947 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000948
Georg Brandl15c5ce92007-03-07 09:09:40 +0000949 # "The specifier name is a ``dotted name'' that may resolve ... to
950 # ... a callable object which returns a TestCase ... instance"
951 def test_loadTestsFromNames__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000952 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000953 testcase_1 = unittest.FunctionTestCase(lambda: None)
954 def return_TestCase():
955 return testcase_1
956 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000957
Georg Brandl15c5ce92007-03-07 09:09:40 +0000958 loader = unittest.TestLoader()
959 suite = loader.loadTestsFromNames(['return_TestCase'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000960 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000961
Georg Brandl15c5ce92007-03-07 09:09:40 +0000962 ref_suite = unittest.TestSuite([testcase_1])
963 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000964
Georg Brandl15c5ce92007-03-07 09:09:40 +0000965 # "The specifier name is a ``dotted name'' that may resolve ... to
966 # ... a callable object which returns a TestCase or TestSuite instance"
967 #
Tim Petersea5962f2007-03-12 18:07:52 +0000968 # Are staticmethods handled correctly?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000969 def test_loadTestsFromNames__callable__call_staticmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000970 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000971 class Test1(unittest.TestCase):
972 def test(self):
973 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000974
Georg Brandl15c5ce92007-03-07 09:09:40 +0000975 testcase_1 = Test1('test')
976 class Foo(unittest.TestCase):
977 @staticmethod
978 def foo():
979 return testcase_1
980 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +0000981
Georg Brandl15c5ce92007-03-07 09:09:40 +0000982 loader = unittest.TestLoader()
983 suite = loader.loadTestsFromNames(['Foo.foo'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000984 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000985
Georg Brandl15c5ce92007-03-07 09:09:40 +0000986 ref_suite = unittest.TestSuite([testcase_1])
987 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000988
Georg Brandl15c5ce92007-03-07 09:09:40 +0000989 # "The specifier name is a ``dotted name'' that may resolve ... to
990 # ... a callable object which returns a TestCase or TestSuite instance"
991 #
992 # What happens when the callable returns something else?
993 def test_loadTestsFromNames__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000994 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000995 def return_wrong():
996 return 6
997 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000998
Georg Brandl15c5ce92007-03-07 09:09:40 +0000999 loader = unittest.TestLoader()
1000 try:
1001 suite = loader.loadTestsFromNames(['return_wrong'], m)
1002 except TypeError:
1003 pass
1004 else:
1005 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +00001006
Georg Brandl15c5ce92007-03-07 09:09:40 +00001007 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +00001008 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001009 def test_loadTestsFromNames__module_not_loaded(self):
1010 # We're going to try to load this module as a side-effect, so it
1011 # better not be loaded before we try.
1012 #
1013 # Why pick audioop? Google shows it isn't used very often, so there's
1014 # a good chance that it won't be imported when this test is run
1015 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +00001016
Georg Brandl15c5ce92007-03-07 09:09:40 +00001017 import sys
1018 if module_name in sys.modules:
1019 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +00001020
Georg Brandl15c5ce92007-03-07 09:09:40 +00001021 loader = unittest.TestLoader()
1022 try:
1023 suite = loader.loadTestsFromNames([module_name])
1024
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001025 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +00001026 self.assertEqual(list(suite), [unittest.TestSuite()])
1027
1028 # audioop should now be loaded, thanks to loadTestsFromName()
Ezio Melottiaa980582010-01-23 23:04:36 +00001029 self.assertIn(module_name, sys.modules)
Georg Brandl15c5ce92007-03-07 09:09:40 +00001030 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +00001031 if module_name in sys.modules:
1032 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +00001033
Georg Brandl15c5ce92007-03-07 09:09:40 +00001034 ################################################################
1035 ### /Tests for TestLoader.loadTestsFromNames()
1036
1037 ### Tests for TestLoader.getTestCaseNames()
1038 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001039
Georg Brandl15c5ce92007-03-07 09:09:40 +00001040 # "Return a sorted sequence of method names found within testCaseClass"
1041 #
1042 # Test.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +00001043 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +00001044 def test_getTestCaseNames(self):
1045 class Test(unittest.TestCase):
1046 def test_1(self): pass
1047 def test_2(self): pass
1048 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001049
Georg Brandl15c5ce92007-03-07 09:09:40 +00001050 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001051
Georg Brandl15c5ce92007-03-07 09:09:40 +00001052 self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])
Tim Petersea5962f2007-03-12 18:07:52 +00001053
Georg Brandl15c5ce92007-03-07 09:09:40 +00001054 # "Return a sorted sequence of method names found within testCaseClass"
1055 #
Tim Petersea5962f2007-03-12 18:07:52 +00001056 # Does getTestCaseNames() behave appropriately if no tests are found?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001057 def test_getTestCaseNames__no_tests(self):
1058 class Test(unittest.TestCase):
1059 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001060
Georg Brandl15c5ce92007-03-07 09:09:40 +00001061 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001062
Georg Brandl15c5ce92007-03-07 09:09:40 +00001063 self.assertEqual(loader.getTestCaseNames(Test), [])
Tim Petersea5962f2007-03-12 18:07:52 +00001064
Georg Brandl15c5ce92007-03-07 09:09:40 +00001065 # "Return a sorted sequence of method names found within testCaseClass"
1066 #
1067 # Are not-TestCases handled gracefully?
1068 #
1069 # XXX This should raise a TypeError, not return a list
1070 #
1071 # XXX It's too late in the 2.5 release cycle to fix this, but it should
1072 # probably be revisited for 2.6
1073 def test_getTestCaseNames__not_a_TestCase(self):
1074 class BadCase(int):
1075 def test_foo(self):
1076 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001077
Georg Brandl15c5ce92007-03-07 09:09:40 +00001078 loader = unittest.TestLoader()
1079 names = loader.getTestCaseNames(BadCase)
Tim Petersea5962f2007-03-12 18:07:52 +00001080
Georg Brandl15c5ce92007-03-07 09:09:40 +00001081 self.assertEqual(names, ['test_foo'])
Tim Petersea5962f2007-03-12 18:07:52 +00001082
Georg Brandl15c5ce92007-03-07 09:09:40 +00001083 # "Return a sorted sequence of method names found within testCaseClass"
1084 #
1085 # Make sure inherited names are handled.
1086 #
1087 # TestP.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +00001088 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +00001089 def test_getTestCaseNames__inheritance(self):
1090 class TestP(unittest.TestCase):
1091 def test_1(self): pass
1092 def test_2(self): pass
1093 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001094
Georg Brandl15c5ce92007-03-07 09:09:40 +00001095 class TestC(TestP):
1096 def test_1(self): pass
1097 def test_3(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001098
Georg Brandl15c5ce92007-03-07 09:09:40 +00001099 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001100
Georg Brandl15c5ce92007-03-07 09:09:40 +00001101 names = ['test_1', 'test_2', 'test_3']
1102 self.assertEqual(loader.getTestCaseNames(TestC), names)
Tim Petersea5962f2007-03-12 18:07:52 +00001103
1104 ################################################################
Georg Brandl15c5ce92007-03-07 09:09:40 +00001105 ### /Tests for TestLoader.getTestCaseNames()
1106
1107 ### Tests for TestLoader.testMethodPrefix
1108 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001109
Georg Brandl15c5ce92007-03-07 09:09:40 +00001110 # "String giving the prefix of method names which will be interpreted as
1111 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001112 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001113 # Implicit in the documentation is that testMethodPrefix is respected by
1114 # all loadTestsFrom* methods.
1115 def test_testMethodPrefix__loadTestsFromTestCase(self):
1116 class Foo(unittest.TestCase):
1117 def test_1(self): pass
1118 def test_2(self): pass
1119 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001120
Georg Brandl15c5ce92007-03-07 09:09:40 +00001121 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1122 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001123
Georg Brandl15c5ce92007-03-07 09:09:40 +00001124 loader = unittest.TestLoader()
1125 loader.testMethodPrefix = 'foo'
1126 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
1127
1128 loader.testMethodPrefix = 'test'
1129 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001130
Georg Brandl15c5ce92007-03-07 09:09:40 +00001131 # "String giving the prefix of method names which will be interpreted as
1132 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001133 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001134 # Implicit in the documentation is that testMethodPrefix is respected by
1135 # all loadTestsFrom* methods.
1136 def test_testMethodPrefix__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001137 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001138 class Foo(unittest.TestCase):
1139 def test_1(self): pass
1140 def test_2(self): pass
1141 def foo_bar(self): pass
1142 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001143
Georg Brandl15c5ce92007-03-07 09:09:40 +00001144 tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
1145 tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]
Tim Petersea5962f2007-03-12 18:07:52 +00001146
Georg Brandl15c5ce92007-03-07 09:09:40 +00001147 loader = unittest.TestLoader()
1148 loader.testMethodPrefix = 'foo'
1149 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
1150
1151 loader.testMethodPrefix = 'test'
1152 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001153
Georg Brandl15c5ce92007-03-07 09:09:40 +00001154 # "String giving the prefix of method names which will be interpreted as
1155 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001156 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001157 # Implicit in the documentation is that testMethodPrefix is respected by
1158 # all loadTestsFrom* methods.
1159 def test_testMethodPrefix__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001160 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001161 class Foo(unittest.TestCase):
1162 def test_1(self): pass
1163 def test_2(self): pass
1164 def foo_bar(self): pass
1165 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001166
Georg Brandl15c5ce92007-03-07 09:09:40 +00001167 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1168 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001169
Georg Brandl15c5ce92007-03-07 09:09:40 +00001170 loader = unittest.TestLoader()
1171 loader.testMethodPrefix = 'foo'
1172 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
1173
1174 loader.testMethodPrefix = 'test'
1175 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001176
Georg Brandl15c5ce92007-03-07 09:09:40 +00001177 # "String giving the prefix of method names which will be interpreted as
1178 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001179 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001180 # Implicit in the documentation is that testMethodPrefix is respected by
1181 # all loadTestsFrom* methods.
1182 def test_testMethodPrefix__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001183 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001184 class Foo(unittest.TestCase):
1185 def test_1(self): pass
1186 def test_2(self): pass
1187 def foo_bar(self): pass
1188 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001189
Georg Brandl15c5ce92007-03-07 09:09:40 +00001190 tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
1191 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1192 tests_2 = unittest.TestSuite([tests_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001193
Georg Brandl15c5ce92007-03-07 09:09:40 +00001194 loader = unittest.TestLoader()
1195 loader.testMethodPrefix = 'foo'
1196 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)
1197
1198 loader.testMethodPrefix = 'test'
1199 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001200
Georg Brandl15c5ce92007-03-07 09:09:40 +00001201 # "The default value is 'test'"
1202 def test_testMethodPrefix__default_value(self):
1203 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001204 self.assertTrue(loader.testMethodPrefix == 'test')
Tim Petersea5962f2007-03-12 18:07:52 +00001205
Georg Brandl15c5ce92007-03-07 09:09:40 +00001206 ################################################################
1207 ### /Tests for TestLoader.testMethodPrefix
1208
Tim Petersea5962f2007-03-12 18:07:52 +00001209 ### Tests for TestLoader.sortTestMethodsUsing
Georg Brandl15c5ce92007-03-07 09:09:40 +00001210 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001211
Georg Brandl15c5ce92007-03-07 09:09:40 +00001212 # "Function to be used to compare method names when sorting them in
1213 # getTestCaseNames() and all the loadTestsFromX() methods"
1214 def test_sortTestMethodsUsing__loadTestsFromTestCase(self):
1215 def reversed_cmp(x, y):
1216 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001217
Georg Brandl15c5ce92007-03-07 09:09:40 +00001218 class Foo(unittest.TestCase):
1219 def test_1(self): pass
1220 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001221
Georg Brandl15c5ce92007-03-07 09:09:40 +00001222 loader = unittest.TestLoader()
1223 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001224
Georg Brandl15c5ce92007-03-07 09:09:40 +00001225 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1226 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001227
Georg Brandl15c5ce92007-03-07 09:09:40 +00001228 # "Function to be used to compare method names when sorting them in
1229 # getTestCaseNames() and all the loadTestsFromX() methods"
1230 def test_sortTestMethodsUsing__loadTestsFromModule(self):
1231 def reversed_cmp(x, y):
1232 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001233
Christian Heimesc756d002007-11-27 21:34:01 +00001234 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001235 class Foo(unittest.TestCase):
1236 def test_1(self): pass
1237 def test_2(self): pass
1238 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001239
Georg Brandl15c5ce92007-03-07 09:09:40 +00001240 loader = unittest.TestLoader()
1241 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001242
Georg Brandl15c5ce92007-03-07 09:09:40 +00001243 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1244 self.assertEqual(list(loader.loadTestsFromModule(m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001245
Georg Brandl15c5ce92007-03-07 09:09:40 +00001246 # "Function to be used to compare method names when sorting them in
1247 # getTestCaseNames() and all the loadTestsFromX() methods"
1248 def test_sortTestMethodsUsing__loadTestsFromName(self):
1249 def reversed_cmp(x, y):
1250 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001251
Christian Heimesc756d002007-11-27 21:34:01 +00001252 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001253 class Foo(unittest.TestCase):
1254 def test_1(self): pass
1255 def test_2(self): pass
1256 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001257
Georg Brandl15c5ce92007-03-07 09:09:40 +00001258 loader = unittest.TestLoader()
1259 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001260
Georg Brandl15c5ce92007-03-07 09:09:40 +00001261 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1262 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001263
Georg Brandl15c5ce92007-03-07 09:09:40 +00001264 # "Function to be used to compare method names when sorting them in
1265 # getTestCaseNames() and all the loadTestsFromX() methods"
1266 def test_sortTestMethodsUsing__loadTestsFromNames(self):
1267 def reversed_cmp(x, y):
1268 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001269
Christian Heimesc756d002007-11-27 21:34:01 +00001270 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001271 class Foo(unittest.TestCase):
1272 def test_1(self): pass
1273 def test_2(self): pass
1274 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001275
Georg Brandl15c5ce92007-03-07 09:09:40 +00001276 loader = unittest.TestLoader()
1277 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001278
Georg Brandl15c5ce92007-03-07 09:09:40 +00001279 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1280 self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001281
Georg Brandl15c5ce92007-03-07 09:09:40 +00001282 # "Function to be used to compare method names when sorting them in
1283 # getTestCaseNames()"
1284 #
1285 # Does it actually affect getTestCaseNames()?
1286 def test_sortTestMethodsUsing__getTestCaseNames(self):
1287 def reversed_cmp(x, y):
1288 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001289
Georg Brandl15c5ce92007-03-07 09:09:40 +00001290 class Foo(unittest.TestCase):
1291 def test_1(self): pass
1292 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001293
Georg Brandl15c5ce92007-03-07 09:09:40 +00001294 loader = unittest.TestLoader()
1295 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001296
Georg Brandl15c5ce92007-03-07 09:09:40 +00001297 test_names = ['test_2', 'test_1']
1298 self.assertEqual(loader.getTestCaseNames(Foo), test_names)
Tim Petersea5962f2007-03-12 18:07:52 +00001299
Georg Brandl15c5ce92007-03-07 09:09:40 +00001300 # "The default value is the built-in cmp() function"
1301 def test_sortTestMethodsUsing__default_value(self):
1302 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001303 self.assertTrue(loader.sortTestMethodsUsing is cmp)
Tim Petersea5962f2007-03-12 18:07:52 +00001304
Georg Brandl15c5ce92007-03-07 09:09:40 +00001305 # "it can be set to None to disable the sort."
1306 #
1307 # XXX How is this different from reassigning cmp? Are the tests returned
1308 # in a random order or something? This behaviour should die
1309 def test_sortTestMethodsUsing__None(self):
1310 class Foo(unittest.TestCase):
1311 def test_1(self): pass
1312 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001313
Georg Brandl15c5ce92007-03-07 09:09:40 +00001314 loader = unittest.TestLoader()
1315 loader.sortTestMethodsUsing = None
Tim Petersea5962f2007-03-12 18:07:52 +00001316
Georg Brandl15c5ce92007-03-07 09:09:40 +00001317 test_names = ['test_2', 'test_1']
1318 self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))
Tim Petersea5962f2007-03-12 18:07:52 +00001319
Georg Brandl15c5ce92007-03-07 09:09:40 +00001320 ################################################################
1321 ### /Tests for TestLoader.sortTestMethodsUsing
Tim Petersea5962f2007-03-12 18:07:52 +00001322
Georg Brandl15c5ce92007-03-07 09:09:40 +00001323 ### Tests for TestLoader.suiteClass
1324 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001325
Georg Brandl15c5ce92007-03-07 09:09:40 +00001326 # "Callable object that constructs a test suite from a list of tests."
1327 def test_suiteClass__loadTestsFromTestCase(self):
1328 class Foo(unittest.TestCase):
1329 def test_1(self): pass
1330 def test_2(self): pass
1331 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001332
Georg Brandl15c5ce92007-03-07 09:09:40 +00001333 tests = [Foo('test_1'), Foo('test_2')]
1334
1335 loader = unittest.TestLoader()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001336 loader.suiteClass = list
Georg Brandl15c5ce92007-03-07 09:09:40 +00001337 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001338
Georg Brandl15c5ce92007-03-07 09:09:40 +00001339 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001340 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001341 def test_suiteClass__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001342 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001343 class Foo(unittest.TestCase):
1344 def test_1(self): pass
1345 def test_2(self): pass
1346 def foo_bar(self): pass
1347 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001348
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001349 tests = [[Foo('test_1'), Foo('test_2')]]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001350
1351 loader = unittest.TestLoader()
1352 loader.suiteClass = list
1353 self.assertEqual(loader.loadTestsFromModule(m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001354
Georg Brandl15c5ce92007-03-07 09:09:40 +00001355 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001356 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001357 def test_suiteClass__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001358 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001359 class Foo(unittest.TestCase):
1360 def test_1(self): pass
1361 def test_2(self): pass
1362 def foo_bar(self): pass
1363 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001364
Georg Brandl15c5ce92007-03-07 09:09:40 +00001365 tests = [Foo('test_1'), Foo('test_2')]
1366
1367 loader = unittest.TestLoader()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001368 loader.suiteClass = list
Georg Brandl15c5ce92007-03-07 09:09:40 +00001369 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001370
Georg Brandl15c5ce92007-03-07 09:09:40 +00001371 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001372 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001373 def test_suiteClass__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001374 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001375 class Foo(unittest.TestCase):
1376 def test_1(self): pass
1377 def test_2(self): pass
1378 def foo_bar(self): pass
1379 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001380
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001381 tests = [[Foo('test_1'), Foo('test_2')]]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001382
1383 loader = unittest.TestLoader()
1384 loader.suiteClass = list
1385 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001386
Georg Brandl15c5ce92007-03-07 09:09:40 +00001387 # "The default value is the TestSuite class"
1388 def test_suiteClass__default_value(self):
1389 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001390 self.assertTrue(loader.suiteClass is unittest.TestSuite)
Tim Petersea5962f2007-03-12 18:07:52 +00001391
Georg Brandl15c5ce92007-03-07 09:09:40 +00001392 ################################################################
1393 ### /Tests for TestLoader.suiteClass
1394
1395### Support code for Test_TestSuite
1396################################################################
1397
1398class Foo(unittest.TestCase):
1399 def test_1(self): pass
1400 def test_2(self): pass
1401 def test_3(self): pass
1402 def runTest(self): pass
1403
1404def _mk_TestSuite(*names):
1405 return unittest.TestSuite(Foo(n) for n in names)
Tim Petersea5962f2007-03-12 18:07:52 +00001406
Georg Brandl15c5ce92007-03-07 09:09:40 +00001407################################################################
1408### /Support code for Test_TestSuite
1409
1410class Test_TestSuite(TestCase, TestEquality):
1411
1412 ### Set up attributes needed by inherited tests
1413 ################################################################
1414
1415 # Used by TestEquality.test_eq
1416 eq_pairs = [(unittest.TestSuite(), unittest.TestSuite())
1417 ,(unittest.TestSuite(), unittest.TestSuite([]))
1418 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001419
1420 # Used by TestEquality.test_ne
Georg Brandl15c5ce92007-03-07 09:09:40 +00001421 ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1'))
1422 ,(unittest.TestSuite([]), _mk_TestSuite('test_1'))
1423 ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3'))
1424 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001425
Georg Brandl15c5ce92007-03-07 09:09:40 +00001426 ################################################################
1427 ### /Set up attributes needed by inherited tests
1428
1429 ### Tests for TestSuite.__init__
1430 ################################################################
1431
1432 # "class TestSuite([tests])"
1433 #
1434 # The tests iterable should be optional
1435 def test_init__tests_optional(self):
1436 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001437
Georg Brandl15c5ce92007-03-07 09:09:40 +00001438 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001439
Georg Brandl15c5ce92007-03-07 09:09:40 +00001440 # "class TestSuite([tests])"
1441 # ...
1442 # "If tests is given, it must be an iterable of individual test cases
1443 # or other test suites that will be used to build the suite initially"
1444 #
1445 # TestSuite should deal with empty tests iterables by allowing the
Tim Petersea5962f2007-03-12 18:07:52 +00001446 # creation of an empty suite
Georg Brandl15c5ce92007-03-07 09:09:40 +00001447 def test_init__empty_tests(self):
1448 suite = unittest.TestSuite([])
Tim Petersea5962f2007-03-12 18:07:52 +00001449
Georg Brandl15c5ce92007-03-07 09:09:40 +00001450 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001451
Georg Brandl15c5ce92007-03-07 09:09:40 +00001452 # "class TestSuite([tests])"
1453 # ...
1454 # "If tests is given, it must be an iterable of individual test cases
1455 # or other test suites that will be used to build the suite initially"
1456 #
Tim Petersea5962f2007-03-12 18:07:52 +00001457 # TestSuite should allow any iterable to provide tests
Georg Brandl15c5ce92007-03-07 09:09:40 +00001458 def test_init__tests_from_any_iterable(self):
1459 def tests():
1460 yield unittest.FunctionTestCase(lambda: None)
1461 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001462
Georg Brandl15c5ce92007-03-07 09:09:40 +00001463 suite_1 = unittest.TestSuite(tests())
1464 self.assertEqual(suite_1.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001465
Georg Brandl15c5ce92007-03-07 09:09:40 +00001466 suite_2 = unittest.TestSuite(suite_1)
1467 self.assertEqual(suite_2.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001468
Georg Brandl15c5ce92007-03-07 09:09:40 +00001469 suite_3 = unittest.TestSuite(set(suite_1))
1470 self.assertEqual(suite_3.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001471
Georg Brandl15c5ce92007-03-07 09:09:40 +00001472 # "class TestSuite([tests])"
1473 # ...
1474 # "If tests is given, it must be an iterable of individual test cases
1475 # or other test suites that will be used to build the suite initially"
1476 #
1477 # Does TestSuite() also allow other TestSuite() instances to be present
1478 # in the tests iterable?
1479 def test_init__TestSuite_instances_in_tests(self):
1480 def tests():
1481 ftc = unittest.FunctionTestCase(lambda: None)
1482 yield unittest.TestSuite([ftc])
1483 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001484
Georg Brandl15c5ce92007-03-07 09:09:40 +00001485 suite = unittest.TestSuite(tests())
1486 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001487
Georg Brandl15c5ce92007-03-07 09:09:40 +00001488 ################################################################
1489 ### /Tests for TestSuite.__init__
1490
1491 # Container types should support the iter protocol
1492 def test_iter(self):
1493 test1 = unittest.FunctionTestCase(lambda: None)
1494 test2 = unittest.FunctionTestCase(lambda: None)
1495 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001496
Georg Brandl15c5ce92007-03-07 09:09:40 +00001497 self.assertEqual(list(suite), [test1, test2])
Tim Petersea5962f2007-03-12 18:07:52 +00001498
Georg Brandl15c5ce92007-03-07 09:09:40 +00001499 # "Return the number of tests represented by the this test object.
1500 # ...this method is also implemented by the TestSuite class, which can
1501 # return larger [greater than 1] values"
1502 #
Tim Petersea5962f2007-03-12 18:07:52 +00001503 # Presumably an empty TestSuite returns 0?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001504 def test_countTestCases_zero_simple(self):
1505 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001506
Georg Brandl15c5ce92007-03-07 09:09:40 +00001507 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001508
Georg Brandl15c5ce92007-03-07 09:09:40 +00001509 # "Return the number of tests represented by the this test object.
1510 # ...this method is also implemented by the TestSuite class, which can
1511 # return larger [greater than 1] values"
1512 #
1513 # Presumably an empty TestSuite (even if it contains other empty
1514 # TestSuite instances) returns 0?
1515 def test_countTestCases_zero_nested(self):
1516 class Test1(unittest.TestCase):
1517 def test(self):
1518 pass
1519
1520 suite = unittest.TestSuite([unittest.TestSuite()])
Tim Petersea5962f2007-03-12 18:07:52 +00001521
Georg Brandl15c5ce92007-03-07 09:09:40 +00001522 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001523
Georg Brandl15c5ce92007-03-07 09:09:40 +00001524 # "Return the number of tests represented by the this test object.
1525 # ...this method is also implemented by the TestSuite class, which can
1526 # return larger [greater than 1] values"
1527 def test_countTestCases_simple(self):
1528 test1 = unittest.FunctionTestCase(lambda: None)
1529 test2 = unittest.FunctionTestCase(lambda: None)
1530 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001531
Georg Brandl15c5ce92007-03-07 09:09:40 +00001532 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001533
Georg Brandl15c5ce92007-03-07 09:09:40 +00001534 # "Return the number of tests represented by the this test object.
1535 # ...this method is also implemented by the TestSuite class, which can
1536 # return larger [greater than 1] values"
1537 #
1538 # Make sure this holds for nested TestSuite instances, too
1539 def test_countTestCases_nested(self):
1540 class Test1(unittest.TestCase):
1541 def test1(self): pass
1542 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001543
Georg Brandl15c5ce92007-03-07 09:09:40 +00001544 test2 = unittest.FunctionTestCase(lambda: None)
1545 test3 = unittest.FunctionTestCase(lambda: None)
1546 child = unittest.TestSuite((Test1('test2'), test2))
1547 parent = unittest.TestSuite((test3, child, Test1('test1')))
Tim Petersea5962f2007-03-12 18:07:52 +00001548
Georg Brandl15c5ce92007-03-07 09:09:40 +00001549 self.assertEqual(parent.countTestCases(), 4)
Tim Petersea5962f2007-03-12 18:07:52 +00001550
Georg Brandl15c5ce92007-03-07 09:09:40 +00001551 # "Run the tests associated with this suite, collecting the result into
1552 # the test result object passed as result."
1553 #
1554 # And if there are no tests? What then?
1555 def test_run__empty_suite(self):
1556 events = []
1557 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001558
Georg Brandl15c5ce92007-03-07 09:09:40 +00001559 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001560
Georg Brandl15c5ce92007-03-07 09:09:40 +00001561 suite.run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001562
Georg Brandl15c5ce92007-03-07 09:09:40 +00001563 self.assertEqual(events, [])
Tim Petersea5962f2007-03-12 18:07:52 +00001564
Georg Brandl15c5ce92007-03-07 09:09:40 +00001565 # "Note that unlike TestCase.run(), TestSuite.run() requires the
1566 # "result object to be passed in."
1567 def test_run__requires_result(self):
1568 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001569
Georg Brandl15c5ce92007-03-07 09:09:40 +00001570 try:
1571 suite.run()
1572 except TypeError:
1573 pass
1574 else:
1575 self.fail("Failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +00001576
Georg Brandl15c5ce92007-03-07 09:09:40 +00001577 # "Run the tests associated with this suite, collecting the result into
Tim Petersea5962f2007-03-12 18:07:52 +00001578 # the test result object passed as result."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001579 def test_run(self):
1580 events = []
1581 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001582
Georg Brandl15c5ce92007-03-07 09:09:40 +00001583 class LoggingCase(unittest.TestCase):
1584 def run(self, result):
1585 events.append('run %s' % self._testMethodName)
Tim Petersea5962f2007-03-12 18:07:52 +00001586
Georg Brandl15c5ce92007-03-07 09:09:40 +00001587 def test1(self): pass
1588 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001589
1590 tests = [LoggingCase('test1'), LoggingCase('test2')]
1591
Georg Brandl15c5ce92007-03-07 09:09:40 +00001592 unittest.TestSuite(tests).run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001593
Georg Brandl15c5ce92007-03-07 09:09:40 +00001594 self.assertEqual(events, ['run test1', 'run test2'])
Tim Petersea5962f2007-03-12 18:07:52 +00001595
1596 # "Add a TestCase ... to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001597 def test_addTest__TestCase(self):
1598 class Foo(unittest.TestCase):
1599 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001600
Georg Brandl15c5ce92007-03-07 09:09:40 +00001601 test = Foo('test')
1602 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001603
Georg Brandl15c5ce92007-03-07 09:09:40 +00001604 suite.addTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001605
Georg Brandl15c5ce92007-03-07 09:09:40 +00001606 self.assertEqual(suite.countTestCases(), 1)
1607 self.assertEqual(list(suite), [test])
Tim Petersea5962f2007-03-12 18:07:52 +00001608
1609 # "Add a ... TestSuite to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001610 def test_addTest__TestSuite(self):
1611 class Foo(unittest.TestCase):
1612 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001613
Georg Brandl15c5ce92007-03-07 09:09:40 +00001614 suite_2 = unittest.TestSuite([Foo('test')])
Tim Petersea5962f2007-03-12 18:07:52 +00001615
Georg Brandl15c5ce92007-03-07 09:09:40 +00001616 suite = unittest.TestSuite()
1617 suite.addTest(suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001618
Georg Brandl15c5ce92007-03-07 09:09:40 +00001619 self.assertEqual(suite.countTestCases(), 1)
1620 self.assertEqual(list(suite), [suite_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001621
Georg Brandl15c5ce92007-03-07 09:09:40 +00001622 # "Add all the tests from an iterable of TestCase and TestSuite
1623 # instances to this test suite."
Tim Petersea5962f2007-03-12 18:07:52 +00001624 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001625 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001626 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001627 def test_addTests(self):
1628 class Foo(unittest.TestCase):
1629 def test_1(self): pass
1630 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001631
Georg Brandl15c5ce92007-03-07 09:09:40 +00001632 test_1 = Foo('test_1')
1633 test_2 = Foo('test_2')
1634 inner_suite = unittest.TestSuite([test_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001635
Georg Brandl15c5ce92007-03-07 09:09:40 +00001636 def gen():
1637 yield test_1
1638 yield test_2
1639 yield inner_suite
Tim Petersea5962f2007-03-12 18:07:52 +00001640
Georg Brandl15c5ce92007-03-07 09:09:40 +00001641 suite_1 = unittest.TestSuite()
1642 suite_1.addTests(gen())
Tim Petersea5962f2007-03-12 18:07:52 +00001643
Georg Brandl15c5ce92007-03-07 09:09:40 +00001644 self.assertEqual(list(suite_1), list(gen()))
Tim Petersea5962f2007-03-12 18:07:52 +00001645
Georg Brandl15c5ce92007-03-07 09:09:40 +00001646 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001647 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001648 suite_2 = unittest.TestSuite()
1649 for t in gen():
1650 suite_2.addTest(t)
Tim Petersea5962f2007-03-12 18:07:52 +00001651
Georg Brandl15c5ce92007-03-07 09:09:40 +00001652 self.assertEqual(suite_1, suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001653
Georg Brandl15c5ce92007-03-07 09:09:40 +00001654 # "Add all the tests from an iterable of TestCase and TestSuite
1655 # instances to this test suite."
1656 #
Tim Petersea5962f2007-03-12 18:07:52 +00001657 # What happens if it doesn't get an iterable?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001658 def test_addTest__noniterable(self):
1659 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001660
Georg Brandl15c5ce92007-03-07 09:09:40 +00001661 try:
1662 suite.addTests(5)
1663 except TypeError:
1664 pass
1665 else:
1666 self.fail("Failed to raise TypeError")
Georg Brandld9e50262007-03-07 11:54:49 +00001667
1668 def test_addTest__noncallable(self):
1669 suite = unittest.TestSuite()
1670 self.assertRaises(TypeError, suite.addTest, 5)
1671
1672 def test_addTest__casesuiteclass(self):
1673 suite = unittest.TestSuite()
1674 self.assertRaises(TypeError, suite.addTest, Test_TestSuite)
1675 self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)
1676
1677 def test_addTests__string(self):
1678 suite = unittest.TestSuite()
1679 self.assertRaises(TypeError, suite.addTests, "foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001680
1681
Georg Brandl15c5ce92007-03-07 09:09:40 +00001682class Test_FunctionTestCase(TestCase):
Tim Petersea5962f2007-03-12 18:07:52 +00001683
Georg Brandl15c5ce92007-03-07 09:09:40 +00001684 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00001685 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001686 def test_countTestCases(self):
1687 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001688
Georg Brandl15c5ce92007-03-07 09:09:40 +00001689 self.assertEqual(test.countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00001690
Georg Brandl15c5ce92007-03-07 09:09:40 +00001691 # "When a setUp() method is defined, the test runner will run that method
1692 # prior to each test. Likewise, if a tearDown() method is defined, the
1693 # test runner will invoke that method after each test. In the example,
1694 # setUp() was used to create a fresh sequence for each test."
1695 #
1696 # Make sure the proper call order is maintained, even if setUp() raises
1697 # an exception.
1698 def test_run_call_order__error_in_setUp(self):
1699 events = []
1700 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001701
Georg Brandl15c5ce92007-03-07 09:09:40 +00001702 def setUp():
1703 events.append('setUp')
1704 raise RuntimeError('raised by setUp')
1705
1706 def test():
1707 events.append('test')
1708
1709 def tearDown():
1710 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001711
1712 expected = ['startTest', 'setUp', 'addError', 'stopTest']
Georg Brandl15c5ce92007-03-07 09:09:40 +00001713 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1714 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001715
Georg Brandl15c5ce92007-03-07 09:09:40 +00001716 # "When a setUp() method is defined, the test runner will run that method
1717 # prior to each test. Likewise, if a tearDown() method is defined, the
1718 # test runner will invoke that method after each test. In the example,
1719 # setUp() was used to create a fresh sequence for each test."
1720 #
1721 # Make sure the proper call order is maintained, even if the test raises
1722 # an error (as opposed to a failure).
1723 def test_run_call_order__error_in_test(self):
1724 events = []
1725 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001726
Georg Brandl15c5ce92007-03-07 09:09:40 +00001727 def setUp():
1728 events.append('setUp')
1729
1730 def test():
1731 events.append('test')
1732 raise RuntimeError('raised by test')
1733
1734 def tearDown():
1735 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001736
Georg Brandl15c5ce92007-03-07 09:09:40 +00001737 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
1738 'stopTest']
1739 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1740 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001741
Georg Brandl15c5ce92007-03-07 09:09:40 +00001742 # "When a setUp() method is defined, the test runner will run that method
1743 # prior to each test. Likewise, if a tearDown() method is defined, the
1744 # test runner will invoke that method after each test. In the example,
1745 # setUp() was used to create a fresh sequence for each test."
1746 #
1747 # Make sure the proper call order is maintained, even if the test signals
1748 # a failure (as opposed to an error).
1749 def test_run_call_order__failure_in_test(self):
1750 events = []
1751 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001752
Georg Brandl15c5ce92007-03-07 09:09:40 +00001753 def setUp():
1754 events.append('setUp')
1755
1756 def test():
1757 events.append('test')
1758 self.fail('raised by test')
1759
1760 def tearDown():
1761 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001762
Georg Brandl15c5ce92007-03-07 09:09:40 +00001763 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
1764 'stopTest']
1765 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1766 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001767
Georg Brandl15c5ce92007-03-07 09:09:40 +00001768 # "When a setUp() method is defined, the test runner will run that method
1769 # prior to each test. Likewise, if a tearDown() method is defined, the
1770 # test runner will invoke that method after each test. In the example,
1771 # setUp() was used to create a fresh sequence for each test."
1772 #
1773 # Make sure the proper call order is maintained, even if tearDown() raises
1774 # an exception.
1775 def test_run_call_order__error_in_tearDown(self):
1776 events = []
1777 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001778
Georg Brandl15c5ce92007-03-07 09:09:40 +00001779 def setUp():
1780 events.append('setUp')
1781
1782 def test():
1783 events.append('test')
1784
1785 def tearDown():
1786 events.append('tearDown')
1787 raise RuntimeError('raised by tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001788
Georg Brandl15c5ce92007-03-07 09:09:40 +00001789 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
1790 'stopTest']
1791 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1792 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001793
Georg Brandl15c5ce92007-03-07 09:09:40 +00001794 # "Return a string identifying the specific test case."
1795 #
1796 # Because of the vague nature of the docs, I'm not going to lock this
1797 # test down too much. Really all that can be asserted is that the id()
1798 # will be a string (either 8-byte or unicode -- again, because the docs
1799 # just say "string")
1800 def test_id(self):
1801 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001802
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001803 self.assertIsInstance(test.id(), basestring)
Tim Petersea5962f2007-03-12 18:07:52 +00001804
Georg Brandl15c5ce92007-03-07 09:09:40 +00001805 # "Returns a one-line description of the test, or None if no description
1806 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001807 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001808 def test_shortDescription__no_docstring(self):
1809 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001810
Georg Brandl15c5ce92007-03-07 09:09:40 +00001811 self.assertEqual(test.shortDescription(), None)
Tim Petersea5962f2007-03-12 18:07:52 +00001812
Georg Brandl15c5ce92007-03-07 09:09:40 +00001813 # "Returns a one-line description of the test, or None if no description
1814 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001815 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001816 def test_shortDescription__singleline_docstring(self):
1817 desc = "this tests foo"
1818 test = unittest.FunctionTestCase(lambda: None, description=desc)
Tim Petersea5962f2007-03-12 18:07:52 +00001819
Georg Brandl15c5ce92007-03-07 09:09:40 +00001820 self.assertEqual(test.shortDescription(), "this tests foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001821
Georg Brandl15c5ce92007-03-07 09:09:40 +00001822class Test_TestResult(TestCase):
1823 # Note: there are not separate tests for TestResult.wasSuccessful(),
1824 # TestResult.errors, TestResult.failures, TestResult.testsRun or
1825 # TestResult.shouldStop because these only have meaning in terms of
1826 # other TestResult methods.
1827 #
1828 # Accordingly, tests for the aforenamed attributes are incorporated
1829 # in with the tests for the defining methods.
1830 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001831
Georg Brandl15c5ce92007-03-07 09:09:40 +00001832 def test_init(self):
1833 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001834
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001835 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001836 self.assertEqual(len(result.errors), 0)
1837 self.assertEqual(len(result.failures), 0)
1838 self.assertEqual(result.testsRun, 0)
1839 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001840
Georg Brandl15c5ce92007-03-07 09:09:40 +00001841 # "This method can be called to signal that the set of tests being
1842 # run should be aborted by setting the TestResult's shouldStop
Tim Petersea5962f2007-03-12 18:07:52 +00001843 # attribute to True."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001844 def test_stop(self):
1845 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001846
Georg Brandl15c5ce92007-03-07 09:09:40 +00001847 result.stop()
Tim Petersea5962f2007-03-12 18:07:52 +00001848
Georg Brandl15c5ce92007-03-07 09:09:40 +00001849 self.assertEqual(result.shouldStop, True)
Tim Petersea5962f2007-03-12 18:07:52 +00001850
Georg Brandl15c5ce92007-03-07 09:09:40 +00001851 # "Called when the test case test is about to be run. The default
1852 # implementation simply increments the instance's testsRun counter."
1853 def test_startTest(self):
1854 class Foo(unittest.TestCase):
1855 def test_1(self):
1856 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001857
Georg Brandl15c5ce92007-03-07 09:09:40 +00001858 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001859
Georg Brandl15c5ce92007-03-07 09:09:40 +00001860 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001861
Georg Brandl15c5ce92007-03-07 09:09:40 +00001862 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001863
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001864 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001865 self.assertEqual(len(result.errors), 0)
1866 self.assertEqual(len(result.failures), 0)
1867 self.assertEqual(result.testsRun, 1)
1868 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001869
Georg Brandl15c5ce92007-03-07 09:09:40 +00001870 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001871
Georg Brandl15c5ce92007-03-07 09:09:40 +00001872 # "Called after the test case test has been executed, regardless of
1873 # the outcome. The default implementation does nothing."
1874 def test_stopTest(self):
1875 class Foo(unittest.TestCase):
1876 def test_1(self):
1877 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001878
Georg Brandl15c5ce92007-03-07 09:09:40 +00001879 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001880
Georg Brandl15c5ce92007-03-07 09:09:40 +00001881 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001882
Georg Brandl15c5ce92007-03-07 09:09:40 +00001883 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001884
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001885 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001886 self.assertEqual(len(result.errors), 0)
1887 self.assertEqual(len(result.failures), 0)
1888 self.assertEqual(result.testsRun, 1)
1889 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001890
Georg Brandl15c5ce92007-03-07 09:09:40 +00001891 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001892
Georg Brandl15c5ce92007-03-07 09:09:40 +00001893 # Same tests as above; make sure nothing has changed
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001894 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001895 self.assertEqual(len(result.errors), 0)
1896 self.assertEqual(len(result.failures), 0)
1897 self.assertEqual(result.testsRun, 1)
1898 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001899
Michael Foord07ef4872009-05-02 22:43:34 +00001900 # "Called before and after tests are run. The default implementation does nothing."
1901 def test_startTestRun_stopTestRun(self):
1902 result = unittest.TestResult()
1903 result.startTestRun()
1904 result.stopTestRun()
1905
Georg Brandl15c5ce92007-03-07 09:09:40 +00001906 # "addSuccess(test)"
1907 # ...
1908 # "Called when the test case test succeeds"
1909 # ...
1910 # "wasSuccessful() - Returns True if all tests run so far have passed,
1911 # otherwise returns False"
1912 # ...
1913 # "testsRun - The total number of tests run so far."
1914 # ...
1915 # "errors - A list containing 2-tuples of TestCase instances and
1916 # formatted tracebacks. Each tuple represents a test which raised an
1917 # unexpected exception. Contains formatted
1918 # tracebacks instead of sys.exc_info() results."
1919 # ...
1920 # "failures - A list containing 2-tuples of TestCase instances and
1921 # formatted tracebacks. Each tuple represents a test where a failure was
1922 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1923 # methods. Contains formatted tracebacks instead
1924 # of sys.exc_info() results."
1925 def test_addSuccess(self):
1926 class Foo(unittest.TestCase):
1927 def test_1(self):
1928 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001929
Georg Brandl15c5ce92007-03-07 09:09:40 +00001930 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001931
Georg Brandl15c5ce92007-03-07 09:09:40 +00001932 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001933
Georg Brandl15c5ce92007-03-07 09:09:40 +00001934 result.startTest(test)
1935 result.addSuccess(test)
1936 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001937
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001938 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001939 self.assertEqual(len(result.errors), 0)
1940 self.assertEqual(len(result.failures), 0)
1941 self.assertEqual(result.testsRun, 1)
1942 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001943
Georg Brandl15c5ce92007-03-07 09:09:40 +00001944 # "addFailure(test, err)"
1945 # ...
1946 # "Called when the test case test signals a failure. err is a tuple of
1947 # the form returned by sys.exc_info(): (type, value, traceback)"
1948 # ...
1949 # "wasSuccessful() - Returns True if all tests run so far have passed,
1950 # otherwise returns False"
1951 # ...
1952 # "testsRun - The total number of tests run so far."
1953 # ...
1954 # "errors - A list containing 2-tuples of TestCase instances and
1955 # formatted tracebacks. Each tuple represents a test which raised an
1956 # unexpected exception. Contains formatted
1957 # tracebacks instead of sys.exc_info() results."
1958 # ...
1959 # "failures - A list containing 2-tuples of TestCase instances and
1960 # formatted tracebacks. Each tuple represents a test where a failure was
1961 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1962 # methods. Contains formatted tracebacks instead
1963 # of sys.exc_info() results."
1964 def test_addFailure(self):
1965 import sys
Tim Petersea5962f2007-03-12 18:07:52 +00001966
Georg Brandl15c5ce92007-03-07 09:09:40 +00001967 class Foo(unittest.TestCase):
1968 def test_1(self):
1969 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001970
Georg Brandl15c5ce92007-03-07 09:09:40 +00001971 test = Foo('test_1')
1972 try:
1973 test.fail("foo")
1974 except:
1975 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00001976
Georg Brandl15c5ce92007-03-07 09:09:40 +00001977 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001978
Georg Brandl15c5ce92007-03-07 09:09:40 +00001979 result.startTest(test)
1980 result.addFailure(test, exc_info_tuple)
1981 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001982
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001983 self.assertFalse(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001984 self.assertEqual(len(result.errors), 0)
1985 self.assertEqual(len(result.failures), 1)
1986 self.assertEqual(result.testsRun, 1)
1987 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001988
Georg Brandl15c5ce92007-03-07 09:09:40 +00001989 test_case, formatted_exc = result.failures[0]
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001990 self.assertTrue(test_case is test)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001991 self.assertIsInstance(formatted_exc, str)
Tim Petersea5962f2007-03-12 18:07:52 +00001992
Georg Brandl15c5ce92007-03-07 09:09:40 +00001993 # "addError(test, err)"
1994 # ...
1995 # "Called when the test case test raises an unexpected exception err
1996 # is a tuple of the form returned by sys.exc_info():
1997 # (type, value, traceback)"
1998 # ...
1999 # "wasSuccessful() - Returns True if all tests run so far have passed,
2000 # otherwise returns False"
2001 # ...
2002 # "testsRun - The total number of tests run so far."
2003 # ...
2004 # "errors - A list containing 2-tuples of TestCase instances and
2005 # formatted tracebacks. Each tuple represents a test which raised an
2006 # unexpected exception. Contains formatted
2007 # tracebacks instead of sys.exc_info() results."
2008 # ...
2009 # "failures - A list containing 2-tuples of TestCase instances and
2010 # formatted tracebacks. Each tuple represents a test where a failure was
2011 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
2012 # methods. Contains formatted tracebacks instead
2013 # of sys.exc_info() results."
2014 def test_addError(self):
2015 import sys
Tim Petersea5962f2007-03-12 18:07:52 +00002016
Georg Brandl15c5ce92007-03-07 09:09:40 +00002017 class Foo(unittest.TestCase):
2018 def test_1(self):
2019 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002020
Georg Brandl15c5ce92007-03-07 09:09:40 +00002021 test = Foo('test_1')
2022 try:
2023 raise TypeError()
2024 except:
2025 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00002026
Georg Brandl15c5ce92007-03-07 09:09:40 +00002027 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00002028
Georg Brandl15c5ce92007-03-07 09:09:40 +00002029 result.startTest(test)
2030 result.addError(test, exc_info_tuple)
2031 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00002032
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002033 self.assertFalse(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00002034 self.assertEqual(len(result.errors), 1)
2035 self.assertEqual(len(result.failures), 0)
2036 self.assertEqual(result.testsRun, 1)
2037 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00002038
Georg Brandl15c5ce92007-03-07 09:09:40 +00002039 test_case, formatted_exc = result.errors[0]
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002040 self.assertTrue(test_case is test)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002041 self.assertIsInstance(formatted_exc, str)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002042
2043### Support code for Test_TestCase
2044################################################################
2045
2046class Foo(unittest.TestCase):
2047 def runTest(self): pass
2048 def test1(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002049
Georg Brandl15c5ce92007-03-07 09:09:40 +00002050class Bar(Foo):
2051 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002052
Michael Foord07ef4872009-05-02 22:43:34 +00002053class LoggingTestCase(unittest.TestCase):
2054 """A test case which logs its calls."""
2055
2056 def __init__(self, events):
2057 super(LoggingTestCase, self).__init__('test')
2058 self.events = events
2059
2060 def setUp(self):
2061 self.events.append('setUp')
2062
2063 def test(self):
2064 self.events.append('test')
2065
2066 def tearDown(self):
2067 self.events.append('tearDown')
2068
2069class ResultWithNoStartTestRunStopTestRun(object):
2070 """An object honouring TestResult before startTestRun/stopTestRun."""
2071
2072 def __init__(self):
2073 self.failures = []
2074 self.errors = []
2075 self.testsRun = 0
2076 self.skipped = []
2077 self.expectedFailures = []
2078 self.unexpectedSuccesses = []
2079 self.shouldStop = False
2080
2081 def startTest(self, test):
2082 pass
2083
2084 def stopTest(self, test):
2085 pass
2086
2087 def addError(self, test):
2088 pass
2089
2090 def addFailure(self, test):
2091 pass
2092
2093 def addSuccess(self, test):
2094 pass
2095
2096 def wasSuccessful(self):
2097 return True
2098
2099
Georg Brandl15c5ce92007-03-07 09:09:40 +00002100################################################################
2101### /Support code for Test_TestCase
2102
2103class Test_TestCase(TestCase, TestEquality, TestHashing):
2104
2105 ### Set up attributes used by inherited tests
2106 ################################################################
2107
2108 # Used by TestHashing.test_hash and TestEquality.test_eq
2109 eq_pairs = [(Foo('test1'), Foo('test1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002110
Georg Brandl15c5ce92007-03-07 09:09:40 +00002111 # Used by TestEquality.test_ne
2112 ne_pairs = [(Foo('test1'), Foo('runTest'))
2113 ,(Foo('test1'), Bar('test1'))
2114 ,(Foo('test1'), Bar('test2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002115
Georg Brandl15c5ce92007-03-07 09:09:40 +00002116 ################################################################
2117 ### /Set up attributes used by inherited tests
Tim Petersea5962f2007-03-12 18:07:52 +00002118
Georg Brandl15c5ce92007-03-07 09:09:40 +00002119
2120 # "class TestCase([methodName])"
2121 # ...
2122 # "Each instance of TestCase will run a single test method: the
2123 # method named methodName."
2124 # ...
2125 # "methodName defaults to "runTest"."
2126 #
2127 # Make sure it really is optional, and that it defaults to the proper
2128 # thing.
2129 def test_init__no_test_name(self):
2130 class Test(unittest.TestCase):
2131 def runTest(self): raise MyException()
2132 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002133
Georg Brandl15c5ce92007-03-07 09:09:40 +00002134 self.assertEqual(Test().id()[-13:], '.Test.runTest')
Tim Petersea5962f2007-03-12 18:07:52 +00002135
Georg Brandl15c5ce92007-03-07 09:09:40 +00002136 # "class TestCase([methodName])"
2137 # ...
2138 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002139 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002140 def test_init__test_name__valid(self):
2141 class Test(unittest.TestCase):
2142 def runTest(self): raise MyException()
2143 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002144
Georg Brandl15c5ce92007-03-07 09:09:40 +00002145 self.assertEqual(Test('test').id()[-10:], '.Test.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002146
Georg Brandl15c5ce92007-03-07 09:09:40 +00002147 # "class TestCase([methodName])"
2148 # ...
2149 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002150 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002151 def test_init__test_name__invalid(self):
2152 class Test(unittest.TestCase):
2153 def runTest(self): raise MyException()
2154 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002155
Georg Brandl15c5ce92007-03-07 09:09:40 +00002156 try:
2157 Test('testfoo')
2158 except ValueError:
2159 pass
2160 else:
2161 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +00002162
Georg Brandl15c5ce92007-03-07 09:09:40 +00002163 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00002164 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00002165 def test_countTestCases(self):
2166 class Foo(unittest.TestCase):
2167 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002168
Georg Brandl15c5ce92007-03-07 09:09:40 +00002169 self.assertEqual(Foo('test').countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00002170
Georg Brandl15c5ce92007-03-07 09:09:40 +00002171 # "Return the default type of test result object to be used to run this
2172 # test. For TestCase instances, this will always be
2173 # unittest.TestResult; subclasses of TestCase should
2174 # override this as necessary."
2175 def test_defaultTestResult(self):
2176 class Foo(unittest.TestCase):
2177 def runTest(self):
2178 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002179
Georg Brandl15c5ce92007-03-07 09:09:40 +00002180 result = Foo().defaultTestResult()
2181 self.assertEqual(type(result), unittest.TestResult)
2182
2183 # "When a setUp() method is defined, the test runner will run that method
2184 # prior to each test. Likewise, if a tearDown() method is defined, the
2185 # test runner will invoke that method after each test. In the example,
2186 # setUp() was used to create a fresh sequence for each test."
2187 #
2188 # Make sure the proper call order is maintained, even if setUp() raises
2189 # an exception.
2190 def test_run_call_order__error_in_setUp(self):
2191 events = []
2192 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002193
Michael Foord07ef4872009-05-02 22:43:34 +00002194 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002195 def setUp(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002196 super(Foo, self).setUp()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002197 raise RuntimeError('raised by Foo.setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002198
Michael Foord07ef4872009-05-02 22:43:34 +00002199 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002200 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2201 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002202
Michael Foord07ef4872009-05-02 22:43:34 +00002203 # "With a temporary result stopTestRun is called when setUp errors.
2204 def test_run_call_order__error_in_setUp_default_result(self):
2205 events = []
2206
2207 class Foo(LoggingTestCase):
2208 def defaultTestResult(self):
2209 return LoggingResult(self.events)
2210
2211 def setUp(self):
2212 super(Foo, self).setUp()
2213 raise RuntimeError('raised by Foo.setUp')
2214
2215 Foo(events).run()
2216 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2217 'stopTest', 'stopTestRun']
2218 self.assertEqual(events, expected)
2219
Georg Brandl15c5ce92007-03-07 09:09:40 +00002220 # "When a setUp() method is defined, the test runner will run that method
2221 # prior to each test. Likewise, if a tearDown() method is defined, the
2222 # test runner will invoke that method after each test. In the example,
2223 # setUp() was used to create a fresh sequence for each test."
2224 #
2225 # Make sure the proper call order is maintained, even if the test raises
2226 # an error (as opposed to a failure).
2227 def test_run_call_order__error_in_test(self):
2228 events = []
2229 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002230
Michael Foord07ef4872009-05-02 22:43:34 +00002231 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002232 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002233 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002234 raise RuntimeError('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002235
Georg Brandl15c5ce92007-03-07 09:09:40 +00002236 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2237 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002238 Foo(events).run(result)
2239 self.assertEqual(events, expected)
2240
2241 # "With a default result, an error in the test still results in stopTestRun
2242 # being called."
2243 def test_run_call_order__error_in_test_default_result(self):
2244 events = []
2245
2246 class Foo(LoggingTestCase):
2247 def defaultTestResult(self):
2248 return LoggingResult(self.events)
2249
2250 def test(self):
2251 super(Foo, self).test()
2252 raise RuntimeError('raised by Foo.test')
2253
2254 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2255 'tearDown', 'stopTest', 'stopTestRun']
2256 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002257 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002258
Georg Brandl15c5ce92007-03-07 09:09:40 +00002259 # "When a setUp() method is defined, the test runner will run that method
2260 # prior to each test. Likewise, if a tearDown() method is defined, the
2261 # test runner will invoke that method after each test. In the example,
2262 # setUp() was used to create a fresh sequence for each test."
2263 #
2264 # Make sure the proper call order is maintained, even if the test signals
2265 # a failure (as opposed to an error).
2266 def test_run_call_order__failure_in_test(self):
2267 events = []
2268 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002269
Michael Foord07ef4872009-05-02 22:43:34 +00002270 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002271 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002272 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002273 self.fail('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002274
Georg Brandl15c5ce92007-03-07 09:09:40 +00002275 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2276 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002277 Foo(events).run(result)
2278 self.assertEqual(events, expected)
2279
2280 # "When a test fails with a default result stopTestRun is still called."
2281 def test_run_call_order__failure_in_test_default_result(self):
2282
2283 class Foo(LoggingTestCase):
2284 def defaultTestResult(self):
2285 return LoggingResult(self.events)
2286 def test(self):
2287 super(Foo, self).test()
2288 self.fail('raised by Foo.test')
2289
2290 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2291 'tearDown', 'stopTest', 'stopTestRun']
2292 events = []
2293 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002294 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002295
Georg Brandl15c5ce92007-03-07 09:09:40 +00002296 # "When a setUp() method is defined, the test runner will run that method
2297 # prior to each test. Likewise, if a tearDown() method is defined, the
2298 # test runner will invoke that method after each test. In the example,
2299 # setUp() was used to create a fresh sequence for each test."
2300 #
2301 # Make sure the proper call order is maintained, even if tearDown() raises
2302 # an exception.
2303 def test_run_call_order__error_in_tearDown(self):
2304 events = []
2305 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002306
Michael Foord07ef4872009-05-02 22:43:34 +00002307 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002308 def tearDown(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002309 super(Foo, self).tearDown()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002310 raise RuntimeError('raised by Foo.tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002311
Michael Foord07ef4872009-05-02 22:43:34 +00002312 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002313 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2314 'stopTest']
2315 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002316
Michael Foord07ef4872009-05-02 22:43:34 +00002317 # "When tearDown errors with a default result stopTestRun is still called."
2318 def test_run_call_order__error_in_tearDown_default_result(self):
2319
2320 class Foo(LoggingTestCase):
2321 def defaultTestResult(self):
2322 return LoggingResult(self.events)
2323 def tearDown(self):
2324 super(Foo, self).tearDown()
2325 raise RuntimeError('raised by Foo.tearDown')
2326
2327 events = []
2328 Foo(events).run()
2329 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2330 'addError', 'stopTest', 'stopTestRun']
2331 self.assertEqual(events, expected)
2332
2333 # "TestCase.run() still works when the defaultTestResult is a TestResult
2334 # that does not support startTestRun and stopTestRun.
2335 def test_run_call_order_default_result(self):
2336
2337 class Foo(unittest.TestCase):
2338 def defaultTestResult(self):
2339 return ResultWithNoStartTestRunStopTestRun()
2340 def test(self):
2341 pass
2342
2343 Foo('test').run()
2344
Georg Brandl15c5ce92007-03-07 09:09:40 +00002345 # "This class attribute gives the exception raised by the test() method.
2346 # If a test framework needs to use a specialized exception, possibly to
2347 # carry additional information, it must subclass this exception in
2348 # order to ``play fair'' with the framework. The initial value of this
2349 # attribute is AssertionError"
2350 def test_failureException__default(self):
2351 class Foo(unittest.TestCase):
2352 def test(self):
2353 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002354
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002355 self.assertTrue(Foo('test').failureException is AssertionError)
Tim Petersea5962f2007-03-12 18:07:52 +00002356
Georg Brandl15c5ce92007-03-07 09:09:40 +00002357 # "This class attribute gives the exception raised by the test() method.
2358 # If a test framework needs to use a specialized exception, possibly to
2359 # carry additional information, it must subclass this exception in
2360 # order to ``play fair'' with the framework."
2361 #
2362 # Make sure TestCase.run() respects the designated failureException
2363 def test_failureException__subclassing__explicit_raise(self):
2364 events = []
2365 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002366
Georg Brandl15c5ce92007-03-07 09:09:40 +00002367 class Foo(unittest.TestCase):
2368 def test(self):
2369 raise RuntimeError()
Tim Petersea5962f2007-03-12 18:07:52 +00002370
Georg Brandl15c5ce92007-03-07 09:09:40 +00002371 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002372
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002373 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002374
2375
Georg Brandl15c5ce92007-03-07 09:09:40 +00002376 Foo('test').run(result)
2377 expected = ['startTest', 'addFailure', 'stopTest']
2378 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002379
Georg Brandl15c5ce92007-03-07 09:09:40 +00002380 # "This class attribute gives the exception raised by the test() method.
2381 # If a test framework needs to use a specialized exception, possibly to
2382 # carry additional information, it must subclass this exception in
2383 # order to ``play fair'' with the framework."
2384 #
2385 # Make sure TestCase.run() respects the designated failureException
2386 def test_failureException__subclassing__implicit_raise(self):
2387 events = []
2388 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002389
Georg Brandl15c5ce92007-03-07 09:09:40 +00002390 class Foo(unittest.TestCase):
2391 def test(self):
2392 self.fail("foo")
Tim Petersea5962f2007-03-12 18:07:52 +00002393
Georg Brandl15c5ce92007-03-07 09:09:40 +00002394 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002395
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002396 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002397
2398
Georg Brandl15c5ce92007-03-07 09:09:40 +00002399 Foo('test').run(result)
2400 expected = ['startTest', 'addFailure', 'stopTest']
2401 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002402
2403 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002404 def test_setUp(self):
2405 class Foo(unittest.TestCase):
2406 def runTest(self):
2407 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002408
Georg Brandl15c5ce92007-03-07 09:09:40 +00002409 # ... and nothing should happen
2410 Foo().setUp()
Tim Petersea5962f2007-03-12 18:07:52 +00002411
2412 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002413 def test_tearDown(self):
2414 class Foo(unittest.TestCase):
2415 def runTest(self):
2416 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002417
Georg Brandl15c5ce92007-03-07 09:09:40 +00002418 # ... and nothing should happen
2419 Foo().tearDown()
Tim Petersea5962f2007-03-12 18:07:52 +00002420
Georg Brandl15c5ce92007-03-07 09:09:40 +00002421 # "Return a string identifying the specific test case."
2422 #
2423 # Because of the vague nature of the docs, I'm not going to lock this
2424 # test down too much. Really all that can be asserted is that the id()
2425 # will be a string (either 8-byte or unicode -- again, because the docs
2426 # just say "string")
2427 def test_id(self):
2428 class Foo(unittest.TestCase):
2429 def runTest(self):
2430 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002431
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002432 self.assertIsInstance(Foo().id(), basestring)
Tim Petersea5962f2007-03-12 18:07:52 +00002433
Georg Brandl15c5ce92007-03-07 09:09:40 +00002434 # "If result is omitted or None, a temporary result object is created
Michael Foord07ef4872009-05-02 22:43:34 +00002435 # and used, but is not made available to the caller. As TestCase owns the
2436 # temporary result startTestRun and stopTestRun are called.
2437
Georg Brandl15c5ce92007-03-07 09:09:40 +00002438 def test_run__uses_defaultTestResult(self):
2439 events = []
Tim Petersea5962f2007-03-12 18:07:52 +00002440
Georg Brandl15c5ce92007-03-07 09:09:40 +00002441 class Foo(unittest.TestCase):
2442 def test(self):
2443 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002444
Georg Brandl15c5ce92007-03-07 09:09:40 +00002445 def defaultTestResult(self):
2446 return LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002447
2448 # Make run() find a result object on its own
Georg Brandl15c5ce92007-03-07 09:09:40 +00002449 Foo('test').run()
Tim Petersea5962f2007-03-12 18:07:52 +00002450
Michael Foord07ef4872009-05-02 22:43:34 +00002451 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2452 'stopTest', 'stopTestRun']
Georg Brandl15c5ce92007-03-07 09:09:40 +00002453 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002454
Gregory P. Smith28399852009-03-31 16:54:10 +00002455 def testShortDescriptionWithoutDocstring(self):
2456 self.assertEqual(
2457 self.shortDescription(),
2458 'testShortDescriptionWithoutDocstring (' + __name__ +
2459 '.Test_TestCase)')
2460
2461 def testShortDescriptionWithOneLineDocstring(self):
2462 """Tests shortDescription() for a method with a docstring."""
2463 self.assertEqual(
2464 self.shortDescription(),
2465 ('testShortDescriptionWithOneLineDocstring '
2466 '(' + __name__ + '.Test_TestCase)\n'
2467 'Tests shortDescription() for a method with a docstring.'))
2468
2469 def testShortDescriptionWithMultiLineDocstring(self):
2470 """Tests shortDescription() for a method with a longer docstring.
2471
2472 This method ensures that only the first line of a docstring is
2473 returned used in the short description, no matter how long the
2474 whole thing is.
2475 """
2476 self.assertEqual(
2477 self.shortDescription(),
2478 ('testShortDescriptionWithMultiLineDocstring '
2479 '(' + __name__ + '.Test_TestCase)\n'
2480 'Tests shortDescription() for a method with a longer '
2481 'docstring.'))
2482
Gregory P. Smith28399852009-03-31 16:54:10 +00002483 def testAddTypeEqualityFunc(self):
2484 class SadSnake(object):
2485 """Dummy class for test_addTypeEqualityFunc."""
2486 s1, s2 = SadSnake(), SadSnake()
2487 self.assertFalse(s1 == s2)
2488 def AllSnakesCreatedEqual(a, b, msg=None):
2489 return type(a) == type(b) == SadSnake
2490 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2491 self.assertEqual(s1, s2)
2492 # No this doesn't clean up and remove the SadSnake equality func
2493 # from this TestCase instance but since its a local nothing else
2494 # will ever notice that.
2495
Michael Foordf2dfef12009-04-05 19:19:28 +00002496 def testAssertIs(self):
2497 thing = object()
2498 self.assertIs(thing, thing)
2499 self.assertRaises(self.failureException, self.assertIs, thing, object())
2500
2501 def testAssertIsNot(self):
2502 thing = object()
2503 self.assertIsNot(thing, object())
2504 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2505
Georg Brandlf895cf52009-10-01 20:59:31 +00002506 def testAssertIsInstance(self):
2507 thing = []
2508 self.assertIsInstance(thing, list)
2509 self.assertRaises(self.failureException, self.assertIsInstance,
2510 thing, dict)
2511
2512 def testAssertNotIsInstance(self):
2513 thing = []
2514 self.assertNotIsInstance(thing, dict)
2515 self.assertRaises(self.failureException, self.assertNotIsInstance,
2516 thing, list)
2517
Gregory P. Smith28399852009-03-31 16:54:10 +00002518 def testAssertIn(self):
2519 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2520
2521 self.assertIn('a', 'abc')
2522 self.assertIn(2, [1, 2, 3])
2523 self.assertIn('monkey', animals)
2524
2525 self.assertNotIn('d', 'abc')
2526 self.assertNotIn(0, [1, 2, 3])
2527 self.assertNotIn('otter', animals)
2528
2529 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2530 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2531 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2532 animals)
2533
2534 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2535 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2536 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2537 animals)
2538
2539 def testAssertDictContainsSubset(self):
2540 self.assertDictContainsSubset({}, {})
2541 self.assertDictContainsSubset({}, {'a': 1})
2542 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2543 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2544 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2545
2546 self.assertRaises(unittest.TestCase.failureException,
2547 self.assertDictContainsSubset, {'a': 2}, {'a': 1},
2548 '.*Mismatched values:.*')
2549
2550 self.assertRaises(unittest.TestCase.failureException,
2551 self.assertDictContainsSubset, {'c': 1}, {'a': 1},
2552 '.*Missing:.*')
2553
2554 self.assertRaises(unittest.TestCase.failureException,
2555 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2556 {'a': 1}, '.*Missing:.*')
2557
2558 self.assertRaises(unittest.TestCase.failureException,
2559 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2560 {'a': 1}, '.*Missing:.*Mismatched values:.*')
2561
2562 def testAssertEqual(self):
2563 equal_pairs = [
2564 ((), ()),
2565 ({}, {}),
2566 ([], []),
2567 (set(), set()),
2568 (frozenset(), frozenset())]
2569 for a, b in equal_pairs:
2570 # This mess of try excepts is to test the assertEqual behavior
2571 # itself.
2572 try:
2573 self.assertEqual(a, b)
2574 except self.failureException:
2575 self.fail('assertEqual(%r, %r) failed' % (a, b))
2576 try:
2577 self.assertEqual(a, b, msg='foo')
2578 except self.failureException:
2579 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2580 try:
2581 self.assertEqual(a, b, 'foo')
2582 except self.failureException:
2583 self.fail('assertEqual(%r, %r) with third parameter failed' %
2584 (a, b))
2585
2586 unequal_pairs = [
2587 ((), []),
2588 ({}, set()),
2589 (set([4,1]), frozenset([4,2])),
2590 (frozenset([4,5]), set([2,3])),
2591 (set([3,4]), set([5,4]))]
2592 for a, b in unequal_pairs:
2593 self.assertRaises(self.failureException, self.assertEqual, a, b)
2594 self.assertRaises(self.failureException, self.assertEqual, a, b,
2595 'foo')
2596 self.assertRaises(self.failureException, self.assertEqual, a, b,
2597 msg='foo')
2598
2599 def testEquality(self):
2600 self.assertListEqual([], [])
2601 self.assertTupleEqual((), ())
2602 self.assertSequenceEqual([], ())
2603
2604 a = [0, 'a', []]
2605 b = []
2606 self.assertRaises(unittest.TestCase.failureException,
2607 self.assertListEqual, a, b)
2608 self.assertRaises(unittest.TestCase.failureException,
2609 self.assertListEqual, tuple(a), tuple(b))
2610 self.assertRaises(unittest.TestCase.failureException,
2611 self.assertSequenceEqual, a, tuple(b))
2612
2613 b.extend(a)
2614 self.assertListEqual(a, b)
2615 self.assertTupleEqual(tuple(a), tuple(b))
2616 self.assertSequenceEqual(a, tuple(b))
2617 self.assertSequenceEqual(tuple(a), b)
2618
2619 self.assertRaises(self.failureException, self.assertListEqual,
2620 a, tuple(b))
2621 self.assertRaises(self.failureException, self.assertTupleEqual,
2622 tuple(a), b)
2623 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2624 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2625 tuple(b))
2626 self.assertRaises(self.failureException, self.assertSequenceEqual,
2627 None, tuple(b))
2628 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2629 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2630 self.assertRaises(self.failureException, self.assertSequenceEqual,
2631 1, 1)
2632
2633 self.assertDictEqual({}, {})
2634
2635 c = { 'x': 1 }
2636 d = {}
2637 self.assertRaises(unittest.TestCase.failureException,
2638 self.assertDictEqual, c, d)
2639
2640 d.update(c)
2641 self.assertDictEqual(c, d)
2642
2643 d['x'] = 0
2644 self.assertRaises(unittest.TestCase.failureException,
2645 self.assertDictEqual, c, d, 'These are unequal')
2646
2647 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2648 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2649 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2650
2651 self.assertSameElements([1, 2, 3], [3, 2, 1])
2652 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2653 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2654 self.assertRaises(self.failureException, self.assertSameElements,
2655 [10], [10, 11])
2656 self.assertRaises(self.failureException, self.assertSameElements,
2657 [10, 11], [10])
2658
2659 # Test that sequences of unhashable objects can be tested for sameness:
2660 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Michael Foordf2dfef12009-04-05 19:19:28 +00002661
Gregory P. Smith28399852009-03-31 16:54:10 +00002662 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2663 self.assertRaises(self.failureException, self.assertSameElements,
2664 [[1]], [[2]])
2665
2666 def testAssertSetEqual(self):
2667 set1 = set()
2668 set2 = set()
2669 self.assertSetEqual(set1, set2)
2670
2671 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2672 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2673 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2674 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2675
2676 set1 = set(['a'])
2677 set2 = set()
2678 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2679
2680 set1 = set(['a'])
2681 set2 = set(['a'])
2682 self.assertSetEqual(set1, set2)
2683
2684 set1 = set(['a'])
2685 set2 = set(['a', 'b'])
2686 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2687
2688 set1 = set(['a'])
2689 set2 = frozenset(['a', 'b'])
2690 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2691
2692 set1 = set(['a', 'b'])
2693 set2 = frozenset(['a', 'b'])
2694 self.assertSetEqual(set1, set2)
2695
2696 set1 = set()
2697 set2 = "foo"
2698 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2699 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2700
2701 # make sure any string formatting is tuple-safe
2702 set1 = set([(0, 1), (2, 3)])
2703 set2 = set([(4, 5)])
2704 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2705
2706 def testInequality(self):
2707 # Try ints
2708 self.assertGreater(2, 1)
2709 self.assertGreaterEqual(2, 1)
2710 self.assertGreaterEqual(1, 1)
2711 self.assertLess(1, 2)
2712 self.assertLessEqual(1, 2)
2713 self.assertLessEqual(1, 1)
2714 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2715 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2716 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2717 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2718 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2719 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2720
2721 # Try Floats
2722 self.assertGreater(1.1, 1.0)
2723 self.assertGreaterEqual(1.1, 1.0)
2724 self.assertGreaterEqual(1.0, 1.0)
2725 self.assertLess(1.0, 1.1)
2726 self.assertLessEqual(1.0, 1.1)
2727 self.assertLessEqual(1.0, 1.0)
2728 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2729 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2730 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2731 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2732 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2733 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2734
2735 # Try Strings
2736 self.assertGreater('bug', 'ant')
2737 self.assertGreaterEqual('bug', 'ant')
2738 self.assertGreaterEqual('ant', 'ant')
2739 self.assertLess('ant', 'bug')
2740 self.assertLessEqual('ant', 'bug')
2741 self.assertLessEqual('ant', 'ant')
2742 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2743 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2744 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2745 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2746 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2747 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2748
2749 # Try Unicode
2750 self.assertGreater(u'bug', u'ant')
2751 self.assertGreaterEqual(u'bug', u'ant')
2752 self.assertGreaterEqual(u'ant', u'ant')
2753 self.assertLess(u'ant', u'bug')
2754 self.assertLessEqual(u'ant', u'bug')
2755 self.assertLessEqual(u'ant', u'ant')
2756 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug')
2757 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant')
2758 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2759 u'bug')
2760 self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant')
2761 self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant')
2762 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant')
2763
2764 # Try Mixed String/Unicode
2765 self.assertGreater('bug', u'ant')
2766 self.assertGreater(u'bug', 'ant')
2767 self.assertGreaterEqual('bug', u'ant')
2768 self.assertGreaterEqual(u'bug', 'ant')
2769 self.assertGreaterEqual('ant', u'ant')
2770 self.assertGreaterEqual(u'ant', 'ant')
2771 self.assertLess('ant', u'bug')
2772 self.assertLess(u'ant', 'bug')
2773 self.assertLessEqual('ant', u'bug')
2774 self.assertLessEqual(u'ant', 'bug')
2775 self.assertLessEqual('ant', u'ant')
2776 self.assertLessEqual(u'ant', 'ant')
2777 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug')
2778 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug')
2779 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant')
2780 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant')
2781 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant',
2782 u'bug')
2783 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2784 'bug')
2785 self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant')
2786 self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant')
2787 self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant')
2788 self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant')
2789 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant')
2790 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant')
2791
2792 def testAssertMultiLineEqual(self):
2793 sample_text = b"""\
2794http://www.python.org/doc/2.3/lib/module-unittest.html
2795test case
2796 A test case is the smallest unit of testing. [...]
2797"""
2798 revised_sample_text = b"""\
2799http://www.python.org/doc/2.4.1/lib/module-unittest.html
2800test case
2801 A test case is the smallest unit of testing. [...] You may provide your
2802 own implementation that does not subclass from TestCase, of course.
2803"""
2804 sample_text_error = b"""
2805- http://www.python.org/doc/2.3/lib/module-unittest.html
2806? ^
2807+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2808? ^^^
2809 test case
2810- A test case is the smallest unit of testing. [...]
2811+ A test case is the smallest unit of testing. [...] You may provide your
2812? +++++++++++++++++++++
2813+ own implementation that does not subclass from TestCase, of course.
2814"""
2815
2816 for type_changer in (lambda x: x, lambda x: x.decode('utf8')):
2817 try:
2818 self.assertMultiLineEqual(type_changer(sample_text),
2819 type_changer(revised_sample_text))
2820 except self.failureException, e:
2821 # no fair testing ourself with ourself, use assertEqual..
2822 self.assertEqual(sample_text_error, str(e).encode('utf8'))
2823
2824 def testAssertIsNone(self):
2825 self.assertIsNone(None)
2826 self.assertRaises(self.failureException, self.assertIsNone, False)
2827 self.assertIsNotNone('DjZoPloGears on Rails')
2828 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2829
2830 def testAssertRegexpMatches(self):
2831 self.assertRegexpMatches('asdfabasdf', r'ab+')
2832 self.assertRaises(self.failureException, self.assertRegexpMatches,
2833 'saaas', r'aaaa')
2834
2835 def testAssertRaisesRegexp(self):
2836 class ExceptionMock(Exception):
2837 pass
2838
2839 def Stub():
2840 raise ExceptionMock('We expect')
2841
2842 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2843 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2844 self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
2845
2846 def testAssertNotRaisesRegexp(self):
2847 self.assertRaisesRegexp(
2848 self.failureException, '^Exception not raised$',
2849 self.assertRaisesRegexp, Exception, re.compile('x'),
2850 lambda: None)
2851 self.assertRaisesRegexp(
2852 self.failureException, '^Exception not raised$',
2853 self.assertRaisesRegexp, Exception, 'x',
2854 lambda: None)
2855 self.assertRaisesRegexp(
2856 self.failureException, '^Exception not raised$',
2857 self.assertRaisesRegexp, Exception, u'x',
2858 lambda: None)
2859
2860 def testAssertRaisesRegexpMismatch(self):
2861 def Stub():
2862 raise Exception('Unexpected')
2863
2864 self.assertRaisesRegexp(
2865 self.failureException,
2866 r'"\^Expected\$" does not match "Unexpected"',
2867 self.assertRaisesRegexp, Exception, '^Expected$',
2868 Stub)
2869 self.assertRaisesRegexp(
2870 self.failureException,
2871 r'"\^Expected\$" does not match "Unexpected"',
2872 self.assertRaisesRegexp, Exception, u'^Expected$',
2873 Stub)
2874 self.assertRaisesRegexp(
2875 self.failureException,
2876 r'"\^Expected\$" does not match "Unexpected"',
2877 self.assertRaisesRegexp, Exception,
2878 re.compile('^Expected$'), Stub)
2879
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00002880 def testAssertRaisesExcValue(self):
2881 class ExceptionMock(Exception):
2882 pass
2883
2884 def Stub(foo):
2885 raise ExceptionMock(foo)
2886 v = "particular value"
2887
2888 ctx = self.assertRaises(ExceptionMock)
2889 with ctx:
2890 Stub(v)
2891 e = ctx.exc_value
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002892 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00002893 self.assertEqual(e.args[0], v)
2894
Gregory P. Smith7558d572009-03-31 19:03:28 +00002895 def testSynonymAssertMethodNames(self):
2896 """Test undocumented method name synonyms.
2897
2898 Please do not use these methods names in your own code.
2899
2900 This test confirms their continued existence and functionality
2901 in order to avoid breaking existing code.
2902 """
2903 self.assertNotEquals(3, 5)
2904 self.assertEquals(3, 3)
2905 self.assertAlmostEquals(2.0, 2.0)
2906 self.assertNotAlmostEquals(3.0, 5.0)
2907 self.assert_(True)
2908
2909 def testPendingDeprecationMethodNames(self):
2910 """Test fail* methods pending deprecation, they will warn in 3.2.
2911
2912 Do not use these methods. They will go away in 3.3.
2913 """
2914 self.failIfEqual(3, 5)
2915 self.failUnlessEqual(3, 3)
2916 self.failUnlessAlmostEqual(2.0, 2.0)
2917 self.failIfAlmostEqual(3.0, 5.0)
2918 self.failUnless(True)
2919 self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam')
2920 self.failIf(False)
2921
Michael Foorde2942d02009-04-02 05:51:54 +00002922 def testDeepcopy(self):
2923 # Issue: 5660
2924 class TestableTest(TestCase):
2925 def testNothing(self):
2926 pass
2927
2928 test = TestableTest('testNothing')
2929
2930 # This shouldn't blow up
2931 deepcopy(test)
2932
Benjamin Peterson692428e2009-03-23 21:50:21 +00002933
2934class Test_TestSkipping(TestCase):
2935
2936 def test_skipping(self):
2937 class Foo(unittest.TestCase):
2938 def test_skip_me(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002939 self.skipTest("skip")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002940 events = []
2941 result = LoggingResult(events)
2942 test = Foo("test_skip_me")
2943 test.run(result)
2944 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2945 self.assertEqual(result.skipped, [(test, "skip")])
2946
2947 # Try letting setUp skip the test now.
2948 class Foo(unittest.TestCase):
2949 def setUp(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002950 self.skipTest("testing")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002951 def test_nothing(self): pass
2952 events = []
2953 result = LoggingResult(events)
2954 test = Foo("test_nothing")
2955 test.run(result)
2956 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2957 self.assertEqual(result.skipped, [(test, "testing")])
2958 self.assertEqual(result.testsRun, 1)
2959
2960 def test_skipping_decorators(self):
2961 op_table = ((unittest.skipUnless, False, True),
2962 (unittest.skipIf, True, False))
2963 for deco, do_skip, dont_skip in op_table:
2964 class Foo(unittest.TestCase):
2965 @deco(do_skip, "testing")
2966 def test_skip(self): pass
2967
2968 @deco(dont_skip, "testing")
2969 def test_dont_skip(self): pass
2970 test_do_skip = Foo("test_skip")
2971 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002972 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002973 events = []
2974 result = LoggingResult(events)
2975 suite.run(result)
2976 self.assertEqual(len(result.skipped), 1)
2977 expected = ['startTest', 'addSkip', 'stopTest',
2978 'startTest', 'addSuccess', 'stopTest']
2979 self.assertEqual(events, expected)
2980 self.assertEqual(result.testsRun, 2)
2981 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
2982 self.assertTrue(result.wasSuccessful())
2983
2984 def test_skip_class(self):
2985 @unittest.skip("testing")
2986 class Foo(unittest.TestCase):
2987 def test_1(self):
2988 record.append(1)
2989 record = []
2990 result = unittest.TestResult()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002991 test = Foo("test_1")
2992 suite = unittest.TestSuite([test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002993 suite.run(result)
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002994 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002995 self.assertEqual(record, [])
2996
2997 def test_expected_failure(self):
2998 class Foo(unittest.TestCase):
2999 @unittest.expectedFailure
3000 def test_die(self):
3001 self.fail("help me!")
3002 events = []
3003 result = LoggingResult(events)
3004 test = Foo("test_die")
3005 test.run(result)
3006 self.assertEqual(events,
3007 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003008 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00003009 self.assertTrue(result.wasSuccessful())
3010
3011 def test_unexpected_success(self):
3012 class Foo(unittest.TestCase):
3013 @unittest.expectedFailure
3014 def test_die(self):
3015 pass
3016 events = []
3017 result = LoggingResult(events)
3018 test = Foo("test_die")
3019 test.run(result)
3020 self.assertEqual(events,
3021 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3022 self.assertFalse(result.failures)
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003023 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003024 self.assertTrue(result.wasSuccessful())
3025
3026
3027
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003028class Test_Assertions(TestCase):
3029 def test_AlmostEqual(self):
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003030 self.assertAlmostEqual(1.00000001, 1.0)
3031 self.assertNotAlmostEqual(1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003032 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003033 self.assertAlmostEqual, 1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003034 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003035 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003036
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003037 self.assertAlmostEqual(1.1, 1.0, places=0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003038 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003039 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003040
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003041 self.assertAlmostEqual(0, .1+.1j, places=0)
3042 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003043 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003044 self.assertAlmostEqual, 0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003045 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003046 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003047
Michael Foordc3f79372009-09-13 16:40:02 +00003048 self.assertAlmostEqual(float('inf'), float('inf'))
3049 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3050 float('inf'), float('inf'))
3051
3052
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003053 def test_assertRaises(self):
3054 def _raise(e):
3055 raise e
3056 self.assertRaises(KeyError, _raise, KeyError)
3057 self.assertRaises(KeyError, _raise, KeyError("key"))
3058 try:
3059 self.assertRaises(KeyError, lambda: None)
Gregory P. Smith28399852009-03-31 16:54:10 +00003060 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003061 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003062 else:
3063 self.fail("assertRaises() didn't fail")
3064 try:
3065 self.assertRaises(KeyError, _raise, ValueError)
3066 except ValueError:
3067 pass
3068 else:
3069 self.fail("assertRaises() didn't let exception pass through")
3070 with self.assertRaises(KeyError):
3071 raise KeyError
3072 with self.assertRaises(KeyError):
3073 raise KeyError("key")
3074 try:
3075 with self.assertRaises(KeyError):
3076 pass
Gregory P. Smith28399852009-03-31 16:54:10 +00003077 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003078 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003079 else:
3080 self.fail("assertRaises() didn't fail")
3081 try:
3082 with self.assertRaises(KeyError):
3083 raise ValueError
3084 except ValueError:
3085 pass
3086 else:
3087 self.fail("assertRaises() didn't let exception pass through")
3088
3089
Michael Foord345b2fe2009-04-02 03:20:38 +00003090class TestLongMessage(TestCase):
3091 """Test that the individual asserts honour longMessage.
3092 This actually tests all the message behaviour for
3093 asserts that use longMessage."""
3094
3095 def setUp(self):
3096 class TestableTestFalse(TestCase):
3097 longMessage = False
3098 failureException = self.failureException
3099
3100 def testTest(self):
3101 pass
3102
3103 class TestableTestTrue(TestCase):
3104 longMessage = True
3105 failureException = self.failureException
3106
3107 def testTest(self):
3108 pass
3109
3110 self.testableTrue = TestableTestTrue('testTest')
3111 self.testableFalse = TestableTestFalse('testTest')
3112
3113 def testDefault(self):
3114 self.assertFalse(TestCase.longMessage)
3115
3116 def test_formatMsg(self):
3117 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3118 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3119
3120 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3121 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3122
3123 def assertMessages(self, methodName, args, errors):
3124 def getMethod(i):
3125 useTestableFalse = i < 2
3126 if useTestableFalse:
3127 test = self.testableFalse
3128 else:
3129 test = self.testableTrue
3130 return getattr(test, methodName)
3131
3132 for i, expected_regexp in enumerate(errors):
3133 testMethod = getMethod(i)
3134 kwargs = {}
3135 withMsg = i % 2
3136 if withMsg:
3137 kwargs = {"msg": "oops"}
3138
3139 with self.assertRaisesRegexp(self.failureException,
3140 expected_regexp=expected_regexp):
3141 testMethod(*args, **kwargs)
3142
3143 def testAssertTrue(self):
3144 self.assertMessages('assertTrue', (False,),
3145 ["^False is not True$", "^oops$", "^False is not True$",
3146 "^False is not True : oops$"])
3147
3148 def testAssertFalse(self):
3149 self.assertMessages('assertFalse', (True,),
3150 ["^True is not False$", "^oops$", "^True is not False$",
3151 "^True is not False : oops$"])
3152
3153 def testNotEqual(self):
3154 self.assertMessages('assertNotEqual', (1, 1),
3155 ["^1 == 1$", "^oops$", "^1 == 1$",
3156 "^1 == 1 : oops$"])
3157
3158 def testAlmostEqual(self):
3159 self.assertMessages('assertAlmostEqual', (1, 2),
3160 ["^1 != 2 within 7 places$", "^oops$",
3161 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3162
3163 def testNotAlmostEqual(self):
3164 self.assertMessages('assertNotAlmostEqual', (1, 1),
3165 ["^1 == 1 within 7 places$", "^oops$",
3166 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3167
3168 def test_baseAssertEqual(self):
3169 self.assertMessages('_baseAssertEqual', (1, 2),
3170 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3171
3172 def testAssertSequenceEqual(self):
3173 # Error messages are multiline so not testing on full message
3174 # assertTupleEqual and assertListEqual delegate to this method
3175 self.assertMessages('assertSequenceEqual', ([], [None]),
3176 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3177 r"\+ \[None\] : oops$"])
3178
3179 def testAssertSetEqual(self):
3180 self.assertMessages('assertSetEqual', (set(), set([None])),
3181 ["None$", "^oops$", "None$",
3182 "None : oops$"])
3183
3184 def testAssertIn(self):
3185 self.assertMessages('assertIn', (None, []),
3186 ['^None not found in \[\]$', "^oops$",
3187 '^None not found in \[\]$',
3188 '^None not found in \[\] : oops$'])
3189
3190 def testAssertNotIn(self):
3191 self.assertMessages('assertNotIn', (None, [None]),
3192 ['^None unexpectedly found in \[None\]$', "^oops$",
3193 '^None unexpectedly found in \[None\]$',
3194 '^None unexpectedly found in \[None\] : oops$'])
3195
3196 def testAssertDictEqual(self):
3197 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3198 [r"\+ \{'key': 'value'\}$", "^oops$",
3199 "\+ \{'key': 'value'\}$",
3200 "\+ \{'key': 'value'\} : oops$"])
3201
3202 def testAssertDictContainsSubset(self):
3203 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3204 ["^Missing: 'key'$", "^oops$",
3205 "^Missing: 'key'$",
3206 "^Missing: 'key' : oops$"])
3207
3208 def testAssertSameElements(self):
3209 self.assertMessages('assertSameElements', ([], [None]),
3210 [r"\[None\]$", "^oops$",
3211 r"\[None\]$",
3212 r"\[None\] : oops$"])
3213
3214 def testAssertMultiLineEqual(self):
3215 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3216 [r"\+ foo$", "^oops$",
3217 r"\+ foo$",
3218 r"\+ foo : oops$"])
3219
3220 def testAssertLess(self):
3221 self.assertMessages('assertLess', (2, 1),
3222 ["^2 not less than 1$", "^oops$",
3223 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3224
3225 def testAssertLessEqual(self):
3226 self.assertMessages('assertLessEqual', (2, 1),
3227 ["^2 not less than or equal to 1$", "^oops$",
3228 "^2 not less than or equal to 1$",
3229 "^2 not less than or equal to 1 : oops$"])
3230
3231 def testAssertGreater(self):
3232 self.assertMessages('assertGreater', (1, 2),
3233 ["^1 not greater than 2$", "^oops$",
3234 "^1 not greater than 2$",
3235 "^1 not greater than 2 : oops$"])
3236
3237 def testAssertGreaterEqual(self):
3238 self.assertMessages('assertGreaterEqual', (1, 2),
3239 ["^1 not greater than or equal to 2$", "^oops$",
3240 "^1 not greater than or equal to 2$",
3241 "^1 not greater than or equal to 2 : oops$"])
3242
3243 def testAssertIsNone(self):
3244 self.assertMessages('assertIsNone', ('not None',),
3245 ["^'not None' is not None$", "^oops$",
3246 "^'not None' is not None$",
3247 "^'not None' is not None : oops$"])
3248
3249 def testAssertIsNotNone(self):
3250 self.assertMessages('assertIsNotNone', (None,),
3251 ["^unexpectedly None$", "^oops$",
3252 "^unexpectedly None$",
3253 "^unexpectedly None : oops$"])
3254
Michael Foordf2dfef12009-04-05 19:19:28 +00003255 def testAssertIs(self):
3256 self.assertMessages('assertIs', (None, 'foo'),
3257 ["^None is not 'foo'$", "^oops$",
3258 "^None is not 'foo'$",
3259 "^None is not 'foo' : oops$"])
3260
3261 def testAssertIsNot(self):
3262 self.assertMessages('assertIsNot', (None, None),
3263 ["^unexpectedly identical: None$", "^oops$",
3264 "^unexpectedly identical: None$",
3265 "^unexpectedly identical: None : oops$"])
3266
Michael Foord345b2fe2009-04-02 03:20:38 +00003267
Michael Foorde2fb98f2009-05-02 20:15:05 +00003268class TestCleanUp(TestCase):
3269
3270 def testCleanUp(self):
3271 class TestableTest(TestCase):
3272 def testNothing(self):
3273 pass
3274
3275 test = TestableTest('testNothing')
3276 self.assertEqual(test._cleanups, [])
3277
3278 cleanups = []
3279
3280 def cleanup1(*args, **kwargs):
3281 cleanups.append((1, args, kwargs))
3282
3283 def cleanup2(*args, **kwargs):
3284 cleanups.append((2, args, kwargs))
3285
3286 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3287 test.addCleanup(cleanup2)
3288
3289 self.assertEqual(test._cleanups,
3290 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3291 (cleanup2, (), {})])
3292
3293 result = test.doCleanups()
3294 self.assertTrue(result)
3295
3296 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3297
3298 def testCleanUpWithErrors(self):
3299 class TestableTest(TestCase):
3300 def testNothing(self):
3301 pass
3302
3303 class MockResult(object):
3304 errors = []
3305 def addError(self, test, exc_info):
3306 self.errors.append((test, exc_info))
3307
3308 result = MockResult()
3309 test = TestableTest('testNothing')
Michael Foorda50af062009-05-21 22:57:02 +00003310 test._resultForDoCleanups = result
Michael Foorde2fb98f2009-05-02 20:15:05 +00003311
3312 exc1 = Exception('foo')
3313 exc2 = Exception('bar')
3314 def cleanup1():
3315 raise exc1
3316
3317 def cleanup2():
3318 raise exc2
3319
3320 test.addCleanup(cleanup1)
3321 test.addCleanup(cleanup2)
3322
3323 self.assertFalse(test.doCleanups())
3324
3325 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3326 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3327 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3328
3329 def testCleanupInRun(self):
3330 blowUp = False
3331 ordering = []
3332
3333 class TestableTest(TestCase):
3334 def setUp(self):
3335 ordering.append('setUp')
3336 if blowUp:
3337 raise Exception('foo')
3338
3339 def testNothing(self):
3340 ordering.append('test')
3341
3342 def tearDown(self):
3343 ordering.append('tearDown')
3344
3345 test = TestableTest('testNothing')
3346
3347 def cleanup1():
3348 ordering.append('cleanup1')
3349 def cleanup2():
3350 ordering.append('cleanup2')
3351 test.addCleanup(cleanup1)
3352 test.addCleanup(cleanup2)
3353
3354 def success(some_test):
3355 self.assertEqual(some_test, test)
3356 ordering.append('success')
3357
3358 result = unittest.TestResult()
3359 result.addSuccess = success
3360
3361 test.run(result)
3362 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3363 'cleanup2', 'cleanup1', 'success'])
3364
3365 blowUp = True
3366 ordering = []
3367 test = TestableTest('testNothing')
3368 test.addCleanup(cleanup1)
3369 test.run(result)
3370 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3371
3372
Michael Foord829f6b82009-05-02 11:43:06 +00003373class Test_TestProgram(TestCase):
3374
3375 # Horrible white box test
3376 def testNoExit(self):
3377 result = object()
3378 test = object()
3379
3380 class FakeRunner(object):
3381 def run(self, test):
3382 self.test = test
3383 return result
3384
3385 runner = FakeRunner()
3386
Michael Foord5d31e052009-05-11 17:59:43 +00003387 oldParseArgs = TestProgram.parseArgs
3388 def restoreParseArgs():
Michael Foord829f6b82009-05-02 11:43:06 +00003389 TestProgram.parseArgs = oldParseArgs
Michael Foord5d31e052009-05-11 17:59:43 +00003390 TestProgram.parseArgs = lambda *args: None
3391 self.addCleanup(restoreParseArgs)
3392
3393 def removeTest():
Michael Foord829f6b82009-05-02 11:43:06 +00003394 del TestProgram.test
Michael Foord5d31e052009-05-11 17:59:43 +00003395 TestProgram.test = test
3396 self.addCleanup(removeTest)
3397
3398 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3399
3400 self.assertEqual(program.result, result)
3401 self.assertEqual(runner.test, test)
3402 self.assertEqual(program.verbosity, 2)
Michael Foord829f6b82009-05-02 11:43:06 +00003403
Michael Foord829f6b82009-05-02 11:43:06 +00003404 class FooBar(unittest.TestCase):
3405 def testPass(self):
3406 assert True
3407 def testFail(self):
3408 assert False
3409
3410 class FooBarLoader(unittest.TestLoader):
3411 """Test loader that returns a suite containing FooBar."""
3412 def loadTestsFromModule(self, module):
3413 return self.suiteClass(
3414 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3415
3416
3417 def test_NonExit(self):
3418 program = unittest.main(exit=False,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003419 argv=["foobar"],
3420 testRunner=unittest.TextTestRunner(stream=StringIO()),
3421 testLoader=self.FooBarLoader())
Michael Foord829f6b82009-05-02 11:43:06 +00003422 self.assertTrue(hasattr(program, 'result'))
3423
3424
3425 def test_Exit(self):
3426 self.assertRaises(
3427 SystemExit,
3428 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003429 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003430 testRunner=unittest.TextTestRunner(stream=StringIO()),
3431 exit=True,
3432 testLoader=self.FooBarLoader())
3433
3434
3435 def test_ExitAsDefault(self):
3436 self.assertRaises(
3437 SystemExit,
3438 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003439 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003440 testRunner=unittest.TextTestRunner(stream=StringIO()),
3441 testLoader=self.FooBarLoader())
3442
3443
Michael Foord07ef4872009-05-02 22:43:34 +00003444class Test_TextTestRunner(TestCase):
3445 """Tests for TextTestRunner."""
3446
3447 def test_works_with_result_without_startTestRun_stopTestRun(self):
3448 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3449 separator2 = ''
3450 def printErrors(self):
3451 pass
3452
3453 class Runner(unittest.TextTestRunner):
3454 def __init__(self):
3455 super(Runner, self).__init__(StringIO())
3456
3457 def _makeResult(self):
3458 return OldTextResult()
3459
3460 runner = Runner()
3461 runner.run(unittest.TestSuite())
3462
3463 def test_startTestRun_stopTestRun_called(self):
3464 class LoggingTextResult(LoggingResult):
3465 separator2 = ''
3466 def printErrors(self):
3467 pass
3468
3469 class LoggingRunner(unittest.TextTestRunner):
3470 def __init__(self, events):
3471 super(LoggingRunner, self).__init__(StringIO())
3472 self._events = events
3473
3474 def _makeResult(self):
3475 return LoggingTextResult(self._events)
3476
3477 events = []
3478 runner = LoggingRunner(events)
3479 runner.run(unittest.TestSuite())
3480 expected = ['startTestRun', 'stopTestRun']
3481 self.assertEqual(events, expected)
3482
Antoine Pitrou0734c632009-11-10 20:49:30 +00003483 def test_pickle_unpickle(self):
3484 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3485 # required by test_multiprocessing under Windows (in verbose mode).
3486 import StringIO
3487 # cStringIO objects are not pickleable, but StringIO objects are.
3488 stream = StringIO.StringIO("foo")
3489 runner = unittest.TextTestRunner(stream)
3490 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
3491 s = pickle.dumps(runner, protocol=protocol)
3492 obj = pickle.loads(s)
3493 # StringIO objects never compare equal, a cheap test instead.
3494 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3495
Michael Foord07ef4872009-05-02 22:43:34 +00003496
Michael Foordb4a81c82009-05-29 20:33:46 +00003497class TestDiscovery(TestCase):
3498
3499 # Heavily mocked tests so I can avoid hitting the filesystem
Michael Foorde91ea562009-09-13 19:07:03 +00003500 def test_get_name_from_path(self):
Michael Foordb4a81c82009-05-29 20:33:46 +00003501 loader = unittest.TestLoader()
3502
Michael Foordb4a81c82009-05-29 20:33:46 +00003503 loader._top_level_dir = '/foo'
Michael Foorde91ea562009-09-13 19:07:03 +00003504 name = loader._get_name_from_path('/foo/bar/baz.py')
3505 self.assertEqual(name, 'bar.baz')
Michael Foordb4a81c82009-05-29 20:33:46 +00003506
3507 if not __debug__:
3508 # asserts are off
3509 return
3510
3511 with self.assertRaises(AssertionError):
Michael Foorde91ea562009-09-13 19:07:03 +00003512 loader._get_name_from_path('/bar/baz.py')
Michael Foordb4a81c82009-05-29 20:33:46 +00003513
3514 def test_find_tests(self):
3515 loader = unittest.TestLoader()
3516
3517 original_listdir = os.listdir
3518 def restore_listdir():
3519 os.listdir = original_listdir
3520 original_isfile = os.path.isfile
3521 def restore_isfile():
3522 os.path.isfile = original_isfile
3523 original_isdir = os.path.isdir
3524 def restore_isdir():
3525 os.path.isdir = original_isdir
3526
3527 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Michael Foorde91ea562009-09-13 19:07:03 +00003528 'test.foo', 'test-not-a-module.py', 'another_dir'],
Michael Foordb4a81c82009-05-29 20:33:46 +00003529 ['test3.py', 'test4.py', ]]
3530 os.listdir = lambda path: path_lists.pop(0)
3531 self.addCleanup(restore_listdir)
3532
3533 def isdir(path):
3534 return path.endswith('dir')
3535 os.path.isdir = isdir
3536 self.addCleanup(restore_isdir)
3537
3538 def isfile(path):
3539 # another_dir is not a package and so shouldn't be recursed into
3540 return not path.endswith('dir') and not 'another_dir' in path
3541 os.path.isfile = isfile
3542 self.addCleanup(restore_isfile)
3543
Michael Foorde91ea562009-09-13 19:07:03 +00003544 loader._get_module_from_name = lambda path: path + ' module'
Michael Foordb4a81c82009-05-29 20:33:46 +00003545 loader.loadTestsFromModule = lambda module: module + ' tests'
3546
3547 loader._top_level_dir = '/foo'
3548 suite = list(loader._find_tests('/foo', 'test*.py'))
3549
Michael Foorde91ea562009-09-13 19:07:03 +00003550 expected = [name + ' module tests' for name in
3551 ('test1', 'test2')]
3552 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3553 ('test3', 'test4')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003554 self.assertEqual(suite, expected)
3555
3556 def test_find_tests_with_package(self):
3557 loader = unittest.TestLoader()
3558
3559 original_listdir = os.listdir
3560 def restore_listdir():
3561 os.listdir = original_listdir
3562 original_isfile = os.path.isfile
3563 def restore_isfile():
3564 os.path.isfile = original_isfile
3565 original_isdir = os.path.isdir
3566 def restore_isdir():
3567 os.path.isdir = original_isdir
3568
3569 directories = ['a_directory', 'test_directory', 'test_directory2']
3570 path_lists = [directories, [], [], []]
3571 os.listdir = lambda path: path_lists.pop(0)
3572 self.addCleanup(restore_listdir)
3573
3574 os.path.isdir = lambda path: True
3575 self.addCleanup(restore_isdir)
3576
3577 os.path.isfile = lambda path: os.path.basename(path) not in directories
3578 self.addCleanup(restore_isfile)
3579
3580 class Module(object):
3581 paths = []
3582 load_tests_args = []
3583
3584 def __init__(self, path):
3585 self.path = path
3586 self.paths.append(path)
3587 if os.path.basename(path) == 'test_directory':
3588 def load_tests(loader, tests, pattern):
3589 self.load_tests_args.append((loader, tests, pattern))
3590 return 'load_tests'
3591 self.load_tests = load_tests
3592
3593 def __eq__(self, other):
3594 return self.path == other.path
3595
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003596 # Silence py3k warning
3597 __hash__ = None
3598
Michael Foorde91ea562009-09-13 19:07:03 +00003599 loader._get_module_from_name = lambda name: Module(name)
Michael Foordb4a81c82009-05-29 20:33:46 +00003600 def loadTestsFromModule(module, use_load_tests):
3601 if use_load_tests:
3602 raise self.failureException('use_load_tests should be False for packages')
3603 return module.path + ' module tests'
3604 loader.loadTestsFromModule = loadTestsFromModule
3605
3606 loader._top_level_dir = '/foo'
3607 # this time no '.py' on the pattern so that it can match
3608 # a test package
3609 suite = list(loader._find_tests('/foo', 'test*'))
3610
3611 # We should have loaded tests from the test_directory package by calling load_tests
3612 # and directly from the test_directory2 package
Michael Foordd53d0852009-06-05 14:14:34 +00003613 self.assertEqual(suite,
Michael Foorde91ea562009-09-13 19:07:03 +00003614 ['load_tests', 'test_directory2' + ' module tests'])
3615 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Michael Foordb4a81c82009-05-29 20:33:46 +00003616
3617 # load_tests should have been called once with loader, tests and pattern
3618 self.assertEqual(Module.load_tests_args,
Michael Foorde91ea562009-09-13 19:07:03 +00003619 [(loader, 'test_directory' + ' module tests', 'test*')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003620
3621 def test_discover(self):
3622 loader = unittest.TestLoader()
3623
3624 original_isfile = os.path.isfile
3625 def restore_isfile():
3626 os.path.isfile = original_isfile
3627
3628 os.path.isfile = lambda path: False
3629 self.addCleanup(restore_isfile)
3630
Nick Coghlanb6edf192009-10-17 08:21:21 +00003631 orig_sys_path = sys.path[:]
3632 def restore_path():
3633 sys.path[:] = orig_sys_path
3634 self.addCleanup(restore_path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003635
Nick Coghlanb6edf192009-10-17 08:21:21 +00003636 full_path = os.path.abspath(os.path.normpath('/foo'))
Michael Foordb4a81c82009-05-29 20:33:46 +00003637 with self.assertRaises(ImportError):
3638 loader.discover('/foo/bar', top_level_dir='/foo')
3639
3640 self.assertEqual(loader._top_level_dir, full_path)
3641 self.assertIn(full_path, sys.path)
3642
3643 os.path.isfile = lambda path: True
3644 _find_tests_args = []
3645 def _find_tests(start_dir, pattern):
3646 _find_tests_args.append((start_dir, pattern))
3647 return ['tests']
3648 loader._find_tests = _find_tests
3649 loader.suiteClass = str
3650
3651 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3652
3653 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3654 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3655 self.assertEqual(suite, "['tests']")
3656 self.assertEqual(loader._top_level_dir, top_level_dir)
3657 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlanb6edf192009-10-17 08:21:21 +00003658 self.assertIn(top_level_dir, sys.path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003659
Michael Foorde91ea562009-09-13 19:07:03 +00003660 def test_discover_with_modules_that_fail_to_import(self):
3661 loader = unittest.TestLoader()
3662
3663 listdir = os.listdir
3664 os.listdir = lambda _: ['test_this_does_not_exist.py']
3665 isfile = os.path.isfile
3666 os.path.isfile = lambda _: True
Nick Coghlanb6edf192009-10-17 08:21:21 +00003667 orig_sys_path = sys.path[:]
Michael Foorde91ea562009-09-13 19:07:03 +00003668 def restore():
3669 os.path.isfile = isfile
3670 os.listdir = listdir
Nick Coghlanb6edf192009-10-17 08:21:21 +00003671 sys.path[:] = orig_sys_path
Michael Foorde91ea562009-09-13 19:07:03 +00003672 self.addCleanup(restore)
3673
3674 suite = loader.discover('.')
Nick Coghlanb6edf192009-10-17 08:21:21 +00003675 self.assertIn(os.getcwd(), sys.path)
Michael Foorde91ea562009-09-13 19:07:03 +00003676 self.assertEqual(suite.countTestCases(), 1)
3677 test = list(list(suite)[0])[0] # extract test from suite
3678
3679 with self.assertRaises(ImportError):
3680 test.test_this_does_not_exist()
3681
Michael Foordb4a81c82009-05-29 20:33:46 +00003682 def test_command_line_handling_parseArgs(self):
3683 # Haha - take that uninstantiable class
3684 program = object.__new__(TestProgram)
3685
3686 args = []
3687 def do_discovery(argv):
3688 args.extend(argv)
3689 program._do_discovery = do_discovery
3690 program.parseArgs(['something', 'discover'])
3691 self.assertEqual(args, [])
3692
3693 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3694 self.assertEqual(args, ['foo', 'bar'])
3695
3696 def test_command_line_handling_do_discovery_too_many_arguments(self):
3697 class Stop(Exception):
3698 pass
3699 def usageExit():
3700 raise Stop
3701
3702 program = object.__new__(TestProgram)
3703 program.usageExit = usageExit
3704
3705 with self.assertRaises(Stop):
3706 # too many args
3707 program._do_discovery(['one', 'two', 'three', 'four'])
3708
3709
3710 def test_command_line_handling_do_discovery_calls_loader(self):
3711 program = object.__new__(TestProgram)
3712
3713 class Loader(object):
3714 args = []
3715 def discover(self, start_dir, pattern, top_level_dir):
3716 self.args.append((start_dir, pattern, top_level_dir))
3717 return 'tests'
3718
3719 program._do_discovery(['-v'], Loader=Loader)
3720 self.assertEqual(program.verbosity, 2)
3721 self.assertEqual(program.test, 'tests')
3722 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3723
3724 Loader.args = []
3725 program = object.__new__(TestProgram)
3726 program._do_discovery(['--verbose'], Loader=Loader)
3727 self.assertEqual(program.test, 'tests')
3728 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3729
3730 Loader.args = []
3731 program = object.__new__(TestProgram)
3732 program._do_discovery([], Loader=Loader)
3733 self.assertEqual(program.test, 'tests')
3734 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3735
3736 Loader.args = []
3737 program = object.__new__(TestProgram)
3738 program._do_discovery(['fish'], Loader=Loader)
3739 self.assertEqual(program.test, 'tests')
3740 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3741
3742 Loader.args = []
3743 program = object.__new__(TestProgram)
3744 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3745 self.assertEqual(program.test, 'tests')
3746 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3747
3748 Loader.args = []
3749 program = object.__new__(TestProgram)
3750 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3751 self.assertEqual(program.test, 'tests')
3752 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3753
3754 Loader.args = []
3755 program = object.__new__(TestProgram)
3756 program._do_discovery(['-s', 'fish'], Loader=Loader)
3757 self.assertEqual(program.test, 'tests')
3758 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3759
3760 Loader.args = []
3761 program = object.__new__(TestProgram)
3762 program._do_discovery(['-t', 'fish'], Loader=Loader)
3763 self.assertEqual(program.test, 'tests')
3764 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3765
3766 Loader.args = []
3767 program = object.__new__(TestProgram)
3768 program._do_discovery(['-p', 'fish'], Loader=Loader)
3769 self.assertEqual(program.test, 'tests')
3770 self.assertEqual(Loader.args, [('.', 'fish', None)])
3771
3772 Loader.args = []
3773 program = object.__new__(TestProgram)
3774 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3775 self.assertEqual(program.test, 'tests')
3776 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3777 self.assertEqual(program.verbosity, 2)
3778
3779
Jim Fultonfafd8742004-08-28 15:22:12 +00003780######################################################################
3781## Main
3782######################################################################
3783
3784def test_main():
Georg Brandl15c5ce92007-03-07 09:09:40 +00003785 test_support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003786 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Michael Foord829f6b82009-05-02 11:43:06 +00003787 Test_TestSkipping, Test_Assertions, TestLongMessage,
Antoine Pitrou0734c632009-11-10 20:49:30 +00003788 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner)
Jim Fultonfafd8742004-08-28 15:22:12 +00003789
Georg Brandl15c5ce92007-03-07 09:09:40 +00003790if __name__ == "__main__":
Tim Petersea5962f2007-03-12 18:07:52 +00003791 test_main()