blob: d3bab2af86f732e700da5ae9a23d70ffbd1a3905 [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
Michael Foord225a0992010-02-18 20:30:09 +00002576 one = ''.join(chr(i) for i in range(255))
Michael Foordc2294dd2010-02-18 21:37:07 +00002577 # this used to cause a UnicodeDecodeError constructing the failure msg
2578 with self.assertRaises(self.failureException):
2579 self.assertDictContainsSubset({'foo': one}, {'foo': u'\uFFFD'})
Gregory P. Smith28399852009-03-31 16:54:10 +00002580
2581 def testAssertEqual(self):
2582 equal_pairs = [
2583 ((), ()),
2584 ({}, {}),
2585 ([], []),
2586 (set(), set()),
2587 (frozenset(), frozenset())]
2588 for a, b in equal_pairs:
2589 # This mess of try excepts is to test the assertEqual behavior
2590 # itself.
2591 try:
2592 self.assertEqual(a, b)
2593 except self.failureException:
2594 self.fail('assertEqual(%r, %r) failed' % (a, b))
2595 try:
2596 self.assertEqual(a, b, msg='foo')
2597 except self.failureException:
2598 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2599 try:
2600 self.assertEqual(a, b, 'foo')
2601 except self.failureException:
2602 self.fail('assertEqual(%r, %r) with third parameter failed' %
2603 (a, b))
2604
2605 unequal_pairs = [
2606 ((), []),
2607 ({}, set()),
2608 (set([4,1]), frozenset([4,2])),
2609 (frozenset([4,5]), set([2,3])),
2610 (set([3,4]), set([5,4]))]
2611 for a, b in unequal_pairs:
2612 self.assertRaises(self.failureException, self.assertEqual, a, b)
2613 self.assertRaises(self.failureException, self.assertEqual, a, b,
2614 'foo')
2615 self.assertRaises(self.failureException, self.assertEqual, a, b,
2616 msg='foo')
2617
2618 def testEquality(self):
2619 self.assertListEqual([], [])
2620 self.assertTupleEqual((), ())
2621 self.assertSequenceEqual([], ())
2622
2623 a = [0, 'a', []]
2624 b = []
2625 self.assertRaises(unittest.TestCase.failureException,
2626 self.assertListEqual, a, b)
2627 self.assertRaises(unittest.TestCase.failureException,
2628 self.assertListEqual, tuple(a), tuple(b))
2629 self.assertRaises(unittest.TestCase.failureException,
2630 self.assertSequenceEqual, a, tuple(b))
2631
2632 b.extend(a)
2633 self.assertListEqual(a, b)
2634 self.assertTupleEqual(tuple(a), tuple(b))
2635 self.assertSequenceEqual(a, tuple(b))
2636 self.assertSequenceEqual(tuple(a), b)
2637
2638 self.assertRaises(self.failureException, self.assertListEqual,
2639 a, tuple(b))
2640 self.assertRaises(self.failureException, self.assertTupleEqual,
2641 tuple(a), b)
2642 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2643 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2644 tuple(b))
2645 self.assertRaises(self.failureException, self.assertSequenceEqual,
2646 None, tuple(b))
2647 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2648 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2649 self.assertRaises(self.failureException, self.assertSequenceEqual,
2650 1, 1)
2651
2652 self.assertDictEqual({}, {})
2653
2654 c = { 'x': 1 }
2655 d = {}
2656 self.assertRaises(unittest.TestCase.failureException,
2657 self.assertDictEqual, c, d)
2658
2659 d.update(c)
2660 self.assertDictEqual(c, d)
2661
2662 d['x'] = 0
2663 self.assertRaises(unittest.TestCase.failureException,
2664 self.assertDictEqual, c, d, 'These are unequal')
2665
2666 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2667 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2668 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2669
2670 self.assertSameElements([1, 2, 3], [3, 2, 1])
2671 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2672 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2673 self.assertRaises(self.failureException, self.assertSameElements,
2674 [10], [10, 11])
2675 self.assertRaises(self.failureException, self.assertSameElements,
2676 [10, 11], [10])
2677
2678 # Test that sequences of unhashable objects can be tested for sameness:
2679 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Michael Foordf2dfef12009-04-05 19:19:28 +00002680
Gregory P. Smith28399852009-03-31 16:54:10 +00002681 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2682 self.assertRaises(self.failureException, self.assertSameElements,
2683 [[1]], [[2]])
2684
2685 def testAssertSetEqual(self):
2686 set1 = set()
2687 set2 = set()
2688 self.assertSetEqual(set1, set2)
2689
2690 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2691 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2692 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2693 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2694
2695 set1 = set(['a'])
2696 set2 = set()
2697 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2698
2699 set1 = set(['a'])
2700 set2 = set(['a'])
2701 self.assertSetEqual(set1, set2)
2702
2703 set1 = set(['a'])
2704 set2 = set(['a', 'b'])
2705 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2706
2707 set1 = set(['a'])
2708 set2 = frozenset(['a', 'b'])
2709 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2710
2711 set1 = set(['a', 'b'])
2712 set2 = frozenset(['a', 'b'])
2713 self.assertSetEqual(set1, set2)
2714
2715 set1 = set()
2716 set2 = "foo"
2717 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2718 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2719
2720 # make sure any string formatting is tuple-safe
2721 set1 = set([(0, 1), (2, 3)])
2722 set2 = set([(4, 5)])
2723 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2724
2725 def testInequality(self):
2726 # Try ints
2727 self.assertGreater(2, 1)
2728 self.assertGreaterEqual(2, 1)
2729 self.assertGreaterEqual(1, 1)
2730 self.assertLess(1, 2)
2731 self.assertLessEqual(1, 2)
2732 self.assertLessEqual(1, 1)
2733 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2734 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2735 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2736 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2737 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2738 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2739
2740 # Try Floats
2741 self.assertGreater(1.1, 1.0)
2742 self.assertGreaterEqual(1.1, 1.0)
2743 self.assertGreaterEqual(1.0, 1.0)
2744 self.assertLess(1.0, 1.1)
2745 self.assertLessEqual(1.0, 1.1)
2746 self.assertLessEqual(1.0, 1.0)
2747 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2748 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2749 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2750 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2751 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2752 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2753
2754 # Try Strings
2755 self.assertGreater('bug', 'ant')
2756 self.assertGreaterEqual('bug', 'ant')
2757 self.assertGreaterEqual('ant', 'ant')
2758 self.assertLess('ant', 'bug')
2759 self.assertLessEqual('ant', 'bug')
2760 self.assertLessEqual('ant', 'ant')
2761 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2762 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2763 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2764 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2765 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2766 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2767
2768 # Try Unicode
2769 self.assertGreater(u'bug', u'ant')
2770 self.assertGreaterEqual(u'bug', u'ant')
2771 self.assertGreaterEqual(u'ant', u'ant')
2772 self.assertLess(u'ant', u'bug')
2773 self.assertLessEqual(u'ant', u'bug')
2774 self.assertLessEqual(u'ant', u'ant')
2775 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug')
2776 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant')
2777 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2778 u'bug')
2779 self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant')
2780 self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant')
2781 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant')
2782
2783 # Try Mixed String/Unicode
2784 self.assertGreater('bug', u'ant')
2785 self.assertGreater(u'bug', 'ant')
2786 self.assertGreaterEqual('bug', u'ant')
2787 self.assertGreaterEqual(u'bug', 'ant')
2788 self.assertGreaterEqual('ant', u'ant')
2789 self.assertGreaterEqual(u'ant', 'ant')
2790 self.assertLess('ant', u'bug')
2791 self.assertLess(u'ant', 'bug')
2792 self.assertLessEqual('ant', u'bug')
2793 self.assertLessEqual(u'ant', 'bug')
2794 self.assertLessEqual('ant', u'ant')
2795 self.assertLessEqual(u'ant', 'ant')
2796 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug')
2797 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug')
2798 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant')
2799 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant')
2800 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant',
2801 u'bug')
2802 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2803 'bug')
2804 self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant')
2805 self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant')
2806 self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant')
2807 self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant')
2808 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant')
2809 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant')
2810
2811 def testAssertMultiLineEqual(self):
2812 sample_text = b"""\
2813http://www.python.org/doc/2.3/lib/module-unittest.html
2814test case
2815 A test case is the smallest unit of testing. [...]
2816"""
2817 revised_sample_text = b"""\
2818http://www.python.org/doc/2.4.1/lib/module-unittest.html
2819test case
2820 A test case is the smallest unit of testing. [...] You may provide your
2821 own implementation that does not subclass from TestCase, of course.
2822"""
2823 sample_text_error = b"""
2824- http://www.python.org/doc/2.3/lib/module-unittest.html
2825? ^
2826+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2827? ^^^
2828 test case
2829- A test case is the smallest unit of testing. [...]
2830+ A test case is the smallest unit of testing. [...] You may provide your
2831? +++++++++++++++++++++
2832+ own implementation that does not subclass from TestCase, of course.
2833"""
2834
2835 for type_changer in (lambda x: x, lambda x: x.decode('utf8')):
2836 try:
2837 self.assertMultiLineEqual(type_changer(sample_text),
2838 type_changer(revised_sample_text))
2839 except self.failureException, e:
Michael Foordfe6349c2010-02-08 22:41:16 +00002840 # assertMultiLineEqual is hooked up as the default for
2841 # unicode strings - so we can't use it for this check
2842 self.assertTrue(sample_text_error == str(e).encode('utf8'))
Gregory P. Smith28399852009-03-31 16:54:10 +00002843
2844 def testAssertIsNone(self):
2845 self.assertIsNone(None)
2846 self.assertRaises(self.failureException, self.assertIsNone, False)
2847 self.assertIsNotNone('DjZoPloGears on Rails')
2848 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2849
2850 def testAssertRegexpMatches(self):
2851 self.assertRegexpMatches('asdfabasdf', r'ab+')
2852 self.assertRaises(self.failureException, self.assertRegexpMatches,
2853 'saaas', r'aaaa')
2854
2855 def testAssertRaisesRegexp(self):
2856 class ExceptionMock(Exception):
2857 pass
2858
2859 def Stub():
2860 raise ExceptionMock('We expect')
2861
2862 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2863 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2864 self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
2865
2866 def testAssertNotRaisesRegexp(self):
2867 self.assertRaisesRegexp(
2868 self.failureException, '^Exception not raised$',
2869 self.assertRaisesRegexp, Exception, re.compile('x'),
2870 lambda: None)
2871 self.assertRaisesRegexp(
2872 self.failureException, '^Exception not raised$',
2873 self.assertRaisesRegexp, Exception, 'x',
2874 lambda: None)
2875 self.assertRaisesRegexp(
2876 self.failureException, '^Exception not raised$',
2877 self.assertRaisesRegexp, Exception, u'x',
2878 lambda: None)
2879
2880 def testAssertRaisesRegexpMismatch(self):
2881 def Stub():
2882 raise Exception('Unexpected')
2883
2884 self.assertRaisesRegexp(
2885 self.failureException,
2886 r'"\^Expected\$" does not match "Unexpected"',
2887 self.assertRaisesRegexp, Exception, '^Expected$',
2888 Stub)
2889 self.assertRaisesRegexp(
2890 self.failureException,
2891 r'"\^Expected\$" does not match "Unexpected"',
2892 self.assertRaisesRegexp, Exception, u'^Expected$',
2893 Stub)
2894 self.assertRaisesRegexp(
2895 self.failureException,
2896 r'"\^Expected\$" does not match "Unexpected"',
2897 self.assertRaisesRegexp, Exception,
2898 re.compile('^Expected$'), Stub)
2899
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00002900 def testAssertRaisesExcValue(self):
2901 class ExceptionMock(Exception):
2902 pass
2903
2904 def Stub(foo):
2905 raise ExceptionMock(foo)
2906 v = "particular value"
2907
2908 ctx = self.assertRaises(ExceptionMock)
2909 with ctx:
2910 Stub(v)
Georg Brandldc3694b2010-02-07 17:02:22 +00002911 e = ctx.exception
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002912 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00002913 self.assertEqual(e.args[0], v)
2914
Gregory P. Smith7558d572009-03-31 19:03:28 +00002915 def testSynonymAssertMethodNames(self):
2916 """Test undocumented method name synonyms.
2917
2918 Please do not use these methods names in your own code.
2919
2920 This test confirms their continued existence and functionality
2921 in order to avoid breaking existing code.
2922 """
2923 self.assertNotEquals(3, 5)
2924 self.assertEquals(3, 3)
2925 self.assertAlmostEquals(2.0, 2.0)
2926 self.assertNotAlmostEquals(3.0, 5.0)
2927 self.assert_(True)
2928
2929 def testPendingDeprecationMethodNames(self):
2930 """Test fail* methods pending deprecation, they will warn in 3.2.
2931
2932 Do not use these methods. They will go away in 3.3.
2933 """
2934 self.failIfEqual(3, 5)
2935 self.failUnlessEqual(3, 3)
2936 self.failUnlessAlmostEqual(2.0, 2.0)
2937 self.failIfAlmostEqual(3.0, 5.0)
2938 self.failUnless(True)
2939 self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam')
2940 self.failIf(False)
2941
Michael Foorde2942d02009-04-02 05:51:54 +00002942 def testDeepcopy(self):
2943 # Issue: 5660
2944 class TestableTest(TestCase):
2945 def testNothing(self):
2946 pass
2947
2948 test = TestableTest('testNothing')
2949
2950 # This shouldn't blow up
2951 deepcopy(test)
2952
Benjamin Peterson692428e2009-03-23 21:50:21 +00002953
2954class Test_TestSkipping(TestCase):
2955
2956 def test_skipping(self):
2957 class Foo(unittest.TestCase):
2958 def test_skip_me(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002959 self.skipTest("skip")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002960 events = []
2961 result = LoggingResult(events)
2962 test = Foo("test_skip_me")
2963 test.run(result)
2964 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2965 self.assertEqual(result.skipped, [(test, "skip")])
2966
2967 # Try letting setUp skip the test now.
2968 class Foo(unittest.TestCase):
2969 def setUp(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002970 self.skipTest("testing")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002971 def test_nothing(self): pass
2972 events = []
2973 result = LoggingResult(events)
2974 test = Foo("test_nothing")
2975 test.run(result)
2976 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2977 self.assertEqual(result.skipped, [(test, "testing")])
2978 self.assertEqual(result.testsRun, 1)
2979
2980 def test_skipping_decorators(self):
2981 op_table = ((unittest.skipUnless, False, True),
2982 (unittest.skipIf, True, False))
2983 for deco, do_skip, dont_skip in op_table:
2984 class Foo(unittest.TestCase):
2985 @deco(do_skip, "testing")
2986 def test_skip(self): pass
2987
2988 @deco(dont_skip, "testing")
2989 def test_dont_skip(self): pass
2990 test_do_skip = Foo("test_skip")
2991 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002992 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002993 events = []
2994 result = LoggingResult(events)
2995 suite.run(result)
2996 self.assertEqual(len(result.skipped), 1)
2997 expected = ['startTest', 'addSkip', 'stopTest',
2998 'startTest', 'addSuccess', 'stopTest']
2999 self.assertEqual(events, expected)
3000 self.assertEqual(result.testsRun, 2)
3001 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
3002 self.assertTrue(result.wasSuccessful())
3003
3004 def test_skip_class(self):
3005 @unittest.skip("testing")
3006 class Foo(unittest.TestCase):
3007 def test_1(self):
3008 record.append(1)
3009 record = []
3010 result = unittest.TestResult()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003011 test = Foo("test_1")
3012 suite = unittest.TestSuite([test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003013 suite.run(result)
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003014 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003015 self.assertEqual(record, [])
3016
3017 def test_expected_failure(self):
3018 class Foo(unittest.TestCase):
3019 @unittest.expectedFailure
3020 def test_die(self):
3021 self.fail("help me!")
3022 events = []
3023 result = LoggingResult(events)
3024 test = Foo("test_die")
3025 test.run(result)
3026 self.assertEqual(events,
3027 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003028 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00003029 self.assertTrue(result.wasSuccessful())
3030
3031 def test_unexpected_success(self):
3032 class Foo(unittest.TestCase):
3033 @unittest.expectedFailure
3034 def test_die(self):
3035 pass
3036 events = []
3037 result = LoggingResult(events)
3038 test = Foo("test_die")
3039 test.run(result)
3040 self.assertEqual(events,
3041 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3042 self.assertFalse(result.failures)
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003043 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003044 self.assertTrue(result.wasSuccessful())
3045
3046
3047
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003048class Test_Assertions(TestCase):
3049 def test_AlmostEqual(self):
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003050 self.assertAlmostEqual(1.00000001, 1.0)
3051 self.assertNotAlmostEqual(1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003052 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003053 self.assertAlmostEqual, 1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003054 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003055 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003056
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003057 self.assertAlmostEqual(1.1, 1.0, places=0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003058 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003059 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003060
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003061 self.assertAlmostEqual(0, .1+.1j, places=0)
3062 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003063 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003064 self.assertAlmostEqual, 0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003065 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003066 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003067
Michael Foordc3f79372009-09-13 16:40:02 +00003068 self.assertAlmostEqual(float('inf'), float('inf'))
3069 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3070 float('inf'), float('inf'))
3071
3072
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003073 def test_assertRaises(self):
3074 def _raise(e):
3075 raise e
3076 self.assertRaises(KeyError, _raise, KeyError)
3077 self.assertRaises(KeyError, _raise, KeyError("key"))
3078 try:
3079 self.assertRaises(KeyError, lambda: None)
Gregory P. Smith28399852009-03-31 16:54:10 +00003080 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003081 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003082 else:
3083 self.fail("assertRaises() didn't fail")
3084 try:
3085 self.assertRaises(KeyError, _raise, ValueError)
3086 except ValueError:
3087 pass
3088 else:
3089 self.fail("assertRaises() didn't let exception pass through")
Michael Foord2bd52dc2010-02-07 18:44:12 +00003090 with self.assertRaises(KeyError) as cm:
3091 try:
3092 raise KeyError
3093 except Exception, e:
3094 raise
3095 self.assertIs(cm.exception, e)
3096
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003097 with self.assertRaises(KeyError):
3098 raise KeyError("key")
3099 try:
3100 with self.assertRaises(KeyError):
3101 pass
Gregory P. Smith28399852009-03-31 16:54:10 +00003102 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003103 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003104 else:
3105 self.fail("assertRaises() didn't fail")
3106 try:
3107 with self.assertRaises(KeyError):
3108 raise ValueError
3109 except ValueError:
3110 pass
3111 else:
3112 self.fail("assertRaises() didn't let exception pass through")
3113
3114
Michael Foord345b2fe2009-04-02 03:20:38 +00003115class TestLongMessage(TestCase):
3116 """Test that the individual asserts honour longMessage.
3117 This actually tests all the message behaviour for
3118 asserts that use longMessage."""
3119
3120 def setUp(self):
3121 class TestableTestFalse(TestCase):
3122 longMessage = False
3123 failureException = self.failureException
3124
3125 def testTest(self):
3126 pass
3127
3128 class TestableTestTrue(TestCase):
3129 longMessage = True
3130 failureException = self.failureException
3131
3132 def testTest(self):
3133 pass
3134
3135 self.testableTrue = TestableTestTrue('testTest')
3136 self.testableFalse = TestableTestFalse('testTest')
3137
3138 def testDefault(self):
3139 self.assertFalse(TestCase.longMessage)
3140
3141 def test_formatMsg(self):
3142 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3143 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3144
3145 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3146 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3147
3148 def assertMessages(self, methodName, args, errors):
3149 def getMethod(i):
3150 useTestableFalse = i < 2
3151 if useTestableFalse:
3152 test = self.testableFalse
3153 else:
3154 test = self.testableTrue
3155 return getattr(test, methodName)
3156
3157 for i, expected_regexp in enumerate(errors):
3158 testMethod = getMethod(i)
3159 kwargs = {}
3160 withMsg = i % 2
3161 if withMsg:
3162 kwargs = {"msg": "oops"}
3163
3164 with self.assertRaisesRegexp(self.failureException,
3165 expected_regexp=expected_regexp):
3166 testMethod(*args, **kwargs)
3167
3168 def testAssertTrue(self):
3169 self.assertMessages('assertTrue', (False,),
3170 ["^False is not True$", "^oops$", "^False is not True$",
3171 "^False is not True : oops$"])
3172
3173 def testAssertFalse(self):
3174 self.assertMessages('assertFalse', (True,),
3175 ["^True is not False$", "^oops$", "^True is not False$",
3176 "^True is not False : oops$"])
3177
3178 def testNotEqual(self):
3179 self.assertMessages('assertNotEqual', (1, 1),
3180 ["^1 == 1$", "^oops$", "^1 == 1$",
3181 "^1 == 1 : oops$"])
3182
3183 def testAlmostEqual(self):
3184 self.assertMessages('assertAlmostEqual', (1, 2),
3185 ["^1 != 2 within 7 places$", "^oops$",
3186 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3187
3188 def testNotAlmostEqual(self):
3189 self.assertMessages('assertNotAlmostEqual', (1, 1),
3190 ["^1 == 1 within 7 places$", "^oops$",
3191 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3192
3193 def test_baseAssertEqual(self):
3194 self.assertMessages('_baseAssertEqual', (1, 2),
3195 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3196
3197 def testAssertSequenceEqual(self):
3198 # Error messages are multiline so not testing on full message
3199 # assertTupleEqual and assertListEqual delegate to this method
3200 self.assertMessages('assertSequenceEqual', ([], [None]),
3201 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3202 r"\+ \[None\] : oops$"])
3203
3204 def testAssertSetEqual(self):
3205 self.assertMessages('assertSetEqual', (set(), set([None])),
3206 ["None$", "^oops$", "None$",
3207 "None : oops$"])
3208
3209 def testAssertIn(self):
3210 self.assertMessages('assertIn', (None, []),
3211 ['^None not found in \[\]$', "^oops$",
3212 '^None not found in \[\]$',
3213 '^None not found in \[\] : oops$'])
3214
3215 def testAssertNotIn(self):
3216 self.assertMessages('assertNotIn', (None, [None]),
3217 ['^None unexpectedly found in \[None\]$', "^oops$",
3218 '^None unexpectedly found in \[None\]$',
3219 '^None unexpectedly found in \[None\] : oops$'])
3220
3221 def testAssertDictEqual(self):
3222 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3223 [r"\+ \{'key': 'value'\}$", "^oops$",
3224 "\+ \{'key': 'value'\}$",
3225 "\+ \{'key': 'value'\} : oops$"])
3226
3227 def testAssertDictContainsSubset(self):
3228 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3229 ["^Missing: 'key'$", "^oops$",
3230 "^Missing: 'key'$",
3231 "^Missing: 'key' : oops$"])
3232
3233 def testAssertSameElements(self):
3234 self.assertMessages('assertSameElements', ([], [None]),
3235 [r"\[None\]$", "^oops$",
3236 r"\[None\]$",
3237 r"\[None\] : oops$"])
3238
3239 def testAssertMultiLineEqual(self):
3240 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3241 [r"\+ foo$", "^oops$",
3242 r"\+ foo$",
3243 r"\+ foo : oops$"])
3244
3245 def testAssertLess(self):
3246 self.assertMessages('assertLess', (2, 1),
3247 ["^2 not less than 1$", "^oops$",
3248 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3249
3250 def testAssertLessEqual(self):
3251 self.assertMessages('assertLessEqual', (2, 1),
3252 ["^2 not less than or equal to 1$", "^oops$",
3253 "^2 not less than or equal to 1$",
3254 "^2 not less than or equal to 1 : oops$"])
3255
3256 def testAssertGreater(self):
3257 self.assertMessages('assertGreater', (1, 2),
3258 ["^1 not greater than 2$", "^oops$",
3259 "^1 not greater than 2$",
3260 "^1 not greater than 2 : oops$"])
3261
3262 def testAssertGreaterEqual(self):
3263 self.assertMessages('assertGreaterEqual', (1, 2),
3264 ["^1 not greater than or equal to 2$", "^oops$",
3265 "^1 not greater than or equal to 2$",
3266 "^1 not greater than or equal to 2 : oops$"])
3267
3268 def testAssertIsNone(self):
3269 self.assertMessages('assertIsNone', ('not None',),
3270 ["^'not None' is not None$", "^oops$",
3271 "^'not None' is not None$",
3272 "^'not None' is not None : oops$"])
3273
3274 def testAssertIsNotNone(self):
3275 self.assertMessages('assertIsNotNone', (None,),
3276 ["^unexpectedly None$", "^oops$",
3277 "^unexpectedly None$",
3278 "^unexpectedly None : oops$"])
3279
Michael Foordf2dfef12009-04-05 19:19:28 +00003280 def testAssertIs(self):
3281 self.assertMessages('assertIs', (None, 'foo'),
3282 ["^None is not 'foo'$", "^oops$",
3283 "^None is not 'foo'$",
3284 "^None is not 'foo' : oops$"])
3285
3286 def testAssertIsNot(self):
3287 self.assertMessages('assertIsNot', (None, None),
3288 ["^unexpectedly identical: None$", "^oops$",
3289 "^unexpectedly identical: None$",
3290 "^unexpectedly identical: None : oops$"])
3291
Michael Foord345b2fe2009-04-02 03:20:38 +00003292
Michael Foorde2fb98f2009-05-02 20:15:05 +00003293class TestCleanUp(TestCase):
3294
3295 def testCleanUp(self):
3296 class TestableTest(TestCase):
3297 def testNothing(self):
3298 pass
3299
3300 test = TestableTest('testNothing')
3301 self.assertEqual(test._cleanups, [])
3302
3303 cleanups = []
3304
3305 def cleanup1(*args, **kwargs):
3306 cleanups.append((1, args, kwargs))
3307
3308 def cleanup2(*args, **kwargs):
3309 cleanups.append((2, args, kwargs))
3310
3311 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3312 test.addCleanup(cleanup2)
3313
3314 self.assertEqual(test._cleanups,
3315 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3316 (cleanup2, (), {})])
3317
3318 result = test.doCleanups()
3319 self.assertTrue(result)
3320
3321 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3322
3323 def testCleanUpWithErrors(self):
3324 class TestableTest(TestCase):
3325 def testNothing(self):
3326 pass
3327
3328 class MockResult(object):
3329 errors = []
3330 def addError(self, test, exc_info):
3331 self.errors.append((test, exc_info))
3332
3333 result = MockResult()
3334 test = TestableTest('testNothing')
Michael Foorda50af062009-05-21 22:57:02 +00003335 test._resultForDoCleanups = result
Michael Foorde2fb98f2009-05-02 20:15:05 +00003336
3337 exc1 = Exception('foo')
3338 exc2 = Exception('bar')
3339 def cleanup1():
3340 raise exc1
3341
3342 def cleanup2():
3343 raise exc2
3344
3345 test.addCleanup(cleanup1)
3346 test.addCleanup(cleanup2)
3347
3348 self.assertFalse(test.doCleanups())
3349
3350 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3351 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3352 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3353
3354 def testCleanupInRun(self):
3355 blowUp = False
3356 ordering = []
3357
3358 class TestableTest(TestCase):
3359 def setUp(self):
3360 ordering.append('setUp')
3361 if blowUp:
3362 raise Exception('foo')
3363
3364 def testNothing(self):
3365 ordering.append('test')
3366
3367 def tearDown(self):
3368 ordering.append('tearDown')
3369
3370 test = TestableTest('testNothing')
3371
3372 def cleanup1():
3373 ordering.append('cleanup1')
3374 def cleanup2():
3375 ordering.append('cleanup2')
3376 test.addCleanup(cleanup1)
3377 test.addCleanup(cleanup2)
3378
3379 def success(some_test):
3380 self.assertEqual(some_test, test)
3381 ordering.append('success')
3382
3383 result = unittest.TestResult()
3384 result.addSuccess = success
3385
3386 test.run(result)
3387 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3388 'cleanup2', 'cleanup1', 'success'])
3389
3390 blowUp = True
3391 ordering = []
3392 test = TestableTest('testNothing')
3393 test.addCleanup(cleanup1)
3394 test.run(result)
3395 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3396
3397
Michael Foord829f6b82009-05-02 11:43:06 +00003398class Test_TestProgram(TestCase):
3399
3400 # Horrible white box test
3401 def testNoExit(self):
3402 result = object()
3403 test = object()
3404
3405 class FakeRunner(object):
3406 def run(self, test):
3407 self.test = test
3408 return result
3409
3410 runner = FakeRunner()
3411
Michael Foord5d31e052009-05-11 17:59:43 +00003412 oldParseArgs = TestProgram.parseArgs
3413 def restoreParseArgs():
Michael Foord829f6b82009-05-02 11:43:06 +00003414 TestProgram.parseArgs = oldParseArgs
Michael Foord5d31e052009-05-11 17:59:43 +00003415 TestProgram.parseArgs = lambda *args: None
3416 self.addCleanup(restoreParseArgs)
3417
3418 def removeTest():
Michael Foord829f6b82009-05-02 11:43:06 +00003419 del TestProgram.test
Michael Foord5d31e052009-05-11 17:59:43 +00003420 TestProgram.test = test
3421 self.addCleanup(removeTest)
3422
3423 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3424
3425 self.assertEqual(program.result, result)
3426 self.assertEqual(runner.test, test)
3427 self.assertEqual(program.verbosity, 2)
Michael Foord829f6b82009-05-02 11:43:06 +00003428
Michael Foord829f6b82009-05-02 11:43:06 +00003429 class FooBar(unittest.TestCase):
3430 def testPass(self):
3431 assert True
3432 def testFail(self):
3433 assert False
3434
3435 class FooBarLoader(unittest.TestLoader):
3436 """Test loader that returns a suite containing FooBar."""
3437 def loadTestsFromModule(self, module):
3438 return self.suiteClass(
3439 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3440
3441
3442 def test_NonExit(self):
3443 program = unittest.main(exit=False,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003444 argv=["foobar"],
3445 testRunner=unittest.TextTestRunner(stream=StringIO()),
3446 testLoader=self.FooBarLoader())
Michael Foord829f6b82009-05-02 11:43:06 +00003447 self.assertTrue(hasattr(program, 'result'))
3448
3449
3450 def test_Exit(self):
3451 self.assertRaises(
3452 SystemExit,
3453 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003454 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003455 testRunner=unittest.TextTestRunner(stream=StringIO()),
3456 exit=True,
3457 testLoader=self.FooBarLoader())
3458
3459
3460 def test_ExitAsDefault(self):
3461 self.assertRaises(
3462 SystemExit,
3463 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003464 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003465 testRunner=unittest.TextTestRunner(stream=StringIO()),
3466 testLoader=self.FooBarLoader())
3467
3468
Michael Foord07ef4872009-05-02 22:43:34 +00003469class Test_TextTestRunner(TestCase):
3470 """Tests for TextTestRunner."""
3471
3472 def test_works_with_result_without_startTestRun_stopTestRun(self):
3473 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3474 separator2 = ''
3475 def printErrors(self):
3476 pass
3477
3478 class Runner(unittest.TextTestRunner):
3479 def __init__(self):
3480 super(Runner, self).__init__(StringIO())
3481
3482 def _makeResult(self):
3483 return OldTextResult()
3484
3485 runner = Runner()
3486 runner.run(unittest.TestSuite())
3487
3488 def test_startTestRun_stopTestRun_called(self):
3489 class LoggingTextResult(LoggingResult):
3490 separator2 = ''
3491 def printErrors(self):
3492 pass
3493
3494 class LoggingRunner(unittest.TextTestRunner):
3495 def __init__(self, events):
3496 super(LoggingRunner, self).__init__(StringIO())
3497 self._events = events
3498
3499 def _makeResult(self):
3500 return LoggingTextResult(self._events)
3501
3502 events = []
3503 runner = LoggingRunner(events)
3504 runner.run(unittest.TestSuite())
3505 expected = ['startTestRun', 'stopTestRun']
3506 self.assertEqual(events, expected)
3507
Antoine Pitrou0734c632009-11-10 20:49:30 +00003508 def test_pickle_unpickle(self):
3509 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3510 # required by test_multiprocessing under Windows (in verbose mode).
3511 import StringIO
3512 # cStringIO objects are not pickleable, but StringIO objects are.
3513 stream = StringIO.StringIO("foo")
3514 runner = unittest.TextTestRunner(stream)
3515 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
3516 s = pickle.dumps(runner, protocol=protocol)
3517 obj = pickle.loads(s)
3518 # StringIO objects never compare equal, a cheap test instead.
3519 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3520
Michael Foorddb43b5a2010-02-10 14:25:12 +00003521 def test_resultclass(self):
3522 def MockResultClass(*args):
3523 return args
3524 STREAM = object()
3525 DESCRIPTIONS = object()
3526 VERBOSITY = object()
3527 runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY,
3528 resultclass=MockResultClass)
3529 self.assertEqual(runner.resultclass, MockResultClass)
3530
3531 expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY)
3532 self.assertEqual(runner._makeResult(), expectedresult)
3533
Michael Foord07ef4872009-05-02 22:43:34 +00003534
Michael Foordb4a81c82009-05-29 20:33:46 +00003535class TestDiscovery(TestCase):
3536
3537 # Heavily mocked tests so I can avoid hitting the filesystem
Michael Foorde91ea562009-09-13 19:07:03 +00003538 def test_get_name_from_path(self):
Michael Foordb4a81c82009-05-29 20:33:46 +00003539 loader = unittest.TestLoader()
3540
Michael Foordb4a81c82009-05-29 20:33:46 +00003541 loader._top_level_dir = '/foo'
Michael Foorde91ea562009-09-13 19:07:03 +00003542 name = loader._get_name_from_path('/foo/bar/baz.py')
3543 self.assertEqual(name, 'bar.baz')
Michael Foordb4a81c82009-05-29 20:33:46 +00003544
3545 if not __debug__:
3546 # asserts are off
3547 return
3548
3549 with self.assertRaises(AssertionError):
Michael Foorde91ea562009-09-13 19:07:03 +00003550 loader._get_name_from_path('/bar/baz.py')
Michael Foordb4a81c82009-05-29 20:33:46 +00003551
3552 def test_find_tests(self):
3553 loader = unittest.TestLoader()
3554
3555 original_listdir = os.listdir
3556 def restore_listdir():
3557 os.listdir = original_listdir
3558 original_isfile = os.path.isfile
3559 def restore_isfile():
3560 os.path.isfile = original_isfile
3561 original_isdir = os.path.isdir
3562 def restore_isdir():
3563 os.path.isdir = original_isdir
3564
3565 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Michael Foorde91ea562009-09-13 19:07:03 +00003566 'test.foo', 'test-not-a-module.py', 'another_dir'],
Michael Foordb4a81c82009-05-29 20:33:46 +00003567 ['test3.py', 'test4.py', ]]
3568 os.listdir = lambda path: path_lists.pop(0)
3569 self.addCleanup(restore_listdir)
3570
3571 def isdir(path):
3572 return path.endswith('dir')
3573 os.path.isdir = isdir
3574 self.addCleanup(restore_isdir)
3575
3576 def isfile(path):
3577 # another_dir is not a package and so shouldn't be recursed into
3578 return not path.endswith('dir') and not 'another_dir' in path
3579 os.path.isfile = isfile
3580 self.addCleanup(restore_isfile)
3581
Michael Foorde91ea562009-09-13 19:07:03 +00003582 loader._get_module_from_name = lambda path: path + ' module'
Michael Foordb4a81c82009-05-29 20:33:46 +00003583 loader.loadTestsFromModule = lambda module: module + ' tests'
3584
3585 loader._top_level_dir = '/foo'
3586 suite = list(loader._find_tests('/foo', 'test*.py'))
3587
Michael Foorde91ea562009-09-13 19:07:03 +00003588 expected = [name + ' module tests' for name in
3589 ('test1', 'test2')]
3590 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3591 ('test3', 'test4')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003592 self.assertEqual(suite, expected)
3593
3594 def test_find_tests_with_package(self):
3595 loader = unittest.TestLoader()
3596
3597 original_listdir = os.listdir
3598 def restore_listdir():
3599 os.listdir = original_listdir
3600 original_isfile = os.path.isfile
3601 def restore_isfile():
3602 os.path.isfile = original_isfile
3603 original_isdir = os.path.isdir
3604 def restore_isdir():
3605 os.path.isdir = original_isdir
3606
3607 directories = ['a_directory', 'test_directory', 'test_directory2']
3608 path_lists = [directories, [], [], []]
3609 os.listdir = lambda path: path_lists.pop(0)
3610 self.addCleanup(restore_listdir)
3611
3612 os.path.isdir = lambda path: True
3613 self.addCleanup(restore_isdir)
3614
3615 os.path.isfile = lambda path: os.path.basename(path) not in directories
3616 self.addCleanup(restore_isfile)
3617
3618 class Module(object):
3619 paths = []
3620 load_tests_args = []
3621
3622 def __init__(self, path):
3623 self.path = path
3624 self.paths.append(path)
3625 if os.path.basename(path) == 'test_directory':
3626 def load_tests(loader, tests, pattern):
3627 self.load_tests_args.append((loader, tests, pattern))
3628 return 'load_tests'
3629 self.load_tests = load_tests
3630
3631 def __eq__(self, other):
3632 return self.path == other.path
3633
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003634 # Silence py3k warning
3635 __hash__ = None
3636
Michael Foorde91ea562009-09-13 19:07:03 +00003637 loader._get_module_from_name = lambda name: Module(name)
Michael Foordb4a81c82009-05-29 20:33:46 +00003638 def loadTestsFromModule(module, use_load_tests):
3639 if use_load_tests:
3640 raise self.failureException('use_load_tests should be False for packages')
3641 return module.path + ' module tests'
3642 loader.loadTestsFromModule = loadTestsFromModule
3643
3644 loader._top_level_dir = '/foo'
3645 # this time no '.py' on the pattern so that it can match
3646 # a test package
3647 suite = list(loader._find_tests('/foo', 'test*'))
3648
3649 # We should have loaded tests from the test_directory package by calling load_tests
3650 # and directly from the test_directory2 package
Michael Foordd53d0852009-06-05 14:14:34 +00003651 self.assertEqual(suite,
Michael Foorde91ea562009-09-13 19:07:03 +00003652 ['load_tests', 'test_directory2' + ' module tests'])
3653 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Michael Foordb4a81c82009-05-29 20:33:46 +00003654
3655 # load_tests should have been called once with loader, tests and pattern
3656 self.assertEqual(Module.load_tests_args,
Michael Foorde91ea562009-09-13 19:07:03 +00003657 [(loader, 'test_directory' + ' module tests', 'test*')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003658
3659 def test_discover(self):
3660 loader = unittest.TestLoader()
3661
3662 original_isfile = os.path.isfile
3663 def restore_isfile():
3664 os.path.isfile = original_isfile
3665
3666 os.path.isfile = lambda path: False
3667 self.addCleanup(restore_isfile)
3668
Nick Coghlanb6edf192009-10-17 08:21:21 +00003669 orig_sys_path = sys.path[:]
3670 def restore_path():
3671 sys.path[:] = orig_sys_path
3672 self.addCleanup(restore_path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003673
Nick Coghlanb6edf192009-10-17 08:21:21 +00003674 full_path = os.path.abspath(os.path.normpath('/foo'))
Michael Foordb4a81c82009-05-29 20:33:46 +00003675 with self.assertRaises(ImportError):
3676 loader.discover('/foo/bar', top_level_dir='/foo')
3677
3678 self.assertEqual(loader._top_level_dir, full_path)
3679 self.assertIn(full_path, sys.path)
3680
3681 os.path.isfile = lambda path: True
3682 _find_tests_args = []
3683 def _find_tests(start_dir, pattern):
3684 _find_tests_args.append((start_dir, pattern))
3685 return ['tests']
3686 loader._find_tests = _find_tests
3687 loader.suiteClass = str
3688
3689 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3690
3691 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3692 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3693 self.assertEqual(suite, "['tests']")
3694 self.assertEqual(loader._top_level_dir, top_level_dir)
3695 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlanb6edf192009-10-17 08:21:21 +00003696 self.assertIn(top_level_dir, sys.path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003697
Michael Foorde91ea562009-09-13 19:07:03 +00003698 def test_discover_with_modules_that_fail_to_import(self):
3699 loader = unittest.TestLoader()
3700
3701 listdir = os.listdir
3702 os.listdir = lambda _: ['test_this_does_not_exist.py']
3703 isfile = os.path.isfile
3704 os.path.isfile = lambda _: True
Nick Coghlanb6edf192009-10-17 08:21:21 +00003705 orig_sys_path = sys.path[:]
Michael Foorde91ea562009-09-13 19:07:03 +00003706 def restore():
3707 os.path.isfile = isfile
3708 os.listdir = listdir
Nick Coghlanb6edf192009-10-17 08:21:21 +00003709 sys.path[:] = orig_sys_path
Michael Foorde91ea562009-09-13 19:07:03 +00003710 self.addCleanup(restore)
3711
3712 suite = loader.discover('.')
Nick Coghlanb6edf192009-10-17 08:21:21 +00003713 self.assertIn(os.getcwd(), sys.path)
Michael Foorde91ea562009-09-13 19:07:03 +00003714 self.assertEqual(suite.countTestCases(), 1)
3715 test = list(list(suite)[0])[0] # extract test from suite
3716
3717 with self.assertRaises(ImportError):
3718 test.test_this_does_not_exist()
3719
Michael Foordb4a81c82009-05-29 20:33:46 +00003720 def test_command_line_handling_parseArgs(self):
3721 # Haha - take that uninstantiable class
3722 program = object.__new__(TestProgram)
3723
3724 args = []
3725 def do_discovery(argv):
3726 args.extend(argv)
3727 program._do_discovery = do_discovery
3728 program.parseArgs(['something', 'discover'])
3729 self.assertEqual(args, [])
3730
3731 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3732 self.assertEqual(args, ['foo', 'bar'])
3733
3734 def test_command_line_handling_do_discovery_too_many_arguments(self):
3735 class Stop(Exception):
3736 pass
3737 def usageExit():
3738 raise Stop
3739
3740 program = object.__new__(TestProgram)
3741 program.usageExit = usageExit
3742
3743 with self.assertRaises(Stop):
3744 # too many args
3745 program._do_discovery(['one', 'two', 'three', 'four'])
3746
3747
3748 def test_command_line_handling_do_discovery_calls_loader(self):
3749 program = object.__new__(TestProgram)
3750
3751 class Loader(object):
3752 args = []
3753 def discover(self, start_dir, pattern, top_level_dir):
3754 self.args.append((start_dir, pattern, top_level_dir))
3755 return 'tests'
3756
3757 program._do_discovery(['-v'], Loader=Loader)
3758 self.assertEqual(program.verbosity, 2)
3759 self.assertEqual(program.test, 'tests')
3760 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3761
3762 Loader.args = []
3763 program = object.__new__(TestProgram)
3764 program._do_discovery(['--verbose'], Loader=Loader)
3765 self.assertEqual(program.test, 'tests')
3766 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3767
3768 Loader.args = []
3769 program = object.__new__(TestProgram)
3770 program._do_discovery([], Loader=Loader)
3771 self.assertEqual(program.test, 'tests')
3772 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3773
3774 Loader.args = []
3775 program = object.__new__(TestProgram)
3776 program._do_discovery(['fish'], Loader=Loader)
3777 self.assertEqual(program.test, 'tests')
3778 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3779
3780 Loader.args = []
3781 program = object.__new__(TestProgram)
3782 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3783 self.assertEqual(program.test, 'tests')
3784 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3785
3786 Loader.args = []
3787 program = object.__new__(TestProgram)
3788 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3789 self.assertEqual(program.test, 'tests')
3790 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3791
3792 Loader.args = []
3793 program = object.__new__(TestProgram)
3794 program._do_discovery(['-s', 'fish'], Loader=Loader)
3795 self.assertEqual(program.test, 'tests')
3796 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3797
3798 Loader.args = []
3799 program = object.__new__(TestProgram)
3800 program._do_discovery(['-t', 'fish'], Loader=Loader)
3801 self.assertEqual(program.test, 'tests')
3802 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3803
3804 Loader.args = []
3805 program = object.__new__(TestProgram)
3806 program._do_discovery(['-p', 'fish'], Loader=Loader)
3807 self.assertEqual(program.test, 'tests')
3808 self.assertEqual(Loader.args, [('.', 'fish', None)])
3809
3810 Loader.args = []
3811 program = object.__new__(TestProgram)
3812 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3813 self.assertEqual(program.test, 'tests')
3814 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3815 self.assertEqual(program.verbosity, 2)
3816
3817
Jim Fultonfafd8742004-08-28 15:22:12 +00003818######################################################################
3819## Main
3820######################################################################
3821
3822def test_main():
Georg Brandl15c5ce92007-03-07 09:09:40 +00003823 test_support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003824 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Michael Foord829f6b82009-05-02 11:43:06 +00003825 Test_TestSkipping, Test_Assertions, TestLongMessage,
Antoine Pitrou0734c632009-11-10 20:49:30 +00003826 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner)
Jim Fultonfafd8742004-08-28 15:22:12 +00003827
Georg Brandl15c5ce92007-03-07 09:09:40 +00003828if __name__ == "__main__":
Tim Petersea5962f2007-03-12 18:07:52 +00003829 test_main()