blob: 7b6922c620923f8eb0d81c712d93da9cc54d22c9 [file] [log] [blame]
Jim Fultonfafd8742004-08-28 15:22:12 +00001"""Test script for unittest.
2
Georg Brandl15c5ce92007-03-07 09:09:40 +00003By Collin Winter <collinw at gmail.com>
4
5Still need testing:
6 TestCase.{assert,fail}* methods (some are tested implicitly)
Jim Fultonfafd8742004-08-28 15:22:12 +00007"""
8
Michael Foordb4a81c82009-05-29 20:33:46 +00009import os
Gregory P. Smith28399852009-03-31 16:54:10 +000010import re
Michael Foordb4a81c82009-05-29 20:33:46 +000011import sys
Georg Brandl15c5ce92007-03-07 09:09:40 +000012from test import test_support
Jim Fultonfafd8742004-08-28 15:22:12 +000013import unittest
Michael Foord829f6b82009-05-02 11:43:06 +000014from unittest import TestCase, TestProgram
Christian Heimesc756d002007-11-27 21:34:01 +000015import types
Michael Foorde2942d02009-04-02 05:51:54 +000016from copy import deepcopy
Michael Foord829f6b82009-05-02 11:43:06 +000017from cStringIO import StringIO
Antoine Pitrou0734c632009-11-10 20:49:30 +000018import pickle
Jim Fultonfafd8742004-08-28 15:22:12 +000019
Michael Foord225a0992010-02-18 20:30:09 +000020
Georg Brandl15c5ce92007-03-07 09:09:40 +000021### Support code
22################################################################
Jim Fultonfafd8742004-08-28 15:22:12 +000023
Georg Brandl15c5ce92007-03-07 09:09:40 +000024class LoggingResult(unittest.TestResult):
25 def __init__(self, log):
26 self._events = log
27 super(LoggingResult, self).__init__()
28
29 def startTest(self, test):
30 self._events.append('startTest')
31 super(LoggingResult, self).startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +000032
Michael Foord07ef4872009-05-02 22:43:34 +000033 def startTestRun(self):
34 self._events.append('startTestRun')
35 super(LoggingResult, self).startTestRun()
36
Georg Brandl15c5ce92007-03-07 09:09:40 +000037 def stopTest(self, test):
38 self._events.append('stopTest')
39 super(LoggingResult, self).stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +000040
Michael Foord07ef4872009-05-02 22:43:34 +000041 def stopTestRun(self):
42 self._events.append('stopTestRun')
43 super(LoggingResult, self).stopTestRun()
44
Georg Brandl15c5ce92007-03-07 09:09:40 +000045 def addFailure(self, *args):
46 self._events.append('addFailure')
47 super(LoggingResult, self).addFailure(*args)
Tim Petersea5962f2007-03-12 18:07:52 +000048
Benjamin Peterson692428e2009-03-23 21:50:21 +000049 def addSuccess(self, *args):
50 self._events.append('addSuccess')
51 super(LoggingResult, self).addSuccess(*args)
52
Georg Brandl15c5ce92007-03-07 09:09:40 +000053 def addError(self, *args):
54 self._events.append('addError')
55 super(LoggingResult, self).addError(*args)
56
Benjamin Peterson692428e2009-03-23 21:50:21 +000057 def addSkip(self, *args):
58 self._events.append('addSkip')
59 super(LoggingResult, self).addSkip(*args)
60
61 def addExpectedFailure(self, *args):
62 self._events.append('addExpectedFailure')
63 super(LoggingResult, self).addExpectedFailure(*args)
64
65 def addUnexpectedSuccess(self, *args):
66 self._events.append('addUnexpectedSuccess')
67 super(LoggingResult, self).addUnexpectedSuccess(*args)
68
69
Georg Brandl15c5ce92007-03-07 09:09:40 +000070class TestEquality(object):
Michael Foord345b2fe2009-04-02 03:20:38 +000071 """Used as a mixin for TestCase"""
72
Tim Petersea5962f2007-03-12 18:07:52 +000073 # Check for a valid __eq__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000074 def test_eq(self):
75 for obj_1, obj_2 in self.eq_pairs:
76 self.assertEqual(obj_1, obj_2)
77 self.assertEqual(obj_2, obj_1)
Tim Petersea5962f2007-03-12 18:07:52 +000078
79 # Check for a valid __ne__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000080 def test_ne(self):
81 for obj_1, obj_2 in self.ne_pairs:
Benjamin Peterson6b0032f2009-06-30 23:30:12 +000082 self.assertNotEqual(obj_1, obj_2)
83 self.assertNotEqual(obj_2, obj_1)
Tim Petersea5962f2007-03-12 18:07:52 +000084
Georg Brandl15c5ce92007-03-07 09:09:40 +000085class TestHashing(object):
Michael Foord345b2fe2009-04-02 03:20:38 +000086 """Used as a mixin for TestCase"""
87
Tim Petersea5962f2007-03-12 18:07:52 +000088 # Check for a valid __hash__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000089 def test_hash(self):
90 for obj_1, obj_2 in self.eq_pairs:
91 try:
Gregory P. Smith28399852009-03-31 16:54:10 +000092 if not hash(obj_1) == hash(obj_2):
93 self.fail("%r and %r do not hash equal" % (obj_1, obj_2))
Georg Brandl15c5ce92007-03-07 09:09:40 +000094 except KeyboardInterrupt:
95 raise
Georg Brandl15c5ce92007-03-07 09:09:40 +000096 except Exception, e:
Gregory P. Smith28399852009-03-31 16:54:10 +000097 self.fail("Problem hashing %r and %r: %s" % (obj_1, obj_2, e))
Tim Petersea5962f2007-03-12 18:07:52 +000098
Georg Brandl15c5ce92007-03-07 09:09:40 +000099 for obj_1, obj_2 in self.ne_pairs:
100 try:
Gregory P. Smith28399852009-03-31 16:54:10 +0000101 if hash(obj_1) == hash(obj_2):
102 self.fail("%s and %s hash equal, but shouldn't" %
103 (obj_1, obj_2))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000104 except KeyboardInterrupt:
105 raise
Georg Brandl15c5ce92007-03-07 09:09:40 +0000106 except Exception, e:
107 self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e))
Tim Petersea5962f2007-03-12 18:07:52 +0000108
Georg Brandl15c5ce92007-03-07 09:09:40 +0000109
Benjamin Peterson692428e2009-03-23 21:50:21 +0000110# List subclass we can add attributes to.
111class MyClassSuite(list):
112
Benjamin Peterson176a56c2009-05-25 00:48:58 +0000113 def __init__(self, tests):
Benjamin Peterson692428e2009-03-23 21:50:21 +0000114 super(MyClassSuite, self).__init__(tests)
115
116
Georg Brandl15c5ce92007-03-07 09:09:40 +0000117################################################################
118### /Support code
119
120class Test_TestLoader(TestCase):
121
122 ### Tests for TestLoader.loadTestsFromTestCase
123 ################################################################
124
125 # "Return a suite of all tests cases contained in the TestCase-derived
126 # class testCaseClass"
127 def test_loadTestsFromTestCase(self):
128 class Foo(unittest.TestCase):
129 def test_1(self): pass
130 def test_2(self): pass
131 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000132
Georg Brandl15c5ce92007-03-07 09:09:40 +0000133 tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +0000134
Georg Brandl15c5ce92007-03-07 09:09:40 +0000135 loader = unittest.TestLoader()
136 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +0000137
Georg Brandl15c5ce92007-03-07 09:09:40 +0000138 # "Return a suite of all tests cases contained in the TestCase-derived
139 # class testCaseClass"
140 #
Tim Petersea5962f2007-03-12 18:07:52 +0000141 # Make sure it does the right thing even if no tests were found
Georg Brandl15c5ce92007-03-07 09:09:40 +0000142 def test_loadTestsFromTestCase__no_matches(self):
143 class Foo(unittest.TestCase):
144 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000145
Georg Brandl15c5ce92007-03-07 09:09:40 +0000146 empty_suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +0000147
Georg Brandl15c5ce92007-03-07 09:09:40 +0000148 loader = unittest.TestLoader()
149 self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite)
Tim Petersea5962f2007-03-12 18:07:52 +0000150
Georg Brandl15c5ce92007-03-07 09:09:40 +0000151 # "Return a suite of all tests cases contained in the TestCase-derived
152 # class testCaseClass"
153 #
154 # What happens if loadTestsFromTestCase() is given an object
155 # that isn't a subclass of TestCase? Specifically, what happens
156 # if testCaseClass is a subclass of TestSuite?
157 #
158 # This is checked for specifically in the code, so we better add a
159 # test for it.
160 def test_loadTestsFromTestCase__TestSuite_subclass(self):
161 class NotATestCase(unittest.TestSuite):
162 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000163
Georg Brandl15c5ce92007-03-07 09:09:40 +0000164 loader = unittest.TestLoader()
165 try:
166 loader.loadTestsFromTestCase(NotATestCase)
167 except TypeError:
168 pass
169 else:
170 self.fail('Should raise TypeError')
Tim Petersea5962f2007-03-12 18:07:52 +0000171
Georg Brandl15c5ce92007-03-07 09:09:40 +0000172 # "Return a suite of all tests cases contained in the TestCase-derived
173 # class testCaseClass"
174 #
175 # Make sure loadTestsFromTestCase() picks up the default test method
176 # name (as specified by TestCase), even though the method name does
177 # not match the default TestLoader.testMethodPrefix string
178 def test_loadTestsFromTestCase__default_method_name(self):
179 class Foo(unittest.TestCase):
180 def runTest(self):
181 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000182
Georg Brandl15c5ce92007-03-07 09:09:40 +0000183 loader = unittest.TestLoader()
184 # This has to be false for the test to succeed
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000185 self.assertFalse('runTest'.startswith(loader.testMethodPrefix))
Tim Petersea5962f2007-03-12 18:07:52 +0000186
Georg Brandl15c5ce92007-03-07 09:09:40 +0000187 suite = loader.loadTestsFromTestCase(Foo)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000188 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000189 self.assertEqual(list(suite), [Foo('runTest')])
190
191 ################################################################
192 ### /Tests for TestLoader.loadTestsFromTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000193
Georg Brandl15c5ce92007-03-07 09:09:40 +0000194 ### Tests for TestLoader.loadTestsFromModule
195 ################################################################
196
197 # "This method searches `module` for classes derived from TestCase"
198 def test_loadTestsFromModule__TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000199 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000200 class MyTestCase(unittest.TestCase):
201 def test(self):
202 pass
203 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000204
Georg Brandl15c5ce92007-03-07 09:09:40 +0000205 loader = unittest.TestLoader()
206 suite = loader.loadTestsFromModule(m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000207 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000208
Georg Brandl15c5ce92007-03-07 09:09:40 +0000209 expected = [loader.suiteClass([MyTestCase('test')])]
210 self.assertEqual(list(suite), expected)
Tim Petersea5962f2007-03-12 18:07:52 +0000211
Georg Brandl15c5ce92007-03-07 09:09:40 +0000212 # "This method searches `module` for classes derived from TestCase"
Tim Petersea5962f2007-03-12 18:07:52 +0000213 #
Georg Brandl15c5ce92007-03-07 09:09:40 +0000214 # What happens if no tests are found (no TestCase instances)?
215 def test_loadTestsFromModule__no_TestCase_instances(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000216 m = types.ModuleType('m')
Tim Petersea5962f2007-03-12 18:07:52 +0000217
Georg Brandl15c5ce92007-03-07 09:09:40 +0000218 loader = unittest.TestLoader()
219 suite = loader.loadTestsFromModule(m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000220 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000221 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000222
Georg Brandl15c5ce92007-03-07 09:09:40 +0000223 # "This method searches `module` for classes derived from TestCase"
224 #
Tim Petersea5962f2007-03-12 18:07:52 +0000225 # What happens if no tests are found (TestCases instances, but no tests)?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000226 def test_loadTestsFromModule__no_TestCase_tests(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000227 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000228 class MyTestCase(unittest.TestCase):
229 pass
230 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000231
Georg Brandl15c5ce92007-03-07 09:09:40 +0000232 loader = unittest.TestLoader()
233 suite = loader.loadTestsFromModule(m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000234 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000235
Georg Brandl15c5ce92007-03-07 09:09:40 +0000236 self.assertEqual(list(suite), [loader.suiteClass()])
Tim Petersea5962f2007-03-12 18:07:52 +0000237
Georg Brandl15c5ce92007-03-07 09:09:40 +0000238 # "This method searches `module` for classes derived from TestCase"s
239 #
240 # What happens if loadTestsFromModule() is given something other
241 # than a module?
242 #
243 # XXX Currently, it succeeds anyway. This flexibility
244 # should either be documented or loadTestsFromModule() should
245 # raise a TypeError
246 #
247 # XXX Certain people are using this behaviour. We'll add a test for it
248 def test_loadTestsFromModule__not_a_module(self):
249 class MyTestCase(unittest.TestCase):
250 def test(self):
251 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000252
Georg Brandl15c5ce92007-03-07 09:09:40 +0000253 class NotAModule(object):
254 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000255
Georg Brandl15c5ce92007-03-07 09:09:40 +0000256 loader = unittest.TestLoader()
257 suite = loader.loadTestsFromModule(NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000258
Georg Brandl15c5ce92007-03-07 09:09:40 +0000259 reference = [unittest.TestSuite([MyTestCase('test')])]
260 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000261
Michael Foordb4a81c82009-05-29 20:33:46 +0000262
263 # Check that loadTestsFromModule honors (or not) a module
264 # with a load_tests function.
265 def test_loadTestsFromModule__load_tests(self):
266 m = types.ModuleType('m')
267 class MyTestCase(unittest.TestCase):
268 def test(self):
269 pass
270 m.testcase_1 = MyTestCase
271
272 load_tests_args = []
273 def load_tests(loader, tests, pattern):
Michael Foord08770602010-02-06 00:22:26 +0000274 self.assertIsInstance(tests, unittest.TestSuite)
Michael Foordb4a81c82009-05-29 20:33:46 +0000275 load_tests_args.extend((loader, tests, pattern))
276 return tests
277 m.load_tests = load_tests
278
279 loader = unittest.TestLoader()
280 suite = loader.loadTestsFromModule(m)
Michael Foord08770602010-02-06 00:22:26 +0000281 self.assertIsInstance(suite, unittest.TestSuite)
Michael Foordb4a81c82009-05-29 20:33:46 +0000282 self.assertEquals(load_tests_args, [loader, suite, None])
283
284 load_tests_args = []
285 suite = loader.loadTestsFromModule(m, use_load_tests=False)
286 self.assertEquals(load_tests_args, [])
287
Georg Brandl15c5ce92007-03-07 09:09:40 +0000288 ################################################################
289 ### /Tests for TestLoader.loadTestsFromModule()
Tim Petersea5962f2007-03-12 18:07:52 +0000290
Georg Brandl15c5ce92007-03-07 09:09:40 +0000291 ### Tests for TestLoader.loadTestsFromName()
292 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000293
Georg Brandl15c5ce92007-03-07 09:09:40 +0000294 # "The specifier name is a ``dotted name'' that may resolve either to
295 # a module, a test case class, a TestSuite instance, a test method
296 # within a test case class, or a callable object which returns a
297 # TestCase or TestSuite instance."
298 #
299 # Is ValueError raised in response to an empty name?
300 def test_loadTestsFromName__empty_name(self):
301 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000302
Georg Brandl15c5ce92007-03-07 09:09:40 +0000303 try:
304 loader.loadTestsFromName('')
305 except ValueError, e:
306 self.assertEqual(str(e), "Empty module name")
307 else:
308 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000309
Georg Brandl15c5ce92007-03-07 09:09:40 +0000310 # "The specifier name is a ``dotted name'' that may resolve either to
311 # a module, a test case class, a TestSuite instance, a test method
312 # within a test case class, or a callable object which returns a
313 # TestCase or TestSuite instance."
314 #
Tim Petersea5962f2007-03-12 18:07:52 +0000315 # What happens when the name contains invalid characters?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000316 def test_loadTestsFromName__malformed_name(self):
317 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000318
Georg Brandl15c5ce92007-03-07 09:09:40 +0000319 # XXX Should this raise ValueError or ImportError?
320 try:
321 loader.loadTestsFromName('abc () //')
322 except ValueError:
323 pass
324 except ImportError:
325 pass
326 else:
327 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000328
Georg Brandl15c5ce92007-03-07 09:09:40 +0000329 # "The specifier name is a ``dotted name'' that may resolve ... to a
330 # module"
331 #
Tim Petersea5962f2007-03-12 18:07:52 +0000332 # What happens when a module by that name can't be found?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000333 def test_loadTestsFromName__unknown_module_name(self):
334 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000335
Georg Brandl15c5ce92007-03-07 09:09:40 +0000336 try:
337 loader.loadTestsFromName('sdasfasfasdf')
338 except ImportError, e:
339 self.assertEqual(str(e), "No module named sdasfasfasdf")
340 else:
341 self.fail("TestLoader.loadTestsFromName failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000342
Georg Brandl15c5ce92007-03-07 09:09:40 +0000343 # "The specifier name is a ``dotted name'' that may resolve either to
344 # a module, a test case class, a TestSuite instance, a test method
345 # within a test case class, or a callable object which returns a
346 # TestCase or TestSuite instance."
347 #
Tim Petersea5962f2007-03-12 18:07:52 +0000348 # What happens when the module is found, but the attribute can't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000349 def test_loadTestsFromName__unknown_attr_name(self):
350 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000351
Georg Brandl15c5ce92007-03-07 09:09:40 +0000352 try:
353 loader.loadTestsFromName('unittest.sdasfasfasdf')
354 except AttributeError, e:
355 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
356 else:
357 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000358
Georg Brandl15c5ce92007-03-07 09:09:40 +0000359 # "The specifier name is a ``dotted name'' that may resolve either to
360 # a module, a test case class, a TestSuite instance, a test method
361 # within a test case class, or a callable object which returns a
362 # TestCase or TestSuite instance."
363 #
364 # What happens when we provide the module, but the attribute can't be
365 # found?
366 def test_loadTestsFromName__relative_unknown_name(self):
367 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000368
Georg Brandl15c5ce92007-03-07 09:09:40 +0000369 try:
370 loader.loadTestsFromName('sdasfasfasdf', unittest)
371 except AttributeError, e:
372 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
373 else:
374 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000375
Georg Brandl15c5ce92007-03-07 09:09:40 +0000376 # "The specifier name is a ``dotted name'' that may resolve either to
377 # a module, a test case class, a TestSuite instance, a test method
378 # within a test case class, or a callable object which returns a
379 # TestCase or TestSuite instance."
380 # ...
381 # "The method optionally resolves name relative to the given module"
382 #
383 # Does loadTestsFromName raise ValueError when passed an empty
384 # name relative to a provided module?
385 #
386 # XXX Should probably raise a ValueError instead of an AttributeError
387 def test_loadTestsFromName__relative_empty_name(self):
388 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000389
Georg Brandl15c5ce92007-03-07 09:09:40 +0000390 try:
391 loader.loadTestsFromName('', unittest)
392 except AttributeError, e:
393 pass
394 else:
395 self.fail("Failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000396
Georg Brandl15c5ce92007-03-07 09:09:40 +0000397 # "The specifier name is a ``dotted name'' that may resolve either to
398 # a module, a test case class, a TestSuite instance, a test method
399 # within a test case class, or a callable object which returns a
400 # TestCase or TestSuite instance."
401 # ...
402 # "The method optionally resolves name relative to the given module"
403 #
404 # What happens when an impossible name is given, relative to the provided
405 # `module`?
406 def test_loadTestsFromName__relative_malformed_name(self):
407 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000408
Georg Brandl15c5ce92007-03-07 09:09:40 +0000409 # XXX Should this raise AttributeError or ValueError?
410 try:
411 loader.loadTestsFromName('abc () //', unittest)
412 except ValueError:
413 pass
414 except AttributeError:
415 pass
416 else:
417 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
418
419 # "The method optionally resolves name relative to the given module"
420 #
421 # Does loadTestsFromName raise TypeError when the `module` argument
422 # isn't a module object?
423 #
424 # XXX Accepts the not-a-module object, ignorning the object's type
425 # This should raise an exception or the method name should be changed
426 #
427 # XXX Some people are relying on this, so keep it for now
428 def test_loadTestsFromName__relative_not_a_module(self):
429 class MyTestCase(unittest.TestCase):
430 def test(self):
431 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000432
Georg Brandl15c5ce92007-03-07 09:09:40 +0000433 class NotAModule(object):
434 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000435
Georg Brandl15c5ce92007-03-07 09:09:40 +0000436 loader = unittest.TestLoader()
437 suite = loader.loadTestsFromName('test_2', NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000438
Georg Brandl15c5ce92007-03-07 09:09:40 +0000439 reference = [MyTestCase('test')]
440 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000441
Georg Brandl15c5ce92007-03-07 09:09:40 +0000442 # "The specifier name is a ``dotted name'' that may resolve either to
443 # a module, a test case class, a TestSuite instance, a test method
444 # within a test case class, or a callable object which returns a
445 # TestCase or TestSuite instance."
446 #
447 # Does it raise an exception if the name resolves to an invalid
448 # object?
449 def test_loadTestsFromName__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000450 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000451 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000452
Georg Brandl15c5ce92007-03-07 09:09:40 +0000453 loader = unittest.TestLoader()
454 try:
455 loader.loadTestsFromName('testcase_1', m)
456 except TypeError:
457 pass
458 else:
459 self.fail("Should have raised TypeError")
460
461 # "The specifier name is a ``dotted name'' that may
462 # resolve either to ... a test case class"
463 def test_loadTestsFromName__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000464 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000465 class MyTestCase(unittest.TestCase):
466 def test(self):
467 pass
468 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000469
Georg Brandl15c5ce92007-03-07 09:09:40 +0000470 loader = unittest.TestLoader()
471 suite = loader.loadTestsFromName('testcase_1', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000472 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000473 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000474
Georg Brandl15c5ce92007-03-07 09:09:40 +0000475 # "The specifier name is a ``dotted name'' that may resolve either to
476 # a module, a test case class, a TestSuite instance, a test method
477 # within a test case class, or a callable object which returns a
478 # TestCase or TestSuite instance."
479 def test_loadTestsFromName__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000480 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000481 class MyTestCase(unittest.TestCase):
482 def test(self):
483 pass
484 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000485
Georg Brandl15c5ce92007-03-07 09:09:40 +0000486 loader = unittest.TestLoader()
487 suite = loader.loadTestsFromName('testsuite', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000488 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000489
Georg Brandl15c5ce92007-03-07 09:09:40 +0000490 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000491
Georg Brandl15c5ce92007-03-07 09:09:40 +0000492 # "The specifier name is a ``dotted name'' that may resolve ... to
493 # ... a test method within a test case class"
494 def test_loadTestsFromName__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000495 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000496 class MyTestCase(unittest.TestCase):
497 def test(self):
498 pass
499 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000500
Georg Brandl15c5ce92007-03-07 09:09:40 +0000501 loader = unittest.TestLoader()
502 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000503 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000504
Georg Brandl15c5ce92007-03-07 09:09:40 +0000505 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000506
Georg Brandl15c5ce92007-03-07 09:09:40 +0000507 # "The specifier name is a ``dotted name'' that may resolve either to
508 # a module, a test case class, a TestSuite instance, a test method
509 # within a test case class, or a callable object which returns a
510 # TestCase or TestSuite instance."
511 #
512 # Does loadTestsFromName() raise the proper exception when trying to
513 # resolve "a test method within a test case class" that doesn't exist
514 # for the given name (relative to a provided module)?
515 def test_loadTestsFromName__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000516 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000517 class MyTestCase(unittest.TestCase):
518 def test(self):
519 pass
520 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000521
Georg Brandl15c5ce92007-03-07 09:09:40 +0000522 loader = unittest.TestLoader()
523 try:
524 loader.loadTestsFromName('testcase_1.testfoo', m)
525 except AttributeError, e:
526 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
527 else:
528 self.fail("Failed to raise AttributeError")
529
530 # "The specifier name is a ``dotted name'' that may resolve ... to
531 # ... a callable object which returns a ... TestSuite instance"
532 def test_loadTestsFromName__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000533 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000534 testcase_1 = unittest.FunctionTestCase(lambda: None)
535 testcase_2 = unittest.FunctionTestCase(lambda: None)
536 def return_TestSuite():
537 return unittest.TestSuite([testcase_1, testcase_2])
538 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000539
Georg Brandl15c5ce92007-03-07 09:09:40 +0000540 loader = unittest.TestLoader()
541 suite = loader.loadTestsFromName('return_TestSuite', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000542 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000543 self.assertEqual(list(suite), [testcase_1, testcase_2])
Tim Petersea5962f2007-03-12 18:07:52 +0000544
Georg Brandl15c5ce92007-03-07 09:09:40 +0000545 # "The specifier name is a ``dotted name'' that may resolve ... to
546 # ... a callable object which returns a TestCase ... instance"
547 def test_loadTestsFromName__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000548 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000549 testcase_1 = unittest.FunctionTestCase(lambda: None)
550 def return_TestCase():
551 return testcase_1
552 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000553
Georg Brandl15c5ce92007-03-07 09:09:40 +0000554 loader = unittest.TestLoader()
555 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000556 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000557 self.assertEqual(list(suite), [testcase_1])
Tim Petersea5962f2007-03-12 18:07:52 +0000558
Georg Brandl15c5ce92007-03-07 09:09:40 +0000559 # "The specifier name is a ``dotted name'' that may resolve ... to
Michael Foord5a9719d2009-09-13 17:28:35 +0000560 # ... a callable object which returns a TestCase ... instance"
561 #*****************************************************************
562 #Override the suiteClass attribute to ensure that the suiteClass
563 #attribute is used
564 def test_loadTestsFromName__callable__TestCase_instance_ProperSuiteClass(self):
565 class SubTestSuite(unittest.TestSuite):
566 pass
567 m = types.ModuleType('m')
568 testcase_1 = unittest.FunctionTestCase(lambda: None)
569 def return_TestCase():
570 return testcase_1
571 m.return_TestCase = return_TestCase
572
573 loader = unittest.TestLoader()
574 loader.suiteClass = SubTestSuite
575 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000576 self.assertIsInstance(suite, loader.suiteClass)
Michael Foord5a9719d2009-09-13 17:28:35 +0000577 self.assertEqual(list(suite), [testcase_1])
578
579 # "The specifier name is a ``dotted name'' that may resolve ... to
580 # ... a test method within a test case class"
581 #*****************************************************************
582 #Override the suiteClass attribute to ensure that the suiteClass
583 #attribute is used
584 def test_loadTestsFromName__relative_testmethod_ProperSuiteClass(self):
585 class SubTestSuite(unittest.TestSuite):
586 pass
587 m = types.ModuleType('m')
588 class MyTestCase(unittest.TestCase):
589 def test(self):
590 pass
591 m.testcase_1 = MyTestCase
592
593 loader = unittest.TestLoader()
594 loader.suiteClass=SubTestSuite
595 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000596 self.assertIsInstance(suite, loader.suiteClass)
Michael Foord5a9719d2009-09-13 17:28:35 +0000597
598 self.assertEqual(list(suite), [MyTestCase('test')])
599
600 # "The specifier name is a ``dotted name'' that may resolve ... to
Georg Brandl15c5ce92007-03-07 09:09:40 +0000601 # ... a callable object which returns a TestCase or TestSuite instance"
602 #
603 # What happens if the callable returns something else?
604 def test_loadTestsFromName__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000605 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000606 def return_wrong():
607 return 6
608 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000609
Georg Brandl15c5ce92007-03-07 09:09:40 +0000610 loader = unittest.TestLoader()
611 try:
612 suite = loader.loadTestsFromName('return_wrong', m)
613 except TypeError:
614 pass
615 else:
616 self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000617
Georg Brandl15c5ce92007-03-07 09:09:40 +0000618 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +0000619 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +0000620 def test_loadTestsFromName__module_not_loaded(self):
621 # We're going to try to load this module as a side-effect, so it
622 # better not be loaded before we try.
623 #
624 # Why pick audioop? Google shows it isn't used very often, so there's
625 # a good chance that it won't be imported when this test is run
626 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +0000627
Georg Brandl15c5ce92007-03-07 09:09:40 +0000628 if module_name in sys.modules:
629 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000630
Georg Brandl15c5ce92007-03-07 09:09:40 +0000631 loader = unittest.TestLoader()
632 try:
633 suite = loader.loadTestsFromName(module_name)
634
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000635 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000636 self.assertEqual(list(suite), [])
637
638 # audioop should now be loaded, thanks to loadTestsFromName()
Ezio Melottiaa980582010-01-23 23:04:36 +0000639 self.assertIn(module_name, sys.modules)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000640 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000641 if module_name in sys.modules:
642 del sys.modules[module_name]
Georg Brandl15c5ce92007-03-07 09:09:40 +0000643
644 ################################################################
645 ### Tests for TestLoader.loadTestsFromName()
646
647 ### Tests for TestLoader.loadTestsFromNames()
648 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000649
Georg Brandl15c5ce92007-03-07 09:09:40 +0000650 # "Similar to loadTestsFromName(), but takes a sequence of names rather
651 # than a single name."
652 #
653 # What happens if that sequence of names is empty?
654 def test_loadTestsFromNames__empty_name_list(self):
655 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000656
Georg Brandl15c5ce92007-03-07 09:09:40 +0000657 suite = loader.loadTestsFromNames([])
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000658 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000659 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000660
Georg Brandl15c5ce92007-03-07 09:09:40 +0000661 # "Similar to loadTestsFromName(), but takes a sequence of names rather
662 # than a single name."
663 # ...
664 # "The method optionally resolves name relative to the given module"
665 #
666 # What happens if that sequence of names is empty?
667 #
668 # XXX Should this raise a ValueError or just return an empty TestSuite?
669 def test_loadTestsFromNames__relative_empty_name_list(self):
670 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000671
Georg Brandl15c5ce92007-03-07 09:09:40 +0000672 suite = loader.loadTestsFromNames([], unittest)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000673 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000674 self.assertEqual(list(suite), [])
675
676 # "The specifier name is a ``dotted name'' that may resolve either to
677 # a module, a test case class, a TestSuite instance, a test method
678 # within a test case class, or a callable object which returns a
679 # TestCase or TestSuite instance."
680 #
681 # Is ValueError raised in response to an empty name?
682 def test_loadTestsFromNames__empty_name(self):
683 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000684
Georg Brandl15c5ce92007-03-07 09:09:40 +0000685 try:
686 loader.loadTestsFromNames([''])
687 except ValueError, e:
688 self.assertEqual(str(e), "Empty module name")
689 else:
690 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000691
Georg Brandl15c5ce92007-03-07 09:09:40 +0000692 # "The specifier name is a ``dotted name'' that may resolve either to
693 # a module, a test case class, a TestSuite instance, a test method
694 # within a test case class, or a callable object which returns a
695 # TestCase or TestSuite instance."
696 #
Tim Petersea5962f2007-03-12 18:07:52 +0000697 # What happens when presented with an impossible module name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000698 def test_loadTestsFromNames__malformed_name(self):
699 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000700
Georg Brandl15c5ce92007-03-07 09:09:40 +0000701 # XXX Should this raise ValueError or ImportError?
702 try:
703 loader.loadTestsFromNames(['abc () //'])
704 except ValueError:
705 pass
706 except ImportError:
707 pass
708 else:
709 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000710
Georg Brandl15c5ce92007-03-07 09:09:40 +0000711 # "The specifier name is a ``dotted name'' that may resolve either to
712 # a module, a test case class, a TestSuite instance, a test method
713 # within a test case class, or a callable object which returns a
714 # TestCase or TestSuite instance."
715 #
Tim Petersea5962f2007-03-12 18:07:52 +0000716 # What happens when no module can be found for the given name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000717 def test_loadTestsFromNames__unknown_module_name(self):
718 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000719
Georg Brandl15c5ce92007-03-07 09:09:40 +0000720 try:
721 loader.loadTestsFromNames(['sdasfasfasdf'])
722 except ImportError, e:
723 self.assertEqual(str(e), "No module named sdasfasfasdf")
724 else:
725 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000726
Georg Brandl15c5ce92007-03-07 09:09:40 +0000727 # "The specifier name is a ``dotted name'' that may resolve either to
728 # a module, a test case class, a TestSuite instance, a test method
729 # within a test case class, or a callable object which returns a
730 # TestCase or TestSuite instance."
731 #
Tim Petersea5962f2007-03-12 18:07:52 +0000732 # What happens when the module can be found, but not the attribute?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000733 def test_loadTestsFromNames__unknown_attr_name(self):
734 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000735
Georg Brandl15c5ce92007-03-07 09:09:40 +0000736 try:
737 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
738 except AttributeError, e:
739 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
740 else:
741 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000742
Georg Brandl15c5ce92007-03-07 09:09:40 +0000743 # "The specifier name is a ``dotted name'' that may resolve either to
744 # a module, a test case class, a TestSuite instance, a test method
745 # within a test case class, or a callable object which returns a
746 # TestCase or TestSuite instance."
747 # ...
748 # "The method optionally resolves name relative to the given module"
749 #
750 # What happens when given an unknown attribute on a specified `module`
751 # argument?
752 def test_loadTestsFromNames__unknown_name_relative_1(self):
753 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000754
Georg Brandl15c5ce92007-03-07 09:09:40 +0000755 try:
756 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
757 except AttributeError, e:
758 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
759 else:
760 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000761
Georg Brandl15c5ce92007-03-07 09:09:40 +0000762 # "The specifier name is a ``dotted name'' that may resolve either to
763 # a module, a test case class, a TestSuite instance, a test method
764 # within a test case class, or a callable object which returns a
765 # TestCase or TestSuite instance."
766 # ...
767 # "The method optionally resolves name relative to the given module"
768 #
769 # Do unknown attributes (relative to a provided module) still raise an
Tim Petersea5962f2007-03-12 18:07:52 +0000770 # exception even in the presence of valid attribute names?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000771 def test_loadTestsFromNames__unknown_name_relative_2(self):
772 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000773
Georg Brandl15c5ce92007-03-07 09:09:40 +0000774 try:
775 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
776 except AttributeError, e:
777 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
778 else:
779 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
780
781 # "The specifier name is a ``dotted name'' that may resolve either to
782 # a module, a test case class, a TestSuite instance, a test method
783 # within a test case class, or a callable object which returns a
784 # TestCase or TestSuite instance."
785 # ...
786 # "The method optionally resolves name relative to the given module"
787 #
788 # What happens when faced with the empty string?
789 #
790 # XXX This currently raises AttributeError, though ValueError is probably
791 # more appropriate
792 def test_loadTestsFromNames__relative_empty_name(self):
793 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000794
Georg Brandl15c5ce92007-03-07 09:09:40 +0000795 try:
796 loader.loadTestsFromNames([''], unittest)
797 except AttributeError:
798 pass
799 else:
800 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000801
Georg Brandl15c5ce92007-03-07 09:09:40 +0000802 # "The specifier name is a ``dotted name'' that may resolve either to
803 # a module, a test case class, a TestSuite instance, a test method
804 # within a test case class, or a callable object which returns a
805 # TestCase or TestSuite instance."
806 # ...
807 # "The method optionally resolves name relative to the given module"
808 #
Tim Petersea5962f2007-03-12 18:07:52 +0000809 # What happens when presented with an impossible attribute name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000810 def test_loadTestsFromNames__relative_malformed_name(self):
811 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000812
Georg Brandl15c5ce92007-03-07 09:09:40 +0000813 # XXX Should this raise AttributeError or ValueError?
814 try:
815 loader.loadTestsFromNames(['abc () //'], unittest)
816 except AttributeError:
817 pass
818 except ValueError:
819 pass
820 else:
821 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
822
823 # "The method optionally resolves name relative to the given module"
824 #
825 # Does loadTestsFromNames() make sure the provided `module` is in fact
826 # a module?
827 #
828 # XXX This validation is currently not done. This flexibility should
829 # either be documented or a TypeError should be raised.
830 def test_loadTestsFromNames__relative_not_a_module(self):
831 class MyTestCase(unittest.TestCase):
832 def test(self):
833 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000834
Georg Brandl15c5ce92007-03-07 09:09:40 +0000835 class NotAModule(object):
836 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000837
Georg Brandl15c5ce92007-03-07 09:09:40 +0000838 loader = unittest.TestLoader()
839 suite = loader.loadTestsFromNames(['test_2'], NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000840
Georg Brandl15c5ce92007-03-07 09:09:40 +0000841 reference = [unittest.TestSuite([MyTestCase('test')])]
842 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000843
Georg Brandl15c5ce92007-03-07 09:09:40 +0000844 # "The specifier name is a ``dotted name'' that may resolve either to
845 # a module, a test case class, a TestSuite instance, a test method
846 # within a test case class, or a callable object which returns a
847 # TestCase or TestSuite instance."
848 #
849 # Does it raise an exception if the name resolves to an invalid
850 # object?
851 def test_loadTestsFromNames__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000852 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000853 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000854
Georg Brandl15c5ce92007-03-07 09:09:40 +0000855 loader = unittest.TestLoader()
856 try:
857 loader.loadTestsFromNames(['testcase_1'], m)
858 except TypeError:
859 pass
860 else:
861 self.fail("Should have raised TypeError")
862
863 # "The specifier name is a ``dotted name'' that may resolve ... to
864 # ... a test case class"
865 def test_loadTestsFromNames__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000866 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000867 class MyTestCase(unittest.TestCase):
868 def test(self):
869 pass
870 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000871
Georg Brandl15c5ce92007-03-07 09:09:40 +0000872 loader = unittest.TestLoader()
873 suite = loader.loadTestsFromNames(['testcase_1'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000874 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000875
Georg Brandl15c5ce92007-03-07 09:09:40 +0000876 expected = loader.suiteClass([MyTestCase('test')])
877 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000878
Georg Brandl15c5ce92007-03-07 09:09:40 +0000879 # "The specifier name is a ``dotted name'' that may resolve ... to
880 # ... a TestSuite instance"
881 def test_loadTestsFromNames__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000882 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000883 class MyTestCase(unittest.TestCase):
884 def test(self):
885 pass
886 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000887
Georg Brandl15c5ce92007-03-07 09:09:40 +0000888 loader = unittest.TestLoader()
889 suite = loader.loadTestsFromNames(['testsuite'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000890 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000891
Georg Brandl15c5ce92007-03-07 09:09:40 +0000892 self.assertEqual(list(suite), [m.testsuite])
Tim Petersea5962f2007-03-12 18:07:52 +0000893
Georg Brandl15c5ce92007-03-07 09:09:40 +0000894 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
895 # test method within a test case class"
896 def test_loadTestsFromNames__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000897 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000898 class MyTestCase(unittest.TestCase):
899 def test(self):
900 pass
901 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000902
Georg Brandl15c5ce92007-03-07 09:09:40 +0000903 loader = unittest.TestLoader()
904 suite = loader.loadTestsFromNames(['testcase_1.test'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000905 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000906
Georg Brandl15c5ce92007-03-07 09:09:40 +0000907 ref_suite = unittest.TestSuite([MyTestCase('test')])
908 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000909
Georg Brandl15c5ce92007-03-07 09:09:40 +0000910 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
911 # test method within a test case class"
912 #
913 # Does the method gracefully handle names that initially look like they
Tim Petersea5962f2007-03-12 18:07:52 +0000914 # resolve to "a test method within a test case class" but don't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000915 def test_loadTestsFromNames__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000916 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000917 class MyTestCase(unittest.TestCase):
918 def test(self):
919 pass
920 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000921
Georg Brandl15c5ce92007-03-07 09:09:40 +0000922 loader = unittest.TestLoader()
923 try:
924 loader.loadTestsFromNames(['testcase_1.testfoo'], m)
925 except AttributeError, e:
926 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
927 else:
928 self.fail("Failed to raise AttributeError")
929
930 # "The specifier name is a ``dotted name'' that may resolve ... to
931 # ... a callable object which returns a ... TestSuite instance"
932 def test_loadTestsFromNames__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000933 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000934 testcase_1 = unittest.FunctionTestCase(lambda: None)
935 testcase_2 = unittest.FunctionTestCase(lambda: None)
936 def return_TestSuite():
937 return unittest.TestSuite([testcase_1, testcase_2])
938 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000939
Georg Brandl15c5ce92007-03-07 09:09:40 +0000940 loader = unittest.TestLoader()
941 suite = loader.loadTestsFromNames(['return_TestSuite'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000942 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000943
Georg Brandl15c5ce92007-03-07 09:09:40 +0000944 expected = unittest.TestSuite([testcase_1, testcase_2])
945 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000946
Georg Brandl15c5ce92007-03-07 09:09:40 +0000947 # "The specifier name is a ``dotted name'' that may resolve ... to
948 # ... a callable object which returns a TestCase ... instance"
949 def test_loadTestsFromNames__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000950 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000951 testcase_1 = unittest.FunctionTestCase(lambda: None)
952 def return_TestCase():
953 return testcase_1
954 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000955
Georg Brandl15c5ce92007-03-07 09:09:40 +0000956 loader = unittest.TestLoader()
957 suite = loader.loadTestsFromNames(['return_TestCase'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000958 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000959
Georg Brandl15c5ce92007-03-07 09:09:40 +0000960 ref_suite = unittest.TestSuite([testcase_1])
961 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000962
Georg Brandl15c5ce92007-03-07 09:09:40 +0000963 # "The specifier name is a ``dotted name'' that may resolve ... to
964 # ... a callable object which returns a TestCase or TestSuite instance"
965 #
Tim Petersea5962f2007-03-12 18:07:52 +0000966 # Are staticmethods handled correctly?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000967 def test_loadTestsFromNames__callable__call_staticmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000968 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000969 class Test1(unittest.TestCase):
970 def test(self):
971 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000972
Georg Brandl15c5ce92007-03-07 09:09:40 +0000973 testcase_1 = Test1('test')
974 class Foo(unittest.TestCase):
975 @staticmethod
976 def foo():
977 return testcase_1
978 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +0000979
Georg Brandl15c5ce92007-03-07 09:09:40 +0000980 loader = unittest.TestLoader()
981 suite = loader.loadTestsFromNames(['Foo.foo'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000982 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000983
Georg Brandl15c5ce92007-03-07 09:09:40 +0000984 ref_suite = unittest.TestSuite([testcase_1])
985 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000986
Georg Brandl15c5ce92007-03-07 09:09:40 +0000987 # "The specifier name is a ``dotted name'' that may resolve ... to
988 # ... a callable object which returns a TestCase or TestSuite instance"
989 #
990 # What happens when the callable returns something else?
991 def test_loadTestsFromNames__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000992 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000993 def return_wrong():
994 return 6
995 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000996
Georg Brandl15c5ce92007-03-07 09:09:40 +0000997 loader = unittest.TestLoader()
998 try:
999 suite = loader.loadTestsFromNames(['return_wrong'], m)
1000 except TypeError:
1001 pass
1002 else:
1003 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +00001004
Georg Brandl15c5ce92007-03-07 09:09:40 +00001005 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +00001006 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001007 def test_loadTestsFromNames__module_not_loaded(self):
1008 # We're going to try to load this module as a side-effect, so it
1009 # better not be loaded before we try.
1010 #
1011 # Why pick audioop? Google shows it isn't used very often, so there's
1012 # a good chance that it won't be imported when this test is run
1013 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +00001014
Georg Brandl15c5ce92007-03-07 09:09:40 +00001015 if module_name in sys.modules:
1016 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +00001017
Georg Brandl15c5ce92007-03-07 09:09:40 +00001018 loader = unittest.TestLoader()
1019 try:
1020 suite = loader.loadTestsFromNames([module_name])
1021
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001022 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +00001023 self.assertEqual(list(suite), [unittest.TestSuite()])
1024
1025 # audioop should now be loaded, thanks to loadTestsFromName()
Ezio Melottiaa980582010-01-23 23:04:36 +00001026 self.assertIn(module_name, sys.modules)
Georg Brandl15c5ce92007-03-07 09:09:40 +00001027 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +00001028 if module_name in sys.modules:
1029 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +00001030
Georg Brandl15c5ce92007-03-07 09:09:40 +00001031 ################################################################
1032 ### /Tests for TestLoader.loadTestsFromNames()
1033
1034 ### Tests for TestLoader.getTestCaseNames()
1035 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001036
Georg Brandl15c5ce92007-03-07 09:09:40 +00001037 # "Return a sorted sequence of method names found within testCaseClass"
1038 #
1039 # Test.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +00001040 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +00001041 def test_getTestCaseNames(self):
1042 class Test(unittest.TestCase):
1043 def test_1(self): pass
1044 def test_2(self): pass
1045 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001046
Georg Brandl15c5ce92007-03-07 09:09:40 +00001047 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001048
Georg Brandl15c5ce92007-03-07 09:09:40 +00001049 self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])
Tim Petersea5962f2007-03-12 18:07:52 +00001050
Georg Brandl15c5ce92007-03-07 09:09:40 +00001051 # "Return a sorted sequence of method names found within testCaseClass"
1052 #
Tim Petersea5962f2007-03-12 18:07:52 +00001053 # Does getTestCaseNames() behave appropriately if no tests are found?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001054 def test_getTestCaseNames__no_tests(self):
1055 class Test(unittest.TestCase):
1056 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001057
Georg Brandl15c5ce92007-03-07 09:09:40 +00001058 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001059
Georg Brandl15c5ce92007-03-07 09:09:40 +00001060 self.assertEqual(loader.getTestCaseNames(Test), [])
Tim Petersea5962f2007-03-12 18:07:52 +00001061
Georg Brandl15c5ce92007-03-07 09:09:40 +00001062 # "Return a sorted sequence of method names found within testCaseClass"
1063 #
1064 # Are not-TestCases handled gracefully?
1065 #
1066 # XXX This should raise a TypeError, not return a list
1067 #
1068 # XXX It's too late in the 2.5 release cycle to fix this, but it should
1069 # probably be revisited for 2.6
1070 def test_getTestCaseNames__not_a_TestCase(self):
1071 class BadCase(int):
1072 def test_foo(self):
1073 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001074
Georg Brandl15c5ce92007-03-07 09:09:40 +00001075 loader = unittest.TestLoader()
1076 names = loader.getTestCaseNames(BadCase)
Tim Petersea5962f2007-03-12 18:07:52 +00001077
Georg Brandl15c5ce92007-03-07 09:09:40 +00001078 self.assertEqual(names, ['test_foo'])
Tim Petersea5962f2007-03-12 18:07:52 +00001079
Georg Brandl15c5ce92007-03-07 09:09:40 +00001080 # "Return a sorted sequence of method names found within testCaseClass"
1081 #
1082 # Make sure inherited names are handled.
1083 #
1084 # TestP.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +00001085 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +00001086 def test_getTestCaseNames__inheritance(self):
1087 class TestP(unittest.TestCase):
1088 def test_1(self): pass
1089 def test_2(self): pass
1090 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001091
Georg Brandl15c5ce92007-03-07 09:09:40 +00001092 class TestC(TestP):
1093 def test_1(self): pass
1094 def test_3(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001095
Georg Brandl15c5ce92007-03-07 09:09:40 +00001096 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001097
Georg Brandl15c5ce92007-03-07 09:09:40 +00001098 names = ['test_1', 'test_2', 'test_3']
1099 self.assertEqual(loader.getTestCaseNames(TestC), names)
Tim Petersea5962f2007-03-12 18:07:52 +00001100
1101 ################################################################
Georg Brandl15c5ce92007-03-07 09:09:40 +00001102 ### /Tests for TestLoader.getTestCaseNames()
1103
1104 ### Tests for TestLoader.testMethodPrefix
1105 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001106
Georg Brandl15c5ce92007-03-07 09:09:40 +00001107 # "String giving the prefix of method names which will be interpreted as
1108 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001109 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001110 # Implicit in the documentation is that testMethodPrefix is respected by
1111 # all loadTestsFrom* methods.
1112 def test_testMethodPrefix__loadTestsFromTestCase(self):
1113 class Foo(unittest.TestCase):
1114 def test_1(self): pass
1115 def test_2(self): pass
1116 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001117
Georg Brandl15c5ce92007-03-07 09:09:40 +00001118 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1119 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001120
Georg Brandl15c5ce92007-03-07 09:09:40 +00001121 loader = unittest.TestLoader()
1122 loader.testMethodPrefix = 'foo'
1123 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
1124
1125 loader.testMethodPrefix = 'test'
1126 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001127
Georg Brandl15c5ce92007-03-07 09:09:40 +00001128 # "String giving the prefix of method names which will be interpreted as
1129 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001130 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001131 # Implicit in the documentation is that testMethodPrefix is respected by
1132 # all loadTestsFrom* methods.
1133 def test_testMethodPrefix__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001134 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001135 class Foo(unittest.TestCase):
1136 def test_1(self): pass
1137 def test_2(self): pass
1138 def foo_bar(self): pass
1139 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001140
Georg Brandl15c5ce92007-03-07 09:09:40 +00001141 tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
1142 tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]
Tim Petersea5962f2007-03-12 18:07:52 +00001143
Georg Brandl15c5ce92007-03-07 09:09:40 +00001144 loader = unittest.TestLoader()
1145 loader.testMethodPrefix = 'foo'
1146 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
1147
1148 loader.testMethodPrefix = 'test'
1149 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001150
Georg Brandl15c5ce92007-03-07 09:09:40 +00001151 # "String giving the prefix of method names which will be interpreted as
1152 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001153 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001154 # Implicit in the documentation is that testMethodPrefix is respected by
1155 # all loadTestsFrom* methods.
1156 def test_testMethodPrefix__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001157 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001158 class Foo(unittest.TestCase):
1159 def test_1(self): pass
1160 def test_2(self): pass
1161 def foo_bar(self): pass
1162 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001163
Georg Brandl15c5ce92007-03-07 09:09:40 +00001164 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1165 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001166
Georg Brandl15c5ce92007-03-07 09:09:40 +00001167 loader = unittest.TestLoader()
1168 loader.testMethodPrefix = 'foo'
1169 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
1170
1171 loader.testMethodPrefix = 'test'
1172 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001173
Georg Brandl15c5ce92007-03-07 09:09:40 +00001174 # "String giving the prefix of method names which will be interpreted as
1175 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001176 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001177 # Implicit in the documentation is that testMethodPrefix is respected by
1178 # all loadTestsFrom* methods.
1179 def test_testMethodPrefix__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001180 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001181 class Foo(unittest.TestCase):
1182 def test_1(self): pass
1183 def test_2(self): pass
1184 def foo_bar(self): pass
1185 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001186
Georg Brandl15c5ce92007-03-07 09:09:40 +00001187 tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
1188 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1189 tests_2 = unittest.TestSuite([tests_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001190
Georg Brandl15c5ce92007-03-07 09:09:40 +00001191 loader = unittest.TestLoader()
1192 loader.testMethodPrefix = 'foo'
1193 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)
1194
1195 loader.testMethodPrefix = 'test'
1196 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001197
Georg Brandl15c5ce92007-03-07 09:09:40 +00001198 # "The default value is 'test'"
1199 def test_testMethodPrefix__default_value(self):
1200 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001201 self.assertTrue(loader.testMethodPrefix == 'test')
Tim Petersea5962f2007-03-12 18:07:52 +00001202
Georg Brandl15c5ce92007-03-07 09:09:40 +00001203 ################################################################
1204 ### /Tests for TestLoader.testMethodPrefix
1205
Tim Petersea5962f2007-03-12 18:07:52 +00001206 ### Tests for TestLoader.sortTestMethodsUsing
Georg Brandl15c5ce92007-03-07 09:09:40 +00001207 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001208
Georg Brandl15c5ce92007-03-07 09:09:40 +00001209 # "Function to be used to compare method names when sorting them in
1210 # getTestCaseNames() and all the loadTestsFromX() methods"
1211 def test_sortTestMethodsUsing__loadTestsFromTestCase(self):
1212 def reversed_cmp(x, y):
1213 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001214
Georg Brandl15c5ce92007-03-07 09:09:40 +00001215 class Foo(unittest.TestCase):
1216 def test_1(self): pass
1217 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001218
Georg Brandl15c5ce92007-03-07 09:09:40 +00001219 loader = unittest.TestLoader()
1220 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001221
Georg Brandl15c5ce92007-03-07 09:09:40 +00001222 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1223 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001224
Georg Brandl15c5ce92007-03-07 09:09:40 +00001225 # "Function to be used to compare method names when sorting them in
1226 # getTestCaseNames() and all the loadTestsFromX() methods"
1227 def test_sortTestMethodsUsing__loadTestsFromModule(self):
1228 def reversed_cmp(x, y):
1229 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001230
Christian Heimesc756d002007-11-27 21:34:01 +00001231 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001232 class Foo(unittest.TestCase):
1233 def test_1(self): pass
1234 def test_2(self): pass
1235 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001236
Georg Brandl15c5ce92007-03-07 09:09:40 +00001237 loader = unittest.TestLoader()
1238 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001239
Georg Brandl15c5ce92007-03-07 09:09:40 +00001240 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1241 self.assertEqual(list(loader.loadTestsFromModule(m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001242
Georg Brandl15c5ce92007-03-07 09:09:40 +00001243 # "Function to be used to compare method names when sorting them in
1244 # getTestCaseNames() and all the loadTestsFromX() methods"
1245 def test_sortTestMethodsUsing__loadTestsFromName(self):
1246 def reversed_cmp(x, y):
1247 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001248
Christian Heimesc756d002007-11-27 21:34:01 +00001249 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001250 class Foo(unittest.TestCase):
1251 def test_1(self): pass
1252 def test_2(self): pass
1253 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001254
Georg Brandl15c5ce92007-03-07 09:09:40 +00001255 loader = unittest.TestLoader()
1256 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001257
Georg Brandl15c5ce92007-03-07 09:09:40 +00001258 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1259 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001260
Georg Brandl15c5ce92007-03-07 09:09:40 +00001261 # "Function to be used to compare method names when sorting them in
1262 # getTestCaseNames() and all the loadTestsFromX() methods"
1263 def test_sortTestMethodsUsing__loadTestsFromNames(self):
1264 def reversed_cmp(x, y):
1265 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001266
Christian Heimesc756d002007-11-27 21:34:01 +00001267 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001268 class Foo(unittest.TestCase):
1269 def test_1(self): pass
1270 def test_2(self): pass
1271 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001272
Georg Brandl15c5ce92007-03-07 09:09:40 +00001273 loader = unittest.TestLoader()
1274 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001275
Georg Brandl15c5ce92007-03-07 09:09:40 +00001276 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1277 self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001278
Georg Brandl15c5ce92007-03-07 09:09:40 +00001279 # "Function to be used to compare method names when sorting them in
1280 # getTestCaseNames()"
1281 #
1282 # Does it actually affect getTestCaseNames()?
1283 def test_sortTestMethodsUsing__getTestCaseNames(self):
1284 def reversed_cmp(x, y):
1285 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001286
Georg Brandl15c5ce92007-03-07 09:09:40 +00001287 class Foo(unittest.TestCase):
1288 def test_1(self): pass
1289 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001290
Georg Brandl15c5ce92007-03-07 09:09:40 +00001291 loader = unittest.TestLoader()
1292 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001293
Georg Brandl15c5ce92007-03-07 09:09:40 +00001294 test_names = ['test_2', 'test_1']
1295 self.assertEqual(loader.getTestCaseNames(Foo), test_names)
Tim Petersea5962f2007-03-12 18:07:52 +00001296
Georg Brandl15c5ce92007-03-07 09:09:40 +00001297 # "The default value is the built-in cmp() function"
1298 def test_sortTestMethodsUsing__default_value(self):
1299 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001300 self.assertTrue(loader.sortTestMethodsUsing is cmp)
Tim Petersea5962f2007-03-12 18:07:52 +00001301
Georg Brandl15c5ce92007-03-07 09:09:40 +00001302 # "it can be set to None to disable the sort."
1303 #
1304 # XXX How is this different from reassigning cmp? Are the tests returned
1305 # in a random order or something? This behaviour should die
1306 def test_sortTestMethodsUsing__None(self):
1307 class Foo(unittest.TestCase):
1308 def test_1(self): pass
1309 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001310
Georg Brandl15c5ce92007-03-07 09:09:40 +00001311 loader = unittest.TestLoader()
1312 loader.sortTestMethodsUsing = None
Tim Petersea5962f2007-03-12 18:07:52 +00001313
Georg Brandl15c5ce92007-03-07 09:09:40 +00001314 test_names = ['test_2', 'test_1']
1315 self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))
Tim Petersea5962f2007-03-12 18:07:52 +00001316
Georg Brandl15c5ce92007-03-07 09:09:40 +00001317 ################################################################
1318 ### /Tests for TestLoader.sortTestMethodsUsing
Tim Petersea5962f2007-03-12 18:07:52 +00001319
Georg Brandl15c5ce92007-03-07 09:09:40 +00001320 ### Tests for TestLoader.suiteClass
1321 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001322
Georg Brandl15c5ce92007-03-07 09:09:40 +00001323 # "Callable object that constructs a test suite from a list of tests."
1324 def test_suiteClass__loadTestsFromTestCase(self):
1325 class Foo(unittest.TestCase):
1326 def test_1(self): pass
1327 def test_2(self): pass
1328 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001329
Georg Brandl15c5ce92007-03-07 09:09:40 +00001330 tests = [Foo('test_1'), Foo('test_2')]
1331
1332 loader = unittest.TestLoader()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001333 loader.suiteClass = list
Georg Brandl15c5ce92007-03-07 09:09:40 +00001334 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001335
Georg Brandl15c5ce92007-03-07 09:09:40 +00001336 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001337 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001338 def test_suiteClass__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001339 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001340 class Foo(unittest.TestCase):
1341 def test_1(self): pass
1342 def test_2(self): pass
1343 def foo_bar(self): pass
1344 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001345
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001346 tests = [[Foo('test_1'), Foo('test_2')]]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001347
1348 loader = unittest.TestLoader()
1349 loader.suiteClass = list
1350 self.assertEqual(loader.loadTestsFromModule(m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001351
Georg Brandl15c5ce92007-03-07 09:09:40 +00001352 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001353 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001354 def test_suiteClass__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001355 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001356 class Foo(unittest.TestCase):
1357 def test_1(self): pass
1358 def test_2(self): pass
1359 def foo_bar(self): pass
1360 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001361
Georg Brandl15c5ce92007-03-07 09:09:40 +00001362 tests = [Foo('test_1'), Foo('test_2')]
1363
1364 loader = unittest.TestLoader()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001365 loader.suiteClass = list
Georg Brandl15c5ce92007-03-07 09:09:40 +00001366 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001367
Georg Brandl15c5ce92007-03-07 09:09:40 +00001368 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001369 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001370 def test_suiteClass__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001371 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001372 class Foo(unittest.TestCase):
1373 def test_1(self): pass
1374 def test_2(self): pass
1375 def foo_bar(self): pass
1376 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001377
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001378 tests = [[Foo('test_1'), Foo('test_2')]]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001379
1380 loader = unittest.TestLoader()
1381 loader.suiteClass = list
1382 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001383
Georg Brandl15c5ce92007-03-07 09:09:40 +00001384 # "The default value is the TestSuite class"
1385 def test_suiteClass__default_value(self):
1386 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001387 self.assertTrue(loader.suiteClass is unittest.TestSuite)
Tim Petersea5962f2007-03-12 18:07:52 +00001388
Georg Brandl15c5ce92007-03-07 09:09:40 +00001389 ################################################################
1390 ### /Tests for TestLoader.suiteClass
1391
1392### Support code for Test_TestSuite
1393################################################################
1394
1395class Foo(unittest.TestCase):
1396 def test_1(self): pass
1397 def test_2(self): pass
1398 def test_3(self): pass
1399 def runTest(self): pass
1400
1401def _mk_TestSuite(*names):
1402 return unittest.TestSuite(Foo(n) for n in names)
Tim Petersea5962f2007-03-12 18:07:52 +00001403
Georg Brandl15c5ce92007-03-07 09:09:40 +00001404################################################################
1405### /Support code for Test_TestSuite
1406
1407class Test_TestSuite(TestCase, TestEquality):
1408
1409 ### Set up attributes needed by inherited tests
1410 ################################################################
1411
1412 # Used by TestEquality.test_eq
1413 eq_pairs = [(unittest.TestSuite(), unittest.TestSuite())
1414 ,(unittest.TestSuite(), unittest.TestSuite([]))
1415 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001416
1417 # Used by TestEquality.test_ne
Georg Brandl15c5ce92007-03-07 09:09:40 +00001418 ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1'))
1419 ,(unittest.TestSuite([]), _mk_TestSuite('test_1'))
1420 ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3'))
1421 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001422
Georg Brandl15c5ce92007-03-07 09:09:40 +00001423 ################################################################
1424 ### /Set up attributes needed by inherited tests
1425
1426 ### Tests for TestSuite.__init__
1427 ################################################################
1428
1429 # "class TestSuite([tests])"
1430 #
1431 # The tests iterable should be optional
1432 def test_init__tests_optional(self):
1433 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001434
Georg Brandl15c5ce92007-03-07 09:09:40 +00001435 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001436
Georg Brandl15c5ce92007-03-07 09:09:40 +00001437 # "class TestSuite([tests])"
1438 # ...
1439 # "If tests is given, it must be an iterable of individual test cases
1440 # or other test suites that will be used to build the suite initially"
1441 #
1442 # TestSuite should deal with empty tests iterables by allowing the
Tim Petersea5962f2007-03-12 18:07:52 +00001443 # creation of an empty suite
Georg Brandl15c5ce92007-03-07 09:09:40 +00001444 def test_init__empty_tests(self):
1445 suite = unittest.TestSuite([])
Tim Petersea5962f2007-03-12 18:07:52 +00001446
Georg Brandl15c5ce92007-03-07 09:09:40 +00001447 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001448
Georg Brandl15c5ce92007-03-07 09:09:40 +00001449 # "class TestSuite([tests])"
1450 # ...
1451 # "If tests is given, it must be an iterable of individual test cases
1452 # or other test suites that will be used to build the suite initially"
1453 #
Tim Petersea5962f2007-03-12 18:07:52 +00001454 # TestSuite should allow any iterable to provide tests
Georg Brandl15c5ce92007-03-07 09:09:40 +00001455 def test_init__tests_from_any_iterable(self):
1456 def tests():
1457 yield unittest.FunctionTestCase(lambda: None)
1458 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001459
Georg Brandl15c5ce92007-03-07 09:09:40 +00001460 suite_1 = unittest.TestSuite(tests())
1461 self.assertEqual(suite_1.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001462
Georg Brandl15c5ce92007-03-07 09:09:40 +00001463 suite_2 = unittest.TestSuite(suite_1)
1464 self.assertEqual(suite_2.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001465
Georg Brandl15c5ce92007-03-07 09:09:40 +00001466 suite_3 = unittest.TestSuite(set(suite_1))
1467 self.assertEqual(suite_3.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001468
Georg Brandl15c5ce92007-03-07 09:09:40 +00001469 # "class TestSuite([tests])"
1470 # ...
1471 # "If tests is given, it must be an iterable of individual test cases
1472 # or other test suites that will be used to build the suite initially"
1473 #
1474 # Does TestSuite() also allow other TestSuite() instances to be present
1475 # in the tests iterable?
1476 def test_init__TestSuite_instances_in_tests(self):
1477 def tests():
1478 ftc = unittest.FunctionTestCase(lambda: None)
1479 yield unittest.TestSuite([ftc])
1480 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001481
Georg Brandl15c5ce92007-03-07 09:09:40 +00001482 suite = unittest.TestSuite(tests())
1483 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001484
Georg Brandl15c5ce92007-03-07 09:09:40 +00001485 ################################################################
1486 ### /Tests for TestSuite.__init__
1487
1488 # Container types should support the iter protocol
1489 def test_iter(self):
1490 test1 = unittest.FunctionTestCase(lambda: None)
1491 test2 = unittest.FunctionTestCase(lambda: None)
1492 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001493
Georg Brandl15c5ce92007-03-07 09:09:40 +00001494 self.assertEqual(list(suite), [test1, test2])
Tim Petersea5962f2007-03-12 18:07:52 +00001495
Georg Brandl15c5ce92007-03-07 09:09:40 +00001496 # "Return the number of tests represented by the this test object.
1497 # ...this method is also implemented by the TestSuite class, which can
1498 # return larger [greater than 1] values"
1499 #
Tim Petersea5962f2007-03-12 18:07:52 +00001500 # Presumably an empty TestSuite returns 0?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001501 def test_countTestCases_zero_simple(self):
1502 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001503
Georg Brandl15c5ce92007-03-07 09:09:40 +00001504 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001505
Georg Brandl15c5ce92007-03-07 09:09:40 +00001506 # "Return the number of tests represented by the this test object.
1507 # ...this method is also implemented by the TestSuite class, which can
1508 # return larger [greater than 1] values"
1509 #
1510 # Presumably an empty TestSuite (even if it contains other empty
1511 # TestSuite instances) returns 0?
1512 def test_countTestCases_zero_nested(self):
1513 class Test1(unittest.TestCase):
1514 def test(self):
1515 pass
1516
1517 suite = unittest.TestSuite([unittest.TestSuite()])
Tim Petersea5962f2007-03-12 18:07:52 +00001518
Georg Brandl15c5ce92007-03-07 09:09:40 +00001519 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001520
Georg Brandl15c5ce92007-03-07 09:09:40 +00001521 # "Return the number of tests represented by the this test object.
1522 # ...this method is also implemented by the TestSuite class, which can
1523 # return larger [greater than 1] values"
1524 def test_countTestCases_simple(self):
1525 test1 = unittest.FunctionTestCase(lambda: None)
1526 test2 = unittest.FunctionTestCase(lambda: None)
1527 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001528
Georg Brandl15c5ce92007-03-07 09:09:40 +00001529 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001530
Georg Brandl15c5ce92007-03-07 09:09:40 +00001531 # "Return the number of tests represented by the this test object.
1532 # ...this method is also implemented by the TestSuite class, which can
1533 # return larger [greater than 1] values"
1534 #
1535 # Make sure this holds for nested TestSuite instances, too
1536 def test_countTestCases_nested(self):
1537 class Test1(unittest.TestCase):
1538 def test1(self): pass
1539 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001540
Georg Brandl15c5ce92007-03-07 09:09:40 +00001541 test2 = unittest.FunctionTestCase(lambda: None)
1542 test3 = unittest.FunctionTestCase(lambda: None)
1543 child = unittest.TestSuite((Test1('test2'), test2))
1544 parent = unittest.TestSuite((test3, child, Test1('test1')))
Tim Petersea5962f2007-03-12 18:07:52 +00001545
Georg Brandl15c5ce92007-03-07 09:09:40 +00001546 self.assertEqual(parent.countTestCases(), 4)
Tim Petersea5962f2007-03-12 18:07:52 +00001547
Georg Brandl15c5ce92007-03-07 09:09:40 +00001548 # "Run the tests associated with this suite, collecting the result into
1549 # the test result object passed as result."
1550 #
1551 # And if there are no tests? What then?
1552 def test_run__empty_suite(self):
1553 events = []
1554 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001555
Georg Brandl15c5ce92007-03-07 09:09:40 +00001556 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001557
Georg Brandl15c5ce92007-03-07 09:09:40 +00001558 suite.run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001559
Georg Brandl15c5ce92007-03-07 09:09:40 +00001560 self.assertEqual(events, [])
Tim Petersea5962f2007-03-12 18:07:52 +00001561
Georg Brandl15c5ce92007-03-07 09:09:40 +00001562 # "Note that unlike TestCase.run(), TestSuite.run() requires the
1563 # "result object to be passed in."
1564 def test_run__requires_result(self):
1565 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001566
Georg Brandl15c5ce92007-03-07 09:09:40 +00001567 try:
1568 suite.run()
1569 except TypeError:
1570 pass
1571 else:
1572 self.fail("Failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +00001573
Georg Brandl15c5ce92007-03-07 09:09:40 +00001574 # "Run the tests associated with this suite, collecting the result into
Tim Petersea5962f2007-03-12 18:07:52 +00001575 # the test result object passed as result."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001576 def test_run(self):
1577 events = []
1578 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001579
Georg Brandl15c5ce92007-03-07 09:09:40 +00001580 class LoggingCase(unittest.TestCase):
1581 def run(self, result):
1582 events.append('run %s' % self._testMethodName)
Tim Petersea5962f2007-03-12 18:07:52 +00001583
Georg Brandl15c5ce92007-03-07 09:09:40 +00001584 def test1(self): pass
1585 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001586
1587 tests = [LoggingCase('test1'), LoggingCase('test2')]
1588
Georg Brandl15c5ce92007-03-07 09:09:40 +00001589 unittest.TestSuite(tests).run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001590
Georg Brandl15c5ce92007-03-07 09:09:40 +00001591 self.assertEqual(events, ['run test1', 'run test2'])
Tim Petersea5962f2007-03-12 18:07:52 +00001592
1593 # "Add a TestCase ... to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001594 def test_addTest__TestCase(self):
1595 class Foo(unittest.TestCase):
1596 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001597
Georg Brandl15c5ce92007-03-07 09:09:40 +00001598 test = Foo('test')
1599 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001600
Georg Brandl15c5ce92007-03-07 09:09:40 +00001601 suite.addTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001602
Georg Brandl15c5ce92007-03-07 09:09:40 +00001603 self.assertEqual(suite.countTestCases(), 1)
1604 self.assertEqual(list(suite), [test])
Tim Petersea5962f2007-03-12 18:07:52 +00001605
1606 # "Add a ... TestSuite to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001607 def test_addTest__TestSuite(self):
1608 class Foo(unittest.TestCase):
1609 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001610
Georg Brandl15c5ce92007-03-07 09:09:40 +00001611 suite_2 = unittest.TestSuite([Foo('test')])
Tim Petersea5962f2007-03-12 18:07:52 +00001612
Georg Brandl15c5ce92007-03-07 09:09:40 +00001613 suite = unittest.TestSuite()
1614 suite.addTest(suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001615
Georg Brandl15c5ce92007-03-07 09:09:40 +00001616 self.assertEqual(suite.countTestCases(), 1)
1617 self.assertEqual(list(suite), [suite_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001618
Georg Brandl15c5ce92007-03-07 09:09:40 +00001619 # "Add all the tests from an iterable of TestCase and TestSuite
1620 # instances to this test suite."
Tim Petersea5962f2007-03-12 18:07:52 +00001621 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001622 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001623 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001624 def test_addTests(self):
1625 class Foo(unittest.TestCase):
1626 def test_1(self): pass
1627 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001628
Georg Brandl15c5ce92007-03-07 09:09:40 +00001629 test_1 = Foo('test_1')
1630 test_2 = Foo('test_2')
1631 inner_suite = unittest.TestSuite([test_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001632
Georg Brandl15c5ce92007-03-07 09:09:40 +00001633 def gen():
1634 yield test_1
1635 yield test_2
1636 yield inner_suite
Tim Petersea5962f2007-03-12 18:07:52 +00001637
Georg Brandl15c5ce92007-03-07 09:09:40 +00001638 suite_1 = unittest.TestSuite()
1639 suite_1.addTests(gen())
Tim Petersea5962f2007-03-12 18:07:52 +00001640
Georg Brandl15c5ce92007-03-07 09:09:40 +00001641 self.assertEqual(list(suite_1), list(gen()))
Tim Petersea5962f2007-03-12 18:07:52 +00001642
Georg Brandl15c5ce92007-03-07 09:09:40 +00001643 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001644 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001645 suite_2 = unittest.TestSuite()
1646 for t in gen():
1647 suite_2.addTest(t)
Tim Petersea5962f2007-03-12 18:07:52 +00001648
Georg Brandl15c5ce92007-03-07 09:09:40 +00001649 self.assertEqual(suite_1, suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001650
Georg Brandl15c5ce92007-03-07 09:09:40 +00001651 # "Add all the tests from an iterable of TestCase and TestSuite
1652 # instances to this test suite."
1653 #
Tim Petersea5962f2007-03-12 18:07:52 +00001654 # What happens if it doesn't get an iterable?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001655 def test_addTest__noniterable(self):
1656 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001657
Georg Brandl15c5ce92007-03-07 09:09:40 +00001658 try:
1659 suite.addTests(5)
1660 except TypeError:
1661 pass
1662 else:
1663 self.fail("Failed to raise TypeError")
Georg Brandld9e50262007-03-07 11:54:49 +00001664
1665 def test_addTest__noncallable(self):
1666 suite = unittest.TestSuite()
1667 self.assertRaises(TypeError, suite.addTest, 5)
1668
1669 def test_addTest__casesuiteclass(self):
1670 suite = unittest.TestSuite()
1671 self.assertRaises(TypeError, suite.addTest, Test_TestSuite)
1672 self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)
1673
1674 def test_addTests__string(self):
1675 suite = unittest.TestSuite()
1676 self.assertRaises(TypeError, suite.addTests, "foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001677
1678
Georg Brandl15c5ce92007-03-07 09:09:40 +00001679class Test_FunctionTestCase(TestCase):
Tim Petersea5962f2007-03-12 18:07:52 +00001680
Georg Brandl15c5ce92007-03-07 09:09:40 +00001681 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00001682 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001683 def test_countTestCases(self):
1684 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001685
Georg Brandl15c5ce92007-03-07 09:09:40 +00001686 self.assertEqual(test.countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00001687
Georg Brandl15c5ce92007-03-07 09:09:40 +00001688 # "When a setUp() method is defined, the test runner will run that method
1689 # prior to each test. Likewise, if a tearDown() method is defined, the
1690 # test runner will invoke that method after each test. In the example,
1691 # setUp() was used to create a fresh sequence for each test."
1692 #
1693 # Make sure the proper call order is maintained, even if setUp() raises
1694 # an exception.
1695 def test_run_call_order__error_in_setUp(self):
1696 events = []
1697 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001698
Georg Brandl15c5ce92007-03-07 09:09:40 +00001699 def setUp():
1700 events.append('setUp')
1701 raise RuntimeError('raised by setUp')
1702
1703 def test():
1704 events.append('test')
1705
1706 def tearDown():
1707 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001708
1709 expected = ['startTest', 'setUp', 'addError', 'stopTest']
Georg Brandl15c5ce92007-03-07 09:09:40 +00001710 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1711 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001712
Georg Brandl15c5ce92007-03-07 09:09:40 +00001713 # "When a setUp() method is defined, the test runner will run that method
1714 # prior to each test. Likewise, if a tearDown() method is defined, the
1715 # test runner will invoke that method after each test. In the example,
1716 # setUp() was used to create a fresh sequence for each test."
1717 #
1718 # Make sure the proper call order is maintained, even if the test raises
1719 # an error (as opposed to a failure).
1720 def test_run_call_order__error_in_test(self):
1721 events = []
1722 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001723
Georg Brandl15c5ce92007-03-07 09:09:40 +00001724 def setUp():
1725 events.append('setUp')
1726
1727 def test():
1728 events.append('test')
1729 raise RuntimeError('raised by test')
1730
1731 def tearDown():
1732 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001733
Georg Brandl15c5ce92007-03-07 09:09:40 +00001734 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
1735 'stopTest']
1736 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1737 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001738
Georg Brandl15c5ce92007-03-07 09:09:40 +00001739 # "When a setUp() method is defined, the test runner will run that method
1740 # prior to each test. Likewise, if a tearDown() method is defined, the
1741 # test runner will invoke that method after each test. In the example,
1742 # setUp() was used to create a fresh sequence for each test."
1743 #
1744 # Make sure the proper call order is maintained, even if the test signals
1745 # a failure (as opposed to an error).
1746 def test_run_call_order__failure_in_test(self):
1747 events = []
1748 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001749
Georg Brandl15c5ce92007-03-07 09:09:40 +00001750 def setUp():
1751 events.append('setUp')
1752
1753 def test():
1754 events.append('test')
1755 self.fail('raised by test')
1756
1757 def tearDown():
1758 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001759
Georg Brandl15c5ce92007-03-07 09:09:40 +00001760 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
1761 'stopTest']
1762 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1763 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001764
Georg Brandl15c5ce92007-03-07 09:09:40 +00001765 # "When a setUp() method is defined, the test runner will run that method
1766 # prior to each test. Likewise, if a tearDown() method is defined, the
1767 # test runner will invoke that method after each test. In the example,
1768 # setUp() was used to create a fresh sequence for each test."
1769 #
1770 # Make sure the proper call order is maintained, even if tearDown() raises
1771 # an exception.
1772 def test_run_call_order__error_in_tearDown(self):
1773 events = []
1774 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001775
Georg Brandl15c5ce92007-03-07 09:09:40 +00001776 def setUp():
1777 events.append('setUp')
1778
1779 def test():
1780 events.append('test')
1781
1782 def tearDown():
1783 events.append('tearDown')
1784 raise RuntimeError('raised by tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001785
Georg Brandl15c5ce92007-03-07 09:09:40 +00001786 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
1787 'stopTest']
1788 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1789 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001790
Georg Brandl15c5ce92007-03-07 09:09:40 +00001791 # "Return a string identifying the specific test case."
1792 #
1793 # Because of the vague nature of the docs, I'm not going to lock this
1794 # test down too much. Really all that can be asserted is that the id()
1795 # will be a string (either 8-byte or unicode -- again, because the docs
1796 # just say "string")
1797 def test_id(self):
1798 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001799
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001800 self.assertIsInstance(test.id(), basestring)
Tim Petersea5962f2007-03-12 18:07:52 +00001801
Georg Brandl15c5ce92007-03-07 09:09:40 +00001802 # "Returns a one-line description of the test, or None if no description
1803 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001804 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001805 def test_shortDescription__no_docstring(self):
1806 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001807
Georg Brandl15c5ce92007-03-07 09:09:40 +00001808 self.assertEqual(test.shortDescription(), None)
Tim Petersea5962f2007-03-12 18:07:52 +00001809
Georg Brandl15c5ce92007-03-07 09:09:40 +00001810 # "Returns a one-line description of the test, or None if no description
1811 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001812 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001813 def test_shortDescription__singleline_docstring(self):
1814 desc = "this tests foo"
1815 test = unittest.FunctionTestCase(lambda: None, description=desc)
Tim Petersea5962f2007-03-12 18:07:52 +00001816
Georg Brandl15c5ce92007-03-07 09:09:40 +00001817 self.assertEqual(test.shortDescription(), "this tests foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001818
Georg Brandl15c5ce92007-03-07 09:09:40 +00001819class Test_TestResult(TestCase):
1820 # Note: there are not separate tests for TestResult.wasSuccessful(),
1821 # TestResult.errors, TestResult.failures, TestResult.testsRun or
1822 # TestResult.shouldStop because these only have meaning in terms of
1823 # other TestResult methods.
1824 #
1825 # Accordingly, tests for the aforenamed attributes are incorporated
1826 # in with the tests for the defining methods.
1827 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001828
Georg Brandl15c5ce92007-03-07 09:09:40 +00001829 def test_init(self):
1830 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001831
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001832 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001833 self.assertEqual(len(result.errors), 0)
1834 self.assertEqual(len(result.failures), 0)
1835 self.assertEqual(result.testsRun, 0)
1836 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001837
Georg Brandl15c5ce92007-03-07 09:09:40 +00001838 # "This method can be called to signal that the set of tests being
1839 # run should be aborted by setting the TestResult's shouldStop
Tim Petersea5962f2007-03-12 18:07:52 +00001840 # attribute to True."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001841 def test_stop(self):
1842 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001843
Georg Brandl15c5ce92007-03-07 09:09:40 +00001844 result.stop()
Tim Petersea5962f2007-03-12 18:07:52 +00001845
Georg Brandl15c5ce92007-03-07 09:09:40 +00001846 self.assertEqual(result.shouldStop, True)
Tim Petersea5962f2007-03-12 18:07:52 +00001847
Georg Brandl15c5ce92007-03-07 09:09:40 +00001848 # "Called when the test case test is about to be run. The default
1849 # implementation simply increments the instance's testsRun counter."
1850 def test_startTest(self):
1851 class Foo(unittest.TestCase):
1852 def test_1(self):
1853 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001854
Georg Brandl15c5ce92007-03-07 09:09:40 +00001855 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001856
Georg Brandl15c5ce92007-03-07 09:09:40 +00001857 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001858
Georg Brandl15c5ce92007-03-07 09:09:40 +00001859 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001860
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001861 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001862 self.assertEqual(len(result.errors), 0)
1863 self.assertEqual(len(result.failures), 0)
1864 self.assertEqual(result.testsRun, 1)
1865 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001866
Georg Brandl15c5ce92007-03-07 09:09:40 +00001867 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001868
Georg Brandl15c5ce92007-03-07 09:09:40 +00001869 # "Called after the test case test has been executed, regardless of
1870 # the outcome. The default implementation does nothing."
1871 def test_stopTest(self):
1872 class Foo(unittest.TestCase):
1873 def test_1(self):
1874 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001875
Georg Brandl15c5ce92007-03-07 09:09:40 +00001876 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001877
Georg Brandl15c5ce92007-03-07 09:09:40 +00001878 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001879
Georg Brandl15c5ce92007-03-07 09:09:40 +00001880 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001881
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001882 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001883 self.assertEqual(len(result.errors), 0)
1884 self.assertEqual(len(result.failures), 0)
1885 self.assertEqual(result.testsRun, 1)
1886 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001887
Georg Brandl15c5ce92007-03-07 09:09:40 +00001888 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001889
Georg Brandl15c5ce92007-03-07 09:09:40 +00001890 # Same tests as above; make sure nothing has changed
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001891 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001892 self.assertEqual(len(result.errors), 0)
1893 self.assertEqual(len(result.failures), 0)
1894 self.assertEqual(result.testsRun, 1)
1895 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001896
Michael Foord07ef4872009-05-02 22:43:34 +00001897 # "Called before and after tests are run. The default implementation does nothing."
1898 def test_startTestRun_stopTestRun(self):
1899 result = unittest.TestResult()
1900 result.startTestRun()
1901 result.stopTestRun()
1902
Georg Brandl15c5ce92007-03-07 09:09:40 +00001903 # "addSuccess(test)"
1904 # ...
1905 # "Called when the test case test succeeds"
1906 # ...
1907 # "wasSuccessful() - Returns True if all tests run so far have passed,
1908 # otherwise returns False"
1909 # ...
1910 # "testsRun - The total number of tests run so far."
1911 # ...
1912 # "errors - A list containing 2-tuples of TestCase instances and
1913 # formatted tracebacks. Each tuple represents a test which raised an
1914 # unexpected exception. Contains formatted
1915 # tracebacks instead of sys.exc_info() results."
1916 # ...
1917 # "failures - A list containing 2-tuples of TestCase instances and
1918 # formatted tracebacks. Each tuple represents a test where a failure was
1919 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1920 # methods. Contains formatted tracebacks instead
1921 # of sys.exc_info() results."
1922 def test_addSuccess(self):
1923 class Foo(unittest.TestCase):
1924 def test_1(self):
1925 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001926
Georg Brandl15c5ce92007-03-07 09:09:40 +00001927 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001928
Georg Brandl15c5ce92007-03-07 09:09:40 +00001929 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001930
Georg Brandl15c5ce92007-03-07 09:09:40 +00001931 result.startTest(test)
1932 result.addSuccess(test)
1933 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001934
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001935 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001936 self.assertEqual(len(result.errors), 0)
1937 self.assertEqual(len(result.failures), 0)
1938 self.assertEqual(result.testsRun, 1)
1939 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001940
Georg Brandl15c5ce92007-03-07 09:09:40 +00001941 # "addFailure(test, err)"
1942 # ...
1943 # "Called when the test case test signals a failure. err is a tuple of
1944 # the form returned by sys.exc_info(): (type, value, traceback)"
1945 # ...
1946 # "wasSuccessful() - Returns True if all tests run so far have passed,
1947 # otherwise returns False"
1948 # ...
1949 # "testsRun - The total number of tests run so far."
1950 # ...
1951 # "errors - A list containing 2-tuples of TestCase instances and
1952 # formatted tracebacks. Each tuple represents a test which raised an
1953 # unexpected exception. Contains formatted
1954 # tracebacks instead of sys.exc_info() results."
1955 # ...
1956 # "failures - A list containing 2-tuples of TestCase instances and
1957 # formatted tracebacks. Each tuple represents a test where a failure was
1958 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1959 # methods. Contains formatted tracebacks instead
1960 # of sys.exc_info() results."
1961 def test_addFailure(self):
Georg Brandl15c5ce92007-03-07 09:09:40 +00001962 class Foo(unittest.TestCase):
1963 def test_1(self):
1964 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001965
Georg Brandl15c5ce92007-03-07 09:09:40 +00001966 test = Foo('test_1')
1967 try:
1968 test.fail("foo")
1969 except:
1970 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00001971
Georg Brandl15c5ce92007-03-07 09:09:40 +00001972 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001973
Georg Brandl15c5ce92007-03-07 09:09:40 +00001974 result.startTest(test)
1975 result.addFailure(test, exc_info_tuple)
1976 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001977
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001978 self.assertFalse(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001979 self.assertEqual(len(result.errors), 0)
1980 self.assertEqual(len(result.failures), 1)
1981 self.assertEqual(result.testsRun, 1)
1982 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001983
Georg Brandl15c5ce92007-03-07 09:09:40 +00001984 test_case, formatted_exc = result.failures[0]
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001985 self.assertTrue(test_case is test)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001986 self.assertIsInstance(formatted_exc, str)
Tim Petersea5962f2007-03-12 18:07:52 +00001987
Georg Brandl15c5ce92007-03-07 09:09:40 +00001988 # "addError(test, err)"
1989 # ...
1990 # "Called when the test case test raises an unexpected exception err
1991 # is a tuple of the form returned by sys.exc_info():
1992 # (type, value, traceback)"
1993 # ...
1994 # "wasSuccessful() - Returns True if all tests run so far have passed,
1995 # otherwise returns False"
1996 # ...
1997 # "testsRun - The total number of tests run so far."
1998 # ...
1999 # "errors - A list containing 2-tuples of TestCase instances and
2000 # formatted tracebacks. Each tuple represents a test which raised an
2001 # unexpected exception. Contains formatted
2002 # tracebacks instead of sys.exc_info() results."
2003 # ...
2004 # "failures - A list containing 2-tuples of TestCase instances and
2005 # formatted tracebacks. Each tuple represents a test where a failure was
2006 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
2007 # methods. Contains formatted tracebacks instead
2008 # of sys.exc_info() results."
2009 def test_addError(self):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002010 class Foo(unittest.TestCase):
2011 def test_1(self):
2012 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002013
Georg Brandl15c5ce92007-03-07 09:09:40 +00002014 test = Foo('test_1')
2015 try:
2016 raise TypeError()
2017 except:
2018 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00002019
Georg Brandl15c5ce92007-03-07 09:09:40 +00002020 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00002021
Georg Brandl15c5ce92007-03-07 09:09:40 +00002022 result.startTest(test)
2023 result.addError(test, exc_info_tuple)
2024 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00002025
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002026 self.assertFalse(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00002027 self.assertEqual(len(result.errors), 1)
2028 self.assertEqual(len(result.failures), 0)
2029 self.assertEqual(result.testsRun, 1)
2030 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00002031
Georg Brandl15c5ce92007-03-07 09:09:40 +00002032 test_case, formatted_exc = result.errors[0]
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002033 self.assertTrue(test_case is test)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002034 self.assertIsInstance(formatted_exc, str)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002035
Michael Foorddb43b5a2010-02-10 14:25:12 +00002036 def testGetDescriptionWithoutDocstring(self):
Michael Foord1c3abf42010-02-10 15:50:58 +00002037 result = unittest.TextTestResult(None, True, 1)
Michael Foorddb43b5a2010-02-10 14:25:12 +00002038 self.assertEqual(
2039 result.getDescription(self),
2040 'testGetDescriptionWithoutDocstring (' + __name__ +
2041 '.Test_TestResult)')
2042
2043 def testGetDescriptionWithOneLineDocstring(self):
2044 """Tests getDescription() for a method with a docstring."""
Michael Foord1c3abf42010-02-10 15:50:58 +00002045 result = unittest.TextTestResult(None, True, 1)
Michael Foorddb43b5a2010-02-10 14:25:12 +00002046 self.assertEqual(
2047 result.getDescription(self),
2048 ('testGetDescriptionWithOneLineDocstring '
2049 '(' + __name__ + '.Test_TestResult)\n'
2050 'Tests getDescription() for a method with a docstring.'))
2051
2052 def testGetDescriptionWithMultiLineDocstring(self):
2053 """Tests getDescription() for a method with a longer docstring.
2054 The second line of the docstring.
2055 """
Michael Foord1c3abf42010-02-10 15:50:58 +00002056 result = unittest.TextTestResult(None, True, 1)
Michael Foorddb43b5a2010-02-10 14:25:12 +00002057 self.assertEqual(
2058 result.getDescription(self),
2059 ('testGetDescriptionWithMultiLineDocstring '
2060 '(' + __name__ + '.Test_TestResult)\n'
2061 'Tests getDescription() for a method with a longer '
2062 'docstring.'))
2063
2064
Georg Brandl15c5ce92007-03-07 09:09:40 +00002065### Support code for Test_TestCase
2066################################################################
2067
2068class Foo(unittest.TestCase):
2069 def runTest(self): pass
2070 def test1(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002071
Georg Brandl15c5ce92007-03-07 09:09:40 +00002072class Bar(Foo):
2073 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002074
Michael Foord07ef4872009-05-02 22:43:34 +00002075class LoggingTestCase(unittest.TestCase):
2076 """A test case which logs its calls."""
2077
2078 def __init__(self, events):
2079 super(LoggingTestCase, self).__init__('test')
2080 self.events = events
2081
2082 def setUp(self):
2083 self.events.append('setUp')
2084
2085 def test(self):
2086 self.events.append('test')
2087
2088 def tearDown(self):
2089 self.events.append('tearDown')
2090
2091class ResultWithNoStartTestRunStopTestRun(object):
2092 """An object honouring TestResult before startTestRun/stopTestRun."""
2093
2094 def __init__(self):
2095 self.failures = []
2096 self.errors = []
2097 self.testsRun = 0
2098 self.skipped = []
2099 self.expectedFailures = []
2100 self.unexpectedSuccesses = []
2101 self.shouldStop = False
2102
2103 def startTest(self, test):
2104 pass
2105
2106 def stopTest(self, test):
2107 pass
2108
2109 def addError(self, test):
2110 pass
2111
2112 def addFailure(self, test):
2113 pass
2114
2115 def addSuccess(self, test):
2116 pass
2117
2118 def wasSuccessful(self):
2119 return True
2120
2121
Georg Brandl15c5ce92007-03-07 09:09:40 +00002122################################################################
2123### /Support code for Test_TestCase
2124
2125class Test_TestCase(TestCase, TestEquality, TestHashing):
2126
2127 ### Set up attributes used by inherited tests
2128 ################################################################
2129
2130 # Used by TestHashing.test_hash and TestEquality.test_eq
2131 eq_pairs = [(Foo('test1'), Foo('test1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002132
Georg Brandl15c5ce92007-03-07 09:09:40 +00002133 # Used by TestEquality.test_ne
2134 ne_pairs = [(Foo('test1'), Foo('runTest'))
2135 ,(Foo('test1'), Bar('test1'))
2136 ,(Foo('test1'), Bar('test2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002137
Georg Brandl15c5ce92007-03-07 09:09:40 +00002138 ################################################################
2139 ### /Set up attributes used by inherited tests
Tim Petersea5962f2007-03-12 18:07:52 +00002140
Georg Brandl15c5ce92007-03-07 09:09:40 +00002141
2142 # "class TestCase([methodName])"
2143 # ...
2144 # "Each instance of TestCase will run a single test method: the
2145 # method named methodName."
2146 # ...
2147 # "methodName defaults to "runTest"."
2148 #
2149 # Make sure it really is optional, and that it defaults to the proper
2150 # thing.
2151 def test_init__no_test_name(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 self.assertEqual(Test().id()[-13:], '.Test.runTest')
Tim Petersea5962f2007-03-12 18:07:52 +00002157
Georg Brandl15c5ce92007-03-07 09:09:40 +00002158 # "class TestCase([methodName])"
2159 # ...
2160 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002161 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002162 def test_init__test_name__valid(self):
2163 class Test(unittest.TestCase):
2164 def runTest(self): raise MyException()
2165 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002166
Georg Brandl15c5ce92007-03-07 09:09:40 +00002167 self.assertEqual(Test('test').id()[-10:], '.Test.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002168
Georg Brandl15c5ce92007-03-07 09:09:40 +00002169 # "class TestCase([methodName])"
2170 # ...
2171 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002172 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002173 def test_init__test_name__invalid(self):
2174 class Test(unittest.TestCase):
2175 def runTest(self): raise MyException()
2176 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002177
Georg Brandl15c5ce92007-03-07 09:09:40 +00002178 try:
2179 Test('testfoo')
2180 except ValueError:
2181 pass
2182 else:
2183 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +00002184
Georg Brandl15c5ce92007-03-07 09:09:40 +00002185 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00002186 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00002187 def test_countTestCases(self):
2188 class Foo(unittest.TestCase):
2189 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002190
Georg Brandl15c5ce92007-03-07 09:09:40 +00002191 self.assertEqual(Foo('test').countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00002192
Georg Brandl15c5ce92007-03-07 09:09:40 +00002193 # "Return the default type of test result object to be used to run this
2194 # test. For TestCase instances, this will always be
2195 # unittest.TestResult; subclasses of TestCase should
2196 # override this as necessary."
2197 def test_defaultTestResult(self):
2198 class Foo(unittest.TestCase):
2199 def runTest(self):
2200 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002201
Georg Brandl15c5ce92007-03-07 09:09:40 +00002202 result = Foo().defaultTestResult()
2203 self.assertEqual(type(result), unittest.TestResult)
2204
2205 # "When a setUp() method is defined, the test runner will run that method
2206 # prior to each test. Likewise, if a tearDown() method is defined, the
2207 # test runner will invoke that method after each test. In the example,
2208 # setUp() was used to create a fresh sequence for each test."
2209 #
2210 # Make sure the proper call order is maintained, even if setUp() raises
2211 # an exception.
2212 def test_run_call_order__error_in_setUp(self):
2213 events = []
2214 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002215
Michael Foord07ef4872009-05-02 22:43:34 +00002216 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002217 def setUp(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002218 super(Foo, self).setUp()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002219 raise RuntimeError('raised by Foo.setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002220
Michael Foord07ef4872009-05-02 22:43:34 +00002221 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002222 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2223 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002224
Michael Foord07ef4872009-05-02 22:43:34 +00002225 # "With a temporary result stopTestRun is called when setUp errors.
2226 def test_run_call_order__error_in_setUp_default_result(self):
2227 events = []
2228
2229 class Foo(LoggingTestCase):
2230 def defaultTestResult(self):
2231 return LoggingResult(self.events)
2232
2233 def setUp(self):
2234 super(Foo, self).setUp()
2235 raise RuntimeError('raised by Foo.setUp')
2236
2237 Foo(events).run()
2238 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2239 'stopTest', 'stopTestRun']
2240 self.assertEqual(events, expected)
2241
Georg Brandl15c5ce92007-03-07 09:09:40 +00002242 # "When a setUp() method is defined, the test runner will run that method
2243 # prior to each test. Likewise, if a tearDown() method is defined, the
2244 # test runner will invoke that method after each test. In the example,
2245 # setUp() was used to create a fresh sequence for each test."
2246 #
2247 # Make sure the proper call order is maintained, even if the test raises
2248 # an error (as opposed to a failure).
2249 def test_run_call_order__error_in_test(self):
2250 events = []
2251 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002252
Michael Foord07ef4872009-05-02 22:43:34 +00002253 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002254 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002255 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002256 raise RuntimeError('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002257
Georg Brandl15c5ce92007-03-07 09:09:40 +00002258 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2259 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002260 Foo(events).run(result)
2261 self.assertEqual(events, expected)
2262
2263 # "With a default result, an error in the test still results in stopTestRun
2264 # being called."
2265 def test_run_call_order__error_in_test_default_result(self):
2266 events = []
2267
2268 class Foo(LoggingTestCase):
2269 def defaultTestResult(self):
2270 return LoggingResult(self.events)
2271
2272 def test(self):
2273 super(Foo, self).test()
2274 raise RuntimeError('raised by Foo.test')
2275
2276 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2277 'tearDown', 'stopTest', 'stopTestRun']
2278 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002279 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002280
Georg Brandl15c5ce92007-03-07 09:09:40 +00002281 # "When a setUp() method is defined, the test runner will run that method
2282 # prior to each test. Likewise, if a tearDown() method is defined, the
2283 # test runner will invoke that method after each test. In the example,
2284 # setUp() was used to create a fresh sequence for each test."
2285 #
2286 # Make sure the proper call order is maintained, even if the test signals
2287 # a failure (as opposed to an error).
2288 def test_run_call_order__failure_in_test(self):
2289 events = []
2290 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002291
Michael Foord07ef4872009-05-02 22:43:34 +00002292 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002293 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002294 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002295 self.fail('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002296
Georg Brandl15c5ce92007-03-07 09:09:40 +00002297 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2298 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002299 Foo(events).run(result)
2300 self.assertEqual(events, expected)
2301
2302 # "When a test fails with a default result stopTestRun is still called."
2303 def test_run_call_order__failure_in_test_default_result(self):
2304
2305 class Foo(LoggingTestCase):
2306 def defaultTestResult(self):
2307 return LoggingResult(self.events)
2308 def test(self):
2309 super(Foo, self).test()
2310 self.fail('raised by Foo.test')
2311
2312 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2313 'tearDown', 'stopTest', 'stopTestRun']
2314 events = []
2315 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002316 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002317
Georg Brandl15c5ce92007-03-07 09:09:40 +00002318 # "When a setUp() method is defined, the test runner will run that method
2319 # prior to each test. Likewise, if a tearDown() method is defined, the
2320 # test runner will invoke that method after each test. In the example,
2321 # setUp() was used to create a fresh sequence for each test."
2322 #
2323 # Make sure the proper call order is maintained, even if tearDown() raises
2324 # an exception.
2325 def test_run_call_order__error_in_tearDown(self):
2326 events = []
2327 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002328
Michael Foord07ef4872009-05-02 22:43:34 +00002329 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002330 def tearDown(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002331 super(Foo, self).tearDown()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002332 raise RuntimeError('raised by Foo.tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002333
Michael Foord07ef4872009-05-02 22:43:34 +00002334 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002335 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2336 'stopTest']
2337 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002338
Michael Foord07ef4872009-05-02 22:43:34 +00002339 # "When tearDown errors with a default result stopTestRun is still called."
2340 def test_run_call_order__error_in_tearDown_default_result(self):
2341
2342 class Foo(LoggingTestCase):
2343 def defaultTestResult(self):
2344 return LoggingResult(self.events)
2345 def tearDown(self):
2346 super(Foo, self).tearDown()
2347 raise RuntimeError('raised by Foo.tearDown')
2348
2349 events = []
2350 Foo(events).run()
2351 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2352 'addError', 'stopTest', 'stopTestRun']
2353 self.assertEqual(events, expected)
2354
2355 # "TestCase.run() still works when the defaultTestResult is a TestResult
2356 # that does not support startTestRun and stopTestRun.
2357 def test_run_call_order_default_result(self):
2358
2359 class Foo(unittest.TestCase):
2360 def defaultTestResult(self):
2361 return ResultWithNoStartTestRunStopTestRun()
2362 def test(self):
2363 pass
2364
2365 Foo('test').run()
2366
Georg Brandl15c5ce92007-03-07 09:09:40 +00002367 # "This class attribute gives the exception raised by the test() method.
2368 # If a test framework needs to use a specialized exception, possibly to
2369 # carry additional information, it must subclass this exception in
2370 # order to ``play fair'' with the framework. The initial value of this
2371 # attribute is AssertionError"
2372 def test_failureException__default(self):
2373 class Foo(unittest.TestCase):
2374 def test(self):
2375 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002376
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002377 self.assertTrue(Foo('test').failureException is AssertionError)
Tim Petersea5962f2007-03-12 18:07:52 +00002378
Georg Brandl15c5ce92007-03-07 09:09:40 +00002379 # "This class attribute gives the exception raised by the test() method.
2380 # If a test framework needs to use a specialized exception, possibly to
2381 # carry additional information, it must subclass this exception in
2382 # order to ``play fair'' with the framework."
2383 #
2384 # Make sure TestCase.run() respects the designated failureException
2385 def test_failureException__subclassing__explicit_raise(self):
2386 events = []
2387 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002388
Georg Brandl15c5ce92007-03-07 09:09:40 +00002389 class Foo(unittest.TestCase):
2390 def test(self):
2391 raise RuntimeError()
Tim Petersea5962f2007-03-12 18:07:52 +00002392
Georg Brandl15c5ce92007-03-07 09:09:40 +00002393 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002394
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002395 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002396
2397
Georg Brandl15c5ce92007-03-07 09:09:40 +00002398 Foo('test').run(result)
2399 expected = ['startTest', 'addFailure', 'stopTest']
2400 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002401
Georg Brandl15c5ce92007-03-07 09:09:40 +00002402 # "This class attribute gives the exception raised by the test() method.
2403 # If a test framework needs to use a specialized exception, possibly to
2404 # carry additional information, it must subclass this exception in
2405 # order to ``play fair'' with the framework."
2406 #
2407 # Make sure TestCase.run() respects the designated failureException
2408 def test_failureException__subclassing__implicit_raise(self):
2409 events = []
2410 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002411
Georg Brandl15c5ce92007-03-07 09:09:40 +00002412 class Foo(unittest.TestCase):
2413 def test(self):
2414 self.fail("foo")
Tim Petersea5962f2007-03-12 18:07:52 +00002415
Georg Brandl15c5ce92007-03-07 09:09:40 +00002416 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002417
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002418 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002419
2420
Georg Brandl15c5ce92007-03-07 09:09:40 +00002421 Foo('test').run(result)
2422 expected = ['startTest', 'addFailure', 'stopTest']
2423 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002424
2425 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002426 def test_setUp(self):
2427 class Foo(unittest.TestCase):
2428 def runTest(self):
2429 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002430
Georg Brandl15c5ce92007-03-07 09:09:40 +00002431 # ... and nothing should happen
2432 Foo().setUp()
Tim Petersea5962f2007-03-12 18:07:52 +00002433
2434 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002435 def test_tearDown(self):
2436 class Foo(unittest.TestCase):
2437 def runTest(self):
2438 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002439
Georg Brandl15c5ce92007-03-07 09:09:40 +00002440 # ... and nothing should happen
2441 Foo().tearDown()
Tim Petersea5962f2007-03-12 18:07:52 +00002442
Georg Brandl15c5ce92007-03-07 09:09:40 +00002443 # "Return a string identifying the specific test case."
2444 #
2445 # Because of the vague nature of the docs, I'm not going to lock this
2446 # test down too much. Really all that can be asserted is that the id()
2447 # will be a string (either 8-byte or unicode -- again, because the docs
2448 # just say "string")
2449 def test_id(self):
2450 class Foo(unittest.TestCase):
2451 def runTest(self):
2452 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002453
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002454 self.assertIsInstance(Foo().id(), basestring)
Tim Petersea5962f2007-03-12 18:07:52 +00002455
Georg Brandl15c5ce92007-03-07 09:09:40 +00002456 # "If result is omitted or None, a temporary result object is created
Michael Foord07ef4872009-05-02 22:43:34 +00002457 # and used, but is not made available to the caller. As TestCase owns the
2458 # temporary result startTestRun and stopTestRun are called.
2459
Georg Brandl15c5ce92007-03-07 09:09:40 +00002460 def test_run__uses_defaultTestResult(self):
2461 events = []
Tim Petersea5962f2007-03-12 18:07:52 +00002462
Georg Brandl15c5ce92007-03-07 09:09:40 +00002463 class Foo(unittest.TestCase):
2464 def test(self):
2465 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002466
Georg Brandl15c5ce92007-03-07 09:09:40 +00002467 def defaultTestResult(self):
2468 return LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002469
2470 # Make run() find a result object on its own
Georg Brandl15c5ce92007-03-07 09:09:40 +00002471 Foo('test').run()
Tim Petersea5962f2007-03-12 18:07:52 +00002472
Michael Foord07ef4872009-05-02 22:43:34 +00002473 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2474 'stopTest', 'stopTestRun']
Georg Brandl15c5ce92007-03-07 09:09:40 +00002475 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002476
Gregory P. Smith28399852009-03-31 16:54:10 +00002477 def testShortDescriptionWithoutDocstring(self):
Michael Foorddb43b5a2010-02-10 14:25:12 +00002478 self.assertIsNone(self.shortDescription())
Gregory P. Smith28399852009-03-31 16:54:10 +00002479
2480 def testShortDescriptionWithOneLineDocstring(self):
2481 """Tests shortDescription() for a method with a docstring."""
2482 self.assertEqual(
2483 self.shortDescription(),
Michael Foorddb43b5a2010-02-10 14:25:12 +00002484 'Tests shortDescription() for a method with a docstring.')
Gregory P. Smith28399852009-03-31 16:54:10 +00002485
2486 def testShortDescriptionWithMultiLineDocstring(self):
2487 """Tests shortDescription() for a method with a longer docstring.
2488
2489 This method ensures that only the first line of a docstring is
2490 returned used in the short description, no matter how long the
2491 whole thing is.
2492 """
2493 self.assertEqual(
2494 self.shortDescription(),
Gregory P. Smith28399852009-03-31 16:54:10 +00002495 'Tests shortDescription() for a method with a longer '
Michael Foorddb43b5a2010-02-10 14:25:12 +00002496 'docstring.')
Gregory P. Smith28399852009-03-31 16:54:10 +00002497
Gregory P. Smith28399852009-03-31 16:54:10 +00002498 def testAddTypeEqualityFunc(self):
2499 class SadSnake(object):
2500 """Dummy class for test_addTypeEqualityFunc."""
2501 s1, s2 = SadSnake(), SadSnake()
2502 self.assertFalse(s1 == s2)
2503 def AllSnakesCreatedEqual(a, b, msg=None):
2504 return type(a) == type(b) == SadSnake
2505 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2506 self.assertEqual(s1, s2)
2507 # No this doesn't clean up and remove the SadSnake equality func
2508 # from this TestCase instance but since its a local nothing else
2509 # will ever notice that.
2510
Michael Foordf2dfef12009-04-05 19:19:28 +00002511 def testAssertIs(self):
2512 thing = object()
2513 self.assertIs(thing, thing)
2514 self.assertRaises(self.failureException, self.assertIs, thing, object())
2515
2516 def testAssertIsNot(self):
2517 thing = object()
2518 self.assertIsNot(thing, object())
2519 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2520
Georg Brandlf895cf52009-10-01 20:59:31 +00002521 def testAssertIsInstance(self):
2522 thing = []
2523 self.assertIsInstance(thing, list)
2524 self.assertRaises(self.failureException, self.assertIsInstance,
2525 thing, dict)
2526
2527 def testAssertNotIsInstance(self):
2528 thing = []
2529 self.assertNotIsInstance(thing, dict)
2530 self.assertRaises(self.failureException, self.assertNotIsInstance,
2531 thing, list)
2532
Gregory P. Smith28399852009-03-31 16:54:10 +00002533 def testAssertIn(self):
2534 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2535
2536 self.assertIn('a', 'abc')
2537 self.assertIn(2, [1, 2, 3])
2538 self.assertIn('monkey', animals)
2539
2540 self.assertNotIn('d', 'abc')
2541 self.assertNotIn(0, [1, 2, 3])
2542 self.assertNotIn('otter', animals)
2543
2544 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2545 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2546 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2547 animals)
2548
2549 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2550 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2551 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2552 animals)
2553
2554 def testAssertDictContainsSubset(self):
2555 self.assertDictContainsSubset({}, {})
2556 self.assertDictContainsSubset({}, {'a': 1})
2557 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2558 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2559 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2560
Michael Foord225a0992010-02-18 20:30:09 +00002561 with self.assertRaises(self.failureException):
2562 self.assertDictContainsSubset({1: "one"}, {})
Gregory P. Smith28399852009-03-31 16:54:10 +00002563
Michael Foord225a0992010-02-18 20:30:09 +00002564 with self.assertRaises(self.failureException):
2565 self.assertDictContainsSubset({'a': 2}, {'a': 1})
Gregory P. Smith28399852009-03-31 16:54:10 +00002566
Michael Foord225a0992010-02-18 20:30:09 +00002567 with self.assertRaises(self.failureException):
2568 self.assertDictContainsSubset({'c': 1}, {'a': 1})
Gregory P. Smith28399852009-03-31 16:54:10 +00002569
Michael Foord225a0992010-02-18 20:30:09 +00002570 with self.assertRaises(self.failureException):
2571 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2572
2573 with self.assertRaises(self.failureException):
2574 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2575
2576 @unittest.expectedFailure
2577 def test_crazy(self):
2578 one = ''.join(chr(i) for i in range(255))
2579 two = u'\uFFFD'
2580 first = {'foo': one}
2581 second = {'foo': two}
2582 self.assertDictContainsSubset(first, second)
Gregory P. Smith28399852009-03-31 16:54:10 +00002583
2584 def testAssertEqual(self):
2585 equal_pairs = [
2586 ((), ()),
2587 ({}, {}),
2588 ([], []),
2589 (set(), set()),
2590 (frozenset(), frozenset())]
2591 for a, b in equal_pairs:
2592 # This mess of try excepts is to test the assertEqual behavior
2593 # itself.
2594 try:
2595 self.assertEqual(a, b)
2596 except self.failureException:
2597 self.fail('assertEqual(%r, %r) failed' % (a, b))
2598 try:
2599 self.assertEqual(a, b, msg='foo')
2600 except self.failureException:
2601 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2602 try:
2603 self.assertEqual(a, b, 'foo')
2604 except self.failureException:
2605 self.fail('assertEqual(%r, %r) with third parameter failed' %
2606 (a, b))
2607
2608 unequal_pairs = [
2609 ((), []),
2610 ({}, set()),
2611 (set([4,1]), frozenset([4,2])),
2612 (frozenset([4,5]), set([2,3])),
2613 (set([3,4]), set([5,4]))]
2614 for a, b in unequal_pairs:
2615 self.assertRaises(self.failureException, self.assertEqual, a, b)
2616 self.assertRaises(self.failureException, self.assertEqual, a, b,
2617 'foo')
2618 self.assertRaises(self.failureException, self.assertEqual, a, b,
2619 msg='foo')
2620
2621 def testEquality(self):
2622 self.assertListEqual([], [])
2623 self.assertTupleEqual((), ())
2624 self.assertSequenceEqual([], ())
2625
2626 a = [0, 'a', []]
2627 b = []
2628 self.assertRaises(unittest.TestCase.failureException,
2629 self.assertListEqual, a, b)
2630 self.assertRaises(unittest.TestCase.failureException,
2631 self.assertListEqual, tuple(a), tuple(b))
2632 self.assertRaises(unittest.TestCase.failureException,
2633 self.assertSequenceEqual, a, tuple(b))
2634
2635 b.extend(a)
2636 self.assertListEqual(a, b)
2637 self.assertTupleEqual(tuple(a), tuple(b))
2638 self.assertSequenceEqual(a, tuple(b))
2639 self.assertSequenceEqual(tuple(a), b)
2640
2641 self.assertRaises(self.failureException, self.assertListEqual,
2642 a, tuple(b))
2643 self.assertRaises(self.failureException, self.assertTupleEqual,
2644 tuple(a), b)
2645 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2646 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2647 tuple(b))
2648 self.assertRaises(self.failureException, self.assertSequenceEqual,
2649 None, tuple(b))
2650 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2651 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2652 self.assertRaises(self.failureException, self.assertSequenceEqual,
2653 1, 1)
2654
2655 self.assertDictEqual({}, {})
2656
2657 c = { 'x': 1 }
2658 d = {}
2659 self.assertRaises(unittest.TestCase.failureException,
2660 self.assertDictEqual, c, d)
2661
2662 d.update(c)
2663 self.assertDictEqual(c, d)
2664
2665 d['x'] = 0
2666 self.assertRaises(unittest.TestCase.failureException,
2667 self.assertDictEqual, c, d, 'These are unequal')
2668
2669 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2670 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2671 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2672
2673 self.assertSameElements([1, 2, 3], [3, 2, 1])
2674 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2675 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2676 self.assertRaises(self.failureException, self.assertSameElements,
2677 [10], [10, 11])
2678 self.assertRaises(self.failureException, self.assertSameElements,
2679 [10, 11], [10])
2680
2681 # Test that sequences of unhashable objects can be tested for sameness:
2682 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Michael Foordf2dfef12009-04-05 19:19:28 +00002683
Gregory P. Smith28399852009-03-31 16:54:10 +00002684 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2685 self.assertRaises(self.failureException, self.assertSameElements,
2686 [[1]], [[2]])
2687
2688 def testAssertSetEqual(self):
2689 set1 = set()
2690 set2 = set()
2691 self.assertSetEqual(set1, set2)
2692
2693 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2694 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2695 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2696 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2697
2698 set1 = set(['a'])
2699 set2 = set()
2700 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2701
2702 set1 = set(['a'])
2703 set2 = set(['a'])
2704 self.assertSetEqual(set1, set2)
2705
2706 set1 = set(['a'])
2707 set2 = set(['a', 'b'])
2708 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2709
2710 set1 = set(['a'])
2711 set2 = frozenset(['a', 'b'])
2712 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2713
2714 set1 = set(['a', 'b'])
2715 set2 = frozenset(['a', 'b'])
2716 self.assertSetEqual(set1, set2)
2717
2718 set1 = set()
2719 set2 = "foo"
2720 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2721 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2722
2723 # make sure any string formatting is tuple-safe
2724 set1 = set([(0, 1), (2, 3)])
2725 set2 = set([(4, 5)])
2726 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2727
2728 def testInequality(self):
2729 # Try ints
2730 self.assertGreater(2, 1)
2731 self.assertGreaterEqual(2, 1)
2732 self.assertGreaterEqual(1, 1)
2733 self.assertLess(1, 2)
2734 self.assertLessEqual(1, 2)
2735 self.assertLessEqual(1, 1)
2736 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2737 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2738 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2739 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2740 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2741 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2742
2743 # Try Floats
2744 self.assertGreater(1.1, 1.0)
2745 self.assertGreaterEqual(1.1, 1.0)
2746 self.assertGreaterEqual(1.0, 1.0)
2747 self.assertLess(1.0, 1.1)
2748 self.assertLessEqual(1.0, 1.1)
2749 self.assertLessEqual(1.0, 1.0)
2750 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2751 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2752 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2753 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2754 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2755 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2756
2757 # Try Strings
2758 self.assertGreater('bug', 'ant')
2759 self.assertGreaterEqual('bug', 'ant')
2760 self.assertGreaterEqual('ant', 'ant')
2761 self.assertLess('ant', 'bug')
2762 self.assertLessEqual('ant', 'bug')
2763 self.assertLessEqual('ant', 'ant')
2764 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2765 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2766 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2767 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2768 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2769 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2770
2771 # Try Unicode
2772 self.assertGreater(u'bug', u'ant')
2773 self.assertGreaterEqual(u'bug', u'ant')
2774 self.assertGreaterEqual(u'ant', u'ant')
2775 self.assertLess(u'ant', u'bug')
2776 self.assertLessEqual(u'ant', u'bug')
2777 self.assertLessEqual(u'ant', u'ant')
2778 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug')
2779 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant')
2780 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2781 u'bug')
2782 self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant')
2783 self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant')
2784 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant')
2785
2786 # Try Mixed String/Unicode
2787 self.assertGreater('bug', u'ant')
2788 self.assertGreater(u'bug', 'ant')
2789 self.assertGreaterEqual('bug', u'ant')
2790 self.assertGreaterEqual(u'bug', 'ant')
2791 self.assertGreaterEqual('ant', u'ant')
2792 self.assertGreaterEqual(u'ant', 'ant')
2793 self.assertLess('ant', u'bug')
2794 self.assertLess(u'ant', 'bug')
2795 self.assertLessEqual('ant', u'bug')
2796 self.assertLessEqual(u'ant', 'bug')
2797 self.assertLessEqual('ant', u'ant')
2798 self.assertLessEqual(u'ant', 'ant')
2799 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug')
2800 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug')
2801 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant')
2802 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant')
2803 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant',
2804 u'bug')
2805 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2806 'bug')
2807 self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant')
2808 self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant')
2809 self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant')
2810 self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant')
2811 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant')
2812 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant')
2813
2814 def testAssertMultiLineEqual(self):
2815 sample_text = b"""\
2816http://www.python.org/doc/2.3/lib/module-unittest.html
2817test case
2818 A test case is the smallest unit of testing. [...]
2819"""
2820 revised_sample_text = b"""\
2821http://www.python.org/doc/2.4.1/lib/module-unittest.html
2822test case
2823 A test case is the smallest unit of testing. [...] You may provide your
2824 own implementation that does not subclass from TestCase, of course.
2825"""
2826 sample_text_error = b"""
2827- http://www.python.org/doc/2.3/lib/module-unittest.html
2828? ^
2829+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2830? ^^^
2831 test case
2832- A test case is the smallest unit of testing. [...]
2833+ A test case is the smallest unit of testing. [...] You may provide your
2834? +++++++++++++++++++++
2835+ own implementation that does not subclass from TestCase, of course.
2836"""
2837
2838 for type_changer in (lambda x: x, lambda x: x.decode('utf8')):
2839 try:
2840 self.assertMultiLineEqual(type_changer(sample_text),
2841 type_changer(revised_sample_text))
2842 except self.failureException, e:
Michael Foordfe6349c2010-02-08 22:41:16 +00002843 # assertMultiLineEqual is hooked up as the default for
2844 # unicode strings - so we can't use it for this check
2845 self.assertTrue(sample_text_error == str(e).encode('utf8'))
Gregory P. Smith28399852009-03-31 16:54:10 +00002846
2847 def testAssertIsNone(self):
2848 self.assertIsNone(None)
2849 self.assertRaises(self.failureException, self.assertIsNone, False)
2850 self.assertIsNotNone('DjZoPloGears on Rails')
2851 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2852
2853 def testAssertRegexpMatches(self):
2854 self.assertRegexpMatches('asdfabasdf', r'ab+')
2855 self.assertRaises(self.failureException, self.assertRegexpMatches,
2856 'saaas', r'aaaa')
2857
2858 def testAssertRaisesRegexp(self):
2859 class ExceptionMock(Exception):
2860 pass
2861
2862 def Stub():
2863 raise ExceptionMock('We expect')
2864
2865 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2866 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2867 self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
2868
2869 def testAssertNotRaisesRegexp(self):
2870 self.assertRaisesRegexp(
2871 self.failureException, '^Exception not raised$',
2872 self.assertRaisesRegexp, Exception, re.compile('x'),
2873 lambda: None)
2874 self.assertRaisesRegexp(
2875 self.failureException, '^Exception not raised$',
2876 self.assertRaisesRegexp, Exception, 'x',
2877 lambda: None)
2878 self.assertRaisesRegexp(
2879 self.failureException, '^Exception not raised$',
2880 self.assertRaisesRegexp, Exception, u'x',
2881 lambda: None)
2882
2883 def testAssertRaisesRegexpMismatch(self):
2884 def Stub():
2885 raise Exception('Unexpected')
2886
2887 self.assertRaisesRegexp(
2888 self.failureException,
2889 r'"\^Expected\$" does not match "Unexpected"',
2890 self.assertRaisesRegexp, Exception, '^Expected$',
2891 Stub)
2892 self.assertRaisesRegexp(
2893 self.failureException,
2894 r'"\^Expected\$" does not match "Unexpected"',
2895 self.assertRaisesRegexp, Exception, u'^Expected$',
2896 Stub)
2897 self.assertRaisesRegexp(
2898 self.failureException,
2899 r'"\^Expected\$" does not match "Unexpected"',
2900 self.assertRaisesRegexp, Exception,
2901 re.compile('^Expected$'), Stub)
2902
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00002903 def testAssertRaisesExcValue(self):
2904 class ExceptionMock(Exception):
2905 pass
2906
2907 def Stub(foo):
2908 raise ExceptionMock(foo)
2909 v = "particular value"
2910
2911 ctx = self.assertRaises(ExceptionMock)
2912 with ctx:
2913 Stub(v)
Georg Brandldc3694b2010-02-07 17:02:22 +00002914 e = ctx.exception
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002915 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00002916 self.assertEqual(e.args[0], v)
2917
Gregory P. Smith7558d572009-03-31 19:03:28 +00002918 def testSynonymAssertMethodNames(self):
2919 """Test undocumented method name synonyms.
2920
2921 Please do not use these methods names in your own code.
2922
2923 This test confirms their continued existence and functionality
2924 in order to avoid breaking existing code.
2925 """
2926 self.assertNotEquals(3, 5)
2927 self.assertEquals(3, 3)
2928 self.assertAlmostEquals(2.0, 2.0)
2929 self.assertNotAlmostEquals(3.0, 5.0)
2930 self.assert_(True)
2931
2932 def testPendingDeprecationMethodNames(self):
2933 """Test fail* methods pending deprecation, they will warn in 3.2.
2934
2935 Do not use these methods. They will go away in 3.3.
2936 """
2937 self.failIfEqual(3, 5)
2938 self.failUnlessEqual(3, 3)
2939 self.failUnlessAlmostEqual(2.0, 2.0)
2940 self.failIfAlmostEqual(3.0, 5.0)
2941 self.failUnless(True)
2942 self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam')
2943 self.failIf(False)
2944
Michael Foorde2942d02009-04-02 05:51:54 +00002945 def testDeepcopy(self):
2946 # Issue: 5660
2947 class TestableTest(TestCase):
2948 def testNothing(self):
2949 pass
2950
2951 test = TestableTest('testNothing')
2952
2953 # This shouldn't blow up
2954 deepcopy(test)
2955
Benjamin Peterson692428e2009-03-23 21:50:21 +00002956
2957class Test_TestSkipping(TestCase):
2958
2959 def test_skipping(self):
2960 class Foo(unittest.TestCase):
2961 def test_skip_me(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002962 self.skipTest("skip")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002963 events = []
2964 result = LoggingResult(events)
2965 test = Foo("test_skip_me")
2966 test.run(result)
2967 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2968 self.assertEqual(result.skipped, [(test, "skip")])
2969
2970 # Try letting setUp skip the test now.
2971 class Foo(unittest.TestCase):
2972 def setUp(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002973 self.skipTest("testing")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002974 def test_nothing(self): pass
2975 events = []
2976 result = LoggingResult(events)
2977 test = Foo("test_nothing")
2978 test.run(result)
2979 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2980 self.assertEqual(result.skipped, [(test, "testing")])
2981 self.assertEqual(result.testsRun, 1)
2982
2983 def test_skipping_decorators(self):
2984 op_table = ((unittest.skipUnless, False, True),
2985 (unittest.skipIf, True, False))
2986 for deco, do_skip, dont_skip in op_table:
2987 class Foo(unittest.TestCase):
2988 @deco(do_skip, "testing")
2989 def test_skip(self): pass
2990
2991 @deco(dont_skip, "testing")
2992 def test_dont_skip(self): pass
2993 test_do_skip = Foo("test_skip")
2994 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002995 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002996 events = []
2997 result = LoggingResult(events)
2998 suite.run(result)
2999 self.assertEqual(len(result.skipped), 1)
3000 expected = ['startTest', 'addSkip', 'stopTest',
3001 'startTest', 'addSuccess', 'stopTest']
3002 self.assertEqual(events, expected)
3003 self.assertEqual(result.testsRun, 2)
3004 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
3005 self.assertTrue(result.wasSuccessful())
3006
3007 def test_skip_class(self):
3008 @unittest.skip("testing")
3009 class Foo(unittest.TestCase):
3010 def test_1(self):
3011 record.append(1)
3012 record = []
3013 result = unittest.TestResult()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003014 test = Foo("test_1")
3015 suite = unittest.TestSuite([test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003016 suite.run(result)
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003017 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003018 self.assertEqual(record, [])
3019
3020 def test_expected_failure(self):
3021 class Foo(unittest.TestCase):
3022 @unittest.expectedFailure
3023 def test_die(self):
3024 self.fail("help me!")
3025 events = []
3026 result = LoggingResult(events)
3027 test = Foo("test_die")
3028 test.run(result)
3029 self.assertEqual(events,
3030 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003031 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00003032 self.assertTrue(result.wasSuccessful())
3033
3034 def test_unexpected_success(self):
3035 class Foo(unittest.TestCase):
3036 @unittest.expectedFailure
3037 def test_die(self):
3038 pass
3039 events = []
3040 result = LoggingResult(events)
3041 test = Foo("test_die")
3042 test.run(result)
3043 self.assertEqual(events,
3044 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3045 self.assertFalse(result.failures)
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003046 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003047 self.assertTrue(result.wasSuccessful())
3048
3049
3050
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003051class Test_Assertions(TestCase):
3052 def test_AlmostEqual(self):
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003053 self.assertAlmostEqual(1.00000001, 1.0)
3054 self.assertNotAlmostEqual(1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003055 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003056 self.assertAlmostEqual, 1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003057 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003058 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003059
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003060 self.assertAlmostEqual(1.1, 1.0, places=0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003061 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003062 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003063
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003064 self.assertAlmostEqual(0, .1+.1j, places=0)
3065 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003066 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003067 self.assertAlmostEqual, 0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003068 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003069 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003070
Michael Foordc3f79372009-09-13 16:40:02 +00003071 self.assertAlmostEqual(float('inf'), float('inf'))
3072 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3073 float('inf'), float('inf'))
3074
3075
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003076 def test_assertRaises(self):
3077 def _raise(e):
3078 raise e
3079 self.assertRaises(KeyError, _raise, KeyError)
3080 self.assertRaises(KeyError, _raise, KeyError("key"))
3081 try:
3082 self.assertRaises(KeyError, lambda: None)
Gregory P. Smith28399852009-03-31 16:54:10 +00003083 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003084 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003085 else:
3086 self.fail("assertRaises() didn't fail")
3087 try:
3088 self.assertRaises(KeyError, _raise, ValueError)
3089 except ValueError:
3090 pass
3091 else:
3092 self.fail("assertRaises() didn't let exception pass through")
Michael Foord2bd52dc2010-02-07 18:44:12 +00003093 with self.assertRaises(KeyError) as cm:
3094 try:
3095 raise KeyError
3096 except Exception, e:
3097 raise
3098 self.assertIs(cm.exception, e)
3099
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003100 with self.assertRaises(KeyError):
3101 raise KeyError("key")
3102 try:
3103 with self.assertRaises(KeyError):
3104 pass
Gregory P. Smith28399852009-03-31 16:54:10 +00003105 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003106 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003107 else:
3108 self.fail("assertRaises() didn't fail")
3109 try:
3110 with self.assertRaises(KeyError):
3111 raise ValueError
3112 except ValueError:
3113 pass
3114 else:
3115 self.fail("assertRaises() didn't let exception pass through")
3116
3117
Michael Foord345b2fe2009-04-02 03:20:38 +00003118class TestLongMessage(TestCase):
3119 """Test that the individual asserts honour longMessage.
3120 This actually tests all the message behaviour for
3121 asserts that use longMessage."""
3122
3123 def setUp(self):
3124 class TestableTestFalse(TestCase):
3125 longMessage = False
3126 failureException = self.failureException
3127
3128 def testTest(self):
3129 pass
3130
3131 class TestableTestTrue(TestCase):
3132 longMessage = True
3133 failureException = self.failureException
3134
3135 def testTest(self):
3136 pass
3137
3138 self.testableTrue = TestableTestTrue('testTest')
3139 self.testableFalse = TestableTestFalse('testTest')
3140
3141 def testDefault(self):
3142 self.assertFalse(TestCase.longMessage)
3143
3144 def test_formatMsg(self):
3145 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3146 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3147
3148 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3149 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3150
3151 def assertMessages(self, methodName, args, errors):
3152 def getMethod(i):
3153 useTestableFalse = i < 2
3154 if useTestableFalse:
3155 test = self.testableFalse
3156 else:
3157 test = self.testableTrue
3158 return getattr(test, methodName)
3159
3160 for i, expected_regexp in enumerate(errors):
3161 testMethod = getMethod(i)
3162 kwargs = {}
3163 withMsg = i % 2
3164 if withMsg:
3165 kwargs = {"msg": "oops"}
3166
3167 with self.assertRaisesRegexp(self.failureException,
3168 expected_regexp=expected_regexp):
3169 testMethod(*args, **kwargs)
3170
3171 def testAssertTrue(self):
3172 self.assertMessages('assertTrue', (False,),
3173 ["^False is not True$", "^oops$", "^False is not True$",
3174 "^False is not True : oops$"])
3175
3176 def testAssertFalse(self):
3177 self.assertMessages('assertFalse', (True,),
3178 ["^True is not False$", "^oops$", "^True is not False$",
3179 "^True is not False : oops$"])
3180
3181 def testNotEqual(self):
3182 self.assertMessages('assertNotEqual', (1, 1),
3183 ["^1 == 1$", "^oops$", "^1 == 1$",
3184 "^1 == 1 : oops$"])
3185
3186 def testAlmostEqual(self):
3187 self.assertMessages('assertAlmostEqual', (1, 2),
3188 ["^1 != 2 within 7 places$", "^oops$",
3189 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3190
3191 def testNotAlmostEqual(self):
3192 self.assertMessages('assertNotAlmostEqual', (1, 1),
3193 ["^1 == 1 within 7 places$", "^oops$",
3194 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3195
3196 def test_baseAssertEqual(self):
3197 self.assertMessages('_baseAssertEqual', (1, 2),
3198 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3199
3200 def testAssertSequenceEqual(self):
3201 # Error messages are multiline so not testing on full message
3202 # assertTupleEqual and assertListEqual delegate to this method
3203 self.assertMessages('assertSequenceEqual', ([], [None]),
3204 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3205 r"\+ \[None\] : oops$"])
3206
3207 def testAssertSetEqual(self):
3208 self.assertMessages('assertSetEqual', (set(), set([None])),
3209 ["None$", "^oops$", "None$",
3210 "None : oops$"])
3211
3212 def testAssertIn(self):
3213 self.assertMessages('assertIn', (None, []),
3214 ['^None not found in \[\]$', "^oops$",
3215 '^None not found in \[\]$',
3216 '^None not found in \[\] : oops$'])
3217
3218 def testAssertNotIn(self):
3219 self.assertMessages('assertNotIn', (None, [None]),
3220 ['^None unexpectedly found in \[None\]$', "^oops$",
3221 '^None unexpectedly found in \[None\]$',
3222 '^None unexpectedly found in \[None\] : oops$'])
3223
3224 def testAssertDictEqual(self):
3225 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3226 [r"\+ \{'key': 'value'\}$", "^oops$",
3227 "\+ \{'key': 'value'\}$",
3228 "\+ \{'key': 'value'\} : oops$"])
3229
3230 def testAssertDictContainsSubset(self):
3231 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3232 ["^Missing: 'key'$", "^oops$",
3233 "^Missing: 'key'$",
3234 "^Missing: 'key' : oops$"])
3235
3236 def testAssertSameElements(self):
3237 self.assertMessages('assertSameElements', ([], [None]),
3238 [r"\[None\]$", "^oops$",
3239 r"\[None\]$",
3240 r"\[None\] : oops$"])
3241
3242 def testAssertMultiLineEqual(self):
3243 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3244 [r"\+ foo$", "^oops$",
3245 r"\+ foo$",
3246 r"\+ foo : oops$"])
3247
3248 def testAssertLess(self):
3249 self.assertMessages('assertLess', (2, 1),
3250 ["^2 not less than 1$", "^oops$",
3251 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3252
3253 def testAssertLessEqual(self):
3254 self.assertMessages('assertLessEqual', (2, 1),
3255 ["^2 not less than or equal to 1$", "^oops$",
3256 "^2 not less than or equal to 1$",
3257 "^2 not less than or equal to 1 : oops$"])
3258
3259 def testAssertGreater(self):
3260 self.assertMessages('assertGreater', (1, 2),
3261 ["^1 not greater than 2$", "^oops$",
3262 "^1 not greater than 2$",
3263 "^1 not greater than 2 : oops$"])
3264
3265 def testAssertGreaterEqual(self):
3266 self.assertMessages('assertGreaterEqual', (1, 2),
3267 ["^1 not greater than or equal to 2$", "^oops$",
3268 "^1 not greater than or equal to 2$",
3269 "^1 not greater than or equal to 2 : oops$"])
3270
3271 def testAssertIsNone(self):
3272 self.assertMessages('assertIsNone', ('not None',),
3273 ["^'not None' is not None$", "^oops$",
3274 "^'not None' is not None$",
3275 "^'not None' is not None : oops$"])
3276
3277 def testAssertIsNotNone(self):
3278 self.assertMessages('assertIsNotNone', (None,),
3279 ["^unexpectedly None$", "^oops$",
3280 "^unexpectedly None$",
3281 "^unexpectedly None : oops$"])
3282
Michael Foordf2dfef12009-04-05 19:19:28 +00003283 def testAssertIs(self):
3284 self.assertMessages('assertIs', (None, 'foo'),
3285 ["^None is not 'foo'$", "^oops$",
3286 "^None is not 'foo'$",
3287 "^None is not 'foo' : oops$"])
3288
3289 def testAssertIsNot(self):
3290 self.assertMessages('assertIsNot', (None, None),
3291 ["^unexpectedly identical: None$", "^oops$",
3292 "^unexpectedly identical: None$",
3293 "^unexpectedly identical: None : oops$"])
3294
Michael Foord345b2fe2009-04-02 03:20:38 +00003295
Michael Foorde2fb98f2009-05-02 20:15:05 +00003296class TestCleanUp(TestCase):
3297
3298 def testCleanUp(self):
3299 class TestableTest(TestCase):
3300 def testNothing(self):
3301 pass
3302
3303 test = TestableTest('testNothing')
3304 self.assertEqual(test._cleanups, [])
3305
3306 cleanups = []
3307
3308 def cleanup1(*args, **kwargs):
3309 cleanups.append((1, args, kwargs))
3310
3311 def cleanup2(*args, **kwargs):
3312 cleanups.append((2, args, kwargs))
3313
3314 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3315 test.addCleanup(cleanup2)
3316
3317 self.assertEqual(test._cleanups,
3318 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3319 (cleanup2, (), {})])
3320
3321 result = test.doCleanups()
3322 self.assertTrue(result)
3323
3324 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3325
3326 def testCleanUpWithErrors(self):
3327 class TestableTest(TestCase):
3328 def testNothing(self):
3329 pass
3330
3331 class MockResult(object):
3332 errors = []
3333 def addError(self, test, exc_info):
3334 self.errors.append((test, exc_info))
3335
3336 result = MockResult()
3337 test = TestableTest('testNothing')
Michael Foorda50af062009-05-21 22:57:02 +00003338 test._resultForDoCleanups = result
Michael Foorde2fb98f2009-05-02 20:15:05 +00003339
3340 exc1 = Exception('foo')
3341 exc2 = Exception('bar')
3342 def cleanup1():
3343 raise exc1
3344
3345 def cleanup2():
3346 raise exc2
3347
3348 test.addCleanup(cleanup1)
3349 test.addCleanup(cleanup2)
3350
3351 self.assertFalse(test.doCleanups())
3352
3353 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3354 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3355 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3356
3357 def testCleanupInRun(self):
3358 blowUp = False
3359 ordering = []
3360
3361 class TestableTest(TestCase):
3362 def setUp(self):
3363 ordering.append('setUp')
3364 if blowUp:
3365 raise Exception('foo')
3366
3367 def testNothing(self):
3368 ordering.append('test')
3369
3370 def tearDown(self):
3371 ordering.append('tearDown')
3372
3373 test = TestableTest('testNothing')
3374
3375 def cleanup1():
3376 ordering.append('cleanup1')
3377 def cleanup2():
3378 ordering.append('cleanup2')
3379 test.addCleanup(cleanup1)
3380 test.addCleanup(cleanup2)
3381
3382 def success(some_test):
3383 self.assertEqual(some_test, test)
3384 ordering.append('success')
3385
3386 result = unittest.TestResult()
3387 result.addSuccess = success
3388
3389 test.run(result)
3390 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3391 'cleanup2', 'cleanup1', 'success'])
3392
3393 blowUp = True
3394 ordering = []
3395 test = TestableTest('testNothing')
3396 test.addCleanup(cleanup1)
3397 test.run(result)
3398 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3399
3400
Michael Foord829f6b82009-05-02 11:43:06 +00003401class Test_TestProgram(TestCase):
3402
3403 # Horrible white box test
3404 def testNoExit(self):
3405 result = object()
3406 test = object()
3407
3408 class FakeRunner(object):
3409 def run(self, test):
3410 self.test = test
3411 return result
3412
3413 runner = FakeRunner()
3414
Michael Foord5d31e052009-05-11 17:59:43 +00003415 oldParseArgs = TestProgram.parseArgs
3416 def restoreParseArgs():
Michael Foord829f6b82009-05-02 11:43:06 +00003417 TestProgram.parseArgs = oldParseArgs
Michael Foord5d31e052009-05-11 17:59:43 +00003418 TestProgram.parseArgs = lambda *args: None
3419 self.addCleanup(restoreParseArgs)
3420
3421 def removeTest():
Michael Foord829f6b82009-05-02 11:43:06 +00003422 del TestProgram.test
Michael Foord5d31e052009-05-11 17:59:43 +00003423 TestProgram.test = test
3424 self.addCleanup(removeTest)
3425
3426 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3427
3428 self.assertEqual(program.result, result)
3429 self.assertEqual(runner.test, test)
3430 self.assertEqual(program.verbosity, 2)
Michael Foord829f6b82009-05-02 11:43:06 +00003431
Michael Foord829f6b82009-05-02 11:43:06 +00003432 class FooBar(unittest.TestCase):
3433 def testPass(self):
3434 assert True
3435 def testFail(self):
3436 assert False
3437
3438 class FooBarLoader(unittest.TestLoader):
3439 """Test loader that returns a suite containing FooBar."""
3440 def loadTestsFromModule(self, module):
3441 return self.suiteClass(
3442 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3443
3444
3445 def test_NonExit(self):
3446 program = unittest.main(exit=False,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003447 argv=["foobar"],
3448 testRunner=unittest.TextTestRunner(stream=StringIO()),
3449 testLoader=self.FooBarLoader())
Michael Foord829f6b82009-05-02 11:43:06 +00003450 self.assertTrue(hasattr(program, 'result'))
3451
3452
3453 def test_Exit(self):
3454 self.assertRaises(
3455 SystemExit,
3456 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003457 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003458 testRunner=unittest.TextTestRunner(stream=StringIO()),
3459 exit=True,
3460 testLoader=self.FooBarLoader())
3461
3462
3463 def test_ExitAsDefault(self):
3464 self.assertRaises(
3465 SystemExit,
3466 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003467 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003468 testRunner=unittest.TextTestRunner(stream=StringIO()),
3469 testLoader=self.FooBarLoader())
3470
3471
Michael Foord07ef4872009-05-02 22:43:34 +00003472class Test_TextTestRunner(TestCase):
3473 """Tests for TextTestRunner."""
3474
3475 def test_works_with_result_without_startTestRun_stopTestRun(self):
3476 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3477 separator2 = ''
3478 def printErrors(self):
3479 pass
3480
3481 class Runner(unittest.TextTestRunner):
3482 def __init__(self):
3483 super(Runner, self).__init__(StringIO())
3484
3485 def _makeResult(self):
3486 return OldTextResult()
3487
3488 runner = Runner()
3489 runner.run(unittest.TestSuite())
3490
3491 def test_startTestRun_stopTestRun_called(self):
3492 class LoggingTextResult(LoggingResult):
3493 separator2 = ''
3494 def printErrors(self):
3495 pass
3496
3497 class LoggingRunner(unittest.TextTestRunner):
3498 def __init__(self, events):
3499 super(LoggingRunner, self).__init__(StringIO())
3500 self._events = events
3501
3502 def _makeResult(self):
3503 return LoggingTextResult(self._events)
3504
3505 events = []
3506 runner = LoggingRunner(events)
3507 runner.run(unittest.TestSuite())
3508 expected = ['startTestRun', 'stopTestRun']
3509 self.assertEqual(events, expected)
3510
Antoine Pitrou0734c632009-11-10 20:49:30 +00003511 def test_pickle_unpickle(self):
3512 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3513 # required by test_multiprocessing under Windows (in verbose mode).
3514 import StringIO
3515 # cStringIO objects are not pickleable, but StringIO objects are.
3516 stream = StringIO.StringIO("foo")
3517 runner = unittest.TextTestRunner(stream)
3518 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
3519 s = pickle.dumps(runner, protocol=protocol)
3520 obj = pickle.loads(s)
3521 # StringIO objects never compare equal, a cheap test instead.
3522 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3523
Michael Foorddb43b5a2010-02-10 14:25:12 +00003524 def test_resultclass(self):
3525 def MockResultClass(*args):
3526 return args
3527 STREAM = object()
3528 DESCRIPTIONS = object()
3529 VERBOSITY = object()
3530 runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY,
3531 resultclass=MockResultClass)
3532 self.assertEqual(runner.resultclass, MockResultClass)
3533
3534 expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY)
3535 self.assertEqual(runner._makeResult(), expectedresult)
3536
Michael Foord07ef4872009-05-02 22:43:34 +00003537
Michael Foordb4a81c82009-05-29 20:33:46 +00003538class TestDiscovery(TestCase):
3539
3540 # Heavily mocked tests so I can avoid hitting the filesystem
Michael Foorde91ea562009-09-13 19:07:03 +00003541 def test_get_name_from_path(self):
Michael Foordb4a81c82009-05-29 20:33:46 +00003542 loader = unittest.TestLoader()
3543
Michael Foordb4a81c82009-05-29 20:33:46 +00003544 loader._top_level_dir = '/foo'
Michael Foorde91ea562009-09-13 19:07:03 +00003545 name = loader._get_name_from_path('/foo/bar/baz.py')
3546 self.assertEqual(name, 'bar.baz')
Michael Foordb4a81c82009-05-29 20:33:46 +00003547
3548 if not __debug__:
3549 # asserts are off
3550 return
3551
3552 with self.assertRaises(AssertionError):
Michael Foorde91ea562009-09-13 19:07:03 +00003553 loader._get_name_from_path('/bar/baz.py')
Michael Foordb4a81c82009-05-29 20:33:46 +00003554
3555 def test_find_tests(self):
3556 loader = unittest.TestLoader()
3557
3558 original_listdir = os.listdir
3559 def restore_listdir():
3560 os.listdir = original_listdir
3561 original_isfile = os.path.isfile
3562 def restore_isfile():
3563 os.path.isfile = original_isfile
3564 original_isdir = os.path.isdir
3565 def restore_isdir():
3566 os.path.isdir = original_isdir
3567
3568 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Michael Foorde91ea562009-09-13 19:07:03 +00003569 'test.foo', 'test-not-a-module.py', 'another_dir'],
Michael Foordb4a81c82009-05-29 20:33:46 +00003570 ['test3.py', 'test4.py', ]]
3571 os.listdir = lambda path: path_lists.pop(0)
3572 self.addCleanup(restore_listdir)
3573
3574 def isdir(path):
3575 return path.endswith('dir')
3576 os.path.isdir = isdir
3577 self.addCleanup(restore_isdir)
3578
3579 def isfile(path):
3580 # another_dir is not a package and so shouldn't be recursed into
3581 return not path.endswith('dir') and not 'another_dir' in path
3582 os.path.isfile = isfile
3583 self.addCleanup(restore_isfile)
3584
Michael Foorde91ea562009-09-13 19:07:03 +00003585 loader._get_module_from_name = lambda path: path + ' module'
Michael Foordb4a81c82009-05-29 20:33:46 +00003586 loader.loadTestsFromModule = lambda module: module + ' tests'
3587
3588 loader._top_level_dir = '/foo'
3589 suite = list(loader._find_tests('/foo', 'test*.py'))
3590
Michael Foorde91ea562009-09-13 19:07:03 +00003591 expected = [name + ' module tests' for name in
3592 ('test1', 'test2')]
3593 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3594 ('test3', 'test4')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003595 self.assertEqual(suite, expected)
3596
3597 def test_find_tests_with_package(self):
3598 loader = unittest.TestLoader()
3599
3600 original_listdir = os.listdir
3601 def restore_listdir():
3602 os.listdir = original_listdir
3603 original_isfile = os.path.isfile
3604 def restore_isfile():
3605 os.path.isfile = original_isfile
3606 original_isdir = os.path.isdir
3607 def restore_isdir():
3608 os.path.isdir = original_isdir
3609
3610 directories = ['a_directory', 'test_directory', 'test_directory2']
3611 path_lists = [directories, [], [], []]
3612 os.listdir = lambda path: path_lists.pop(0)
3613 self.addCleanup(restore_listdir)
3614
3615 os.path.isdir = lambda path: True
3616 self.addCleanup(restore_isdir)
3617
3618 os.path.isfile = lambda path: os.path.basename(path) not in directories
3619 self.addCleanup(restore_isfile)
3620
3621 class Module(object):
3622 paths = []
3623 load_tests_args = []
3624
3625 def __init__(self, path):
3626 self.path = path
3627 self.paths.append(path)
3628 if os.path.basename(path) == 'test_directory':
3629 def load_tests(loader, tests, pattern):
3630 self.load_tests_args.append((loader, tests, pattern))
3631 return 'load_tests'
3632 self.load_tests = load_tests
3633
3634 def __eq__(self, other):
3635 return self.path == other.path
3636
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003637 # Silence py3k warning
3638 __hash__ = None
3639
Michael Foorde91ea562009-09-13 19:07:03 +00003640 loader._get_module_from_name = lambda name: Module(name)
Michael Foordb4a81c82009-05-29 20:33:46 +00003641 def loadTestsFromModule(module, use_load_tests):
3642 if use_load_tests:
3643 raise self.failureException('use_load_tests should be False for packages')
3644 return module.path + ' module tests'
3645 loader.loadTestsFromModule = loadTestsFromModule
3646
3647 loader._top_level_dir = '/foo'
3648 # this time no '.py' on the pattern so that it can match
3649 # a test package
3650 suite = list(loader._find_tests('/foo', 'test*'))
3651
3652 # We should have loaded tests from the test_directory package by calling load_tests
3653 # and directly from the test_directory2 package
Michael Foordd53d0852009-06-05 14:14:34 +00003654 self.assertEqual(suite,
Michael Foorde91ea562009-09-13 19:07:03 +00003655 ['load_tests', 'test_directory2' + ' module tests'])
3656 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Michael Foordb4a81c82009-05-29 20:33:46 +00003657
3658 # load_tests should have been called once with loader, tests and pattern
3659 self.assertEqual(Module.load_tests_args,
Michael Foorde91ea562009-09-13 19:07:03 +00003660 [(loader, 'test_directory' + ' module tests', 'test*')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003661
3662 def test_discover(self):
3663 loader = unittest.TestLoader()
3664
3665 original_isfile = os.path.isfile
3666 def restore_isfile():
3667 os.path.isfile = original_isfile
3668
3669 os.path.isfile = lambda path: False
3670 self.addCleanup(restore_isfile)
3671
Nick Coghlanb6edf192009-10-17 08:21:21 +00003672 orig_sys_path = sys.path[:]
3673 def restore_path():
3674 sys.path[:] = orig_sys_path
3675 self.addCleanup(restore_path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003676
Nick Coghlanb6edf192009-10-17 08:21:21 +00003677 full_path = os.path.abspath(os.path.normpath('/foo'))
Michael Foordb4a81c82009-05-29 20:33:46 +00003678 with self.assertRaises(ImportError):
3679 loader.discover('/foo/bar', top_level_dir='/foo')
3680
3681 self.assertEqual(loader._top_level_dir, full_path)
3682 self.assertIn(full_path, sys.path)
3683
3684 os.path.isfile = lambda path: True
3685 _find_tests_args = []
3686 def _find_tests(start_dir, pattern):
3687 _find_tests_args.append((start_dir, pattern))
3688 return ['tests']
3689 loader._find_tests = _find_tests
3690 loader.suiteClass = str
3691
3692 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3693
3694 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3695 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3696 self.assertEqual(suite, "['tests']")
3697 self.assertEqual(loader._top_level_dir, top_level_dir)
3698 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlanb6edf192009-10-17 08:21:21 +00003699 self.assertIn(top_level_dir, sys.path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003700
Michael Foorde91ea562009-09-13 19:07:03 +00003701 def test_discover_with_modules_that_fail_to_import(self):
3702 loader = unittest.TestLoader()
3703
3704 listdir = os.listdir
3705 os.listdir = lambda _: ['test_this_does_not_exist.py']
3706 isfile = os.path.isfile
3707 os.path.isfile = lambda _: True
Nick Coghlanb6edf192009-10-17 08:21:21 +00003708 orig_sys_path = sys.path[:]
Michael Foorde91ea562009-09-13 19:07:03 +00003709 def restore():
3710 os.path.isfile = isfile
3711 os.listdir = listdir
Nick Coghlanb6edf192009-10-17 08:21:21 +00003712 sys.path[:] = orig_sys_path
Michael Foorde91ea562009-09-13 19:07:03 +00003713 self.addCleanup(restore)
3714
3715 suite = loader.discover('.')
Nick Coghlanb6edf192009-10-17 08:21:21 +00003716 self.assertIn(os.getcwd(), sys.path)
Michael Foorde91ea562009-09-13 19:07:03 +00003717 self.assertEqual(suite.countTestCases(), 1)
3718 test = list(list(suite)[0])[0] # extract test from suite
3719
3720 with self.assertRaises(ImportError):
3721 test.test_this_does_not_exist()
3722
Michael Foordb4a81c82009-05-29 20:33:46 +00003723 def test_command_line_handling_parseArgs(self):
3724 # Haha - take that uninstantiable class
3725 program = object.__new__(TestProgram)
3726
3727 args = []
3728 def do_discovery(argv):
3729 args.extend(argv)
3730 program._do_discovery = do_discovery
3731 program.parseArgs(['something', 'discover'])
3732 self.assertEqual(args, [])
3733
3734 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3735 self.assertEqual(args, ['foo', 'bar'])
3736
3737 def test_command_line_handling_do_discovery_too_many_arguments(self):
3738 class Stop(Exception):
3739 pass
3740 def usageExit():
3741 raise Stop
3742
3743 program = object.__new__(TestProgram)
3744 program.usageExit = usageExit
3745
3746 with self.assertRaises(Stop):
3747 # too many args
3748 program._do_discovery(['one', 'two', 'three', 'four'])
3749
3750
3751 def test_command_line_handling_do_discovery_calls_loader(self):
3752 program = object.__new__(TestProgram)
3753
3754 class Loader(object):
3755 args = []
3756 def discover(self, start_dir, pattern, top_level_dir):
3757 self.args.append((start_dir, pattern, top_level_dir))
3758 return 'tests'
3759
3760 program._do_discovery(['-v'], Loader=Loader)
3761 self.assertEqual(program.verbosity, 2)
3762 self.assertEqual(program.test, 'tests')
3763 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3764
3765 Loader.args = []
3766 program = object.__new__(TestProgram)
3767 program._do_discovery(['--verbose'], Loader=Loader)
3768 self.assertEqual(program.test, 'tests')
3769 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3770
3771 Loader.args = []
3772 program = object.__new__(TestProgram)
3773 program._do_discovery([], Loader=Loader)
3774 self.assertEqual(program.test, 'tests')
3775 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3776
3777 Loader.args = []
3778 program = object.__new__(TestProgram)
3779 program._do_discovery(['fish'], Loader=Loader)
3780 self.assertEqual(program.test, 'tests')
3781 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3782
3783 Loader.args = []
3784 program = object.__new__(TestProgram)
3785 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3786 self.assertEqual(program.test, 'tests')
3787 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3788
3789 Loader.args = []
3790 program = object.__new__(TestProgram)
3791 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3792 self.assertEqual(program.test, 'tests')
3793 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3794
3795 Loader.args = []
3796 program = object.__new__(TestProgram)
3797 program._do_discovery(['-s', 'fish'], Loader=Loader)
3798 self.assertEqual(program.test, 'tests')
3799 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3800
3801 Loader.args = []
3802 program = object.__new__(TestProgram)
3803 program._do_discovery(['-t', 'fish'], Loader=Loader)
3804 self.assertEqual(program.test, 'tests')
3805 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3806
3807 Loader.args = []
3808 program = object.__new__(TestProgram)
3809 program._do_discovery(['-p', 'fish'], Loader=Loader)
3810 self.assertEqual(program.test, 'tests')
3811 self.assertEqual(Loader.args, [('.', 'fish', None)])
3812
3813 Loader.args = []
3814 program = object.__new__(TestProgram)
3815 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3816 self.assertEqual(program.test, 'tests')
3817 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3818 self.assertEqual(program.verbosity, 2)
3819
3820
Jim Fultonfafd8742004-08-28 15:22:12 +00003821######################################################################
3822## Main
3823######################################################################
3824
3825def test_main():
Georg Brandl15c5ce92007-03-07 09:09:40 +00003826 test_support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003827 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Michael Foord829f6b82009-05-02 11:43:06 +00003828 Test_TestSkipping, Test_Assertions, TestLongMessage,
Antoine Pitrou0734c632009-11-10 20:49:30 +00003829 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner)
Jim Fultonfafd8742004-08-28 15:22:12 +00003830
Georg Brandl15c5ce92007-03-07 09:09:40 +00003831if __name__ == "__main__":
Tim Petersea5962f2007-03-12 18:07:52 +00003832 test_main()