blob: 459334b9580d1e3d4ead6ce1f4bbd1f4c0669b15 [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
Gregory P. Smith28399852009-03-31 16:54:10 +00002503 def testAssertIn(self):
2504 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2505
2506 self.assertIn('a', 'abc')
2507 self.assertIn(2, [1, 2, 3])
2508 self.assertIn('monkey', animals)
2509
2510 self.assertNotIn('d', 'abc')
2511 self.assertNotIn(0, [1, 2, 3])
2512 self.assertNotIn('otter', animals)
2513
2514 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2515 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2516 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2517 animals)
2518
2519 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2520 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2521 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2522 animals)
2523
2524 def testAssertDictContainsSubset(self):
2525 self.assertDictContainsSubset({}, {})
2526 self.assertDictContainsSubset({}, {'a': 1})
2527 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2528 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2529 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2530
2531 self.assertRaises(unittest.TestCase.failureException,
2532 self.assertDictContainsSubset, {'a': 2}, {'a': 1},
2533 '.*Mismatched values:.*')
2534
2535 self.assertRaises(unittest.TestCase.failureException,
2536 self.assertDictContainsSubset, {'c': 1}, {'a': 1},
2537 '.*Missing:.*')
2538
2539 self.assertRaises(unittest.TestCase.failureException,
2540 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2541 {'a': 1}, '.*Missing:.*')
2542
2543 self.assertRaises(unittest.TestCase.failureException,
2544 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2545 {'a': 1}, '.*Missing:.*Mismatched values:.*')
2546
2547 def testAssertEqual(self):
2548 equal_pairs = [
2549 ((), ()),
2550 ({}, {}),
2551 ([], []),
2552 (set(), set()),
2553 (frozenset(), frozenset())]
2554 for a, b in equal_pairs:
2555 # This mess of try excepts is to test the assertEqual behavior
2556 # itself.
2557 try:
2558 self.assertEqual(a, b)
2559 except self.failureException:
2560 self.fail('assertEqual(%r, %r) failed' % (a, b))
2561 try:
2562 self.assertEqual(a, b, msg='foo')
2563 except self.failureException:
2564 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2565 try:
2566 self.assertEqual(a, b, 'foo')
2567 except self.failureException:
2568 self.fail('assertEqual(%r, %r) with third parameter failed' %
2569 (a, b))
2570
2571 unequal_pairs = [
2572 ((), []),
2573 ({}, set()),
2574 (set([4,1]), frozenset([4,2])),
2575 (frozenset([4,5]), set([2,3])),
2576 (set([3,4]), set([5,4]))]
2577 for a, b in unequal_pairs:
2578 self.assertRaises(self.failureException, self.assertEqual, a, b)
2579 self.assertRaises(self.failureException, self.assertEqual, a, b,
2580 'foo')
2581 self.assertRaises(self.failureException, self.assertEqual, a, b,
2582 msg='foo')
2583
2584 def testEquality(self):
2585 self.assertListEqual([], [])
2586 self.assertTupleEqual((), ())
2587 self.assertSequenceEqual([], ())
2588
2589 a = [0, 'a', []]
2590 b = []
2591 self.assertRaises(unittest.TestCase.failureException,
2592 self.assertListEqual, a, b)
2593 self.assertRaises(unittest.TestCase.failureException,
2594 self.assertListEqual, tuple(a), tuple(b))
2595 self.assertRaises(unittest.TestCase.failureException,
2596 self.assertSequenceEqual, a, tuple(b))
2597
2598 b.extend(a)
2599 self.assertListEqual(a, b)
2600 self.assertTupleEqual(tuple(a), tuple(b))
2601 self.assertSequenceEqual(a, tuple(b))
2602 self.assertSequenceEqual(tuple(a), b)
2603
2604 self.assertRaises(self.failureException, self.assertListEqual,
2605 a, tuple(b))
2606 self.assertRaises(self.failureException, self.assertTupleEqual,
2607 tuple(a), b)
2608 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2609 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2610 tuple(b))
2611 self.assertRaises(self.failureException, self.assertSequenceEqual,
2612 None, tuple(b))
2613 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2614 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2615 self.assertRaises(self.failureException, self.assertSequenceEqual,
2616 1, 1)
2617
2618 self.assertDictEqual({}, {})
2619
2620 c = { 'x': 1 }
2621 d = {}
2622 self.assertRaises(unittest.TestCase.failureException,
2623 self.assertDictEqual, c, d)
2624
2625 d.update(c)
2626 self.assertDictEqual(c, d)
2627
2628 d['x'] = 0
2629 self.assertRaises(unittest.TestCase.failureException,
2630 self.assertDictEqual, c, d, 'These are unequal')
2631
2632 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2633 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2634 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2635
2636 self.assertSameElements([1, 2, 3], [3, 2, 1])
2637 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2638 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2639 self.assertRaises(self.failureException, self.assertSameElements,
2640 [10], [10, 11])
2641 self.assertRaises(self.failureException, self.assertSameElements,
2642 [10, 11], [10])
2643
2644 # Test that sequences of unhashable objects can be tested for sameness:
2645 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Michael Foordf2dfef12009-04-05 19:19:28 +00002646
Gregory P. Smith28399852009-03-31 16:54:10 +00002647 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2648 self.assertRaises(self.failureException, self.assertSameElements,
2649 [[1]], [[2]])
2650
2651 def testAssertSetEqual(self):
2652 set1 = set()
2653 set2 = set()
2654 self.assertSetEqual(set1, set2)
2655
2656 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2657 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2658 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2659 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2660
2661 set1 = set(['a'])
2662 set2 = set()
2663 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2664
2665 set1 = set(['a'])
2666 set2 = set(['a'])
2667 self.assertSetEqual(set1, set2)
2668
2669 set1 = set(['a'])
2670 set2 = set(['a', 'b'])
2671 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2672
2673 set1 = set(['a'])
2674 set2 = frozenset(['a', 'b'])
2675 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2676
2677 set1 = set(['a', 'b'])
2678 set2 = frozenset(['a', 'b'])
2679 self.assertSetEqual(set1, set2)
2680
2681 set1 = set()
2682 set2 = "foo"
2683 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2684 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2685
2686 # make sure any string formatting is tuple-safe
2687 set1 = set([(0, 1), (2, 3)])
2688 set2 = set([(4, 5)])
2689 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2690
2691 def testInequality(self):
2692 # Try ints
2693 self.assertGreater(2, 1)
2694 self.assertGreaterEqual(2, 1)
2695 self.assertGreaterEqual(1, 1)
2696 self.assertLess(1, 2)
2697 self.assertLessEqual(1, 2)
2698 self.assertLessEqual(1, 1)
2699 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2700 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2701 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2702 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2703 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2704 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2705
2706 # Try Floats
2707 self.assertGreater(1.1, 1.0)
2708 self.assertGreaterEqual(1.1, 1.0)
2709 self.assertGreaterEqual(1.0, 1.0)
2710 self.assertLess(1.0, 1.1)
2711 self.assertLessEqual(1.0, 1.1)
2712 self.assertLessEqual(1.0, 1.0)
2713 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2714 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2715 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2716 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2717 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2718 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2719
2720 # Try Strings
2721 self.assertGreater('bug', 'ant')
2722 self.assertGreaterEqual('bug', 'ant')
2723 self.assertGreaterEqual('ant', 'ant')
2724 self.assertLess('ant', 'bug')
2725 self.assertLessEqual('ant', 'bug')
2726 self.assertLessEqual('ant', 'ant')
2727 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2728 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2729 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2730 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2731 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2732 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2733
2734 # Try Unicode
2735 self.assertGreater(u'bug', u'ant')
2736 self.assertGreaterEqual(u'bug', u'ant')
2737 self.assertGreaterEqual(u'ant', u'ant')
2738 self.assertLess(u'ant', u'bug')
2739 self.assertLessEqual(u'ant', u'bug')
2740 self.assertLessEqual(u'ant', u'ant')
2741 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug')
2742 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant')
2743 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2744 u'bug')
2745 self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant')
2746 self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant')
2747 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant')
2748
2749 # Try Mixed String/Unicode
2750 self.assertGreater('bug', u'ant')
2751 self.assertGreater(u'bug', 'ant')
2752 self.assertGreaterEqual('bug', u'ant')
2753 self.assertGreaterEqual(u'bug', 'ant')
2754 self.assertGreaterEqual('ant', u'ant')
2755 self.assertGreaterEqual(u'ant', 'ant')
2756 self.assertLess('ant', u'bug')
2757 self.assertLess(u'ant', 'bug')
2758 self.assertLessEqual('ant', u'bug')
2759 self.assertLessEqual(u'ant', 'bug')
2760 self.assertLessEqual('ant', u'ant')
2761 self.assertLessEqual(u'ant', 'ant')
2762 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug')
2763 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug')
2764 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant')
2765 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant')
2766 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant',
2767 u'bug')
2768 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2769 'bug')
2770 self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant')
2771 self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant')
2772 self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant')
2773 self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant')
2774 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant')
2775 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant')
2776
2777 def testAssertMultiLineEqual(self):
2778 sample_text = b"""\
2779http://www.python.org/doc/2.3/lib/module-unittest.html
2780test case
2781 A test case is the smallest unit of testing. [...]
2782"""
2783 revised_sample_text = b"""\
2784http://www.python.org/doc/2.4.1/lib/module-unittest.html
2785test case
2786 A test case is the smallest unit of testing. [...] You may provide your
2787 own implementation that does not subclass from TestCase, of course.
2788"""
2789 sample_text_error = b"""
2790- http://www.python.org/doc/2.3/lib/module-unittest.html
2791? ^
2792+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2793? ^^^
2794 test case
2795- A test case is the smallest unit of testing. [...]
2796+ A test case is the smallest unit of testing. [...] You may provide your
2797? +++++++++++++++++++++
2798+ own implementation that does not subclass from TestCase, of course.
2799"""
2800
2801 for type_changer in (lambda x: x, lambda x: x.decode('utf8')):
2802 try:
2803 self.assertMultiLineEqual(type_changer(sample_text),
2804 type_changer(revised_sample_text))
2805 except self.failureException, e:
2806 # no fair testing ourself with ourself, use assertEqual..
2807 self.assertEqual(sample_text_error, str(e).encode('utf8'))
2808
2809 def testAssertIsNone(self):
2810 self.assertIsNone(None)
2811 self.assertRaises(self.failureException, self.assertIsNone, False)
2812 self.assertIsNotNone('DjZoPloGears on Rails')
2813 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2814
2815 def testAssertRegexpMatches(self):
2816 self.assertRegexpMatches('asdfabasdf', r'ab+')
2817 self.assertRaises(self.failureException, self.assertRegexpMatches,
2818 'saaas', r'aaaa')
2819
2820 def testAssertRaisesRegexp(self):
2821 class ExceptionMock(Exception):
2822 pass
2823
2824 def Stub():
2825 raise ExceptionMock('We expect')
2826
2827 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2828 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2829 self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
2830
2831 def testAssertNotRaisesRegexp(self):
2832 self.assertRaisesRegexp(
2833 self.failureException, '^Exception not raised$',
2834 self.assertRaisesRegexp, Exception, re.compile('x'),
2835 lambda: None)
2836 self.assertRaisesRegexp(
2837 self.failureException, '^Exception not raised$',
2838 self.assertRaisesRegexp, Exception, 'x',
2839 lambda: None)
2840 self.assertRaisesRegexp(
2841 self.failureException, '^Exception not raised$',
2842 self.assertRaisesRegexp, Exception, u'x',
2843 lambda: None)
2844
2845 def testAssertRaisesRegexpMismatch(self):
2846 def Stub():
2847 raise Exception('Unexpected')
2848
2849 self.assertRaisesRegexp(
2850 self.failureException,
2851 r'"\^Expected\$" does not match "Unexpected"',
2852 self.assertRaisesRegexp, Exception, '^Expected$',
2853 Stub)
2854 self.assertRaisesRegexp(
2855 self.failureException,
2856 r'"\^Expected\$" does not match "Unexpected"',
2857 self.assertRaisesRegexp, Exception, u'^Expected$',
2858 Stub)
2859 self.assertRaisesRegexp(
2860 self.failureException,
2861 r'"\^Expected\$" does not match "Unexpected"',
2862 self.assertRaisesRegexp, Exception,
2863 re.compile('^Expected$'), Stub)
2864
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00002865 def testAssertRaisesExcValue(self):
2866 class ExceptionMock(Exception):
2867 pass
2868
2869 def Stub(foo):
2870 raise ExceptionMock(foo)
2871 v = "particular value"
2872
2873 ctx = self.assertRaises(ExceptionMock)
2874 with ctx:
2875 Stub(v)
2876 e = ctx.exc_value
2877 self.assertTrue(isinstance(e, ExceptionMock))
2878 self.assertEqual(e.args[0], v)
2879
Gregory P. Smith7558d572009-03-31 19:03:28 +00002880 def testSynonymAssertMethodNames(self):
2881 """Test undocumented method name synonyms.
2882
2883 Please do not use these methods names in your own code.
2884
2885 This test confirms their continued existence and functionality
2886 in order to avoid breaking existing code.
2887 """
2888 self.assertNotEquals(3, 5)
2889 self.assertEquals(3, 3)
2890 self.assertAlmostEquals(2.0, 2.0)
2891 self.assertNotAlmostEquals(3.0, 5.0)
2892 self.assert_(True)
2893
2894 def testPendingDeprecationMethodNames(self):
2895 """Test fail* methods pending deprecation, they will warn in 3.2.
2896
2897 Do not use these methods. They will go away in 3.3.
2898 """
2899 self.failIfEqual(3, 5)
2900 self.failUnlessEqual(3, 3)
2901 self.failUnlessAlmostEqual(2.0, 2.0)
2902 self.failIfAlmostEqual(3.0, 5.0)
2903 self.failUnless(True)
2904 self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam')
2905 self.failIf(False)
2906
Michael Foorde2942d02009-04-02 05:51:54 +00002907 def testDeepcopy(self):
2908 # Issue: 5660
2909 class TestableTest(TestCase):
2910 def testNothing(self):
2911 pass
2912
2913 test = TestableTest('testNothing')
2914
2915 # This shouldn't blow up
2916 deepcopy(test)
2917
Benjamin Peterson692428e2009-03-23 21:50:21 +00002918
2919class Test_TestSkipping(TestCase):
2920
2921 def test_skipping(self):
2922 class Foo(unittest.TestCase):
2923 def test_skip_me(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002924 self.skipTest("skip")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002925 events = []
2926 result = LoggingResult(events)
2927 test = Foo("test_skip_me")
2928 test.run(result)
2929 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2930 self.assertEqual(result.skipped, [(test, "skip")])
2931
2932 # Try letting setUp skip the test now.
2933 class Foo(unittest.TestCase):
2934 def setUp(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002935 self.skipTest("testing")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002936 def test_nothing(self): pass
2937 events = []
2938 result = LoggingResult(events)
2939 test = Foo("test_nothing")
2940 test.run(result)
2941 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2942 self.assertEqual(result.skipped, [(test, "testing")])
2943 self.assertEqual(result.testsRun, 1)
2944
2945 def test_skipping_decorators(self):
2946 op_table = ((unittest.skipUnless, False, True),
2947 (unittest.skipIf, True, False))
2948 for deco, do_skip, dont_skip in op_table:
2949 class Foo(unittest.TestCase):
2950 @deco(do_skip, "testing")
2951 def test_skip(self): pass
2952
2953 @deco(dont_skip, "testing")
2954 def test_dont_skip(self): pass
2955 test_do_skip = Foo("test_skip")
2956 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002957 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002958 events = []
2959 result = LoggingResult(events)
2960 suite.run(result)
2961 self.assertEqual(len(result.skipped), 1)
2962 expected = ['startTest', 'addSkip', 'stopTest',
2963 'startTest', 'addSuccess', 'stopTest']
2964 self.assertEqual(events, expected)
2965 self.assertEqual(result.testsRun, 2)
2966 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
2967 self.assertTrue(result.wasSuccessful())
2968
2969 def test_skip_class(self):
2970 @unittest.skip("testing")
2971 class Foo(unittest.TestCase):
2972 def test_1(self):
2973 record.append(1)
2974 record = []
2975 result = unittest.TestResult()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002976 test = Foo("test_1")
2977 suite = unittest.TestSuite([test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002978 suite.run(result)
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002979 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002980 self.assertEqual(record, [])
2981
2982 def test_expected_failure(self):
2983 class Foo(unittest.TestCase):
2984 @unittest.expectedFailure
2985 def test_die(self):
2986 self.fail("help me!")
2987 events = []
2988 result = LoggingResult(events)
2989 test = Foo("test_die")
2990 test.run(result)
2991 self.assertEqual(events,
2992 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00002993 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00002994 self.assertTrue(result.wasSuccessful())
2995
2996 def test_unexpected_success(self):
2997 class Foo(unittest.TestCase):
2998 @unittest.expectedFailure
2999 def test_die(self):
3000 pass
3001 events = []
3002 result = LoggingResult(events)
3003 test = Foo("test_die")
3004 test.run(result)
3005 self.assertEqual(events,
3006 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3007 self.assertFalse(result.failures)
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003008 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003009 self.assertTrue(result.wasSuccessful())
3010
3011
3012
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003013class Test_Assertions(TestCase):
3014 def test_AlmostEqual(self):
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003015 self.assertAlmostEqual(1.00000001, 1.0)
3016 self.assertNotAlmostEqual(1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003017 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003018 self.assertAlmostEqual, 1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003019 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003020 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003021
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003022 self.assertAlmostEqual(1.1, 1.0, places=0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003023 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003024 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003025
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003026 self.assertAlmostEqual(0, .1+.1j, places=0)
3027 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003028 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003029 self.assertAlmostEqual, 0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003030 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003031 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003032
Michael Foordc3f79372009-09-13 16:40:02 +00003033 self.assertAlmostEqual(float('inf'), float('inf'))
3034 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3035 float('inf'), float('inf'))
3036
3037
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003038 def test_assertRaises(self):
3039 def _raise(e):
3040 raise e
3041 self.assertRaises(KeyError, _raise, KeyError)
3042 self.assertRaises(KeyError, _raise, KeyError("key"))
3043 try:
3044 self.assertRaises(KeyError, lambda: None)
Gregory P. Smith28399852009-03-31 16:54:10 +00003045 except self.failureException as e:
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003046 self.assert_("KeyError not raised" in e, str(e))
3047 else:
3048 self.fail("assertRaises() didn't fail")
3049 try:
3050 self.assertRaises(KeyError, _raise, ValueError)
3051 except ValueError:
3052 pass
3053 else:
3054 self.fail("assertRaises() didn't let exception pass through")
3055 with self.assertRaises(KeyError):
3056 raise KeyError
3057 with self.assertRaises(KeyError):
3058 raise KeyError("key")
3059 try:
3060 with self.assertRaises(KeyError):
3061 pass
Gregory P. Smith28399852009-03-31 16:54:10 +00003062 except self.failureException as e:
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003063 self.assert_("KeyError not raised" in e, str(e))
3064 else:
3065 self.fail("assertRaises() didn't fail")
3066 try:
3067 with self.assertRaises(KeyError):
3068 raise ValueError
3069 except ValueError:
3070 pass
3071 else:
3072 self.fail("assertRaises() didn't let exception pass through")
3073
3074
Michael Foord345b2fe2009-04-02 03:20:38 +00003075class TestLongMessage(TestCase):
3076 """Test that the individual asserts honour longMessage.
3077 This actually tests all the message behaviour for
3078 asserts that use longMessage."""
3079
3080 def setUp(self):
3081 class TestableTestFalse(TestCase):
3082 longMessage = False
3083 failureException = self.failureException
3084
3085 def testTest(self):
3086 pass
3087
3088 class TestableTestTrue(TestCase):
3089 longMessage = True
3090 failureException = self.failureException
3091
3092 def testTest(self):
3093 pass
3094
3095 self.testableTrue = TestableTestTrue('testTest')
3096 self.testableFalse = TestableTestFalse('testTest')
3097
3098 def testDefault(self):
3099 self.assertFalse(TestCase.longMessage)
3100
3101 def test_formatMsg(self):
3102 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3103 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3104
3105 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3106 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3107
3108 def assertMessages(self, methodName, args, errors):
3109 def getMethod(i):
3110 useTestableFalse = i < 2
3111 if useTestableFalse:
3112 test = self.testableFalse
3113 else:
3114 test = self.testableTrue
3115 return getattr(test, methodName)
3116
3117 for i, expected_regexp in enumerate(errors):
3118 testMethod = getMethod(i)
3119 kwargs = {}
3120 withMsg = i % 2
3121 if withMsg:
3122 kwargs = {"msg": "oops"}
3123
3124 with self.assertRaisesRegexp(self.failureException,
3125 expected_regexp=expected_regexp):
3126 testMethod(*args, **kwargs)
3127
3128 def testAssertTrue(self):
3129 self.assertMessages('assertTrue', (False,),
3130 ["^False is not True$", "^oops$", "^False is not True$",
3131 "^False is not True : oops$"])
3132
3133 def testAssertFalse(self):
3134 self.assertMessages('assertFalse', (True,),
3135 ["^True is not False$", "^oops$", "^True is not False$",
3136 "^True is not False : oops$"])
3137
3138 def testNotEqual(self):
3139 self.assertMessages('assertNotEqual', (1, 1),
3140 ["^1 == 1$", "^oops$", "^1 == 1$",
3141 "^1 == 1 : oops$"])
3142
3143 def testAlmostEqual(self):
3144 self.assertMessages('assertAlmostEqual', (1, 2),
3145 ["^1 != 2 within 7 places$", "^oops$",
3146 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3147
3148 def testNotAlmostEqual(self):
3149 self.assertMessages('assertNotAlmostEqual', (1, 1),
3150 ["^1 == 1 within 7 places$", "^oops$",
3151 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3152
3153 def test_baseAssertEqual(self):
3154 self.assertMessages('_baseAssertEqual', (1, 2),
3155 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3156
3157 def testAssertSequenceEqual(self):
3158 # Error messages are multiline so not testing on full message
3159 # assertTupleEqual and assertListEqual delegate to this method
3160 self.assertMessages('assertSequenceEqual', ([], [None]),
3161 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3162 r"\+ \[None\] : oops$"])
3163
3164 def testAssertSetEqual(self):
3165 self.assertMessages('assertSetEqual', (set(), set([None])),
3166 ["None$", "^oops$", "None$",
3167 "None : oops$"])
3168
3169 def testAssertIn(self):
3170 self.assertMessages('assertIn', (None, []),
3171 ['^None not found in \[\]$', "^oops$",
3172 '^None not found in \[\]$',
3173 '^None not found in \[\] : oops$'])
3174
3175 def testAssertNotIn(self):
3176 self.assertMessages('assertNotIn', (None, [None]),
3177 ['^None unexpectedly found in \[None\]$', "^oops$",
3178 '^None unexpectedly found in \[None\]$',
3179 '^None unexpectedly found in \[None\] : oops$'])
3180
3181 def testAssertDictEqual(self):
3182 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3183 [r"\+ \{'key': 'value'\}$", "^oops$",
3184 "\+ \{'key': 'value'\}$",
3185 "\+ \{'key': 'value'\} : oops$"])
3186
3187 def testAssertDictContainsSubset(self):
3188 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3189 ["^Missing: 'key'$", "^oops$",
3190 "^Missing: 'key'$",
3191 "^Missing: 'key' : oops$"])
3192
3193 def testAssertSameElements(self):
3194 self.assertMessages('assertSameElements', ([], [None]),
3195 [r"\[None\]$", "^oops$",
3196 r"\[None\]$",
3197 r"\[None\] : oops$"])
3198
3199 def testAssertMultiLineEqual(self):
3200 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3201 [r"\+ foo$", "^oops$",
3202 r"\+ foo$",
3203 r"\+ foo : oops$"])
3204
3205 def testAssertLess(self):
3206 self.assertMessages('assertLess', (2, 1),
3207 ["^2 not less than 1$", "^oops$",
3208 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3209
3210 def testAssertLessEqual(self):
3211 self.assertMessages('assertLessEqual', (2, 1),
3212 ["^2 not less than or equal to 1$", "^oops$",
3213 "^2 not less than or equal to 1$",
3214 "^2 not less than or equal to 1 : oops$"])
3215
3216 def testAssertGreater(self):
3217 self.assertMessages('assertGreater', (1, 2),
3218 ["^1 not greater than 2$", "^oops$",
3219 "^1 not greater than 2$",
3220 "^1 not greater than 2 : oops$"])
3221
3222 def testAssertGreaterEqual(self):
3223 self.assertMessages('assertGreaterEqual', (1, 2),
3224 ["^1 not greater than or equal to 2$", "^oops$",
3225 "^1 not greater than or equal to 2$",
3226 "^1 not greater than or equal to 2 : oops$"])
3227
3228 def testAssertIsNone(self):
3229 self.assertMessages('assertIsNone', ('not None',),
3230 ["^'not None' is not None$", "^oops$",
3231 "^'not None' is not None$",
3232 "^'not None' is not None : oops$"])
3233
3234 def testAssertIsNotNone(self):
3235 self.assertMessages('assertIsNotNone', (None,),
3236 ["^unexpectedly None$", "^oops$",
3237 "^unexpectedly None$",
3238 "^unexpectedly None : oops$"])
3239
Michael Foordf2dfef12009-04-05 19:19:28 +00003240 def testAssertIs(self):
3241 self.assertMessages('assertIs', (None, 'foo'),
3242 ["^None is not 'foo'$", "^oops$",
3243 "^None is not 'foo'$",
3244 "^None is not 'foo' : oops$"])
3245
3246 def testAssertIsNot(self):
3247 self.assertMessages('assertIsNot', (None, None),
3248 ["^unexpectedly identical: None$", "^oops$",
3249 "^unexpectedly identical: None$",
3250 "^unexpectedly identical: None : oops$"])
3251
Michael Foord345b2fe2009-04-02 03:20:38 +00003252
Michael Foorde2fb98f2009-05-02 20:15:05 +00003253class TestCleanUp(TestCase):
3254
3255 def testCleanUp(self):
3256 class TestableTest(TestCase):
3257 def testNothing(self):
3258 pass
3259
3260 test = TestableTest('testNothing')
3261 self.assertEqual(test._cleanups, [])
3262
3263 cleanups = []
3264
3265 def cleanup1(*args, **kwargs):
3266 cleanups.append((1, args, kwargs))
3267
3268 def cleanup2(*args, **kwargs):
3269 cleanups.append((2, args, kwargs))
3270
3271 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3272 test.addCleanup(cleanup2)
3273
3274 self.assertEqual(test._cleanups,
3275 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3276 (cleanup2, (), {})])
3277
3278 result = test.doCleanups()
3279 self.assertTrue(result)
3280
3281 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3282
3283 def testCleanUpWithErrors(self):
3284 class TestableTest(TestCase):
3285 def testNothing(self):
3286 pass
3287
3288 class MockResult(object):
3289 errors = []
3290 def addError(self, test, exc_info):
3291 self.errors.append((test, exc_info))
3292
3293 result = MockResult()
3294 test = TestableTest('testNothing')
Michael Foorda50af062009-05-21 22:57:02 +00003295 test._resultForDoCleanups = result
Michael Foorde2fb98f2009-05-02 20:15:05 +00003296
3297 exc1 = Exception('foo')
3298 exc2 = Exception('bar')
3299 def cleanup1():
3300 raise exc1
3301
3302 def cleanup2():
3303 raise exc2
3304
3305 test.addCleanup(cleanup1)
3306 test.addCleanup(cleanup2)
3307
3308 self.assertFalse(test.doCleanups())
3309
3310 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3311 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3312 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3313
3314 def testCleanupInRun(self):
3315 blowUp = False
3316 ordering = []
3317
3318 class TestableTest(TestCase):
3319 def setUp(self):
3320 ordering.append('setUp')
3321 if blowUp:
3322 raise Exception('foo')
3323
3324 def testNothing(self):
3325 ordering.append('test')
3326
3327 def tearDown(self):
3328 ordering.append('tearDown')
3329
3330 test = TestableTest('testNothing')
3331
3332 def cleanup1():
3333 ordering.append('cleanup1')
3334 def cleanup2():
3335 ordering.append('cleanup2')
3336 test.addCleanup(cleanup1)
3337 test.addCleanup(cleanup2)
3338
3339 def success(some_test):
3340 self.assertEqual(some_test, test)
3341 ordering.append('success')
3342
3343 result = unittest.TestResult()
3344 result.addSuccess = success
3345
3346 test.run(result)
3347 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3348 'cleanup2', 'cleanup1', 'success'])
3349
3350 blowUp = True
3351 ordering = []
3352 test = TestableTest('testNothing')
3353 test.addCleanup(cleanup1)
3354 test.run(result)
3355 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3356
3357
Michael Foord829f6b82009-05-02 11:43:06 +00003358class Test_TestProgram(TestCase):
3359
3360 # Horrible white box test
3361 def testNoExit(self):
3362 result = object()
3363 test = object()
3364
3365 class FakeRunner(object):
3366 def run(self, test):
3367 self.test = test
3368 return result
3369
3370 runner = FakeRunner()
3371
Michael Foord5d31e052009-05-11 17:59:43 +00003372 oldParseArgs = TestProgram.parseArgs
3373 def restoreParseArgs():
Michael Foord829f6b82009-05-02 11:43:06 +00003374 TestProgram.parseArgs = oldParseArgs
Michael Foord5d31e052009-05-11 17:59:43 +00003375 TestProgram.parseArgs = lambda *args: None
3376 self.addCleanup(restoreParseArgs)
3377
3378 def removeTest():
Michael Foord829f6b82009-05-02 11:43:06 +00003379 del TestProgram.test
Michael Foord5d31e052009-05-11 17:59:43 +00003380 TestProgram.test = test
3381 self.addCleanup(removeTest)
3382
3383 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3384
3385 self.assertEqual(program.result, result)
3386 self.assertEqual(runner.test, test)
3387 self.assertEqual(program.verbosity, 2)
Michael Foord829f6b82009-05-02 11:43:06 +00003388
Michael Foord829f6b82009-05-02 11:43:06 +00003389 class FooBar(unittest.TestCase):
3390 def testPass(self):
3391 assert True
3392 def testFail(self):
3393 assert False
3394
3395 class FooBarLoader(unittest.TestLoader):
3396 """Test loader that returns a suite containing FooBar."""
3397 def loadTestsFromModule(self, module):
3398 return self.suiteClass(
3399 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3400
3401
3402 def test_NonExit(self):
3403 program = unittest.main(exit=False,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003404 argv=["foobar"],
3405 testRunner=unittest.TextTestRunner(stream=StringIO()),
3406 testLoader=self.FooBarLoader())
Michael Foord829f6b82009-05-02 11:43:06 +00003407 self.assertTrue(hasattr(program, 'result'))
3408
3409
3410 def test_Exit(self):
3411 self.assertRaises(
3412 SystemExit,
3413 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003414 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003415 testRunner=unittest.TextTestRunner(stream=StringIO()),
3416 exit=True,
3417 testLoader=self.FooBarLoader())
3418
3419
3420 def test_ExitAsDefault(self):
3421 self.assertRaises(
3422 SystemExit,
3423 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003424 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003425 testRunner=unittest.TextTestRunner(stream=StringIO()),
3426 testLoader=self.FooBarLoader())
3427
3428
Michael Foord07ef4872009-05-02 22:43:34 +00003429class Test_TextTestRunner(TestCase):
3430 """Tests for TextTestRunner."""
3431
3432 def test_works_with_result_without_startTestRun_stopTestRun(self):
3433 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3434 separator2 = ''
3435 def printErrors(self):
3436 pass
3437
3438 class Runner(unittest.TextTestRunner):
3439 def __init__(self):
3440 super(Runner, self).__init__(StringIO())
3441
3442 def _makeResult(self):
3443 return OldTextResult()
3444
3445 runner = Runner()
3446 runner.run(unittest.TestSuite())
3447
3448 def test_startTestRun_stopTestRun_called(self):
3449 class LoggingTextResult(LoggingResult):
3450 separator2 = ''
3451 def printErrors(self):
3452 pass
3453
3454 class LoggingRunner(unittest.TextTestRunner):
3455 def __init__(self, events):
3456 super(LoggingRunner, self).__init__(StringIO())
3457 self._events = events
3458
3459 def _makeResult(self):
3460 return LoggingTextResult(self._events)
3461
3462 events = []
3463 runner = LoggingRunner(events)
3464 runner.run(unittest.TestSuite())
3465 expected = ['startTestRun', 'stopTestRun']
3466 self.assertEqual(events, expected)
3467
3468
Michael Foordb4a81c82009-05-29 20:33:46 +00003469class TestDiscovery(TestCase):
3470
3471 # Heavily mocked tests so I can avoid hitting the filesystem
Michael Foorde91ea562009-09-13 19:07:03 +00003472 def test_get_name_from_path(self):
Michael Foordb4a81c82009-05-29 20:33:46 +00003473 loader = unittest.TestLoader()
3474
Michael Foordb4a81c82009-05-29 20:33:46 +00003475 loader._top_level_dir = '/foo'
Michael Foorde91ea562009-09-13 19:07:03 +00003476 name = loader._get_name_from_path('/foo/bar/baz.py')
3477 self.assertEqual(name, 'bar.baz')
Michael Foordb4a81c82009-05-29 20:33:46 +00003478
3479 if not __debug__:
3480 # asserts are off
3481 return
3482
3483 with self.assertRaises(AssertionError):
Michael Foorde91ea562009-09-13 19:07:03 +00003484 loader._get_name_from_path('/bar/baz.py')
Michael Foordb4a81c82009-05-29 20:33:46 +00003485
3486 def test_find_tests(self):
3487 loader = unittest.TestLoader()
3488
3489 original_listdir = os.listdir
3490 def restore_listdir():
3491 os.listdir = original_listdir
3492 original_isfile = os.path.isfile
3493 def restore_isfile():
3494 os.path.isfile = original_isfile
3495 original_isdir = os.path.isdir
3496 def restore_isdir():
3497 os.path.isdir = original_isdir
3498
3499 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Michael Foorde91ea562009-09-13 19:07:03 +00003500 'test.foo', 'test-not-a-module.py', 'another_dir'],
Michael Foordb4a81c82009-05-29 20:33:46 +00003501 ['test3.py', 'test4.py', ]]
3502 os.listdir = lambda path: path_lists.pop(0)
3503 self.addCleanup(restore_listdir)
3504
3505 def isdir(path):
3506 return path.endswith('dir')
3507 os.path.isdir = isdir
3508 self.addCleanup(restore_isdir)
3509
3510 def isfile(path):
3511 # another_dir is not a package and so shouldn't be recursed into
3512 return not path.endswith('dir') and not 'another_dir' in path
3513 os.path.isfile = isfile
3514 self.addCleanup(restore_isfile)
3515
Michael Foorde91ea562009-09-13 19:07:03 +00003516 loader._get_module_from_name = lambda path: path + ' module'
Michael Foordb4a81c82009-05-29 20:33:46 +00003517 loader.loadTestsFromModule = lambda module: module + ' tests'
3518
3519 loader._top_level_dir = '/foo'
3520 suite = list(loader._find_tests('/foo', 'test*.py'))
3521
Michael Foorde91ea562009-09-13 19:07:03 +00003522 expected = [name + ' module tests' for name in
3523 ('test1', 'test2')]
3524 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3525 ('test3', 'test4')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003526 self.assertEqual(suite, expected)
3527
3528 def test_find_tests_with_package(self):
3529 loader = unittest.TestLoader()
3530
3531 original_listdir = os.listdir
3532 def restore_listdir():
3533 os.listdir = original_listdir
3534 original_isfile = os.path.isfile
3535 def restore_isfile():
3536 os.path.isfile = original_isfile
3537 original_isdir = os.path.isdir
3538 def restore_isdir():
3539 os.path.isdir = original_isdir
3540
3541 directories = ['a_directory', 'test_directory', 'test_directory2']
3542 path_lists = [directories, [], [], []]
3543 os.listdir = lambda path: path_lists.pop(0)
3544 self.addCleanup(restore_listdir)
3545
3546 os.path.isdir = lambda path: True
3547 self.addCleanup(restore_isdir)
3548
3549 os.path.isfile = lambda path: os.path.basename(path) not in directories
3550 self.addCleanup(restore_isfile)
3551
3552 class Module(object):
3553 paths = []
3554 load_tests_args = []
3555
3556 def __init__(self, path):
3557 self.path = path
3558 self.paths.append(path)
3559 if os.path.basename(path) == 'test_directory':
3560 def load_tests(loader, tests, pattern):
3561 self.load_tests_args.append((loader, tests, pattern))
3562 return 'load_tests'
3563 self.load_tests = load_tests
3564
3565 def __eq__(self, other):
3566 return self.path == other.path
3567
Michael Foorde91ea562009-09-13 19:07:03 +00003568 loader._get_module_from_name = lambda name: Module(name)
Michael Foordb4a81c82009-05-29 20:33:46 +00003569 def loadTestsFromModule(module, use_load_tests):
3570 if use_load_tests:
3571 raise self.failureException('use_load_tests should be False for packages')
3572 return module.path + ' module tests'
3573 loader.loadTestsFromModule = loadTestsFromModule
3574
3575 loader._top_level_dir = '/foo'
3576 # this time no '.py' on the pattern so that it can match
3577 # a test package
3578 suite = list(loader._find_tests('/foo', 'test*'))
3579
3580 # We should have loaded tests from the test_directory package by calling load_tests
3581 # and directly from the test_directory2 package
Michael Foordd53d0852009-06-05 14:14:34 +00003582 self.assertEqual(suite,
Michael Foorde91ea562009-09-13 19:07:03 +00003583 ['load_tests', 'test_directory2' + ' module tests'])
3584 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Michael Foordb4a81c82009-05-29 20:33:46 +00003585
3586 # load_tests should have been called once with loader, tests and pattern
3587 self.assertEqual(Module.load_tests_args,
Michael Foorde91ea562009-09-13 19:07:03 +00003588 [(loader, 'test_directory' + ' module tests', 'test*')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003589
3590 def test_discover(self):
3591 loader = unittest.TestLoader()
3592
3593 original_isfile = os.path.isfile
3594 def restore_isfile():
3595 os.path.isfile = original_isfile
3596
3597 os.path.isfile = lambda path: False
3598 self.addCleanup(restore_isfile)
3599
3600 full_path = os.path.abspath(os.path.normpath('/foo'))
3601 def clean_path():
3602 if sys.path[-1] == full_path:
3603 sys.path.pop(-1)
3604 self.addCleanup(clean_path)
3605
3606 with self.assertRaises(ImportError):
3607 loader.discover('/foo/bar', top_level_dir='/foo')
3608
3609 self.assertEqual(loader._top_level_dir, full_path)
3610 self.assertIn(full_path, sys.path)
3611
3612 os.path.isfile = lambda path: True
3613 _find_tests_args = []
3614 def _find_tests(start_dir, pattern):
3615 _find_tests_args.append((start_dir, pattern))
3616 return ['tests']
3617 loader._find_tests = _find_tests
3618 loader.suiteClass = str
3619
3620 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3621
3622 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3623 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3624 self.assertEqual(suite, "['tests']")
3625 self.assertEqual(loader._top_level_dir, top_level_dir)
3626 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
3627
Michael Foorde91ea562009-09-13 19:07:03 +00003628 def test_discover_with_modules_that_fail_to_import(self):
3629 loader = unittest.TestLoader()
3630
3631 listdir = os.listdir
3632 os.listdir = lambda _: ['test_this_does_not_exist.py']
3633 isfile = os.path.isfile
3634 os.path.isfile = lambda _: True
3635 def restore():
3636 os.path.isfile = isfile
3637 os.listdir = listdir
3638 self.addCleanup(restore)
3639
3640 suite = loader.discover('.')
3641 self.assertEqual(suite.countTestCases(), 1)
3642 test = list(list(suite)[0])[0] # extract test from suite
3643
3644 with self.assertRaises(ImportError):
3645 test.test_this_does_not_exist()
3646
Michael Foordb4a81c82009-05-29 20:33:46 +00003647 def test_command_line_handling_parseArgs(self):
3648 # Haha - take that uninstantiable class
3649 program = object.__new__(TestProgram)
3650
3651 args = []
3652 def do_discovery(argv):
3653 args.extend(argv)
3654 program._do_discovery = do_discovery
3655 program.parseArgs(['something', 'discover'])
3656 self.assertEqual(args, [])
3657
3658 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3659 self.assertEqual(args, ['foo', 'bar'])
3660
3661 def test_command_line_handling_do_discovery_too_many_arguments(self):
3662 class Stop(Exception):
3663 pass
3664 def usageExit():
3665 raise Stop
3666
3667 program = object.__new__(TestProgram)
3668 program.usageExit = usageExit
3669
3670 with self.assertRaises(Stop):
3671 # too many args
3672 program._do_discovery(['one', 'two', 'three', 'four'])
3673
3674
3675 def test_command_line_handling_do_discovery_calls_loader(self):
3676 program = object.__new__(TestProgram)
3677
3678 class Loader(object):
3679 args = []
3680 def discover(self, start_dir, pattern, top_level_dir):
3681 self.args.append((start_dir, pattern, top_level_dir))
3682 return 'tests'
3683
3684 program._do_discovery(['-v'], Loader=Loader)
3685 self.assertEqual(program.verbosity, 2)
3686 self.assertEqual(program.test, 'tests')
3687 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3688
3689 Loader.args = []
3690 program = object.__new__(TestProgram)
3691 program._do_discovery(['--verbose'], Loader=Loader)
3692 self.assertEqual(program.test, 'tests')
3693 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3694
3695 Loader.args = []
3696 program = object.__new__(TestProgram)
3697 program._do_discovery([], Loader=Loader)
3698 self.assertEqual(program.test, 'tests')
3699 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3700
3701 Loader.args = []
3702 program = object.__new__(TestProgram)
3703 program._do_discovery(['fish'], Loader=Loader)
3704 self.assertEqual(program.test, 'tests')
3705 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3706
3707 Loader.args = []
3708 program = object.__new__(TestProgram)
3709 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3710 self.assertEqual(program.test, 'tests')
3711 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3712
3713 Loader.args = []
3714 program = object.__new__(TestProgram)
3715 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3716 self.assertEqual(program.test, 'tests')
3717 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3718
3719 Loader.args = []
3720 program = object.__new__(TestProgram)
3721 program._do_discovery(['-s', 'fish'], Loader=Loader)
3722 self.assertEqual(program.test, 'tests')
3723 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3724
3725 Loader.args = []
3726 program = object.__new__(TestProgram)
3727 program._do_discovery(['-t', 'fish'], Loader=Loader)
3728 self.assertEqual(program.test, 'tests')
3729 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3730
3731 Loader.args = []
3732 program = object.__new__(TestProgram)
3733 program._do_discovery(['-p', 'fish'], Loader=Loader)
3734 self.assertEqual(program.test, 'tests')
3735 self.assertEqual(Loader.args, [('.', 'fish', None)])
3736
3737 Loader.args = []
3738 program = object.__new__(TestProgram)
3739 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3740 self.assertEqual(program.test, 'tests')
3741 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3742 self.assertEqual(program.verbosity, 2)
3743
3744
Jim Fultonfafd8742004-08-28 15:22:12 +00003745######################################################################
3746## Main
3747######################################################################
3748
3749def test_main():
Georg Brandl15c5ce92007-03-07 09:09:40 +00003750 test_support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003751 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Michael Foord829f6b82009-05-02 11:43:06 +00003752 Test_TestSkipping, Test_Assertions, TestLongMessage,
Michael Foordb4a81c82009-05-29 20:33:46 +00003753 Test_TestProgram, TestCleanUp, TestDiscovery)
Jim Fultonfafd8742004-08-28 15:22:12 +00003754
Georg Brandl15c5ce92007-03-07 09:09:40 +00003755if __name__ == "__main__":
Tim Petersea5962f2007-03-12 18:07:52 +00003756 test_main()