blob: 726ac85fbfdc64e5454f6a23107b16194ca1846b [file] [log] [blame]
Jim Fultonfafd8742004-08-28 15:22:12 +00001"""Test script for unittest.
2
Georg Brandl15c5ce92007-03-07 09:09:40 +00003By Collin Winter <collinw at gmail.com>
4
5Still need testing:
6 TestCase.{assert,fail}* methods (some are tested implicitly)
Jim Fultonfafd8742004-08-28 15:22:12 +00007"""
8
Michael Foord07ef4872009-05-02 22:43:34 +00009from StringIO import StringIO
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +000010import __builtin__
Michael Foordb4a81c82009-05-29 20:33:46 +000011import os
Gregory P. Smith28399852009-03-31 16:54:10 +000012import re
Michael Foordb4a81c82009-05-29 20:33:46 +000013import sys
Georg Brandl15c5ce92007-03-07 09:09:40 +000014from test import test_support
Jim Fultonfafd8742004-08-28 15:22:12 +000015import unittest
Michael Foord829f6b82009-05-02 11:43:06 +000016from unittest import TestCase, TestProgram
Christian Heimesc756d002007-11-27 21:34:01 +000017import types
Michael Foorde2942d02009-04-02 05:51:54 +000018from copy import deepcopy
Michael Foord829f6b82009-05-02 11:43:06 +000019from cStringIO import StringIO
Jim Fultonfafd8742004-08-28 15:22:12 +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)
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000188 self.assertTrue(isinstance(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)
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000207 self.assertTrue(isinstance(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)
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000220 self.assertTrue(isinstance(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)
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000234 self.assertTrue(isinstance(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):
274 load_tests_args.extend((loader, tests, pattern))
275 return tests
276 m.load_tests = load_tests
277
278 loader = unittest.TestLoader()
279 suite = loader.loadTestsFromModule(m)
280 self.assertEquals(load_tests_args, [loader, suite, None])
281
282 load_tests_args = []
283 suite = loader.loadTestsFromModule(m, use_load_tests=False)
284 self.assertEquals(load_tests_args, [])
285
Georg Brandl15c5ce92007-03-07 09:09:40 +0000286 ################################################################
287 ### /Tests for TestLoader.loadTestsFromModule()
Tim Petersea5962f2007-03-12 18:07:52 +0000288
Georg Brandl15c5ce92007-03-07 09:09:40 +0000289 ### Tests for TestLoader.loadTestsFromName()
290 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000291
Georg Brandl15c5ce92007-03-07 09:09:40 +0000292 # "The specifier name is a ``dotted name'' that may resolve either to
293 # a module, a test case class, a TestSuite instance, a test method
294 # within a test case class, or a callable object which returns a
295 # TestCase or TestSuite instance."
296 #
297 # Is ValueError raised in response to an empty name?
298 def test_loadTestsFromName__empty_name(self):
299 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000300
Georg Brandl15c5ce92007-03-07 09:09:40 +0000301 try:
302 loader.loadTestsFromName('')
303 except ValueError, e:
304 self.assertEqual(str(e), "Empty module name")
305 else:
306 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000307
Georg Brandl15c5ce92007-03-07 09:09:40 +0000308 # "The specifier name is a ``dotted name'' that may resolve either to
309 # a module, a test case class, a TestSuite instance, a test method
310 # within a test case class, or a callable object which returns a
311 # TestCase or TestSuite instance."
312 #
Tim Petersea5962f2007-03-12 18:07:52 +0000313 # What happens when the name contains invalid characters?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000314 def test_loadTestsFromName__malformed_name(self):
315 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000316
Georg Brandl15c5ce92007-03-07 09:09:40 +0000317 # XXX Should this raise ValueError or ImportError?
318 try:
319 loader.loadTestsFromName('abc () //')
320 except ValueError:
321 pass
322 except ImportError:
323 pass
324 else:
325 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000326
Georg Brandl15c5ce92007-03-07 09:09:40 +0000327 # "The specifier name is a ``dotted name'' that may resolve ... to a
328 # module"
329 #
Tim Petersea5962f2007-03-12 18:07:52 +0000330 # What happens when a module by that name can't be found?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000331 def test_loadTestsFromName__unknown_module_name(self):
332 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000333
Georg Brandl15c5ce92007-03-07 09:09:40 +0000334 try:
335 loader.loadTestsFromName('sdasfasfasdf')
336 except ImportError, e:
337 self.assertEqual(str(e), "No module named sdasfasfasdf")
338 else:
339 self.fail("TestLoader.loadTestsFromName failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000340
Georg Brandl15c5ce92007-03-07 09:09:40 +0000341 # "The specifier name is a ``dotted name'' that may resolve either to
342 # a module, a test case class, a TestSuite instance, a test method
343 # within a test case class, or a callable object which returns a
344 # TestCase or TestSuite instance."
345 #
Tim Petersea5962f2007-03-12 18:07:52 +0000346 # What happens when the module is found, but the attribute can't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000347 def test_loadTestsFromName__unknown_attr_name(self):
348 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000349
Georg Brandl15c5ce92007-03-07 09:09:40 +0000350 try:
351 loader.loadTestsFromName('unittest.sdasfasfasdf')
352 except AttributeError, e:
353 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
354 else:
355 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000356
Georg Brandl15c5ce92007-03-07 09:09:40 +0000357 # "The specifier name is a ``dotted name'' that may resolve either to
358 # a module, a test case class, a TestSuite instance, a test method
359 # within a test case class, or a callable object which returns a
360 # TestCase or TestSuite instance."
361 #
362 # What happens when we provide the module, but the attribute can't be
363 # found?
364 def test_loadTestsFromName__relative_unknown_name(self):
365 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000366
Georg Brandl15c5ce92007-03-07 09:09:40 +0000367 try:
368 loader.loadTestsFromName('sdasfasfasdf', unittest)
369 except AttributeError, e:
370 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
371 else:
372 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000373
Georg Brandl15c5ce92007-03-07 09:09:40 +0000374 # "The specifier name is a ``dotted name'' that may resolve either to
375 # a module, a test case class, a TestSuite instance, a test method
376 # within a test case class, or a callable object which returns a
377 # TestCase or TestSuite instance."
378 # ...
379 # "The method optionally resolves name relative to the given module"
380 #
381 # Does loadTestsFromName raise ValueError when passed an empty
382 # name relative to a provided module?
383 #
384 # XXX Should probably raise a ValueError instead of an AttributeError
385 def test_loadTestsFromName__relative_empty_name(self):
386 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000387
Georg Brandl15c5ce92007-03-07 09:09:40 +0000388 try:
389 loader.loadTestsFromName('', unittest)
390 except AttributeError, e:
391 pass
392 else:
393 self.fail("Failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000394
Georg Brandl15c5ce92007-03-07 09:09:40 +0000395 # "The specifier name is a ``dotted name'' that may resolve either to
396 # a module, a test case class, a TestSuite instance, a test method
397 # within a test case class, or a callable object which returns a
398 # TestCase or TestSuite instance."
399 # ...
400 # "The method optionally resolves name relative to the given module"
401 #
402 # What happens when an impossible name is given, relative to the provided
403 # `module`?
404 def test_loadTestsFromName__relative_malformed_name(self):
405 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000406
Georg Brandl15c5ce92007-03-07 09:09:40 +0000407 # XXX Should this raise AttributeError or ValueError?
408 try:
409 loader.loadTestsFromName('abc () //', unittest)
410 except ValueError:
411 pass
412 except AttributeError:
413 pass
414 else:
415 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
416
417 # "The method optionally resolves name relative to the given module"
418 #
419 # Does loadTestsFromName raise TypeError when the `module` argument
420 # isn't a module object?
421 #
422 # XXX Accepts the not-a-module object, ignorning the object's type
423 # This should raise an exception or the method name should be changed
424 #
425 # XXX Some people are relying on this, so keep it for now
426 def test_loadTestsFromName__relative_not_a_module(self):
427 class MyTestCase(unittest.TestCase):
428 def test(self):
429 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000430
Georg Brandl15c5ce92007-03-07 09:09:40 +0000431 class NotAModule(object):
432 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000433
Georg Brandl15c5ce92007-03-07 09:09:40 +0000434 loader = unittest.TestLoader()
435 suite = loader.loadTestsFromName('test_2', NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000436
Georg Brandl15c5ce92007-03-07 09:09:40 +0000437 reference = [MyTestCase('test')]
438 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000439
Georg Brandl15c5ce92007-03-07 09:09:40 +0000440 # "The specifier name is a ``dotted name'' that may resolve either to
441 # a module, a test case class, a TestSuite instance, a test method
442 # within a test case class, or a callable object which returns a
443 # TestCase or TestSuite instance."
444 #
445 # Does it raise an exception if the name resolves to an invalid
446 # object?
447 def test_loadTestsFromName__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000448 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000449 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000450
Georg Brandl15c5ce92007-03-07 09:09:40 +0000451 loader = unittest.TestLoader()
452 try:
453 loader.loadTestsFromName('testcase_1', m)
454 except TypeError:
455 pass
456 else:
457 self.fail("Should have raised TypeError")
458
459 # "The specifier name is a ``dotted name'' that may
460 # resolve either to ... a test case class"
461 def test_loadTestsFromName__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000462 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000463 class MyTestCase(unittest.TestCase):
464 def test(self):
465 pass
466 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000467
Georg Brandl15c5ce92007-03-07 09:09:40 +0000468 loader = unittest.TestLoader()
469 suite = loader.loadTestsFromName('testcase_1', m)
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000470 self.assertTrue(isinstance(suite, loader.suiteClass))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000471 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000472
Georg Brandl15c5ce92007-03-07 09:09:40 +0000473 # "The specifier name is a ``dotted name'' that may resolve either to
474 # a module, a test case class, a TestSuite instance, a test method
475 # within a test case class, or a callable object which returns a
476 # TestCase or TestSuite instance."
477 def test_loadTestsFromName__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000478 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000479 class MyTestCase(unittest.TestCase):
480 def test(self):
481 pass
482 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000483
Georg Brandl15c5ce92007-03-07 09:09:40 +0000484 loader = unittest.TestLoader()
485 suite = loader.loadTestsFromName('testsuite', m)
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000486 self.assertTrue(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000487
Georg Brandl15c5ce92007-03-07 09:09:40 +0000488 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000489
Georg Brandl15c5ce92007-03-07 09:09:40 +0000490 # "The specifier name is a ``dotted name'' that may resolve ... to
491 # ... a test method within a test case class"
492 def test_loadTestsFromName__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000493 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000494 class MyTestCase(unittest.TestCase):
495 def test(self):
496 pass
497 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000498
Georg Brandl15c5ce92007-03-07 09:09:40 +0000499 loader = unittest.TestLoader()
500 suite = loader.loadTestsFromName('testcase_1.test', m)
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000501 self.assertTrue(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000502
Georg Brandl15c5ce92007-03-07 09:09:40 +0000503 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000504
Georg Brandl15c5ce92007-03-07 09:09:40 +0000505 # "The specifier name is a ``dotted name'' that may resolve either to
506 # a module, a test case class, a TestSuite instance, a test method
507 # within a test case class, or a callable object which returns a
508 # TestCase or TestSuite instance."
509 #
510 # Does loadTestsFromName() raise the proper exception when trying to
511 # resolve "a test method within a test case class" that doesn't exist
512 # for the given name (relative to a provided module)?
513 def test_loadTestsFromName__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000514 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000515 class MyTestCase(unittest.TestCase):
516 def test(self):
517 pass
518 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000519
Georg Brandl15c5ce92007-03-07 09:09:40 +0000520 loader = unittest.TestLoader()
521 try:
522 loader.loadTestsFromName('testcase_1.testfoo', m)
523 except AttributeError, e:
524 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
525 else:
526 self.fail("Failed to raise AttributeError")
527
528 # "The specifier name is a ``dotted name'' that may resolve ... to
529 # ... a callable object which returns a ... TestSuite instance"
530 def test_loadTestsFromName__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000531 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000532 testcase_1 = unittest.FunctionTestCase(lambda: None)
533 testcase_2 = unittest.FunctionTestCase(lambda: None)
534 def return_TestSuite():
535 return unittest.TestSuite([testcase_1, testcase_2])
536 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000537
Georg Brandl15c5ce92007-03-07 09:09:40 +0000538 loader = unittest.TestLoader()
539 suite = loader.loadTestsFromName('return_TestSuite', m)
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000540 self.assertTrue(isinstance(suite, loader.suiteClass))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000541 self.assertEqual(list(suite), [testcase_1, testcase_2])
Tim Petersea5962f2007-03-12 18:07:52 +0000542
Georg Brandl15c5ce92007-03-07 09:09:40 +0000543 # "The specifier name is a ``dotted name'' that may resolve ... to
544 # ... a callable object which returns a TestCase ... instance"
545 def test_loadTestsFromName__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000546 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000547 testcase_1 = unittest.FunctionTestCase(lambda: None)
548 def return_TestCase():
549 return testcase_1
550 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000551
Georg Brandl15c5ce92007-03-07 09:09:40 +0000552 loader = unittest.TestLoader()
553 suite = loader.loadTestsFromName('return_TestCase', m)
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000554 self.assertTrue(isinstance(suite, loader.suiteClass))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000555 self.assertEqual(list(suite), [testcase_1])
Tim Petersea5962f2007-03-12 18:07:52 +0000556
Georg Brandl15c5ce92007-03-07 09:09:40 +0000557 # "The specifier name is a ``dotted name'' that may resolve ... to
Michael Foord5a9719d2009-09-13 17:28:35 +0000558 # ... a callable object which returns a TestCase ... instance"
559 #*****************************************************************
560 #Override the suiteClass attribute to ensure that the suiteClass
561 #attribute is used
562 def test_loadTestsFromName__callable__TestCase_instance_ProperSuiteClass(self):
563 class SubTestSuite(unittest.TestSuite):
564 pass
565 m = types.ModuleType('m')
566 testcase_1 = unittest.FunctionTestCase(lambda: None)
567 def return_TestCase():
568 return testcase_1
569 m.return_TestCase = return_TestCase
570
571 loader = unittest.TestLoader()
572 loader.suiteClass = SubTestSuite
573 suite = loader.loadTestsFromName('return_TestCase', m)
574 self.assertTrue(isinstance(suite, loader.suiteClass))
575 self.assertEqual(list(suite), [testcase_1])
576
577 # "The specifier name is a ``dotted name'' that may resolve ... to
578 # ... a test method within a test case class"
579 #*****************************************************************
580 #Override the suiteClass attribute to ensure that the suiteClass
581 #attribute is used
582 def test_loadTestsFromName__relative_testmethod_ProperSuiteClass(self):
583 class SubTestSuite(unittest.TestSuite):
584 pass
585 m = types.ModuleType('m')
586 class MyTestCase(unittest.TestCase):
587 def test(self):
588 pass
589 m.testcase_1 = MyTestCase
590
591 loader = unittest.TestLoader()
592 loader.suiteClass=SubTestSuite
593 suite = loader.loadTestsFromName('testcase_1.test', m)
594 self.assertTrue(isinstance(suite, loader.suiteClass))
595
596 self.assertEqual(list(suite), [MyTestCase('test')])
597
598 # "The specifier name is a ``dotted name'' that may resolve ... to
Georg Brandl15c5ce92007-03-07 09:09:40 +0000599 # ... a callable object which returns a TestCase or TestSuite instance"
600 #
601 # What happens if the callable returns something else?
602 def test_loadTestsFromName__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000603 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000604 def return_wrong():
605 return 6
606 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000607
Georg Brandl15c5ce92007-03-07 09:09:40 +0000608 loader = unittest.TestLoader()
609 try:
610 suite = loader.loadTestsFromName('return_wrong', m)
611 except TypeError:
612 pass
613 else:
614 self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000615
Georg Brandl15c5ce92007-03-07 09:09:40 +0000616 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +0000617 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +0000618 def test_loadTestsFromName__module_not_loaded(self):
619 # We're going to try to load this module as a side-effect, so it
620 # better not be loaded before we try.
621 #
622 # Why pick audioop? Google shows it isn't used very often, so there's
623 # a good chance that it won't be imported when this test is run
624 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +0000625
Georg Brandl15c5ce92007-03-07 09:09:40 +0000626 import sys
627 if module_name in sys.modules:
628 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000629
Georg Brandl15c5ce92007-03-07 09:09:40 +0000630 loader = unittest.TestLoader()
631 try:
632 suite = loader.loadTestsFromName(module_name)
633
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000634 self.assertTrue(isinstance(suite, loader.suiteClass))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000635 self.assertEqual(list(suite), [])
636
637 # audioop should now be loaded, thanks to loadTestsFromName()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000638 self.assertTrue(module_name in sys.modules)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000639 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000640 if module_name in sys.modules:
641 del sys.modules[module_name]
Georg Brandl15c5ce92007-03-07 09:09:40 +0000642
643 ################################################################
644 ### Tests for TestLoader.loadTestsFromName()
645
646 ### Tests for TestLoader.loadTestsFromNames()
647 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000648
Georg Brandl15c5ce92007-03-07 09:09:40 +0000649 # "Similar to loadTestsFromName(), but takes a sequence of names rather
650 # than a single name."
651 #
652 # What happens if that sequence of names is empty?
653 def test_loadTestsFromNames__empty_name_list(self):
654 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000655
Georg Brandl15c5ce92007-03-07 09:09:40 +0000656 suite = loader.loadTestsFromNames([])
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000657 self.assertTrue(isinstance(suite, loader.suiteClass))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000658 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000659
Georg Brandl15c5ce92007-03-07 09:09:40 +0000660 # "Similar to loadTestsFromName(), but takes a sequence of names rather
661 # than a single name."
662 # ...
663 # "The method optionally resolves name relative to the given module"
664 #
665 # What happens if that sequence of names is empty?
666 #
667 # XXX Should this raise a ValueError or just return an empty TestSuite?
668 def test_loadTestsFromNames__relative_empty_name_list(self):
669 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000670
Georg Brandl15c5ce92007-03-07 09:09:40 +0000671 suite = loader.loadTestsFromNames([], unittest)
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000672 self.assertTrue(isinstance(suite, loader.suiteClass))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000673 self.assertEqual(list(suite), [])
674
675 # "The specifier name is a ``dotted name'' that may resolve either to
676 # a module, a test case class, a TestSuite instance, a test method
677 # within a test case class, or a callable object which returns a
678 # TestCase or TestSuite instance."
679 #
680 # Is ValueError raised in response to an empty name?
681 def test_loadTestsFromNames__empty_name(self):
682 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000683
Georg Brandl15c5ce92007-03-07 09:09:40 +0000684 try:
685 loader.loadTestsFromNames([''])
686 except ValueError, e:
687 self.assertEqual(str(e), "Empty module name")
688 else:
689 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000690
Georg Brandl15c5ce92007-03-07 09:09:40 +0000691 # "The specifier name is a ``dotted name'' that may resolve either to
692 # a module, a test case class, a TestSuite instance, a test method
693 # within a test case class, or a callable object which returns a
694 # TestCase or TestSuite instance."
695 #
Tim Petersea5962f2007-03-12 18:07:52 +0000696 # What happens when presented with an impossible module name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000697 def test_loadTestsFromNames__malformed_name(self):
698 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000699
Georg Brandl15c5ce92007-03-07 09:09:40 +0000700 # XXX Should this raise ValueError or ImportError?
701 try:
702 loader.loadTestsFromNames(['abc () //'])
703 except ValueError:
704 pass
705 except ImportError:
706 pass
707 else:
708 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000709
Georg Brandl15c5ce92007-03-07 09:09:40 +0000710 # "The specifier name is a ``dotted name'' that may resolve either to
711 # a module, a test case class, a TestSuite instance, a test method
712 # within a test case class, or a callable object which returns a
713 # TestCase or TestSuite instance."
714 #
Tim Petersea5962f2007-03-12 18:07:52 +0000715 # What happens when no module can be found for the given name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000716 def test_loadTestsFromNames__unknown_module_name(self):
717 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000718
Georg Brandl15c5ce92007-03-07 09:09:40 +0000719 try:
720 loader.loadTestsFromNames(['sdasfasfasdf'])
721 except ImportError, e:
722 self.assertEqual(str(e), "No module named sdasfasfasdf")
723 else:
724 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000725
Georg Brandl15c5ce92007-03-07 09:09:40 +0000726 # "The specifier name is a ``dotted name'' that may resolve either to
727 # a module, a test case class, a TestSuite instance, a test method
728 # within a test case class, or a callable object which returns a
729 # TestCase or TestSuite instance."
730 #
Tim Petersea5962f2007-03-12 18:07:52 +0000731 # What happens when the module can be found, but not the attribute?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000732 def test_loadTestsFromNames__unknown_attr_name(self):
733 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000734
Georg Brandl15c5ce92007-03-07 09:09:40 +0000735 try:
736 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
737 except AttributeError, e:
738 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
739 else:
740 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000741
Georg Brandl15c5ce92007-03-07 09:09:40 +0000742 # "The specifier name is a ``dotted name'' that may resolve either to
743 # a module, a test case class, a TestSuite instance, a test method
744 # within a test case class, or a callable object which returns a
745 # TestCase or TestSuite instance."
746 # ...
747 # "The method optionally resolves name relative to the given module"
748 #
749 # What happens when given an unknown attribute on a specified `module`
750 # argument?
751 def test_loadTestsFromNames__unknown_name_relative_1(self):
752 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000753
Georg Brandl15c5ce92007-03-07 09:09:40 +0000754 try:
755 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
756 except AttributeError, e:
757 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
758 else:
759 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000760
Georg Brandl15c5ce92007-03-07 09:09:40 +0000761 # "The specifier name is a ``dotted name'' that may resolve either to
762 # a module, a test case class, a TestSuite instance, a test method
763 # within a test case class, or a callable object which returns a
764 # TestCase or TestSuite instance."
765 # ...
766 # "The method optionally resolves name relative to the given module"
767 #
768 # Do unknown attributes (relative to a provided module) still raise an
Tim Petersea5962f2007-03-12 18:07:52 +0000769 # exception even in the presence of valid attribute names?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000770 def test_loadTestsFromNames__unknown_name_relative_2(self):
771 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000772
Georg Brandl15c5ce92007-03-07 09:09:40 +0000773 try:
774 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
775 except AttributeError, e:
776 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
777 else:
778 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
779
780 # "The specifier name is a ``dotted name'' that may resolve either to
781 # a module, a test case class, a TestSuite instance, a test method
782 # within a test case class, or a callable object which returns a
783 # TestCase or TestSuite instance."
784 # ...
785 # "The method optionally resolves name relative to the given module"
786 #
787 # What happens when faced with the empty string?
788 #
789 # XXX This currently raises AttributeError, though ValueError is probably
790 # more appropriate
791 def test_loadTestsFromNames__relative_empty_name(self):
792 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000793
Georg Brandl15c5ce92007-03-07 09:09:40 +0000794 try:
795 loader.loadTestsFromNames([''], unittest)
796 except AttributeError:
797 pass
798 else:
799 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000800
Georg Brandl15c5ce92007-03-07 09:09:40 +0000801 # "The specifier name is a ``dotted name'' that may resolve either to
802 # a module, a test case class, a TestSuite instance, a test method
803 # within a test case class, or a callable object which returns a
804 # TestCase or TestSuite instance."
805 # ...
806 # "The method optionally resolves name relative to the given module"
807 #
Tim Petersea5962f2007-03-12 18:07:52 +0000808 # What happens when presented with an impossible attribute name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000809 def test_loadTestsFromNames__relative_malformed_name(self):
810 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000811
Georg Brandl15c5ce92007-03-07 09:09:40 +0000812 # XXX Should this raise AttributeError or ValueError?
813 try:
814 loader.loadTestsFromNames(['abc () //'], unittest)
815 except AttributeError:
816 pass
817 except ValueError:
818 pass
819 else:
820 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
821
822 # "The method optionally resolves name relative to the given module"
823 #
824 # Does loadTestsFromNames() make sure the provided `module` is in fact
825 # a module?
826 #
827 # XXX This validation is currently not done. This flexibility should
828 # either be documented or a TypeError should be raised.
829 def test_loadTestsFromNames__relative_not_a_module(self):
830 class MyTestCase(unittest.TestCase):
831 def test(self):
832 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000833
Georg Brandl15c5ce92007-03-07 09:09:40 +0000834 class NotAModule(object):
835 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000836
Georg Brandl15c5ce92007-03-07 09:09:40 +0000837 loader = unittest.TestLoader()
838 suite = loader.loadTestsFromNames(['test_2'], NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000839
Georg Brandl15c5ce92007-03-07 09:09:40 +0000840 reference = [unittest.TestSuite([MyTestCase('test')])]
841 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000842
Georg Brandl15c5ce92007-03-07 09:09:40 +0000843 # "The specifier name is a ``dotted name'' that may resolve either to
844 # a module, a test case class, a TestSuite instance, a test method
845 # within a test case class, or a callable object which returns a
846 # TestCase or TestSuite instance."
847 #
848 # Does it raise an exception if the name resolves to an invalid
849 # object?
850 def test_loadTestsFromNames__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000851 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000852 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000853
Georg Brandl15c5ce92007-03-07 09:09:40 +0000854 loader = unittest.TestLoader()
855 try:
856 loader.loadTestsFromNames(['testcase_1'], m)
857 except TypeError:
858 pass
859 else:
860 self.fail("Should have raised TypeError")
861
862 # "The specifier name is a ``dotted name'' that may resolve ... to
863 # ... a test case class"
864 def test_loadTestsFromNames__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000865 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000866 class MyTestCase(unittest.TestCase):
867 def test(self):
868 pass
869 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000870
Georg Brandl15c5ce92007-03-07 09:09:40 +0000871 loader = unittest.TestLoader()
872 suite = loader.loadTestsFromNames(['testcase_1'], m)
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000873 self.assertTrue(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000874
Georg Brandl15c5ce92007-03-07 09:09:40 +0000875 expected = loader.suiteClass([MyTestCase('test')])
876 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000877
Georg Brandl15c5ce92007-03-07 09:09:40 +0000878 # "The specifier name is a ``dotted name'' that may resolve ... to
879 # ... a TestSuite instance"
880 def test_loadTestsFromNames__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000881 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000882 class MyTestCase(unittest.TestCase):
883 def test(self):
884 pass
885 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000886
Georg Brandl15c5ce92007-03-07 09:09:40 +0000887 loader = unittest.TestLoader()
888 suite = loader.loadTestsFromNames(['testsuite'], m)
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000889 self.assertTrue(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000890
Georg Brandl15c5ce92007-03-07 09:09:40 +0000891 self.assertEqual(list(suite), [m.testsuite])
Tim Petersea5962f2007-03-12 18:07:52 +0000892
Georg Brandl15c5ce92007-03-07 09:09:40 +0000893 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
894 # test method within a test case class"
895 def test_loadTestsFromNames__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000896 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000897 class MyTestCase(unittest.TestCase):
898 def test(self):
899 pass
900 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000901
Georg Brandl15c5ce92007-03-07 09:09:40 +0000902 loader = unittest.TestLoader()
903 suite = loader.loadTestsFromNames(['testcase_1.test'], m)
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000904 self.assertTrue(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000905
Georg Brandl15c5ce92007-03-07 09:09:40 +0000906 ref_suite = unittest.TestSuite([MyTestCase('test')])
907 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000908
Georg Brandl15c5ce92007-03-07 09:09:40 +0000909 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
910 # test method within a test case class"
911 #
912 # Does the method gracefully handle names that initially look like they
Tim Petersea5962f2007-03-12 18:07:52 +0000913 # resolve to "a test method within a test case class" but don't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000914 def test_loadTestsFromNames__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000915 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000916 class MyTestCase(unittest.TestCase):
917 def test(self):
918 pass
919 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000920
Georg Brandl15c5ce92007-03-07 09:09:40 +0000921 loader = unittest.TestLoader()
922 try:
923 loader.loadTestsFromNames(['testcase_1.testfoo'], m)
924 except AttributeError, e:
925 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
926 else:
927 self.fail("Failed to raise AttributeError")
928
929 # "The specifier name is a ``dotted name'' that may resolve ... to
930 # ... a callable object which returns a ... TestSuite instance"
931 def test_loadTestsFromNames__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000932 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000933 testcase_1 = unittest.FunctionTestCase(lambda: None)
934 testcase_2 = unittest.FunctionTestCase(lambda: None)
935 def return_TestSuite():
936 return unittest.TestSuite([testcase_1, testcase_2])
937 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000938
Georg Brandl15c5ce92007-03-07 09:09:40 +0000939 loader = unittest.TestLoader()
940 suite = loader.loadTestsFromNames(['return_TestSuite'], m)
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000941 self.assertTrue(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000942
Georg Brandl15c5ce92007-03-07 09:09:40 +0000943 expected = unittest.TestSuite([testcase_1, testcase_2])
944 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000945
Georg Brandl15c5ce92007-03-07 09:09:40 +0000946 # "The specifier name is a ``dotted name'' that may resolve ... to
947 # ... a callable object which returns a TestCase ... instance"
948 def test_loadTestsFromNames__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000949 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000950 testcase_1 = unittest.FunctionTestCase(lambda: None)
951 def return_TestCase():
952 return testcase_1
953 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000954
Georg Brandl15c5ce92007-03-07 09:09:40 +0000955 loader = unittest.TestLoader()
956 suite = loader.loadTestsFromNames(['return_TestCase'], m)
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000957 self.assertTrue(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000958
Georg Brandl15c5ce92007-03-07 09:09:40 +0000959 ref_suite = unittest.TestSuite([testcase_1])
960 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000961
Georg Brandl15c5ce92007-03-07 09:09:40 +0000962 # "The specifier name is a ``dotted name'' that may resolve ... to
963 # ... a callable object which returns a TestCase or TestSuite instance"
964 #
Tim Petersea5962f2007-03-12 18:07:52 +0000965 # Are staticmethods handled correctly?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000966 def test_loadTestsFromNames__callable__call_staticmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000967 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000968 class Test1(unittest.TestCase):
969 def test(self):
970 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000971
Georg Brandl15c5ce92007-03-07 09:09:40 +0000972 testcase_1 = Test1('test')
973 class Foo(unittest.TestCase):
974 @staticmethod
975 def foo():
976 return testcase_1
977 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +0000978
Georg Brandl15c5ce92007-03-07 09:09:40 +0000979 loader = unittest.TestLoader()
980 suite = loader.loadTestsFromNames(['Foo.foo'], m)
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000981 self.assertTrue(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000982
Georg Brandl15c5ce92007-03-07 09:09:40 +0000983 ref_suite = unittest.TestSuite([testcase_1])
984 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000985
Georg Brandl15c5ce92007-03-07 09:09:40 +0000986 # "The specifier name is a ``dotted name'' that may resolve ... to
987 # ... a callable object which returns a TestCase or TestSuite instance"
988 #
989 # What happens when the callable returns something else?
990 def test_loadTestsFromNames__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000991 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000992 def return_wrong():
993 return 6
994 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000995
Georg Brandl15c5ce92007-03-07 09:09:40 +0000996 loader = unittest.TestLoader()
997 try:
998 suite = loader.loadTestsFromNames(['return_wrong'], m)
999 except TypeError:
1000 pass
1001 else:
1002 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +00001003
Georg Brandl15c5ce92007-03-07 09:09:40 +00001004 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +00001005 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001006 def test_loadTestsFromNames__module_not_loaded(self):
1007 # We're going to try to load this module as a side-effect, so it
1008 # better not be loaded before we try.
1009 #
1010 # Why pick audioop? Google shows it isn't used very often, so there's
1011 # a good chance that it won't be imported when this test is run
1012 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +00001013
Georg Brandl15c5ce92007-03-07 09:09:40 +00001014 import sys
1015 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
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001022 self.assertTrue(isinstance(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()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001026 self.assertTrue(module_name in 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
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001800 self.assertTrue(isinstance(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):
1962 import sys
Tim Petersea5962f2007-03-12 18:07:52 +00001963
Georg Brandl15c5ce92007-03-07 09:09:40 +00001964 class Foo(unittest.TestCase):
1965 def test_1(self):
1966 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001967
Georg Brandl15c5ce92007-03-07 09:09:40 +00001968 test = Foo('test_1')
1969 try:
1970 test.fail("foo")
1971 except:
1972 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00001973
Georg Brandl15c5ce92007-03-07 09:09:40 +00001974 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001975
Georg Brandl15c5ce92007-03-07 09:09:40 +00001976 result.startTest(test)
1977 result.addFailure(test, exc_info_tuple)
1978 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001979
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001980 self.assertFalse(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001981 self.assertEqual(len(result.errors), 0)
1982 self.assertEqual(len(result.failures), 1)
1983 self.assertEqual(result.testsRun, 1)
1984 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001985
Georg Brandl15c5ce92007-03-07 09:09:40 +00001986 test_case, formatted_exc = result.failures[0]
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001987 self.assertTrue(test_case is test)
1988 self.assertTrue(isinstance(formatted_exc, str))
Tim Petersea5962f2007-03-12 18:07:52 +00001989
Georg Brandl15c5ce92007-03-07 09:09:40 +00001990 # "addError(test, err)"
1991 # ...
1992 # "Called when the test case test raises an unexpected exception err
1993 # is a tuple of the form returned by sys.exc_info():
1994 # (type, value, traceback)"
1995 # ...
1996 # "wasSuccessful() - Returns True if all tests run so far have passed,
1997 # otherwise returns False"
1998 # ...
1999 # "testsRun - The total number of tests run so far."
2000 # ...
2001 # "errors - A list containing 2-tuples of TestCase instances and
2002 # formatted tracebacks. Each tuple represents a test which raised an
2003 # unexpected exception. Contains formatted
2004 # tracebacks instead of sys.exc_info() results."
2005 # ...
2006 # "failures - A list containing 2-tuples of TestCase instances and
2007 # formatted tracebacks. Each tuple represents a test where a failure was
2008 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
2009 # methods. Contains formatted tracebacks instead
2010 # of sys.exc_info() results."
2011 def test_addError(self):
2012 import sys
Tim Petersea5962f2007-03-12 18:07:52 +00002013
Georg Brandl15c5ce92007-03-07 09:09:40 +00002014 class Foo(unittest.TestCase):
2015 def test_1(self):
2016 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002017
Georg Brandl15c5ce92007-03-07 09:09:40 +00002018 test = Foo('test_1')
2019 try:
2020 raise TypeError()
2021 except:
2022 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00002023
Georg Brandl15c5ce92007-03-07 09:09:40 +00002024 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00002025
Georg Brandl15c5ce92007-03-07 09:09:40 +00002026 result.startTest(test)
2027 result.addError(test, exc_info_tuple)
2028 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00002029
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002030 self.assertFalse(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00002031 self.assertEqual(len(result.errors), 1)
2032 self.assertEqual(len(result.failures), 0)
2033 self.assertEqual(result.testsRun, 1)
2034 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00002035
Georg Brandl15c5ce92007-03-07 09:09:40 +00002036 test_case, formatted_exc = result.errors[0]
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002037 self.assertTrue(test_case is test)
2038 self.assertTrue(isinstance(formatted_exc, str))
Georg Brandl15c5ce92007-03-07 09:09:40 +00002039
2040### Support code for Test_TestCase
2041################################################################
2042
2043class Foo(unittest.TestCase):
2044 def runTest(self): pass
2045 def test1(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002046
Georg Brandl15c5ce92007-03-07 09:09:40 +00002047class Bar(Foo):
2048 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002049
Michael Foord07ef4872009-05-02 22:43:34 +00002050class LoggingTestCase(unittest.TestCase):
2051 """A test case which logs its calls."""
2052
2053 def __init__(self, events):
2054 super(LoggingTestCase, self).__init__('test')
2055 self.events = events
2056
2057 def setUp(self):
2058 self.events.append('setUp')
2059
2060 def test(self):
2061 self.events.append('test')
2062
2063 def tearDown(self):
2064 self.events.append('tearDown')
2065
2066class ResultWithNoStartTestRunStopTestRun(object):
2067 """An object honouring TestResult before startTestRun/stopTestRun."""
2068
2069 def __init__(self):
2070 self.failures = []
2071 self.errors = []
2072 self.testsRun = 0
2073 self.skipped = []
2074 self.expectedFailures = []
2075 self.unexpectedSuccesses = []
2076 self.shouldStop = False
2077
2078 def startTest(self, test):
2079 pass
2080
2081 def stopTest(self, test):
2082 pass
2083
2084 def addError(self, test):
2085 pass
2086
2087 def addFailure(self, test):
2088 pass
2089
2090 def addSuccess(self, test):
2091 pass
2092
2093 def wasSuccessful(self):
2094 return True
2095
2096
Georg Brandl15c5ce92007-03-07 09:09:40 +00002097################################################################
2098### /Support code for Test_TestCase
2099
2100class Test_TestCase(TestCase, TestEquality, TestHashing):
2101
2102 ### Set up attributes used by inherited tests
2103 ################################################################
2104
2105 # Used by TestHashing.test_hash and TestEquality.test_eq
2106 eq_pairs = [(Foo('test1'), Foo('test1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002107
Georg Brandl15c5ce92007-03-07 09:09:40 +00002108 # Used by TestEquality.test_ne
2109 ne_pairs = [(Foo('test1'), Foo('runTest'))
2110 ,(Foo('test1'), Bar('test1'))
2111 ,(Foo('test1'), Bar('test2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002112
Georg Brandl15c5ce92007-03-07 09:09:40 +00002113 ################################################################
2114 ### /Set up attributes used by inherited tests
Tim Petersea5962f2007-03-12 18:07:52 +00002115
Georg Brandl15c5ce92007-03-07 09:09:40 +00002116
2117 # "class TestCase([methodName])"
2118 # ...
2119 # "Each instance of TestCase will run a single test method: the
2120 # method named methodName."
2121 # ...
2122 # "methodName defaults to "runTest"."
2123 #
2124 # Make sure it really is optional, and that it defaults to the proper
2125 # thing.
2126 def test_init__no_test_name(self):
2127 class Test(unittest.TestCase):
2128 def runTest(self): raise MyException()
2129 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002130
Georg Brandl15c5ce92007-03-07 09:09:40 +00002131 self.assertEqual(Test().id()[-13:], '.Test.runTest')
Tim Petersea5962f2007-03-12 18:07:52 +00002132
Georg Brandl15c5ce92007-03-07 09:09:40 +00002133 # "class TestCase([methodName])"
2134 # ...
2135 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002136 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002137 def test_init__test_name__valid(self):
2138 class Test(unittest.TestCase):
2139 def runTest(self): raise MyException()
2140 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002141
Georg Brandl15c5ce92007-03-07 09:09:40 +00002142 self.assertEqual(Test('test').id()[-10:], '.Test.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002143
Georg Brandl15c5ce92007-03-07 09:09:40 +00002144 # "class TestCase([methodName])"
2145 # ...
2146 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002147 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002148 def test_init__test_name__invalid(self):
2149 class Test(unittest.TestCase):
2150 def runTest(self): raise MyException()
2151 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002152
Georg Brandl15c5ce92007-03-07 09:09:40 +00002153 try:
2154 Test('testfoo')
2155 except ValueError:
2156 pass
2157 else:
2158 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +00002159
Georg Brandl15c5ce92007-03-07 09:09:40 +00002160 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00002161 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00002162 def test_countTestCases(self):
2163 class Foo(unittest.TestCase):
2164 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002165
Georg Brandl15c5ce92007-03-07 09:09:40 +00002166 self.assertEqual(Foo('test').countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00002167
Georg Brandl15c5ce92007-03-07 09:09:40 +00002168 # "Return the default type of test result object to be used to run this
2169 # test. For TestCase instances, this will always be
2170 # unittest.TestResult; subclasses of TestCase should
2171 # override this as necessary."
2172 def test_defaultTestResult(self):
2173 class Foo(unittest.TestCase):
2174 def runTest(self):
2175 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002176
Georg Brandl15c5ce92007-03-07 09:09:40 +00002177 result = Foo().defaultTestResult()
2178 self.assertEqual(type(result), unittest.TestResult)
2179
2180 # "When a setUp() method is defined, the test runner will run that method
2181 # prior to each test. Likewise, if a tearDown() method is defined, the
2182 # test runner will invoke that method after each test. In the example,
2183 # setUp() was used to create a fresh sequence for each test."
2184 #
2185 # Make sure the proper call order is maintained, even if setUp() raises
2186 # an exception.
2187 def test_run_call_order__error_in_setUp(self):
2188 events = []
2189 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002190
Michael Foord07ef4872009-05-02 22:43:34 +00002191 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002192 def setUp(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002193 super(Foo, self).setUp()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002194 raise RuntimeError('raised by Foo.setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002195
Michael Foord07ef4872009-05-02 22:43:34 +00002196 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002197 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2198 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002199
Michael Foord07ef4872009-05-02 22:43:34 +00002200 # "With a temporary result stopTestRun is called when setUp errors.
2201 def test_run_call_order__error_in_setUp_default_result(self):
2202 events = []
2203
2204 class Foo(LoggingTestCase):
2205 def defaultTestResult(self):
2206 return LoggingResult(self.events)
2207
2208 def setUp(self):
2209 super(Foo, self).setUp()
2210 raise RuntimeError('raised by Foo.setUp')
2211
2212 Foo(events).run()
2213 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2214 'stopTest', 'stopTestRun']
2215 self.assertEqual(events, expected)
2216
Georg Brandl15c5ce92007-03-07 09:09:40 +00002217 # "When a setUp() method is defined, the test runner will run that method
2218 # prior to each test. Likewise, if a tearDown() method is defined, the
2219 # test runner will invoke that method after each test. In the example,
2220 # setUp() was used to create a fresh sequence for each test."
2221 #
2222 # Make sure the proper call order is maintained, even if the test raises
2223 # an error (as opposed to a failure).
2224 def test_run_call_order__error_in_test(self):
2225 events = []
2226 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002227
Michael Foord07ef4872009-05-02 22:43:34 +00002228 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002229 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002230 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002231 raise RuntimeError('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002232
Georg Brandl15c5ce92007-03-07 09:09:40 +00002233 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2234 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002235 Foo(events).run(result)
2236 self.assertEqual(events, expected)
2237
2238 # "With a default result, an error in the test still results in stopTestRun
2239 # being called."
2240 def test_run_call_order__error_in_test_default_result(self):
2241 events = []
2242
2243 class Foo(LoggingTestCase):
2244 def defaultTestResult(self):
2245 return LoggingResult(self.events)
2246
2247 def test(self):
2248 super(Foo, self).test()
2249 raise RuntimeError('raised by Foo.test')
2250
2251 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2252 'tearDown', 'stopTest', 'stopTestRun']
2253 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002254 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002255
Georg Brandl15c5ce92007-03-07 09:09:40 +00002256 # "When a setUp() method is defined, the test runner will run that method
2257 # prior to each test. Likewise, if a tearDown() method is defined, the
2258 # test runner will invoke that method after each test. In the example,
2259 # setUp() was used to create a fresh sequence for each test."
2260 #
2261 # Make sure the proper call order is maintained, even if the test signals
2262 # a failure (as opposed to an error).
2263 def test_run_call_order__failure_in_test(self):
2264 events = []
2265 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002266
Michael Foord07ef4872009-05-02 22:43:34 +00002267 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002268 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002269 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002270 self.fail('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002271
Georg Brandl15c5ce92007-03-07 09:09:40 +00002272 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2273 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002274 Foo(events).run(result)
2275 self.assertEqual(events, expected)
2276
2277 # "When a test fails with a default result stopTestRun is still called."
2278 def test_run_call_order__failure_in_test_default_result(self):
2279
2280 class Foo(LoggingTestCase):
2281 def defaultTestResult(self):
2282 return LoggingResult(self.events)
2283 def test(self):
2284 super(Foo, self).test()
2285 self.fail('raised by Foo.test')
2286
2287 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2288 'tearDown', 'stopTest', 'stopTestRun']
2289 events = []
2290 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002291 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002292
Georg Brandl15c5ce92007-03-07 09:09:40 +00002293 # "When a setUp() method is defined, the test runner will run that method
2294 # prior to each test. Likewise, if a tearDown() method is defined, the
2295 # test runner will invoke that method after each test. In the example,
2296 # setUp() was used to create a fresh sequence for each test."
2297 #
2298 # Make sure the proper call order is maintained, even if tearDown() raises
2299 # an exception.
2300 def test_run_call_order__error_in_tearDown(self):
2301 events = []
2302 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002303
Michael Foord07ef4872009-05-02 22:43:34 +00002304 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002305 def tearDown(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002306 super(Foo, self).tearDown()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002307 raise RuntimeError('raised by Foo.tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002308
Michael Foord07ef4872009-05-02 22:43:34 +00002309 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002310 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2311 'stopTest']
2312 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002313
Michael Foord07ef4872009-05-02 22:43:34 +00002314 # "When tearDown errors with a default result stopTestRun is still called."
2315 def test_run_call_order__error_in_tearDown_default_result(self):
2316
2317 class Foo(LoggingTestCase):
2318 def defaultTestResult(self):
2319 return LoggingResult(self.events)
2320 def tearDown(self):
2321 super(Foo, self).tearDown()
2322 raise RuntimeError('raised by Foo.tearDown')
2323
2324 events = []
2325 Foo(events).run()
2326 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2327 'addError', 'stopTest', 'stopTestRun']
2328 self.assertEqual(events, expected)
2329
2330 # "TestCase.run() still works when the defaultTestResult is a TestResult
2331 # that does not support startTestRun and stopTestRun.
2332 def test_run_call_order_default_result(self):
2333
2334 class Foo(unittest.TestCase):
2335 def defaultTestResult(self):
2336 return ResultWithNoStartTestRunStopTestRun()
2337 def test(self):
2338 pass
2339
2340 Foo('test').run()
2341
Georg Brandl15c5ce92007-03-07 09:09:40 +00002342 # "This class attribute gives the exception raised by the test() method.
2343 # If a test framework needs to use a specialized exception, possibly to
2344 # carry additional information, it must subclass this exception in
2345 # order to ``play fair'' with the framework. The initial value of this
2346 # attribute is AssertionError"
2347 def test_failureException__default(self):
2348 class Foo(unittest.TestCase):
2349 def test(self):
2350 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002351
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002352 self.assertTrue(Foo('test').failureException is AssertionError)
Tim Petersea5962f2007-03-12 18:07:52 +00002353
Georg Brandl15c5ce92007-03-07 09:09:40 +00002354 # "This class attribute gives the exception raised by the test() method.
2355 # If a test framework needs to use a specialized exception, possibly to
2356 # carry additional information, it must subclass this exception in
2357 # order to ``play fair'' with the framework."
2358 #
2359 # Make sure TestCase.run() respects the designated failureException
2360 def test_failureException__subclassing__explicit_raise(self):
2361 events = []
2362 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002363
Georg Brandl15c5ce92007-03-07 09:09:40 +00002364 class Foo(unittest.TestCase):
2365 def test(self):
2366 raise RuntimeError()
Tim Petersea5962f2007-03-12 18:07:52 +00002367
Georg Brandl15c5ce92007-03-07 09:09:40 +00002368 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002369
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002370 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002371
2372
Georg Brandl15c5ce92007-03-07 09:09:40 +00002373 Foo('test').run(result)
2374 expected = ['startTest', 'addFailure', 'stopTest']
2375 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002376
Georg Brandl15c5ce92007-03-07 09:09:40 +00002377 # "This class attribute gives the exception raised by the test() method.
2378 # If a test framework needs to use a specialized exception, possibly to
2379 # carry additional information, it must subclass this exception in
2380 # order to ``play fair'' with the framework."
2381 #
2382 # Make sure TestCase.run() respects the designated failureException
2383 def test_failureException__subclassing__implicit_raise(self):
2384 events = []
2385 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002386
Georg Brandl15c5ce92007-03-07 09:09:40 +00002387 class Foo(unittest.TestCase):
2388 def test(self):
2389 self.fail("foo")
Tim Petersea5962f2007-03-12 18:07:52 +00002390
Georg Brandl15c5ce92007-03-07 09:09:40 +00002391 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002392
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002393 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002394
2395
Georg Brandl15c5ce92007-03-07 09:09:40 +00002396 Foo('test').run(result)
2397 expected = ['startTest', 'addFailure', 'stopTest']
2398 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002399
2400 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002401 def test_setUp(self):
2402 class Foo(unittest.TestCase):
2403 def runTest(self):
2404 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002405
Georg Brandl15c5ce92007-03-07 09:09:40 +00002406 # ... and nothing should happen
2407 Foo().setUp()
Tim Petersea5962f2007-03-12 18:07:52 +00002408
2409 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002410 def test_tearDown(self):
2411 class Foo(unittest.TestCase):
2412 def runTest(self):
2413 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002414
Georg Brandl15c5ce92007-03-07 09:09:40 +00002415 # ... and nothing should happen
2416 Foo().tearDown()
Tim Petersea5962f2007-03-12 18:07:52 +00002417
Georg Brandl15c5ce92007-03-07 09:09:40 +00002418 # "Return a string identifying the specific test case."
2419 #
2420 # Because of the vague nature of the docs, I'm not going to lock this
2421 # test down too much. Really all that can be asserted is that the id()
2422 # will be a string (either 8-byte or unicode -- again, because the docs
2423 # just say "string")
2424 def test_id(self):
2425 class Foo(unittest.TestCase):
2426 def runTest(self):
2427 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002428
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002429 self.assertTrue(isinstance(Foo().id(), basestring))
Tim Petersea5962f2007-03-12 18:07:52 +00002430
Georg Brandl15c5ce92007-03-07 09:09:40 +00002431 # "If result is omitted or None, a temporary result object is created
Michael Foord07ef4872009-05-02 22:43:34 +00002432 # and used, but is not made available to the caller. As TestCase owns the
2433 # temporary result startTestRun and stopTestRun are called.
2434
Georg Brandl15c5ce92007-03-07 09:09:40 +00002435 def test_run__uses_defaultTestResult(self):
2436 events = []
Tim Petersea5962f2007-03-12 18:07:52 +00002437
Georg Brandl15c5ce92007-03-07 09:09:40 +00002438 class Foo(unittest.TestCase):
2439 def test(self):
2440 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002441
Georg Brandl15c5ce92007-03-07 09:09:40 +00002442 def defaultTestResult(self):
2443 return LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002444
2445 # Make run() find a result object on its own
Georg Brandl15c5ce92007-03-07 09:09:40 +00002446 Foo('test').run()
Tim Petersea5962f2007-03-12 18:07:52 +00002447
Michael Foord07ef4872009-05-02 22:43:34 +00002448 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2449 'stopTest', 'stopTestRun']
Georg Brandl15c5ce92007-03-07 09:09:40 +00002450 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002451
Gregory P. Smith28399852009-03-31 16:54:10 +00002452 def testShortDescriptionWithoutDocstring(self):
2453 self.assertEqual(
2454 self.shortDescription(),
2455 'testShortDescriptionWithoutDocstring (' + __name__ +
2456 '.Test_TestCase)')
2457
2458 def testShortDescriptionWithOneLineDocstring(self):
2459 """Tests shortDescription() for a method with a docstring."""
2460 self.assertEqual(
2461 self.shortDescription(),
2462 ('testShortDescriptionWithOneLineDocstring '
2463 '(' + __name__ + '.Test_TestCase)\n'
2464 'Tests shortDescription() for a method with a docstring.'))
2465
2466 def testShortDescriptionWithMultiLineDocstring(self):
2467 """Tests shortDescription() for a method with a longer docstring.
2468
2469 This method ensures that only the first line of a docstring is
2470 returned used in the short description, no matter how long the
2471 whole thing is.
2472 """
2473 self.assertEqual(
2474 self.shortDescription(),
2475 ('testShortDescriptionWithMultiLineDocstring '
2476 '(' + __name__ + '.Test_TestCase)\n'
2477 'Tests shortDescription() for a method with a longer '
2478 'docstring.'))
2479
Gregory P. Smith28399852009-03-31 16:54:10 +00002480 def testAddTypeEqualityFunc(self):
2481 class SadSnake(object):
2482 """Dummy class for test_addTypeEqualityFunc."""
2483 s1, s2 = SadSnake(), SadSnake()
2484 self.assertFalse(s1 == s2)
2485 def AllSnakesCreatedEqual(a, b, msg=None):
2486 return type(a) == type(b) == SadSnake
2487 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2488 self.assertEqual(s1, s2)
2489 # No this doesn't clean up and remove the SadSnake equality func
2490 # from this TestCase instance but since its a local nothing else
2491 # will ever notice that.
2492
Michael Foordf2dfef12009-04-05 19:19:28 +00002493 def testAssertIs(self):
2494 thing = object()
2495 self.assertIs(thing, thing)
2496 self.assertRaises(self.failureException, self.assertIs, thing, object())
2497
2498 def testAssertIsNot(self):
2499 thing = object()
2500 self.assertIsNot(thing, object())
2501 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2502
Georg Brandlf895cf52009-10-01 20:59:31 +00002503 def testAssertIsInstance(self):
2504 thing = []
2505 self.assertIsInstance(thing, list)
2506 self.assertRaises(self.failureException, self.assertIsInstance,
2507 thing, dict)
2508
2509 def testAssertNotIsInstance(self):
2510 thing = []
2511 self.assertNotIsInstance(thing, dict)
2512 self.assertRaises(self.failureException, self.assertNotIsInstance,
2513 thing, list)
2514
Gregory P. Smith28399852009-03-31 16:54:10 +00002515 def testAssertIn(self):
2516 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2517
2518 self.assertIn('a', 'abc')
2519 self.assertIn(2, [1, 2, 3])
2520 self.assertIn('monkey', animals)
2521
2522 self.assertNotIn('d', 'abc')
2523 self.assertNotIn(0, [1, 2, 3])
2524 self.assertNotIn('otter', animals)
2525
2526 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2527 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2528 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2529 animals)
2530
2531 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2532 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2533 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2534 animals)
2535
2536 def testAssertDictContainsSubset(self):
2537 self.assertDictContainsSubset({}, {})
2538 self.assertDictContainsSubset({}, {'a': 1})
2539 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2540 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2541 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2542
2543 self.assertRaises(unittest.TestCase.failureException,
2544 self.assertDictContainsSubset, {'a': 2}, {'a': 1},
2545 '.*Mismatched values:.*')
2546
2547 self.assertRaises(unittest.TestCase.failureException,
2548 self.assertDictContainsSubset, {'c': 1}, {'a': 1},
2549 '.*Missing:.*')
2550
2551 self.assertRaises(unittest.TestCase.failureException,
2552 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2553 {'a': 1}, '.*Missing:.*')
2554
2555 self.assertRaises(unittest.TestCase.failureException,
2556 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2557 {'a': 1}, '.*Missing:.*Mismatched values:.*')
2558
2559 def testAssertEqual(self):
2560 equal_pairs = [
2561 ((), ()),
2562 ({}, {}),
2563 ([], []),
2564 (set(), set()),
2565 (frozenset(), frozenset())]
2566 for a, b in equal_pairs:
2567 # This mess of try excepts is to test the assertEqual behavior
2568 # itself.
2569 try:
2570 self.assertEqual(a, b)
2571 except self.failureException:
2572 self.fail('assertEqual(%r, %r) failed' % (a, b))
2573 try:
2574 self.assertEqual(a, b, msg='foo')
2575 except self.failureException:
2576 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2577 try:
2578 self.assertEqual(a, b, 'foo')
2579 except self.failureException:
2580 self.fail('assertEqual(%r, %r) with third parameter failed' %
2581 (a, b))
2582
2583 unequal_pairs = [
2584 ((), []),
2585 ({}, set()),
2586 (set([4,1]), frozenset([4,2])),
2587 (frozenset([4,5]), set([2,3])),
2588 (set([3,4]), set([5,4]))]
2589 for a, b in unequal_pairs:
2590 self.assertRaises(self.failureException, self.assertEqual, a, b)
2591 self.assertRaises(self.failureException, self.assertEqual, a, b,
2592 'foo')
2593 self.assertRaises(self.failureException, self.assertEqual, a, b,
2594 msg='foo')
2595
2596 def testEquality(self):
2597 self.assertListEqual([], [])
2598 self.assertTupleEqual((), ())
2599 self.assertSequenceEqual([], ())
2600
2601 a = [0, 'a', []]
2602 b = []
2603 self.assertRaises(unittest.TestCase.failureException,
2604 self.assertListEqual, a, b)
2605 self.assertRaises(unittest.TestCase.failureException,
2606 self.assertListEqual, tuple(a), tuple(b))
2607 self.assertRaises(unittest.TestCase.failureException,
2608 self.assertSequenceEqual, a, tuple(b))
2609
2610 b.extend(a)
2611 self.assertListEqual(a, b)
2612 self.assertTupleEqual(tuple(a), tuple(b))
2613 self.assertSequenceEqual(a, tuple(b))
2614 self.assertSequenceEqual(tuple(a), b)
2615
2616 self.assertRaises(self.failureException, self.assertListEqual,
2617 a, tuple(b))
2618 self.assertRaises(self.failureException, self.assertTupleEqual,
2619 tuple(a), b)
2620 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2621 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2622 tuple(b))
2623 self.assertRaises(self.failureException, self.assertSequenceEqual,
2624 None, tuple(b))
2625 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2626 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2627 self.assertRaises(self.failureException, self.assertSequenceEqual,
2628 1, 1)
2629
2630 self.assertDictEqual({}, {})
2631
2632 c = { 'x': 1 }
2633 d = {}
2634 self.assertRaises(unittest.TestCase.failureException,
2635 self.assertDictEqual, c, d)
2636
2637 d.update(c)
2638 self.assertDictEqual(c, d)
2639
2640 d['x'] = 0
2641 self.assertRaises(unittest.TestCase.failureException,
2642 self.assertDictEqual, c, d, 'These are unequal')
2643
2644 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2645 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2646 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2647
2648 self.assertSameElements([1, 2, 3], [3, 2, 1])
2649 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2650 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2651 self.assertRaises(self.failureException, self.assertSameElements,
2652 [10], [10, 11])
2653 self.assertRaises(self.failureException, self.assertSameElements,
2654 [10, 11], [10])
2655
2656 # Test that sequences of unhashable objects can be tested for sameness:
2657 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Michael Foordf2dfef12009-04-05 19:19:28 +00002658
Gregory P. Smith28399852009-03-31 16:54:10 +00002659 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2660 self.assertRaises(self.failureException, self.assertSameElements,
2661 [[1]], [[2]])
2662
2663 def testAssertSetEqual(self):
2664 set1 = set()
2665 set2 = set()
2666 self.assertSetEqual(set1, set2)
2667
2668 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2669 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2670 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2671 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2672
2673 set1 = set(['a'])
2674 set2 = set()
2675 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2676
2677 set1 = set(['a'])
2678 set2 = set(['a'])
2679 self.assertSetEqual(set1, set2)
2680
2681 set1 = set(['a'])
2682 set2 = set(['a', 'b'])
2683 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2684
2685 set1 = set(['a'])
2686 set2 = frozenset(['a', 'b'])
2687 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2688
2689 set1 = set(['a', 'b'])
2690 set2 = frozenset(['a', 'b'])
2691 self.assertSetEqual(set1, set2)
2692
2693 set1 = set()
2694 set2 = "foo"
2695 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2696 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2697
2698 # make sure any string formatting is tuple-safe
2699 set1 = set([(0, 1), (2, 3)])
2700 set2 = set([(4, 5)])
2701 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2702
2703 def testInequality(self):
2704 # Try ints
2705 self.assertGreater(2, 1)
2706 self.assertGreaterEqual(2, 1)
2707 self.assertGreaterEqual(1, 1)
2708 self.assertLess(1, 2)
2709 self.assertLessEqual(1, 2)
2710 self.assertLessEqual(1, 1)
2711 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2712 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2713 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2714 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2715 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2716 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2717
2718 # Try Floats
2719 self.assertGreater(1.1, 1.0)
2720 self.assertGreaterEqual(1.1, 1.0)
2721 self.assertGreaterEqual(1.0, 1.0)
2722 self.assertLess(1.0, 1.1)
2723 self.assertLessEqual(1.0, 1.1)
2724 self.assertLessEqual(1.0, 1.0)
2725 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2726 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2727 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2728 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2729 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2730 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2731
2732 # Try Strings
2733 self.assertGreater('bug', 'ant')
2734 self.assertGreaterEqual('bug', 'ant')
2735 self.assertGreaterEqual('ant', 'ant')
2736 self.assertLess('ant', 'bug')
2737 self.assertLessEqual('ant', 'bug')
2738 self.assertLessEqual('ant', 'ant')
2739 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2740 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2741 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2742 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2743 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2744 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2745
2746 # Try Unicode
2747 self.assertGreater(u'bug', u'ant')
2748 self.assertGreaterEqual(u'bug', u'ant')
2749 self.assertGreaterEqual(u'ant', u'ant')
2750 self.assertLess(u'ant', u'bug')
2751 self.assertLessEqual(u'ant', u'bug')
2752 self.assertLessEqual(u'ant', u'ant')
2753 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug')
2754 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant')
2755 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2756 u'bug')
2757 self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant')
2758 self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant')
2759 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant')
2760
2761 # Try Mixed String/Unicode
2762 self.assertGreater('bug', u'ant')
2763 self.assertGreater(u'bug', 'ant')
2764 self.assertGreaterEqual('bug', u'ant')
2765 self.assertGreaterEqual(u'bug', 'ant')
2766 self.assertGreaterEqual('ant', u'ant')
2767 self.assertGreaterEqual(u'ant', 'ant')
2768 self.assertLess('ant', u'bug')
2769 self.assertLess(u'ant', 'bug')
2770 self.assertLessEqual('ant', u'bug')
2771 self.assertLessEqual(u'ant', 'bug')
2772 self.assertLessEqual('ant', u'ant')
2773 self.assertLessEqual(u'ant', 'ant')
2774 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug')
2775 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug')
2776 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant')
2777 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant')
2778 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant',
2779 u'bug')
2780 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2781 'bug')
2782 self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant')
2783 self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant')
2784 self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant')
2785 self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant')
2786 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant')
2787 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant')
2788
2789 def testAssertMultiLineEqual(self):
2790 sample_text = b"""\
2791http://www.python.org/doc/2.3/lib/module-unittest.html
2792test case
2793 A test case is the smallest unit of testing. [...]
2794"""
2795 revised_sample_text = b"""\
2796http://www.python.org/doc/2.4.1/lib/module-unittest.html
2797test case
2798 A test case is the smallest unit of testing. [...] You may provide your
2799 own implementation that does not subclass from TestCase, of course.
2800"""
2801 sample_text_error = b"""
2802- http://www.python.org/doc/2.3/lib/module-unittest.html
2803? ^
2804+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2805? ^^^
2806 test case
2807- A test case is the smallest unit of testing. [...]
2808+ A test case is the smallest unit of testing. [...] You may provide your
2809? +++++++++++++++++++++
2810+ own implementation that does not subclass from TestCase, of course.
2811"""
2812
2813 for type_changer in (lambda x: x, lambda x: x.decode('utf8')):
2814 try:
2815 self.assertMultiLineEqual(type_changer(sample_text),
2816 type_changer(revised_sample_text))
2817 except self.failureException, e:
2818 # no fair testing ourself with ourself, use assertEqual..
2819 self.assertEqual(sample_text_error, str(e).encode('utf8'))
2820
2821 def testAssertIsNone(self):
2822 self.assertIsNone(None)
2823 self.assertRaises(self.failureException, self.assertIsNone, False)
2824 self.assertIsNotNone('DjZoPloGears on Rails')
2825 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2826
2827 def testAssertRegexpMatches(self):
2828 self.assertRegexpMatches('asdfabasdf', r'ab+')
2829 self.assertRaises(self.failureException, self.assertRegexpMatches,
2830 'saaas', r'aaaa')
2831
2832 def testAssertRaisesRegexp(self):
2833 class ExceptionMock(Exception):
2834 pass
2835
2836 def Stub():
2837 raise ExceptionMock('We expect')
2838
2839 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2840 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2841 self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
2842
2843 def testAssertNotRaisesRegexp(self):
2844 self.assertRaisesRegexp(
2845 self.failureException, '^Exception not raised$',
2846 self.assertRaisesRegexp, Exception, re.compile('x'),
2847 lambda: None)
2848 self.assertRaisesRegexp(
2849 self.failureException, '^Exception not raised$',
2850 self.assertRaisesRegexp, Exception, 'x',
2851 lambda: None)
2852 self.assertRaisesRegexp(
2853 self.failureException, '^Exception not raised$',
2854 self.assertRaisesRegexp, Exception, u'x',
2855 lambda: None)
2856
2857 def testAssertRaisesRegexpMismatch(self):
2858 def Stub():
2859 raise Exception('Unexpected')
2860
2861 self.assertRaisesRegexp(
2862 self.failureException,
2863 r'"\^Expected\$" does not match "Unexpected"',
2864 self.assertRaisesRegexp, Exception, '^Expected$',
2865 Stub)
2866 self.assertRaisesRegexp(
2867 self.failureException,
2868 r'"\^Expected\$" does not match "Unexpected"',
2869 self.assertRaisesRegexp, Exception, u'^Expected$',
2870 Stub)
2871 self.assertRaisesRegexp(
2872 self.failureException,
2873 r'"\^Expected\$" does not match "Unexpected"',
2874 self.assertRaisesRegexp, Exception,
2875 re.compile('^Expected$'), Stub)
2876
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00002877 def testAssertRaisesExcValue(self):
2878 class ExceptionMock(Exception):
2879 pass
2880
2881 def Stub(foo):
2882 raise ExceptionMock(foo)
2883 v = "particular value"
2884
2885 ctx = self.assertRaises(ExceptionMock)
2886 with ctx:
2887 Stub(v)
2888 e = ctx.exc_value
2889 self.assertTrue(isinstance(e, ExceptionMock))
2890 self.assertEqual(e.args[0], v)
2891
Gregory P. Smith7558d572009-03-31 19:03:28 +00002892 def testSynonymAssertMethodNames(self):
2893 """Test undocumented method name synonyms.
2894
2895 Please do not use these methods names in your own code.
2896
2897 This test confirms their continued existence and functionality
2898 in order to avoid breaking existing code.
2899 """
2900 self.assertNotEquals(3, 5)
2901 self.assertEquals(3, 3)
2902 self.assertAlmostEquals(2.0, 2.0)
2903 self.assertNotAlmostEquals(3.0, 5.0)
2904 self.assert_(True)
2905
2906 def testPendingDeprecationMethodNames(self):
2907 """Test fail* methods pending deprecation, they will warn in 3.2.
2908
2909 Do not use these methods. They will go away in 3.3.
2910 """
2911 self.failIfEqual(3, 5)
2912 self.failUnlessEqual(3, 3)
2913 self.failUnlessAlmostEqual(2.0, 2.0)
2914 self.failIfAlmostEqual(3.0, 5.0)
2915 self.failUnless(True)
2916 self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam')
2917 self.failIf(False)
2918
Michael Foorde2942d02009-04-02 05:51:54 +00002919 def testDeepcopy(self):
2920 # Issue: 5660
2921 class TestableTest(TestCase):
2922 def testNothing(self):
2923 pass
2924
2925 test = TestableTest('testNothing')
2926
2927 # This shouldn't blow up
2928 deepcopy(test)
2929
Benjamin Peterson692428e2009-03-23 21:50:21 +00002930
2931class Test_TestSkipping(TestCase):
2932
2933 def test_skipping(self):
2934 class Foo(unittest.TestCase):
2935 def test_skip_me(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002936 self.skipTest("skip")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002937 events = []
2938 result = LoggingResult(events)
2939 test = Foo("test_skip_me")
2940 test.run(result)
2941 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2942 self.assertEqual(result.skipped, [(test, "skip")])
2943
2944 # Try letting setUp skip the test now.
2945 class Foo(unittest.TestCase):
2946 def setUp(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002947 self.skipTest("testing")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002948 def test_nothing(self): pass
2949 events = []
2950 result = LoggingResult(events)
2951 test = Foo("test_nothing")
2952 test.run(result)
2953 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2954 self.assertEqual(result.skipped, [(test, "testing")])
2955 self.assertEqual(result.testsRun, 1)
2956
2957 def test_skipping_decorators(self):
2958 op_table = ((unittest.skipUnless, False, True),
2959 (unittest.skipIf, True, False))
2960 for deco, do_skip, dont_skip in op_table:
2961 class Foo(unittest.TestCase):
2962 @deco(do_skip, "testing")
2963 def test_skip(self): pass
2964
2965 @deco(dont_skip, "testing")
2966 def test_dont_skip(self): pass
2967 test_do_skip = Foo("test_skip")
2968 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002969 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002970 events = []
2971 result = LoggingResult(events)
2972 suite.run(result)
2973 self.assertEqual(len(result.skipped), 1)
2974 expected = ['startTest', 'addSkip', 'stopTest',
2975 'startTest', 'addSuccess', 'stopTest']
2976 self.assertEqual(events, expected)
2977 self.assertEqual(result.testsRun, 2)
2978 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
2979 self.assertTrue(result.wasSuccessful())
2980
2981 def test_skip_class(self):
2982 @unittest.skip("testing")
2983 class Foo(unittest.TestCase):
2984 def test_1(self):
2985 record.append(1)
2986 record = []
2987 result = unittest.TestResult()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002988 test = Foo("test_1")
2989 suite = unittest.TestSuite([test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002990 suite.run(result)
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002991 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002992 self.assertEqual(record, [])
2993
2994 def test_expected_failure(self):
2995 class Foo(unittest.TestCase):
2996 @unittest.expectedFailure
2997 def test_die(self):
2998 self.fail("help me!")
2999 events = []
3000 result = LoggingResult(events)
3001 test = Foo("test_die")
3002 test.run(result)
3003 self.assertEqual(events,
3004 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003005 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00003006 self.assertTrue(result.wasSuccessful())
3007
3008 def test_unexpected_success(self):
3009 class Foo(unittest.TestCase):
3010 @unittest.expectedFailure
3011 def test_die(self):
3012 pass
3013 events = []
3014 result = LoggingResult(events)
3015 test = Foo("test_die")
3016 test.run(result)
3017 self.assertEqual(events,
3018 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3019 self.assertFalse(result.failures)
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003020 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003021 self.assertTrue(result.wasSuccessful())
3022
3023
3024
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003025class Test_Assertions(TestCase):
3026 def test_AlmostEqual(self):
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003027 self.assertAlmostEqual(1.00000001, 1.0)
3028 self.assertNotAlmostEqual(1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003029 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003030 self.assertAlmostEqual, 1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003031 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003032 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003033
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003034 self.assertAlmostEqual(1.1, 1.0, places=0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003035 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003036 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003037
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003038 self.assertAlmostEqual(0, .1+.1j, places=0)
3039 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003040 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003041 self.assertAlmostEqual, 0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003042 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003043 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003044
Michael Foordc3f79372009-09-13 16:40:02 +00003045 self.assertAlmostEqual(float('inf'), float('inf'))
3046 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3047 float('inf'), float('inf'))
3048
3049
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003050 def test_assertRaises(self):
3051 def _raise(e):
3052 raise e
3053 self.assertRaises(KeyError, _raise, KeyError)
3054 self.assertRaises(KeyError, _raise, KeyError("key"))
3055 try:
3056 self.assertRaises(KeyError, lambda: None)
Gregory P. Smith28399852009-03-31 16:54:10 +00003057 except self.failureException as e:
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003058 self.assert_("KeyError not raised" in e, str(e))
3059 else:
3060 self.fail("assertRaises() didn't fail")
3061 try:
3062 self.assertRaises(KeyError, _raise, ValueError)
3063 except ValueError:
3064 pass
3065 else:
3066 self.fail("assertRaises() didn't let exception pass through")
3067 with self.assertRaises(KeyError):
3068 raise KeyError
3069 with self.assertRaises(KeyError):
3070 raise KeyError("key")
3071 try:
3072 with self.assertRaises(KeyError):
3073 pass
Gregory P. Smith28399852009-03-31 16:54:10 +00003074 except self.failureException as e:
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003075 self.assert_("KeyError not raised" in e, str(e))
3076 else:
3077 self.fail("assertRaises() didn't fail")
3078 try:
3079 with self.assertRaises(KeyError):
3080 raise ValueError
3081 except ValueError:
3082 pass
3083 else:
3084 self.fail("assertRaises() didn't let exception pass through")
3085
3086
Michael Foord345b2fe2009-04-02 03:20:38 +00003087class TestLongMessage(TestCase):
3088 """Test that the individual asserts honour longMessage.
3089 This actually tests all the message behaviour for
3090 asserts that use longMessage."""
3091
3092 def setUp(self):
3093 class TestableTestFalse(TestCase):
3094 longMessage = False
3095 failureException = self.failureException
3096
3097 def testTest(self):
3098 pass
3099
3100 class TestableTestTrue(TestCase):
3101 longMessage = True
3102 failureException = self.failureException
3103
3104 def testTest(self):
3105 pass
3106
3107 self.testableTrue = TestableTestTrue('testTest')
3108 self.testableFalse = TestableTestFalse('testTest')
3109
3110 def testDefault(self):
3111 self.assertFalse(TestCase.longMessage)
3112
3113 def test_formatMsg(self):
3114 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3115 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3116
3117 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3118 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3119
3120 def assertMessages(self, methodName, args, errors):
3121 def getMethod(i):
3122 useTestableFalse = i < 2
3123 if useTestableFalse:
3124 test = self.testableFalse
3125 else:
3126 test = self.testableTrue
3127 return getattr(test, methodName)
3128
3129 for i, expected_regexp in enumerate(errors):
3130 testMethod = getMethod(i)
3131 kwargs = {}
3132 withMsg = i % 2
3133 if withMsg:
3134 kwargs = {"msg": "oops"}
3135
3136 with self.assertRaisesRegexp(self.failureException,
3137 expected_regexp=expected_regexp):
3138 testMethod(*args, **kwargs)
3139
3140 def testAssertTrue(self):
3141 self.assertMessages('assertTrue', (False,),
3142 ["^False is not True$", "^oops$", "^False is not True$",
3143 "^False is not True : oops$"])
3144
3145 def testAssertFalse(self):
3146 self.assertMessages('assertFalse', (True,),
3147 ["^True is not False$", "^oops$", "^True is not False$",
3148 "^True is not False : oops$"])
3149
3150 def testNotEqual(self):
3151 self.assertMessages('assertNotEqual', (1, 1),
3152 ["^1 == 1$", "^oops$", "^1 == 1$",
3153 "^1 == 1 : oops$"])
3154
3155 def testAlmostEqual(self):
3156 self.assertMessages('assertAlmostEqual', (1, 2),
3157 ["^1 != 2 within 7 places$", "^oops$",
3158 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3159
3160 def testNotAlmostEqual(self):
3161 self.assertMessages('assertNotAlmostEqual', (1, 1),
3162 ["^1 == 1 within 7 places$", "^oops$",
3163 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3164
3165 def test_baseAssertEqual(self):
3166 self.assertMessages('_baseAssertEqual', (1, 2),
3167 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3168
3169 def testAssertSequenceEqual(self):
3170 # Error messages are multiline so not testing on full message
3171 # assertTupleEqual and assertListEqual delegate to this method
3172 self.assertMessages('assertSequenceEqual', ([], [None]),
3173 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3174 r"\+ \[None\] : oops$"])
3175
3176 def testAssertSetEqual(self):
3177 self.assertMessages('assertSetEqual', (set(), set([None])),
3178 ["None$", "^oops$", "None$",
3179 "None : oops$"])
3180
3181 def testAssertIn(self):
3182 self.assertMessages('assertIn', (None, []),
3183 ['^None not found in \[\]$', "^oops$",
3184 '^None not found in \[\]$',
3185 '^None not found in \[\] : oops$'])
3186
3187 def testAssertNotIn(self):
3188 self.assertMessages('assertNotIn', (None, [None]),
3189 ['^None unexpectedly found in \[None\]$', "^oops$",
3190 '^None unexpectedly found in \[None\]$',
3191 '^None unexpectedly found in \[None\] : oops$'])
3192
3193 def testAssertDictEqual(self):
3194 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3195 [r"\+ \{'key': 'value'\}$", "^oops$",
3196 "\+ \{'key': 'value'\}$",
3197 "\+ \{'key': 'value'\} : oops$"])
3198
3199 def testAssertDictContainsSubset(self):
3200 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3201 ["^Missing: 'key'$", "^oops$",
3202 "^Missing: 'key'$",
3203 "^Missing: 'key' : oops$"])
3204
3205 def testAssertSameElements(self):
3206 self.assertMessages('assertSameElements', ([], [None]),
3207 [r"\[None\]$", "^oops$",
3208 r"\[None\]$",
3209 r"\[None\] : oops$"])
3210
3211 def testAssertMultiLineEqual(self):
3212 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3213 [r"\+ foo$", "^oops$",
3214 r"\+ foo$",
3215 r"\+ foo : oops$"])
3216
3217 def testAssertLess(self):
3218 self.assertMessages('assertLess', (2, 1),
3219 ["^2 not less than 1$", "^oops$",
3220 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3221
3222 def testAssertLessEqual(self):
3223 self.assertMessages('assertLessEqual', (2, 1),
3224 ["^2 not less than or equal to 1$", "^oops$",
3225 "^2 not less than or equal to 1$",
3226 "^2 not less than or equal to 1 : oops$"])
3227
3228 def testAssertGreater(self):
3229 self.assertMessages('assertGreater', (1, 2),
3230 ["^1 not greater than 2$", "^oops$",
3231 "^1 not greater than 2$",
3232 "^1 not greater than 2 : oops$"])
3233
3234 def testAssertGreaterEqual(self):
3235 self.assertMessages('assertGreaterEqual', (1, 2),
3236 ["^1 not greater than or equal to 2$", "^oops$",
3237 "^1 not greater than or equal to 2$",
3238 "^1 not greater than or equal to 2 : oops$"])
3239
3240 def testAssertIsNone(self):
3241 self.assertMessages('assertIsNone', ('not None',),
3242 ["^'not None' is not None$", "^oops$",
3243 "^'not None' is not None$",
3244 "^'not None' is not None : oops$"])
3245
3246 def testAssertIsNotNone(self):
3247 self.assertMessages('assertIsNotNone', (None,),
3248 ["^unexpectedly None$", "^oops$",
3249 "^unexpectedly None$",
3250 "^unexpectedly None : oops$"])
3251
Michael Foordf2dfef12009-04-05 19:19:28 +00003252 def testAssertIs(self):
3253 self.assertMessages('assertIs', (None, 'foo'),
3254 ["^None is not 'foo'$", "^oops$",
3255 "^None is not 'foo'$",
3256 "^None is not 'foo' : oops$"])
3257
3258 def testAssertIsNot(self):
3259 self.assertMessages('assertIsNot', (None, None),
3260 ["^unexpectedly identical: None$", "^oops$",
3261 "^unexpectedly identical: None$",
3262 "^unexpectedly identical: None : oops$"])
3263
Michael Foord345b2fe2009-04-02 03:20:38 +00003264
Michael Foorde2fb98f2009-05-02 20:15:05 +00003265class TestCleanUp(TestCase):
3266
3267 def testCleanUp(self):
3268 class TestableTest(TestCase):
3269 def testNothing(self):
3270 pass
3271
3272 test = TestableTest('testNothing')
3273 self.assertEqual(test._cleanups, [])
3274
3275 cleanups = []
3276
3277 def cleanup1(*args, **kwargs):
3278 cleanups.append((1, args, kwargs))
3279
3280 def cleanup2(*args, **kwargs):
3281 cleanups.append((2, args, kwargs))
3282
3283 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3284 test.addCleanup(cleanup2)
3285
3286 self.assertEqual(test._cleanups,
3287 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3288 (cleanup2, (), {})])
3289
3290 result = test.doCleanups()
3291 self.assertTrue(result)
3292
3293 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3294
3295 def testCleanUpWithErrors(self):
3296 class TestableTest(TestCase):
3297 def testNothing(self):
3298 pass
3299
3300 class MockResult(object):
3301 errors = []
3302 def addError(self, test, exc_info):
3303 self.errors.append((test, exc_info))
3304
3305 result = MockResult()
3306 test = TestableTest('testNothing')
Michael Foorda50af062009-05-21 22:57:02 +00003307 test._resultForDoCleanups = result
Michael Foorde2fb98f2009-05-02 20:15:05 +00003308
3309 exc1 = Exception('foo')
3310 exc2 = Exception('bar')
3311 def cleanup1():
3312 raise exc1
3313
3314 def cleanup2():
3315 raise exc2
3316
3317 test.addCleanup(cleanup1)
3318 test.addCleanup(cleanup2)
3319
3320 self.assertFalse(test.doCleanups())
3321
3322 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3323 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3324 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3325
3326 def testCleanupInRun(self):
3327 blowUp = False
3328 ordering = []
3329
3330 class TestableTest(TestCase):
3331 def setUp(self):
3332 ordering.append('setUp')
3333 if blowUp:
3334 raise Exception('foo')
3335
3336 def testNothing(self):
3337 ordering.append('test')
3338
3339 def tearDown(self):
3340 ordering.append('tearDown')
3341
3342 test = TestableTest('testNothing')
3343
3344 def cleanup1():
3345 ordering.append('cleanup1')
3346 def cleanup2():
3347 ordering.append('cleanup2')
3348 test.addCleanup(cleanup1)
3349 test.addCleanup(cleanup2)
3350
3351 def success(some_test):
3352 self.assertEqual(some_test, test)
3353 ordering.append('success')
3354
3355 result = unittest.TestResult()
3356 result.addSuccess = success
3357
3358 test.run(result)
3359 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3360 'cleanup2', 'cleanup1', 'success'])
3361
3362 blowUp = True
3363 ordering = []
3364 test = TestableTest('testNothing')
3365 test.addCleanup(cleanup1)
3366 test.run(result)
3367 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3368
3369
Michael Foord829f6b82009-05-02 11:43:06 +00003370class Test_TestProgram(TestCase):
3371
3372 # Horrible white box test
3373 def testNoExit(self):
3374 result = object()
3375 test = object()
3376
3377 class FakeRunner(object):
3378 def run(self, test):
3379 self.test = test
3380 return result
3381
3382 runner = FakeRunner()
3383
Michael Foord5d31e052009-05-11 17:59:43 +00003384 oldParseArgs = TestProgram.parseArgs
3385 def restoreParseArgs():
Michael Foord829f6b82009-05-02 11:43:06 +00003386 TestProgram.parseArgs = oldParseArgs
Michael Foord5d31e052009-05-11 17:59:43 +00003387 TestProgram.parseArgs = lambda *args: None
3388 self.addCleanup(restoreParseArgs)
3389
3390 def removeTest():
Michael Foord829f6b82009-05-02 11:43:06 +00003391 del TestProgram.test
Michael Foord5d31e052009-05-11 17:59:43 +00003392 TestProgram.test = test
3393 self.addCleanup(removeTest)
3394
3395 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3396
3397 self.assertEqual(program.result, result)
3398 self.assertEqual(runner.test, test)
3399 self.assertEqual(program.verbosity, 2)
Michael Foord829f6b82009-05-02 11:43:06 +00003400
Michael Foord829f6b82009-05-02 11:43:06 +00003401 class FooBar(unittest.TestCase):
3402 def testPass(self):
3403 assert True
3404 def testFail(self):
3405 assert False
3406
3407 class FooBarLoader(unittest.TestLoader):
3408 """Test loader that returns a suite containing FooBar."""
3409 def loadTestsFromModule(self, module):
3410 return self.suiteClass(
3411 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3412
3413
3414 def test_NonExit(self):
3415 program = unittest.main(exit=False,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003416 argv=["foobar"],
3417 testRunner=unittest.TextTestRunner(stream=StringIO()),
3418 testLoader=self.FooBarLoader())
Michael Foord829f6b82009-05-02 11:43:06 +00003419 self.assertTrue(hasattr(program, 'result'))
3420
3421
3422 def test_Exit(self):
3423 self.assertRaises(
3424 SystemExit,
3425 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003426 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003427 testRunner=unittest.TextTestRunner(stream=StringIO()),
3428 exit=True,
3429 testLoader=self.FooBarLoader())
3430
3431
3432 def test_ExitAsDefault(self):
3433 self.assertRaises(
3434 SystemExit,
3435 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003436 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003437 testRunner=unittest.TextTestRunner(stream=StringIO()),
3438 testLoader=self.FooBarLoader())
3439
3440
Michael Foord07ef4872009-05-02 22:43:34 +00003441class Test_TextTestRunner(TestCase):
3442 """Tests for TextTestRunner."""
3443
3444 def test_works_with_result_without_startTestRun_stopTestRun(self):
3445 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3446 separator2 = ''
3447 def printErrors(self):
3448 pass
3449
3450 class Runner(unittest.TextTestRunner):
3451 def __init__(self):
3452 super(Runner, self).__init__(StringIO())
3453
3454 def _makeResult(self):
3455 return OldTextResult()
3456
3457 runner = Runner()
3458 runner.run(unittest.TestSuite())
3459
3460 def test_startTestRun_stopTestRun_called(self):
3461 class LoggingTextResult(LoggingResult):
3462 separator2 = ''
3463 def printErrors(self):
3464 pass
3465
3466 class LoggingRunner(unittest.TextTestRunner):
3467 def __init__(self, events):
3468 super(LoggingRunner, self).__init__(StringIO())
3469 self._events = events
3470
3471 def _makeResult(self):
3472 return LoggingTextResult(self._events)
3473
3474 events = []
3475 runner = LoggingRunner(events)
3476 runner.run(unittest.TestSuite())
3477 expected = ['startTestRun', 'stopTestRun']
3478 self.assertEqual(events, expected)
3479
3480
Michael Foordb4a81c82009-05-29 20:33:46 +00003481class TestDiscovery(TestCase):
3482
3483 # Heavily mocked tests so I can avoid hitting the filesystem
Michael Foorde91ea562009-09-13 19:07:03 +00003484 def test_get_name_from_path(self):
Michael Foordb4a81c82009-05-29 20:33:46 +00003485 loader = unittest.TestLoader()
3486
Michael Foordb4a81c82009-05-29 20:33:46 +00003487 loader._top_level_dir = '/foo'
Michael Foorde91ea562009-09-13 19:07:03 +00003488 name = loader._get_name_from_path('/foo/bar/baz.py')
3489 self.assertEqual(name, 'bar.baz')
Michael Foordb4a81c82009-05-29 20:33:46 +00003490
3491 if not __debug__:
3492 # asserts are off
3493 return
3494
3495 with self.assertRaises(AssertionError):
Michael Foorde91ea562009-09-13 19:07:03 +00003496 loader._get_name_from_path('/bar/baz.py')
Michael Foordb4a81c82009-05-29 20:33:46 +00003497
3498 def test_find_tests(self):
3499 loader = unittest.TestLoader()
3500
3501 original_listdir = os.listdir
3502 def restore_listdir():
3503 os.listdir = original_listdir
3504 original_isfile = os.path.isfile
3505 def restore_isfile():
3506 os.path.isfile = original_isfile
3507 original_isdir = os.path.isdir
3508 def restore_isdir():
3509 os.path.isdir = original_isdir
3510
3511 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Michael Foorde91ea562009-09-13 19:07:03 +00003512 'test.foo', 'test-not-a-module.py', 'another_dir'],
Michael Foordb4a81c82009-05-29 20:33:46 +00003513 ['test3.py', 'test4.py', ]]
3514 os.listdir = lambda path: path_lists.pop(0)
3515 self.addCleanup(restore_listdir)
3516
3517 def isdir(path):
3518 return path.endswith('dir')
3519 os.path.isdir = isdir
3520 self.addCleanup(restore_isdir)
3521
3522 def isfile(path):
3523 # another_dir is not a package and so shouldn't be recursed into
3524 return not path.endswith('dir') and not 'another_dir' in path
3525 os.path.isfile = isfile
3526 self.addCleanup(restore_isfile)
3527
Michael Foorde91ea562009-09-13 19:07:03 +00003528 loader._get_module_from_name = lambda path: path + ' module'
Michael Foordb4a81c82009-05-29 20:33:46 +00003529 loader.loadTestsFromModule = lambda module: module + ' tests'
3530
3531 loader._top_level_dir = '/foo'
3532 suite = list(loader._find_tests('/foo', 'test*.py'))
3533
Michael Foorde91ea562009-09-13 19:07:03 +00003534 expected = [name + ' module tests' for name in
3535 ('test1', 'test2')]
3536 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3537 ('test3', 'test4')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003538 self.assertEqual(suite, expected)
3539
3540 def test_find_tests_with_package(self):
3541 loader = unittest.TestLoader()
3542
3543 original_listdir = os.listdir
3544 def restore_listdir():
3545 os.listdir = original_listdir
3546 original_isfile = os.path.isfile
3547 def restore_isfile():
3548 os.path.isfile = original_isfile
3549 original_isdir = os.path.isdir
3550 def restore_isdir():
3551 os.path.isdir = original_isdir
3552
3553 directories = ['a_directory', 'test_directory', 'test_directory2']
3554 path_lists = [directories, [], [], []]
3555 os.listdir = lambda path: path_lists.pop(0)
3556 self.addCleanup(restore_listdir)
3557
3558 os.path.isdir = lambda path: True
3559 self.addCleanup(restore_isdir)
3560
3561 os.path.isfile = lambda path: os.path.basename(path) not in directories
3562 self.addCleanup(restore_isfile)
3563
3564 class Module(object):
3565 paths = []
3566 load_tests_args = []
3567
3568 def __init__(self, path):
3569 self.path = path
3570 self.paths.append(path)
3571 if os.path.basename(path) == 'test_directory':
3572 def load_tests(loader, tests, pattern):
3573 self.load_tests_args.append((loader, tests, pattern))
3574 return 'load_tests'
3575 self.load_tests = load_tests
3576
3577 def __eq__(self, other):
3578 return self.path == other.path
3579
Michael Foorde91ea562009-09-13 19:07:03 +00003580 loader._get_module_from_name = lambda name: Module(name)
Michael Foordb4a81c82009-05-29 20:33:46 +00003581 def loadTestsFromModule(module, use_load_tests):
3582 if use_load_tests:
3583 raise self.failureException('use_load_tests should be False for packages')
3584 return module.path + ' module tests'
3585 loader.loadTestsFromModule = loadTestsFromModule
3586
3587 loader._top_level_dir = '/foo'
3588 # this time no '.py' on the pattern so that it can match
3589 # a test package
3590 suite = list(loader._find_tests('/foo', 'test*'))
3591
3592 # We should have loaded tests from the test_directory package by calling load_tests
3593 # and directly from the test_directory2 package
Michael Foordd53d0852009-06-05 14:14:34 +00003594 self.assertEqual(suite,
Michael Foorde91ea562009-09-13 19:07:03 +00003595 ['load_tests', 'test_directory2' + ' module tests'])
3596 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Michael Foordb4a81c82009-05-29 20:33:46 +00003597
3598 # load_tests should have been called once with loader, tests and pattern
3599 self.assertEqual(Module.load_tests_args,
Michael Foorde91ea562009-09-13 19:07:03 +00003600 [(loader, 'test_directory' + ' module tests', 'test*')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003601
3602 def test_discover(self):
3603 loader = unittest.TestLoader()
3604
3605 original_isfile = os.path.isfile
3606 def restore_isfile():
3607 os.path.isfile = original_isfile
3608
3609 os.path.isfile = lambda path: False
3610 self.addCleanup(restore_isfile)
3611
Nick Coghlanb6edf192009-10-17 08:21:21 +00003612 orig_sys_path = sys.path[:]
3613 def restore_path():
3614 sys.path[:] = orig_sys_path
3615 self.addCleanup(restore_path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003616
Nick Coghlanb6edf192009-10-17 08:21:21 +00003617 full_path = os.path.abspath(os.path.normpath('/foo'))
Michael Foordb4a81c82009-05-29 20:33:46 +00003618 with self.assertRaises(ImportError):
3619 loader.discover('/foo/bar', top_level_dir='/foo')
3620
3621 self.assertEqual(loader._top_level_dir, full_path)
3622 self.assertIn(full_path, sys.path)
3623
3624 os.path.isfile = lambda path: True
3625 _find_tests_args = []
3626 def _find_tests(start_dir, pattern):
3627 _find_tests_args.append((start_dir, pattern))
3628 return ['tests']
3629 loader._find_tests = _find_tests
3630 loader.suiteClass = str
3631
3632 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3633
3634 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3635 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3636 self.assertEqual(suite, "['tests']")
3637 self.assertEqual(loader._top_level_dir, top_level_dir)
3638 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlanb6edf192009-10-17 08:21:21 +00003639 self.assertIn(top_level_dir, sys.path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003640
Michael Foorde91ea562009-09-13 19:07:03 +00003641 def test_discover_with_modules_that_fail_to_import(self):
3642 loader = unittest.TestLoader()
3643
3644 listdir = os.listdir
3645 os.listdir = lambda _: ['test_this_does_not_exist.py']
3646 isfile = os.path.isfile
3647 os.path.isfile = lambda _: True
Nick Coghlanb6edf192009-10-17 08:21:21 +00003648 orig_sys_path = sys.path[:]
Michael Foorde91ea562009-09-13 19:07:03 +00003649 def restore():
3650 os.path.isfile = isfile
3651 os.listdir = listdir
Nick Coghlanb6edf192009-10-17 08:21:21 +00003652 sys.path[:] = orig_sys_path
Michael Foorde91ea562009-09-13 19:07:03 +00003653 self.addCleanup(restore)
3654
3655 suite = loader.discover('.')
Nick Coghlanb6edf192009-10-17 08:21:21 +00003656 self.assertIn(os.getcwd(), sys.path)
Michael Foorde91ea562009-09-13 19:07:03 +00003657 self.assertEqual(suite.countTestCases(), 1)
3658 test = list(list(suite)[0])[0] # extract test from suite
3659
3660 with self.assertRaises(ImportError):
3661 test.test_this_does_not_exist()
3662
Michael Foordb4a81c82009-05-29 20:33:46 +00003663 def test_command_line_handling_parseArgs(self):
3664 # Haha - take that uninstantiable class
3665 program = object.__new__(TestProgram)
3666
3667 args = []
3668 def do_discovery(argv):
3669 args.extend(argv)
3670 program._do_discovery = do_discovery
3671 program.parseArgs(['something', 'discover'])
3672 self.assertEqual(args, [])
3673
3674 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3675 self.assertEqual(args, ['foo', 'bar'])
3676
3677 def test_command_line_handling_do_discovery_too_many_arguments(self):
3678 class Stop(Exception):
3679 pass
3680 def usageExit():
3681 raise Stop
3682
3683 program = object.__new__(TestProgram)
3684 program.usageExit = usageExit
3685
3686 with self.assertRaises(Stop):
3687 # too many args
3688 program._do_discovery(['one', 'two', 'three', 'four'])
3689
3690
3691 def test_command_line_handling_do_discovery_calls_loader(self):
3692 program = object.__new__(TestProgram)
3693
3694 class Loader(object):
3695 args = []
3696 def discover(self, start_dir, pattern, top_level_dir):
3697 self.args.append((start_dir, pattern, top_level_dir))
3698 return 'tests'
3699
3700 program._do_discovery(['-v'], Loader=Loader)
3701 self.assertEqual(program.verbosity, 2)
3702 self.assertEqual(program.test, 'tests')
3703 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3704
3705 Loader.args = []
3706 program = object.__new__(TestProgram)
3707 program._do_discovery(['--verbose'], Loader=Loader)
3708 self.assertEqual(program.test, 'tests')
3709 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3710
3711 Loader.args = []
3712 program = object.__new__(TestProgram)
3713 program._do_discovery([], Loader=Loader)
3714 self.assertEqual(program.test, 'tests')
3715 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3716
3717 Loader.args = []
3718 program = object.__new__(TestProgram)
3719 program._do_discovery(['fish'], Loader=Loader)
3720 self.assertEqual(program.test, 'tests')
3721 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3722
3723 Loader.args = []
3724 program = object.__new__(TestProgram)
3725 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3726 self.assertEqual(program.test, 'tests')
3727 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3728
3729 Loader.args = []
3730 program = object.__new__(TestProgram)
3731 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3732 self.assertEqual(program.test, 'tests')
3733 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3734
3735 Loader.args = []
3736 program = object.__new__(TestProgram)
3737 program._do_discovery(['-s', 'fish'], Loader=Loader)
3738 self.assertEqual(program.test, 'tests')
3739 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3740
3741 Loader.args = []
3742 program = object.__new__(TestProgram)
3743 program._do_discovery(['-t', 'fish'], Loader=Loader)
3744 self.assertEqual(program.test, 'tests')
3745 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3746
3747 Loader.args = []
3748 program = object.__new__(TestProgram)
3749 program._do_discovery(['-p', 'fish'], Loader=Loader)
3750 self.assertEqual(program.test, 'tests')
3751 self.assertEqual(Loader.args, [('.', 'fish', None)])
3752
3753 Loader.args = []
3754 program = object.__new__(TestProgram)
3755 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3756 self.assertEqual(program.test, 'tests')
3757 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3758 self.assertEqual(program.verbosity, 2)
3759
3760
Jim Fultonfafd8742004-08-28 15:22:12 +00003761######################################################################
3762## Main
3763######################################################################
3764
3765def test_main():
Georg Brandl15c5ce92007-03-07 09:09:40 +00003766 test_support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003767 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Michael Foord829f6b82009-05-02 11:43:06 +00003768 Test_TestSkipping, Test_Assertions, TestLongMessage,
Michael Foordb4a81c82009-05-29 20:33:46 +00003769 Test_TestProgram, TestCleanUp, TestDiscovery)
Jim Fultonfafd8742004-08-28 15:22:12 +00003770
Georg Brandl15c5ce92007-03-07 09:09:40 +00003771if __name__ == "__main__":
Tim Petersea5962f2007-03-12 18:07:52 +00003772 test_main()