blob: 5c3921dfd984f58a867af0af3ba4834c57248929 [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
558 # ... a callable object which returns a TestCase or TestSuite instance"
559 #
560 # What happens if the callable returns something else?
561 def test_loadTestsFromName__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000562 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000563 def return_wrong():
564 return 6
565 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000566
Georg Brandl15c5ce92007-03-07 09:09:40 +0000567 loader = unittest.TestLoader()
568 try:
569 suite = loader.loadTestsFromName('return_wrong', m)
570 except TypeError:
571 pass
572 else:
573 self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000574
Georg Brandl15c5ce92007-03-07 09:09:40 +0000575 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +0000576 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +0000577 def test_loadTestsFromName__module_not_loaded(self):
578 # We're going to try to load this module as a side-effect, so it
579 # better not be loaded before we try.
580 #
581 # Why pick audioop? Google shows it isn't used very often, so there's
582 # a good chance that it won't be imported when this test is run
583 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +0000584
Georg Brandl15c5ce92007-03-07 09:09:40 +0000585 import sys
586 if module_name in sys.modules:
587 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000588
Georg Brandl15c5ce92007-03-07 09:09:40 +0000589 loader = unittest.TestLoader()
590 try:
591 suite = loader.loadTestsFromName(module_name)
592
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000593 self.assertTrue(isinstance(suite, loader.suiteClass))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000594 self.assertEqual(list(suite), [])
595
596 # audioop should now be loaded, thanks to loadTestsFromName()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000597 self.assertTrue(module_name in sys.modules)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000598 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000599 if module_name in sys.modules:
600 del sys.modules[module_name]
Georg Brandl15c5ce92007-03-07 09:09:40 +0000601
602 ################################################################
603 ### Tests for TestLoader.loadTestsFromName()
604
605 ### Tests for TestLoader.loadTestsFromNames()
606 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000607
Georg Brandl15c5ce92007-03-07 09:09:40 +0000608 # "Similar to loadTestsFromName(), but takes a sequence of names rather
609 # than a single name."
610 #
611 # What happens if that sequence of names is empty?
612 def test_loadTestsFromNames__empty_name_list(self):
613 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000614
Georg Brandl15c5ce92007-03-07 09:09:40 +0000615 suite = loader.loadTestsFromNames([])
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000616 self.assertTrue(isinstance(suite, loader.suiteClass))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000617 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000618
Georg Brandl15c5ce92007-03-07 09:09:40 +0000619 # "Similar to loadTestsFromName(), but takes a sequence of names rather
620 # than a single name."
621 # ...
622 # "The method optionally resolves name relative to the given module"
623 #
624 # What happens if that sequence of names is empty?
625 #
626 # XXX Should this raise a ValueError or just return an empty TestSuite?
627 def test_loadTestsFromNames__relative_empty_name_list(self):
628 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000629
Georg Brandl15c5ce92007-03-07 09:09:40 +0000630 suite = loader.loadTestsFromNames([], unittest)
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000631 self.assertTrue(isinstance(suite, loader.suiteClass))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000632 self.assertEqual(list(suite), [])
633
634 # "The specifier name is a ``dotted name'' that may resolve either to
635 # a module, a test case class, a TestSuite instance, a test method
636 # within a test case class, or a callable object which returns a
637 # TestCase or TestSuite instance."
638 #
639 # Is ValueError raised in response to an empty name?
640 def test_loadTestsFromNames__empty_name(self):
641 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000642
Georg Brandl15c5ce92007-03-07 09:09:40 +0000643 try:
644 loader.loadTestsFromNames([''])
645 except ValueError, e:
646 self.assertEqual(str(e), "Empty module name")
647 else:
648 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000649
Georg Brandl15c5ce92007-03-07 09:09:40 +0000650 # "The specifier name is a ``dotted name'' that may resolve either to
651 # a module, a test case class, a TestSuite instance, a test method
652 # within a test case class, or a callable object which returns a
653 # TestCase or TestSuite instance."
654 #
Tim Petersea5962f2007-03-12 18:07:52 +0000655 # What happens when presented with an impossible module name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000656 def test_loadTestsFromNames__malformed_name(self):
657 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000658
Georg Brandl15c5ce92007-03-07 09:09:40 +0000659 # XXX Should this raise ValueError or ImportError?
660 try:
661 loader.loadTestsFromNames(['abc () //'])
662 except ValueError:
663 pass
664 except ImportError:
665 pass
666 else:
667 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000668
Georg Brandl15c5ce92007-03-07 09:09:40 +0000669 # "The specifier name is a ``dotted name'' that may resolve either to
670 # a module, a test case class, a TestSuite instance, a test method
671 # within a test case class, or a callable object which returns a
672 # TestCase or TestSuite instance."
673 #
Tim Petersea5962f2007-03-12 18:07:52 +0000674 # What happens when no module can be found for the given name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000675 def test_loadTestsFromNames__unknown_module_name(self):
676 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000677
Georg Brandl15c5ce92007-03-07 09:09:40 +0000678 try:
679 loader.loadTestsFromNames(['sdasfasfasdf'])
680 except ImportError, e:
681 self.assertEqual(str(e), "No module named sdasfasfasdf")
682 else:
683 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000684
Georg Brandl15c5ce92007-03-07 09:09:40 +0000685 # "The specifier name is a ``dotted name'' that may resolve either to
686 # a module, a test case class, a TestSuite instance, a test method
687 # within a test case class, or a callable object which returns a
688 # TestCase or TestSuite instance."
689 #
Tim Petersea5962f2007-03-12 18:07:52 +0000690 # What happens when the module can be found, but not the attribute?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000691 def test_loadTestsFromNames__unknown_attr_name(self):
692 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000693
Georg Brandl15c5ce92007-03-07 09:09:40 +0000694 try:
695 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
696 except AttributeError, e:
697 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
698 else:
699 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000700
Georg Brandl15c5ce92007-03-07 09:09:40 +0000701 # "The specifier name is a ``dotted name'' that may resolve either to
702 # a module, a test case class, a TestSuite instance, a test method
703 # within a test case class, or a callable object which returns a
704 # TestCase or TestSuite instance."
705 # ...
706 # "The method optionally resolves name relative to the given module"
707 #
708 # What happens when given an unknown attribute on a specified `module`
709 # argument?
710 def test_loadTestsFromNames__unknown_name_relative_1(self):
711 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000712
Georg Brandl15c5ce92007-03-07 09:09:40 +0000713 try:
714 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
715 except AttributeError, e:
716 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
717 else:
718 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000719
Georg Brandl15c5ce92007-03-07 09:09:40 +0000720 # "The specifier name is a ``dotted name'' that may resolve either to
721 # a module, a test case class, a TestSuite instance, a test method
722 # within a test case class, or a callable object which returns a
723 # TestCase or TestSuite instance."
724 # ...
725 # "The method optionally resolves name relative to the given module"
726 #
727 # Do unknown attributes (relative to a provided module) still raise an
Tim Petersea5962f2007-03-12 18:07:52 +0000728 # exception even in the presence of valid attribute names?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000729 def test_loadTestsFromNames__unknown_name_relative_2(self):
730 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000731
Georg Brandl15c5ce92007-03-07 09:09:40 +0000732 try:
733 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
734 except AttributeError, e:
735 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
736 else:
737 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
738
739 # "The specifier name is a ``dotted name'' that may resolve either to
740 # a module, a test case class, a TestSuite instance, a test method
741 # within a test case class, or a callable object which returns a
742 # TestCase or TestSuite instance."
743 # ...
744 # "The method optionally resolves name relative to the given module"
745 #
746 # What happens when faced with the empty string?
747 #
748 # XXX This currently raises AttributeError, though ValueError is probably
749 # more appropriate
750 def test_loadTestsFromNames__relative_empty_name(self):
751 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000752
Georg Brandl15c5ce92007-03-07 09:09:40 +0000753 try:
754 loader.loadTestsFromNames([''], unittest)
755 except AttributeError:
756 pass
757 else:
758 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000759
Georg Brandl15c5ce92007-03-07 09:09:40 +0000760 # "The specifier name is a ``dotted name'' that may resolve either to
761 # a module, a test case class, a TestSuite instance, a test method
762 # within a test case class, or a callable object which returns a
763 # TestCase or TestSuite instance."
764 # ...
765 # "The method optionally resolves name relative to the given module"
766 #
Tim Petersea5962f2007-03-12 18:07:52 +0000767 # What happens when presented with an impossible attribute name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000768 def test_loadTestsFromNames__relative_malformed_name(self):
769 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000770
Georg Brandl15c5ce92007-03-07 09:09:40 +0000771 # XXX Should this raise AttributeError or ValueError?
772 try:
773 loader.loadTestsFromNames(['abc () //'], unittest)
774 except AttributeError:
775 pass
776 except ValueError:
777 pass
778 else:
779 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
780
781 # "The method optionally resolves name relative to the given module"
782 #
783 # Does loadTestsFromNames() make sure the provided `module` is in fact
784 # a module?
785 #
786 # XXX This validation is currently not done. This flexibility should
787 # either be documented or a TypeError should be raised.
788 def test_loadTestsFromNames__relative_not_a_module(self):
789 class MyTestCase(unittest.TestCase):
790 def test(self):
791 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000792
Georg Brandl15c5ce92007-03-07 09:09:40 +0000793 class NotAModule(object):
794 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000795
Georg Brandl15c5ce92007-03-07 09:09:40 +0000796 loader = unittest.TestLoader()
797 suite = loader.loadTestsFromNames(['test_2'], NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000798
Georg Brandl15c5ce92007-03-07 09:09:40 +0000799 reference = [unittest.TestSuite([MyTestCase('test')])]
800 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000801
Georg Brandl15c5ce92007-03-07 09:09:40 +0000802 # "The specifier name is a ``dotted name'' that may resolve either to
803 # a module, a test case class, a TestSuite instance, a test method
804 # within a test case class, or a callable object which returns a
805 # TestCase or TestSuite instance."
806 #
807 # Does it raise an exception if the name resolves to an invalid
808 # object?
809 def test_loadTestsFromNames__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000810 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000811 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000812
Georg Brandl15c5ce92007-03-07 09:09:40 +0000813 loader = unittest.TestLoader()
814 try:
815 loader.loadTestsFromNames(['testcase_1'], m)
816 except TypeError:
817 pass
818 else:
819 self.fail("Should have raised TypeError")
820
821 # "The specifier name is a ``dotted name'' that may resolve ... to
822 # ... a test case class"
823 def test_loadTestsFromNames__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000824 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000825 class MyTestCase(unittest.TestCase):
826 def test(self):
827 pass
828 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000829
Georg Brandl15c5ce92007-03-07 09:09:40 +0000830 loader = unittest.TestLoader()
831 suite = loader.loadTestsFromNames(['testcase_1'], m)
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000832 self.assertTrue(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000833
Georg Brandl15c5ce92007-03-07 09:09:40 +0000834 expected = loader.suiteClass([MyTestCase('test')])
835 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000836
Georg Brandl15c5ce92007-03-07 09:09:40 +0000837 # "The specifier name is a ``dotted name'' that may resolve ... to
838 # ... a TestSuite instance"
839 def test_loadTestsFromNames__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000840 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000841 class MyTestCase(unittest.TestCase):
842 def test(self):
843 pass
844 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000845
Georg Brandl15c5ce92007-03-07 09:09:40 +0000846 loader = unittest.TestLoader()
847 suite = loader.loadTestsFromNames(['testsuite'], m)
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000848 self.assertTrue(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000849
Georg Brandl15c5ce92007-03-07 09:09:40 +0000850 self.assertEqual(list(suite), [m.testsuite])
Tim Petersea5962f2007-03-12 18:07:52 +0000851
Georg Brandl15c5ce92007-03-07 09:09:40 +0000852 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
853 # test method within a test case class"
854 def test_loadTestsFromNames__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000855 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000856 class MyTestCase(unittest.TestCase):
857 def test(self):
858 pass
859 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000860
Georg Brandl15c5ce92007-03-07 09:09:40 +0000861 loader = unittest.TestLoader()
862 suite = loader.loadTestsFromNames(['testcase_1.test'], m)
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000863 self.assertTrue(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000864
Georg Brandl15c5ce92007-03-07 09:09:40 +0000865 ref_suite = unittest.TestSuite([MyTestCase('test')])
866 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000867
Georg Brandl15c5ce92007-03-07 09:09:40 +0000868 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
869 # test method within a test case class"
870 #
871 # Does the method gracefully handle names that initially look like they
Tim Petersea5962f2007-03-12 18:07:52 +0000872 # resolve to "a test method within a test case class" but don't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000873 def test_loadTestsFromNames__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000874 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000875 class MyTestCase(unittest.TestCase):
876 def test(self):
877 pass
878 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000879
Georg Brandl15c5ce92007-03-07 09:09:40 +0000880 loader = unittest.TestLoader()
881 try:
882 loader.loadTestsFromNames(['testcase_1.testfoo'], m)
883 except AttributeError, e:
884 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
885 else:
886 self.fail("Failed to raise AttributeError")
887
888 # "The specifier name is a ``dotted name'' that may resolve ... to
889 # ... a callable object which returns a ... TestSuite instance"
890 def test_loadTestsFromNames__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000891 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000892 testcase_1 = unittest.FunctionTestCase(lambda: None)
893 testcase_2 = unittest.FunctionTestCase(lambda: None)
894 def return_TestSuite():
895 return unittest.TestSuite([testcase_1, testcase_2])
896 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000897
Georg Brandl15c5ce92007-03-07 09:09:40 +0000898 loader = unittest.TestLoader()
899 suite = loader.loadTestsFromNames(['return_TestSuite'], m)
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000900 self.assertTrue(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000901
Georg Brandl15c5ce92007-03-07 09:09:40 +0000902 expected = unittest.TestSuite([testcase_1, testcase_2])
903 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000904
Georg Brandl15c5ce92007-03-07 09:09:40 +0000905 # "The specifier name is a ``dotted name'' that may resolve ... to
906 # ... a callable object which returns a TestCase ... instance"
907 def test_loadTestsFromNames__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000908 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000909 testcase_1 = unittest.FunctionTestCase(lambda: None)
910 def return_TestCase():
911 return testcase_1
912 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000913
Georg Brandl15c5ce92007-03-07 09:09:40 +0000914 loader = unittest.TestLoader()
915 suite = loader.loadTestsFromNames(['return_TestCase'], m)
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000916 self.assertTrue(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000917
Georg Brandl15c5ce92007-03-07 09:09:40 +0000918 ref_suite = unittest.TestSuite([testcase_1])
919 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000920
Georg Brandl15c5ce92007-03-07 09:09:40 +0000921 # "The specifier name is a ``dotted name'' that may resolve ... to
922 # ... a callable object which returns a TestCase or TestSuite instance"
923 #
Tim Petersea5962f2007-03-12 18:07:52 +0000924 # Are staticmethods handled correctly?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000925 def test_loadTestsFromNames__callable__call_staticmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000926 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000927 class Test1(unittest.TestCase):
928 def test(self):
929 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000930
Georg Brandl15c5ce92007-03-07 09:09:40 +0000931 testcase_1 = Test1('test')
932 class Foo(unittest.TestCase):
933 @staticmethod
934 def foo():
935 return testcase_1
936 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +0000937
Georg Brandl15c5ce92007-03-07 09:09:40 +0000938 loader = unittest.TestLoader()
939 suite = loader.loadTestsFromNames(['Foo.foo'], m)
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000940 self.assertTrue(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000941
Georg Brandl15c5ce92007-03-07 09:09:40 +0000942 ref_suite = unittest.TestSuite([testcase_1])
943 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000944
Georg Brandl15c5ce92007-03-07 09:09:40 +0000945 # "The specifier name is a ``dotted name'' that may resolve ... to
946 # ... a callable object which returns a TestCase or TestSuite instance"
947 #
948 # What happens when the callable returns something else?
949 def test_loadTestsFromNames__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000950 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000951 def return_wrong():
952 return 6
953 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000954
Georg Brandl15c5ce92007-03-07 09:09:40 +0000955 loader = unittest.TestLoader()
956 try:
957 suite = loader.loadTestsFromNames(['return_wrong'], m)
958 except TypeError:
959 pass
960 else:
961 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000962
Georg Brandl15c5ce92007-03-07 09:09:40 +0000963 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +0000964 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +0000965 def test_loadTestsFromNames__module_not_loaded(self):
966 # We're going to try to load this module as a side-effect, so it
967 # better not be loaded before we try.
968 #
969 # Why pick audioop? Google shows it isn't used very often, so there's
970 # a good chance that it won't be imported when this test is run
971 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +0000972
Georg Brandl15c5ce92007-03-07 09:09:40 +0000973 import sys
974 if module_name in sys.modules:
975 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000976
Georg Brandl15c5ce92007-03-07 09:09:40 +0000977 loader = unittest.TestLoader()
978 try:
979 suite = loader.loadTestsFromNames([module_name])
980
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000981 self.assertTrue(isinstance(suite, loader.suiteClass))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000982 self.assertEqual(list(suite), [unittest.TestSuite()])
983
984 # audioop should now be loaded, thanks to loadTestsFromName()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000985 self.assertTrue(module_name in sys.modules)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000986 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000987 if module_name in sys.modules:
988 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000989
Georg Brandl15c5ce92007-03-07 09:09:40 +0000990 ################################################################
991 ### /Tests for TestLoader.loadTestsFromNames()
992
993 ### Tests for TestLoader.getTestCaseNames()
994 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000995
Georg Brandl15c5ce92007-03-07 09:09:40 +0000996 # "Return a sorted sequence of method names found within testCaseClass"
997 #
998 # Test.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +0000999 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +00001000 def test_getTestCaseNames(self):
1001 class Test(unittest.TestCase):
1002 def test_1(self): pass
1003 def test_2(self): pass
1004 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001005
Georg Brandl15c5ce92007-03-07 09:09:40 +00001006 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001007
Georg Brandl15c5ce92007-03-07 09:09:40 +00001008 self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])
Tim Petersea5962f2007-03-12 18:07:52 +00001009
Georg Brandl15c5ce92007-03-07 09:09:40 +00001010 # "Return a sorted sequence of method names found within testCaseClass"
1011 #
Tim Petersea5962f2007-03-12 18:07:52 +00001012 # Does getTestCaseNames() behave appropriately if no tests are found?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001013 def test_getTestCaseNames__no_tests(self):
1014 class Test(unittest.TestCase):
1015 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001016
Georg Brandl15c5ce92007-03-07 09:09:40 +00001017 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001018
Georg Brandl15c5ce92007-03-07 09:09:40 +00001019 self.assertEqual(loader.getTestCaseNames(Test), [])
Tim Petersea5962f2007-03-12 18:07:52 +00001020
Georg Brandl15c5ce92007-03-07 09:09:40 +00001021 # "Return a sorted sequence of method names found within testCaseClass"
1022 #
1023 # Are not-TestCases handled gracefully?
1024 #
1025 # XXX This should raise a TypeError, not return a list
1026 #
1027 # XXX It's too late in the 2.5 release cycle to fix this, but it should
1028 # probably be revisited for 2.6
1029 def test_getTestCaseNames__not_a_TestCase(self):
1030 class BadCase(int):
1031 def test_foo(self):
1032 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001033
Georg Brandl15c5ce92007-03-07 09:09:40 +00001034 loader = unittest.TestLoader()
1035 names = loader.getTestCaseNames(BadCase)
Tim Petersea5962f2007-03-12 18:07:52 +00001036
Georg Brandl15c5ce92007-03-07 09:09:40 +00001037 self.assertEqual(names, ['test_foo'])
Tim Petersea5962f2007-03-12 18:07:52 +00001038
Georg Brandl15c5ce92007-03-07 09:09:40 +00001039 # "Return a sorted sequence of method names found within testCaseClass"
1040 #
1041 # Make sure inherited names are handled.
1042 #
1043 # TestP.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +00001044 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +00001045 def test_getTestCaseNames__inheritance(self):
1046 class TestP(unittest.TestCase):
1047 def test_1(self): pass
1048 def test_2(self): pass
1049 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001050
Georg Brandl15c5ce92007-03-07 09:09:40 +00001051 class TestC(TestP):
1052 def test_1(self): pass
1053 def test_3(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001054
Georg Brandl15c5ce92007-03-07 09:09:40 +00001055 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001056
Georg Brandl15c5ce92007-03-07 09:09:40 +00001057 names = ['test_1', 'test_2', 'test_3']
1058 self.assertEqual(loader.getTestCaseNames(TestC), names)
Tim Petersea5962f2007-03-12 18:07:52 +00001059
1060 ################################################################
Georg Brandl15c5ce92007-03-07 09:09:40 +00001061 ### /Tests for TestLoader.getTestCaseNames()
1062
1063 ### Tests for TestLoader.testMethodPrefix
1064 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001065
Georg Brandl15c5ce92007-03-07 09:09:40 +00001066 # "String giving the prefix of method names which will be interpreted as
1067 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001068 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001069 # Implicit in the documentation is that testMethodPrefix is respected by
1070 # all loadTestsFrom* methods.
1071 def test_testMethodPrefix__loadTestsFromTestCase(self):
1072 class Foo(unittest.TestCase):
1073 def test_1(self): pass
1074 def test_2(self): pass
1075 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001076
Georg Brandl15c5ce92007-03-07 09:09:40 +00001077 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1078 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001079
Georg Brandl15c5ce92007-03-07 09:09:40 +00001080 loader = unittest.TestLoader()
1081 loader.testMethodPrefix = 'foo'
1082 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
1083
1084 loader.testMethodPrefix = 'test'
1085 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001086
Georg Brandl15c5ce92007-03-07 09:09:40 +00001087 # "String giving the prefix of method names which will be interpreted as
1088 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001089 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001090 # Implicit in the documentation is that testMethodPrefix is respected by
1091 # all loadTestsFrom* methods.
1092 def test_testMethodPrefix__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001093 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001094 class Foo(unittest.TestCase):
1095 def test_1(self): pass
1096 def test_2(self): pass
1097 def foo_bar(self): pass
1098 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001099
Georg Brandl15c5ce92007-03-07 09:09:40 +00001100 tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
1101 tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]
Tim Petersea5962f2007-03-12 18:07:52 +00001102
Georg Brandl15c5ce92007-03-07 09:09:40 +00001103 loader = unittest.TestLoader()
1104 loader.testMethodPrefix = 'foo'
1105 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
1106
1107 loader.testMethodPrefix = 'test'
1108 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001109
Georg Brandl15c5ce92007-03-07 09:09:40 +00001110 # "String giving the prefix of method names which will be interpreted as
1111 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001112 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001113 # Implicit in the documentation is that testMethodPrefix is respected by
1114 # all loadTestsFrom* methods.
1115 def test_testMethodPrefix__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001116 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001117 class Foo(unittest.TestCase):
1118 def test_1(self): pass
1119 def test_2(self): pass
1120 def foo_bar(self): pass
1121 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001122
Georg Brandl15c5ce92007-03-07 09:09:40 +00001123 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1124 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001125
Georg Brandl15c5ce92007-03-07 09:09:40 +00001126 loader = unittest.TestLoader()
1127 loader.testMethodPrefix = 'foo'
1128 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
1129
1130 loader.testMethodPrefix = 'test'
1131 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001132
Georg Brandl15c5ce92007-03-07 09:09:40 +00001133 # "String giving the prefix of method names which will be interpreted as
1134 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001135 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001136 # Implicit in the documentation is that testMethodPrefix is respected by
1137 # all loadTestsFrom* methods.
1138 def test_testMethodPrefix__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001139 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001140 class Foo(unittest.TestCase):
1141 def test_1(self): pass
1142 def test_2(self): pass
1143 def foo_bar(self): pass
1144 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001145
Georg Brandl15c5ce92007-03-07 09:09:40 +00001146 tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
1147 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1148 tests_2 = unittest.TestSuite([tests_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001149
Georg Brandl15c5ce92007-03-07 09:09:40 +00001150 loader = unittest.TestLoader()
1151 loader.testMethodPrefix = 'foo'
1152 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)
1153
1154 loader.testMethodPrefix = 'test'
1155 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001156
Georg Brandl15c5ce92007-03-07 09:09:40 +00001157 # "The default value is 'test'"
1158 def test_testMethodPrefix__default_value(self):
1159 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001160 self.assertTrue(loader.testMethodPrefix == 'test')
Tim Petersea5962f2007-03-12 18:07:52 +00001161
Georg Brandl15c5ce92007-03-07 09:09:40 +00001162 ################################################################
1163 ### /Tests for TestLoader.testMethodPrefix
1164
Tim Petersea5962f2007-03-12 18:07:52 +00001165 ### Tests for TestLoader.sortTestMethodsUsing
Georg Brandl15c5ce92007-03-07 09:09:40 +00001166 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001167
Georg Brandl15c5ce92007-03-07 09:09:40 +00001168 # "Function to be used to compare method names when sorting them in
1169 # getTestCaseNames() and all the loadTestsFromX() methods"
1170 def test_sortTestMethodsUsing__loadTestsFromTestCase(self):
1171 def reversed_cmp(x, y):
1172 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001173
Georg Brandl15c5ce92007-03-07 09:09:40 +00001174 class Foo(unittest.TestCase):
1175 def test_1(self): pass
1176 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001177
Georg Brandl15c5ce92007-03-07 09:09:40 +00001178 loader = unittest.TestLoader()
1179 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001180
Georg Brandl15c5ce92007-03-07 09:09:40 +00001181 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1182 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001183
Georg Brandl15c5ce92007-03-07 09:09:40 +00001184 # "Function to be used to compare method names when sorting them in
1185 # getTestCaseNames() and all the loadTestsFromX() methods"
1186 def test_sortTestMethodsUsing__loadTestsFromModule(self):
1187 def reversed_cmp(x, y):
1188 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001189
Christian Heimesc756d002007-11-27 21:34:01 +00001190 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001191 class Foo(unittest.TestCase):
1192 def test_1(self): pass
1193 def test_2(self): pass
1194 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001195
Georg Brandl15c5ce92007-03-07 09:09:40 +00001196 loader = unittest.TestLoader()
1197 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001198
Georg Brandl15c5ce92007-03-07 09:09:40 +00001199 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1200 self.assertEqual(list(loader.loadTestsFromModule(m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001201
Georg Brandl15c5ce92007-03-07 09:09:40 +00001202 # "Function to be used to compare method names when sorting them in
1203 # getTestCaseNames() and all the loadTestsFromX() methods"
1204 def test_sortTestMethodsUsing__loadTestsFromName(self):
1205 def reversed_cmp(x, y):
1206 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001207
Christian Heimesc756d002007-11-27 21:34:01 +00001208 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001209 class Foo(unittest.TestCase):
1210 def test_1(self): pass
1211 def test_2(self): pass
1212 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001213
Georg Brandl15c5ce92007-03-07 09:09:40 +00001214 loader = unittest.TestLoader()
1215 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001216
Georg Brandl15c5ce92007-03-07 09:09:40 +00001217 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1218 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001219
Georg Brandl15c5ce92007-03-07 09:09:40 +00001220 # "Function to be used to compare method names when sorting them in
1221 # getTestCaseNames() and all the loadTestsFromX() methods"
1222 def test_sortTestMethodsUsing__loadTestsFromNames(self):
1223 def reversed_cmp(x, y):
1224 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001225
Christian Heimesc756d002007-11-27 21:34:01 +00001226 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001227 class Foo(unittest.TestCase):
1228 def test_1(self): pass
1229 def test_2(self): pass
1230 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001231
Georg Brandl15c5ce92007-03-07 09:09:40 +00001232 loader = unittest.TestLoader()
1233 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001234
Georg Brandl15c5ce92007-03-07 09:09:40 +00001235 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1236 self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001237
Georg Brandl15c5ce92007-03-07 09:09:40 +00001238 # "Function to be used to compare method names when sorting them in
1239 # getTestCaseNames()"
1240 #
1241 # Does it actually affect getTestCaseNames()?
1242 def test_sortTestMethodsUsing__getTestCaseNames(self):
1243 def reversed_cmp(x, y):
1244 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001245
Georg Brandl15c5ce92007-03-07 09:09:40 +00001246 class Foo(unittest.TestCase):
1247 def test_1(self): pass
1248 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001249
Georg Brandl15c5ce92007-03-07 09:09:40 +00001250 loader = unittest.TestLoader()
1251 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001252
Georg Brandl15c5ce92007-03-07 09:09:40 +00001253 test_names = ['test_2', 'test_1']
1254 self.assertEqual(loader.getTestCaseNames(Foo), test_names)
Tim Petersea5962f2007-03-12 18:07:52 +00001255
Georg Brandl15c5ce92007-03-07 09:09:40 +00001256 # "The default value is the built-in cmp() function"
1257 def test_sortTestMethodsUsing__default_value(self):
1258 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001259 self.assertTrue(loader.sortTestMethodsUsing is cmp)
Tim Petersea5962f2007-03-12 18:07:52 +00001260
Georg Brandl15c5ce92007-03-07 09:09:40 +00001261 # "it can be set to None to disable the sort."
1262 #
1263 # XXX How is this different from reassigning cmp? Are the tests returned
1264 # in a random order or something? This behaviour should die
1265 def test_sortTestMethodsUsing__None(self):
1266 class Foo(unittest.TestCase):
1267 def test_1(self): pass
1268 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001269
Georg Brandl15c5ce92007-03-07 09:09:40 +00001270 loader = unittest.TestLoader()
1271 loader.sortTestMethodsUsing = None
Tim Petersea5962f2007-03-12 18:07:52 +00001272
Georg Brandl15c5ce92007-03-07 09:09:40 +00001273 test_names = ['test_2', 'test_1']
1274 self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))
Tim Petersea5962f2007-03-12 18:07:52 +00001275
Georg Brandl15c5ce92007-03-07 09:09:40 +00001276 ################################################################
1277 ### /Tests for TestLoader.sortTestMethodsUsing
Tim Petersea5962f2007-03-12 18:07:52 +00001278
Georg Brandl15c5ce92007-03-07 09:09:40 +00001279 ### Tests for TestLoader.suiteClass
1280 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001281
Georg Brandl15c5ce92007-03-07 09:09:40 +00001282 # "Callable object that constructs a test suite from a list of tests."
1283 def test_suiteClass__loadTestsFromTestCase(self):
1284 class Foo(unittest.TestCase):
1285 def test_1(self): pass
1286 def test_2(self): pass
1287 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001288
Georg Brandl15c5ce92007-03-07 09:09:40 +00001289 tests = [Foo('test_1'), Foo('test_2')]
1290
1291 loader = unittest.TestLoader()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001292 loader.suiteClass = list
Georg Brandl15c5ce92007-03-07 09:09:40 +00001293 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001294
Georg Brandl15c5ce92007-03-07 09:09:40 +00001295 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001296 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001297 def test_suiteClass__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001298 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001299 class Foo(unittest.TestCase):
1300 def test_1(self): pass
1301 def test_2(self): pass
1302 def foo_bar(self): pass
1303 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001304
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001305 tests = [[Foo('test_1'), Foo('test_2')]]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001306
1307 loader = unittest.TestLoader()
1308 loader.suiteClass = list
1309 self.assertEqual(loader.loadTestsFromModule(m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001310
Georg Brandl15c5ce92007-03-07 09:09:40 +00001311 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001312 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001313 def test_suiteClass__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001314 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001315 class Foo(unittest.TestCase):
1316 def test_1(self): pass
1317 def test_2(self): pass
1318 def foo_bar(self): pass
1319 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001320
Georg Brandl15c5ce92007-03-07 09:09:40 +00001321 tests = [Foo('test_1'), Foo('test_2')]
1322
1323 loader = unittest.TestLoader()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001324 loader.suiteClass = list
Georg Brandl15c5ce92007-03-07 09:09:40 +00001325 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001326
Georg Brandl15c5ce92007-03-07 09:09:40 +00001327 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001328 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001329 def test_suiteClass__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001330 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001331 class Foo(unittest.TestCase):
1332 def test_1(self): pass
1333 def test_2(self): pass
1334 def foo_bar(self): pass
1335 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001336
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001337 tests = [[Foo('test_1'), Foo('test_2')]]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001338
1339 loader = unittest.TestLoader()
1340 loader.suiteClass = list
1341 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001342
Georg Brandl15c5ce92007-03-07 09:09:40 +00001343 # "The default value is the TestSuite class"
1344 def test_suiteClass__default_value(self):
1345 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001346 self.assertTrue(loader.suiteClass is unittest.TestSuite)
Tim Petersea5962f2007-03-12 18:07:52 +00001347
Georg Brandl15c5ce92007-03-07 09:09:40 +00001348 ################################################################
1349 ### /Tests for TestLoader.suiteClass
1350
1351### Support code for Test_TestSuite
1352################################################################
1353
1354class Foo(unittest.TestCase):
1355 def test_1(self): pass
1356 def test_2(self): pass
1357 def test_3(self): pass
1358 def runTest(self): pass
1359
1360def _mk_TestSuite(*names):
1361 return unittest.TestSuite(Foo(n) for n in names)
Tim Petersea5962f2007-03-12 18:07:52 +00001362
Georg Brandl15c5ce92007-03-07 09:09:40 +00001363################################################################
1364### /Support code for Test_TestSuite
1365
1366class Test_TestSuite(TestCase, TestEquality):
1367
1368 ### Set up attributes needed by inherited tests
1369 ################################################################
1370
1371 # Used by TestEquality.test_eq
1372 eq_pairs = [(unittest.TestSuite(), unittest.TestSuite())
1373 ,(unittest.TestSuite(), unittest.TestSuite([]))
1374 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001375
1376 # Used by TestEquality.test_ne
Georg Brandl15c5ce92007-03-07 09:09:40 +00001377 ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1'))
1378 ,(unittest.TestSuite([]), _mk_TestSuite('test_1'))
1379 ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3'))
1380 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001381
Georg Brandl15c5ce92007-03-07 09:09:40 +00001382 ################################################################
1383 ### /Set up attributes needed by inherited tests
1384
1385 ### Tests for TestSuite.__init__
1386 ################################################################
1387
1388 # "class TestSuite([tests])"
1389 #
1390 # The tests iterable should be optional
1391 def test_init__tests_optional(self):
1392 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001393
Georg Brandl15c5ce92007-03-07 09:09:40 +00001394 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001395
Georg Brandl15c5ce92007-03-07 09:09:40 +00001396 # "class TestSuite([tests])"
1397 # ...
1398 # "If tests is given, it must be an iterable of individual test cases
1399 # or other test suites that will be used to build the suite initially"
1400 #
1401 # TestSuite should deal with empty tests iterables by allowing the
Tim Petersea5962f2007-03-12 18:07:52 +00001402 # creation of an empty suite
Georg Brandl15c5ce92007-03-07 09:09:40 +00001403 def test_init__empty_tests(self):
1404 suite = unittest.TestSuite([])
Tim Petersea5962f2007-03-12 18:07:52 +00001405
Georg Brandl15c5ce92007-03-07 09:09:40 +00001406 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001407
Georg Brandl15c5ce92007-03-07 09:09:40 +00001408 # "class TestSuite([tests])"
1409 # ...
1410 # "If tests is given, it must be an iterable of individual test cases
1411 # or other test suites that will be used to build the suite initially"
1412 #
Tim Petersea5962f2007-03-12 18:07:52 +00001413 # TestSuite should allow any iterable to provide tests
Georg Brandl15c5ce92007-03-07 09:09:40 +00001414 def test_init__tests_from_any_iterable(self):
1415 def tests():
1416 yield unittest.FunctionTestCase(lambda: None)
1417 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001418
Georg Brandl15c5ce92007-03-07 09:09:40 +00001419 suite_1 = unittest.TestSuite(tests())
1420 self.assertEqual(suite_1.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001421
Georg Brandl15c5ce92007-03-07 09:09:40 +00001422 suite_2 = unittest.TestSuite(suite_1)
1423 self.assertEqual(suite_2.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001424
Georg Brandl15c5ce92007-03-07 09:09:40 +00001425 suite_3 = unittest.TestSuite(set(suite_1))
1426 self.assertEqual(suite_3.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001427
Georg Brandl15c5ce92007-03-07 09:09:40 +00001428 # "class TestSuite([tests])"
1429 # ...
1430 # "If tests is given, it must be an iterable of individual test cases
1431 # or other test suites that will be used to build the suite initially"
1432 #
1433 # Does TestSuite() also allow other TestSuite() instances to be present
1434 # in the tests iterable?
1435 def test_init__TestSuite_instances_in_tests(self):
1436 def tests():
1437 ftc = unittest.FunctionTestCase(lambda: None)
1438 yield unittest.TestSuite([ftc])
1439 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001440
Georg Brandl15c5ce92007-03-07 09:09:40 +00001441 suite = unittest.TestSuite(tests())
1442 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001443
Georg Brandl15c5ce92007-03-07 09:09:40 +00001444 ################################################################
1445 ### /Tests for TestSuite.__init__
1446
1447 # Container types should support the iter protocol
1448 def test_iter(self):
1449 test1 = unittest.FunctionTestCase(lambda: None)
1450 test2 = unittest.FunctionTestCase(lambda: None)
1451 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001452
Georg Brandl15c5ce92007-03-07 09:09:40 +00001453 self.assertEqual(list(suite), [test1, test2])
Tim Petersea5962f2007-03-12 18:07:52 +00001454
Georg Brandl15c5ce92007-03-07 09:09:40 +00001455 # "Return the number of tests represented by the this test object.
1456 # ...this method is also implemented by the TestSuite class, which can
1457 # return larger [greater than 1] values"
1458 #
Tim Petersea5962f2007-03-12 18:07:52 +00001459 # Presumably an empty TestSuite returns 0?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001460 def test_countTestCases_zero_simple(self):
1461 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001462
Georg Brandl15c5ce92007-03-07 09:09:40 +00001463 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001464
Georg Brandl15c5ce92007-03-07 09:09:40 +00001465 # "Return the number of tests represented by the this test object.
1466 # ...this method is also implemented by the TestSuite class, which can
1467 # return larger [greater than 1] values"
1468 #
1469 # Presumably an empty TestSuite (even if it contains other empty
1470 # TestSuite instances) returns 0?
1471 def test_countTestCases_zero_nested(self):
1472 class Test1(unittest.TestCase):
1473 def test(self):
1474 pass
1475
1476 suite = unittest.TestSuite([unittest.TestSuite()])
Tim Petersea5962f2007-03-12 18:07:52 +00001477
Georg Brandl15c5ce92007-03-07 09:09:40 +00001478 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001479
Georg Brandl15c5ce92007-03-07 09:09:40 +00001480 # "Return the number of tests represented by the this test object.
1481 # ...this method is also implemented by the TestSuite class, which can
1482 # return larger [greater than 1] values"
1483 def test_countTestCases_simple(self):
1484 test1 = unittest.FunctionTestCase(lambda: None)
1485 test2 = unittest.FunctionTestCase(lambda: None)
1486 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001487
Georg Brandl15c5ce92007-03-07 09:09:40 +00001488 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001489
Georg Brandl15c5ce92007-03-07 09:09:40 +00001490 # "Return the number of tests represented by the this test object.
1491 # ...this method is also implemented by the TestSuite class, which can
1492 # return larger [greater than 1] values"
1493 #
1494 # Make sure this holds for nested TestSuite instances, too
1495 def test_countTestCases_nested(self):
1496 class Test1(unittest.TestCase):
1497 def test1(self): pass
1498 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001499
Georg Brandl15c5ce92007-03-07 09:09:40 +00001500 test2 = unittest.FunctionTestCase(lambda: None)
1501 test3 = unittest.FunctionTestCase(lambda: None)
1502 child = unittest.TestSuite((Test1('test2'), test2))
1503 parent = unittest.TestSuite((test3, child, Test1('test1')))
Tim Petersea5962f2007-03-12 18:07:52 +00001504
Georg Brandl15c5ce92007-03-07 09:09:40 +00001505 self.assertEqual(parent.countTestCases(), 4)
Tim Petersea5962f2007-03-12 18:07:52 +00001506
Georg Brandl15c5ce92007-03-07 09:09:40 +00001507 # "Run the tests associated with this suite, collecting the result into
1508 # the test result object passed as result."
1509 #
1510 # And if there are no tests? What then?
1511 def test_run__empty_suite(self):
1512 events = []
1513 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001514
Georg Brandl15c5ce92007-03-07 09:09:40 +00001515 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001516
Georg Brandl15c5ce92007-03-07 09:09:40 +00001517 suite.run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001518
Georg Brandl15c5ce92007-03-07 09:09:40 +00001519 self.assertEqual(events, [])
Tim Petersea5962f2007-03-12 18:07:52 +00001520
Georg Brandl15c5ce92007-03-07 09:09:40 +00001521 # "Note that unlike TestCase.run(), TestSuite.run() requires the
1522 # "result object to be passed in."
1523 def test_run__requires_result(self):
1524 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001525
Georg Brandl15c5ce92007-03-07 09:09:40 +00001526 try:
1527 suite.run()
1528 except TypeError:
1529 pass
1530 else:
1531 self.fail("Failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +00001532
Georg Brandl15c5ce92007-03-07 09:09:40 +00001533 # "Run the tests associated with this suite, collecting the result into
Tim Petersea5962f2007-03-12 18:07:52 +00001534 # the test result object passed as result."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001535 def test_run(self):
1536 events = []
1537 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001538
Georg Brandl15c5ce92007-03-07 09:09:40 +00001539 class LoggingCase(unittest.TestCase):
1540 def run(self, result):
1541 events.append('run %s' % self._testMethodName)
Tim Petersea5962f2007-03-12 18:07:52 +00001542
Georg Brandl15c5ce92007-03-07 09:09:40 +00001543 def test1(self): pass
1544 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001545
1546 tests = [LoggingCase('test1'), LoggingCase('test2')]
1547
Georg Brandl15c5ce92007-03-07 09:09:40 +00001548 unittest.TestSuite(tests).run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001549
Georg Brandl15c5ce92007-03-07 09:09:40 +00001550 self.assertEqual(events, ['run test1', 'run test2'])
Tim Petersea5962f2007-03-12 18:07:52 +00001551
1552 # "Add a TestCase ... to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001553 def test_addTest__TestCase(self):
1554 class Foo(unittest.TestCase):
1555 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001556
Georg Brandl15c5ce92007-03-07 09:09:40 +00001557 test = Foo('test')
1558 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001559
Georg Brandl15c5ce92007-03-07 09:09:40 +00001560 suite.addTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001561
Georg Brandl15c5ce92007-03-07 09:09:40 +00001562 self.assertEqual(suite.countTestCases(), 1)
1563 self.assertEqual(list(suite), [test])
Tim Petersea5962f2007-03-12 18:07:52 +00001564
1565 # "Add a ... TestSuite to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001566 def test_addTest__TestSuite(self):
1567 class Foo(unittest.TestCase):
1568 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001569
Georg Brandl15c5ce92007-03-07 09:09:40 +00001570 suite_2 = unittest.TestSuite([Foo('test')])
Tim Petersea5962f2007-03-12 18:07:52 +00001571
Georg Brandl15c5ce92007-03-07 09:09:40 +00001572 suite = unittest.TestSuite()
1573 suite.addTest(suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001574
Georg Brandl15c5ce92007-03-07 09:09:40 +00001575 self.assertEqual(suite.countTestCases(), 1)
1576 self.assertEqual(list(suite), [suite_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001577
Georg Brandl15c5ce92007-03-07 09:09:40 +00001578 # "Add all the tests from an iterable of TestCase and TestSuite
1579 # instances to this test suite."
Tim Petersea5962f2007-03-12 18:07:52 +00001580 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001581 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001582 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001583 def test_addTests(self):
1584 class Foo(unittest.TestCase):
1585 def test_1(self): pass
1586 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001587
Georg Brandl15c5ce92007-03-07 09:09:40 +00001588 test_1 = Foo('test_1')
1589 test_2 = Foo('test_2')
1590 inner_suite = unittest.TestSuite([test_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001591
Georg Brandl15c5ce92007-03-07 09:09:40 +00001592 def gen():
1593 yield test_1
1594 yield test_2
1595 yield inner_suite
Tim Petersea5962f2007-03-12 18:07:52 +00001596
Georg Brandl15c5ce92007-03-07 09:09:40 +00001597 suite_1 = unittest.TestSuite()
1598 suite_1.addTests(gen())
Tim Petersea5962f2007-03-12 18:07:52 +00001599
Georg Brandl15c5ce92007-03-07 09:09:40 +00001600 self.assertEqual(list(suite_1), list(gen()))
Tim Petersea5962f2007-03-12 18:07:52 +00001601
Georg Brandl15c5ce92007-03-07 09:09:40 +00001602 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001603 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001604 suite_2 = unittest.TestSuite()
1605 for t in gen():
1606 suite_2.addTest(t)
Tim Petersea5962f2007-03-12 18:07:52 +00001607
Georg Brandl15c5ce92007-03-07 09:09:40 +00001608 self.assertEqual(suite_1, suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001609
Georg Brandl15c5ce92007-03-07 09:09:40 +00001610 # "Add all the tests from an iterable of TestCase and TestSuite
1611 # instances to this test suite."
1612 #
Tim Petersea5962f2007-03-12 18:07:52 +00001613 # What happens if it doesn't get an iterable?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001614 def test_addTest__noniterable(self):
1615 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001616
Georg Brandl15c5ce92007-03-07 09:09:40 +00001617 try:
1618 suite.addTests(5)
1619 except TypeError:
1620 pass
1621 else:
1622 self.fail("Failed to raise TypeError")
Georg Brandld9e50262007-03-07 11:54:49 +00001623
1624 def test_addTest__noncallable(self):
1625 suite = unittest.TestSuite()
1626 self.assertRaises(TypeError, suite.addTest, 5)
1627
1628 def test_addTest__casesuiteclass(self):
1629 suite = unittest.TestSuite()
1630 self.assertRaises(TypeError, suite.addTest, Test_TestSuite)
1631 self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)
1632
1633 def test_addTests__string(self):
1634 suite = unittest.TestSuite()
1635 self.assertRaises(TypeError, suite.addTests, "foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001636
1637
Georg Brandl15c5ce92007-03-07 09:09:40 +00001638class Test_FunctionTestCase(TestCase):
Tim Petersea5962f2007-03-12 18:07:52 +00001639
Georg Brandl15c5ce92007-03-07 09:09:40 +00001640 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00001641 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001642 def test_countTestCases(self):
1643 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001644
Georg Brandl15c5ce92007-03-07 09:09:40 +00001645 self.assertEqual(test.countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00001646
Georg Brandl15c5ce92007-03-07 09:09:40 +00001647 # "When a setUp() method is defined, the test runner will run that method
1648 # prior to each test. Likewise, if a tearDown() method is defined, the
1649 # test runner will invoke that method after each test. In the example,
1650 # setUp() was used to create a fresh sequence for each test."
1651 #
1652 # Make sure the proper call order is maintained, even if setUp() raises
1653 # an exception.
1654 def test_run_call_order__error_in_setUp(self):
1655 events = []
1656 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001657
Georg Brandl15c5ce92007-03-07 09:09:40 +00001658 def setUp():
1659 events.append('setUp')
1660 raise RuntimeError('raised by setUp')
1661
1662 def test():
1663 events.append('test')
1664
1665 def tearDown():
1666 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001667
1668 expected = ['startTest', 'setUp', 'addError', 'stopTest']
Georg Brandl15c5ce92007-03-07 09:09:40 +00001669 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1670 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001671
Georg Brandl15c5ce92007-03-07 09:09:40 +00001672 # "When a setUp() method is defined, the test runner will run that method
1673 # prior to each test. Likewise, if a tearDown() method is defined, the
1674 # test runner will invoke that method after each test. In the example,
1675 # setUp() was used to create a fresh sequence for each test."
1676 #
1677 # Make sure the proper call order is maintained, even if the test raises
1678 # an error (as opposed to a failure).
1679 def test_run_call_order__error_in_test(self):
1680 events = []
1681 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001682
Georg Brandl15c5ce92007-03-07 09:09:40 +00001683 def setUp():
1684 events.append('setUp')
1685
1686 def test():
1687 events.append('test')
1688 raise RuntimeError('raised by test')
1689
1690 def tearDown():
1691 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001692
Georg Brandl15c5ce92007-03-07 09:09:40 +00001693 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
1694 'stopTest']
1695 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1696 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001697
Georg Brandl15c5ce92007-03-07 09:09:40 +00001698 # "When a setUp() method is defined, the test runner will run that method
1699 # prior to each test. Likewise, if a tearDown() method is defined, the
1700 # test runner will invoke that method after each test. In the example,
1701 # setUp() was used to create a fresh sequence for each test."
1702 #
1703 # Make sure the proper call order is maintained, even if the test signals
1704 # a failure (as opposed to an error).
1705 def test_run_call_order__failure_in_test(self):
1706 events = []
1707 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001708
Georg Brandl15c5ce92007-03-07 09:09:40 +00001709 def setUp():
1710 events.append('setUp')
1711
1712 def test():
1713 events.append('test')
1714 self.fail('raised by test')
1715
1716 def tearDown():
1717 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001718
Georg Brandl15c5ce92007-03-07 09:09:40 +00001719 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
1720 'stopTest']
1721 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1722 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001723
Georg Brandl15c5ce92007-03-07 09:09:40 +00001724 # "When a setUp() method is defined, the test runner will run that method
1725 # prior to each test. Likewise, if a tearDown() method is defined, the
1726 # test runner will invoke that method after each test. In the example,
1727 # setUp() was used to create a fresh sequence for each test."
1728 #
1729 # Make sure the proper call order is maintained, even if tearDown() raises
1730 # an exception.
1731 def test_run_call_order__error_in_tearDown(self):
1732 events = []
1733 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001734
Georg Brandl15c5ce92007-03-07 09:09:40 +00001735 def setUp():
1736 events.append('setUp')
1737
1738 def test():
1739 events.append('test')
1740
1741 def tearDown():
1742 events.append('tearDown')
1743 raise RuntimeError('raised by tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001744
Georg Brandl15c5ce92007-03-07 09:09:40 +00001745 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
1746 'stopTest']
1747 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1748 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001749
Georg Brandl15c5ce92007-03-07 09:09:40 +00001750 # "Return a string identifying the specific test case."
1751 #
1752 # Because of the vague nature of the docs, I'm not going to lock this
1753 # test down too much. Really all that can be asserted is that the id()
1754 # will be a string (either 8-byte or unicode -- again, because the docs
1755 # just say "string")
1756 def test_id(self):
1757 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001758
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001759 self.assertTrue(isinstance(test.id(), basestring))
Tim Petersea5962f2007-03-12 18:07:52 +00001760
Georg Brandl15c5ce92007-03-07 09:09:40 +00001761 # "Returns a one-line description of the test, or None if no description
1762 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001763 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001764 def test_shortDescription__no_docstring(self):
1765 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001766
Georg Brandl15c5ce92007-03-07 09:09:40 +00001767 self.assertEqual(test.shortDescription(), None)
Tim Petersea5962f2007-03-12 18:07:52 +00001768
Georg Brandl15c5ce92007-03-07 09:09:40 +00001769 # "Returns a one-line description of the test, or None if no description
1770 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001771 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001772 def test_shortDescription__singleline_docstring(self):
1773 desc = "this tests foo"
1774 test = unittest.FunctionTestCase(lambda: None, description=desc)
Tim Petersea5962f2007-03-12 18:07:52 +00001775
Georg Brandl15c5ce92007-03-07 09:09:40 +00001776 self.assertEqual(test.shortDescription(), "this tests foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001777
Georg Brandl15c5ce92007-03-07 09:09:40 +00001778class Test_TestResult(TestCase):
1779 # Note: there are not separate tests for TestResult.wasSuccessful(),
1780 # TestResult.errors, TestResult.failures, TestResult.testsRun or
1781 # TestResult.shouldStop because these only have meaning in terms of
1782 # other TestResult methods.
1783 #
1784 # Accordingly, tests for the aforenamed attributes are incorporated
1785 # in with the tests for the defining methods.
1786 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001787
Georg Brandl15c5ce92007-03-07 09:09:40 +00001788 def test_init(self):
1789 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001790
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001791 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001792 self.assertEqual(len(result.errors), 0)
1793 self.assertEqual(len(result.failures), 0)
1794 self.assertEqual(result.testsRun, 0)
1795 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001796
Georg Brandl15c5ce92007-03-07 09:09:40 +00001797 # "This method can be called to signal that the set of tests being
1798 # run should be aborted by setting the TestResult's shouldStop
Tim Petersea5962f2007-03-12 18:07:52 +00001799 # attribute to True."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001800 def test_stop(self):
1801 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001802
Georg Brandl15c5ce92007-03-07 09:09:40 +00001803 result.stop()
Tim Petersea5962f2007-03-12 18:07:52 +00001804
Georg Brandl15c5ce92007-03-07 09:09:40 +00001805 self.assertEqual(result.shouldStop, True)
Tim Petersea5962f2007-03-12 18:07:52 +00001806
Georg Brandl15c5ce92007-03-07 09:09:40 +00001807 # "Called when the test case test is about to be run. The default
1808 # implementation simply increments the instance's testsRun counter."
1809 def test_startTest(self):
1810 class Foo(unittest.TestCase):
1811 def test_1(self):
1812 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001813
Georg Brandl15c5ce92007-03-07 09:09:40 +00001814 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001815
Georg Brandl15c5ce92007-03-07 09:09:40 +00001816 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001817
Georg Brandl15c5ce92007-03-07 09:09:40 +00001818 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001819
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001820 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001821 self.assertEqual(len(result.errors), 0)
1822 self.assertEqual(len(result.failures), 0)
1823 self.assertEqual(result.testsRun, 1)
1824 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001825
Georg Brandl15c5ce92007-03-07 09:09:40 +00001826 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001827
Georg Brandl15c5ce92007-03-07 09:09:40 +00001828 # "Called after the test case test has been executed, regardless of
1829 # the outcome. The default implementation does nothing."
1830 def test_stopTest(self):
1831 class Foo(unittest.TestCase):
1832 def test_1(self):
1833 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001834
Georg Brandl15c5ce92007-03-07 09:09:40 +00001835 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001836
Georg Brandl15c5ce92007-03-07 09:09:40 +00001837 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001838
Georg Brandl15c5ce92007-03-07 09:09:40 +00001839 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001840
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001841 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001842 self.assertEqual(len(result.errors), 0)
1843 self.assertEqual(len(result.failures), 0)
1844 self.assertEqual(result.testsRun, 1)
1845 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001846
Georg Brandl15c5ce92007-03-07 09:09:40 +00001847 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001848
Georg Brandl15c5ce92007-03-07 09:09:40 +00001849 # Same tests as above; make sure nothing has changed
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001850 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001851 self.assertEqual(len(result.errors), 0)
1852 self.assertEqual(len(result.failures), 0)
1853 self.assertEqual(result.testsRun, 1)
1854 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001855
Michael Foord07ef4872009-05-02 22:43:34 +00001856 # "Called before and after tests are run. The default implementation does nothing."
1857 def test_startTestRun_stopTestRun(self):
1858 result = unittest.TestResult()
1859 result.startTestRun()
1860 result.stopTestRun()
1861
Georg Brandl15c5ce92007-03-07 09:09:40 +00001862 # "addSuccess(test)"
1863 # ...
1864 # "Called when the test case test succeeds"
1865 # ...
1866 # "wasSuccessful() - Returns True if all tests run so far have passed,
1867 # otherwise returns False"
1868 # ...
1869 # "testsRun - The total number of tests run so far."
1870 # ...
1871 # "errors - A list containing 2-tuples of TestCase instances and
1872 # formatted tracebacks. Each tuple represents a test which raised an
1873 # unexpected exception. Contains formatted
1874 # tracebacks instead of sys.exc_info() results."
1875 # ...
1876 # "failures - A list containing 2-tuples of TestCase instances and
1877 # formatted tracebacks. Each tuple represents a test where a failure was
1878 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1879 # methods. Contains formatted tracebacks instead
1880 # of sys.exc_info() results."
1881 def test_addSuccess(self):
1882 class Foo(unittest.TestCase):
1883 def test_1(self):
1884 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001885
Georg Brandl15c5ce92007-03-07 09:09:40 +00001886 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001887
Georg Brandl15c5ce92007-03-07 09:09:40 +00001888 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001889
Georg Brandl15c5ce92007-03-07 09:09:40 +00001890 result.startTest(test)
1891 result.addSuccess(test)
1892 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001893
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001894 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001895 self.assertEqual(len(result.errors), 0)
1896 self.assertEqual(len(result.failures), 0)
1897 self.assertEqual(result.testsRun, 1)
1898 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001899
Georg Brandl15c5ce92007-03-07 09:09:40 +00001900 # "addFailure(test, err)"
1901 # ...
1902 # "Called when the test case test signals a failure. err is a tuple of
1903 # the form returned by sys.exc_info(): (type, value, traceback)"
1904 # ...
1905 # "wasSuccessful() - Returns True if all tests run so far have passed,
1906 # otherwise returns False"
1907 # ...
1908 # "testsRun - The total number of tests run so far."
1909 # ...
1910 # "errors - A list containing 2-tuples of TestCase instances and
1911 # formatted tracebacks. Each tuple represents a test which raised an
1912 # unexpected exception. Contains formatted
1913 # tracebacks instead of sys.exc_info() results."
1914 # ...
1915 # "failures - A list containing 2-tuples of TestCase instances and
1916 # formatted tracebacks. Each tuple represents a test where a failure was
1917 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1918 # methods. Contains formatted tracebacks instead
1919 # of sys.exc_info() results."
1920 def test_addFailure(self):
1921 import sys
Tim Petersea5962f2007-03-12 18:07:52 +00001922
Georg Brandl15c5ce92007-03-07 09:09:40 +00001923 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')
1928 try:
1929 test.fail("foo")
1930 except:
1931 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00001932
Georg Brandl15c5ce92007-03-07 09:09:40 +00001933 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001934
Georg Brandl15c5ce92007-03-07 09:09:40 +00001935 result.startTest(test)
1936 result.addFailure(test, exc_info_tuple)
1937 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001938
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001939 self.assertFalse(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001940 self.assertEqual(len(result.errors), 0)
1941 self.assertEqual(len(result.failures), 1)
1942 self.assertEqual(result.testsRun, 1)
1943 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001944
Georg Brandl15c5ce92007-03-07 09:09:40 +00001945 test_case, formatted_exc = result.failures[0]
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001946 self.assertTrue(test_case is test)
1947 self.assertTrue(isinstance(formatted_exc, str))
Tim Petersea5962f2007-03-12 18:07:52 +00001948
Georg Brandl15c5ce92007-03-07 09:09:40 +00001949 # "addError(test, err)"
1950 # ...
1951 # "Called when the test case test raises an unexpected exception err
1952 # is a tuple of the form returned by sys.exc_info():
1953 # (type, value, traceback)"
1954 # ...
1955 # "wasSuccessful() - Returns True if all tests run so far have passed,
1956 # otherwise returns False"
1957 # ...
1958 # "testsRun - The total number of tests run so far."
1959 # ...
1960 # "errors - A list containing 2-tuples of TestCase instances and
1961 # formatted tracebacks. Each tuple represents a test which raised an
1962 # unexpected exception. Contains formatted
1963 # tracebacks instead of sys.exc_info() results."
1964 # ...
1965 # "failures - A list containing 2-tuples of TestCase instances and
1966 # formatted tracebacks. Each tuple represents a test where a failure was
1967 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1968 # methods. Contains formatted tracebacks instead
1969 # of sys.exc_info() results."
1970 def test_addError(self):
1971 import sys
Tim Petersea5962f2007-03-12 18:07:52 +00001972
Georg Brandl15c5ce92007-03-07 09:09:40 +00001973 class Foo(unittest.TestCase):
1974 def test_1(self):
1975 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001976
Georg Brandl15c5ce92007-03-07 09:09:40 +00001977 test = Foo('test_1')
1978 try:
1979 raise TypeError()
1980 except:
1981 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00001982
Georg Brandl15c5ce92007-03-07 09:09:40 +00001983 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001984
Georg Brandl15c5ce92007-03-07 09:09:40 +00001985 result.startTest(test)
1986 result.addError(test, exc_info_tuple)
1987 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001988
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001989 self.assertFalse(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001990 self.assertEqual(len(result.errors), 1)
1991 self.assertEqual(len(result.failures), 0)
1992 self.assertEqual(result.testsRun, 1)
1993 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001994
Georg Brandl15c5ce92007-03-07 09:09:40 +00001995 test_case, formatted_exc = result.errors[0]
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001996 self.assertTrue(test_case is test)
1997 self.assertTrue(isinstance(formatted_exc, str))
Georg Brandl15c5ce92007-03-07 09:09:40 +00001998
1999### Support code for Test_TestCase
2000################################################################
2001
2002class Foo(unittest.TestCase):
2003 def runTest(self): pass
2004 def test1(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002005
Georg Brandl15c5ce92007-03-07 09:09:40 +00002006class Bar(Foo):
2007 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002008
Michael Foord07ef4872009-05-02 22:43:34 +00002009class LoggingTestCase(unittest.TestCase):
2010 """A test case which logs its calls."""
2011
2012 def __init__(self, events):
2013 super(LoggingTestCase, self).__init__('test')
2014 self.events = events
2015
2016 def setUp(self):
2017 self.events.append('setUp')
2018
2019 def test(self):
2020 self.events.append('test')
2021
2022 def tearDown(self):
2023 self.events.append('tearDown')
2024
2025class ResultWithNoStartTestRunStopTestRun(object):
2026 """An object honouring TestResult before startTestRun/stopTestRun."""
2027
2028 def __init__(self):
2029 self.failures = []
2030 self.errors = []
2031 self.testsRun = 0
2032 self.skipped = []
2033 self.expectedFailures = []
2034 self.unexpectedSuccesses = []
2035 self.shouldStop = False
2036
2037 def startTest(self, test):
2038 pass
2039
2040 def stopTest(self, test):
2041 pass
2042
2043 def addError(self, test):
2044 pass
2045
2046 def addFailure(self, test):
2047 pass
2048
2049 def addSuccess(self, test):
2050 pass
2051
2052 def wasSuccessful(self):
2053 return True
2054
2055
Georg Brandl15c5ce92007-03-07 09:09:40 +00002056################################################################
2057### /Support code for Test_TestCase
2058
2059class Test_TestCase(TestCase, TestEquality, TestHashing):
2060
2061 ### Set up attributes used by inherited tests
2062 ################################################################
2063
2064 # Used by TestHashing.test_hash and TestEquality.test_eq
2065 eq_pairs = [(Foo('test1'), Foo('test1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002066
Georg Brandl15c5ce92007-03-07 09:09:40 +00002067 # Used by TestEquality.test_ne
2068 ne_pairs = [(Foo('test1'), Foo('runTest'))
2069 ,(Foo('test1'), Bar('test1'))
2070 ,(Foo('test1'), Bar('test2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002071
Georg Brandl15c5ce92007-03-07 09:09:40 +00002072 ################################################################
2073 ### /Set up attributes used by inherited tests
Tim Petersea5962f2007-03-12 18:07:52 +00002074
Georg Brandl15c5ce92007-03-07 09:09:40 +00002075
2076 # "class TestCase([methodName])"
2077 # ...
2078 # "Each instance of TestCase will run a single test method: the
2079 # method named methodName."
2080 # ...
2081 # "methodName defaults to "runTest"."
2082 #
2083 # Make sure it really is optional, and that it defaults to the proper
2084 # thing.
2085 def test_init__no_test_name(self):
2086 class Test(unittest.TestCase):
2087 def runTest(self): raise MyException()
2088 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002089
Georg Brandl15c5ce92007-03-07 09:09:40 +00002090 self.assertEqual(Test().id()[-13:], '.Test.runTest')
Tim Petersea5962f2007-03-12 18:07:52 +00002091
Georg Brandl15c5ce92007-03-07 09:09:40 +00002092 # "class TestCase([methodName])"
2093 # ...
2094 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002095 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002096 def test_init__test_name__valid(self):
2097 class Test(unittest.TestCase):
2098 def runTest(self): raise MyException()
2099 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002100
Georg Brandl15c5ce92007-03-07 09:09:40 +00002101 self.assertEqual(Test('test').id()[-10:], '.Test.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002102
Georg Brandl15c5ce92007-03-07 09:09:40 +00002103 # "class TestCase([methodName])"
2104 # ...
2105 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002106 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002107 def test_init__test_name__invalid(self):
2108 class Test(unittest.TestCase):
2109 def runTest(self): raise MyException()
2110 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002111
Georg Brandl15c5ce92007-03-07 09:09:40 +00002112 try:
2113 Test('testfoo')
2114 except ValueError:
2115 pass
2116 else:
2117 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +00002118
Georg Brandl15c5ce92007-03-07 09:09:40 +00002119 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00002120 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00002121 def test_countTestCases(self):
2122 class Foo(unittest.TestCase):
2123 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002124
Georg Brandl15c5ce92007-03-07 09:09:40 +00002125 self.assertEqual(Foo('test').countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00002126
Georg Brandl15c5ce92007-03-07 09:09:40 +00002127 # "Return the default type of test result object to be used to run this
2128 # test. For TestCase instances, this will always be
2129 # unittest.TestResult; subclasses of TestCase should
2130 # override this as necessary."
2131 def test_defaultTestResult(self):
2132 class Foo(unittest.TestCase):
2133 def runTest(self):
2134 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002135
Georg Brandl15c5ce92007-03-07 09:09:40 +00002136 result = Foo().defaultTestResult()
2137 self.assertEqual(type(result), unittest.TestResult)
2138
2139 # "When a setUp() method is defined, the test runner will run that method
2140 # prior to each test. Likewise, if a tearDown() method is defined, the
2141 # test runner will invoke that method after each test. In the example,
2142 # setUp() was used to create a fresh sequence for each test."
2143 #
2144 # Make sure the proper call order is maintained, even if setUp() raises
2145 # an exception.
2146 def test_run_call_order__error_in_setUp(self):
2147 events = []
2148 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002149
Michael Foord07ef4872009-05-02 22:43:34 +00002150 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002151 def setUp(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002152 super(Foo, self).setUp()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002153 raise RuntimeError('raised by Foo.setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002154
Michael Foord07ef4872009-05-02 22:43:34 +00002155 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002156 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2157 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002158
Michael Foord07ef4872009-05-02 22:43:34 +00002159 # "With a temporary result stopTestRun is called when setUp errors.
2160 def test_run_call_order__error_in_setUp_default_result(self):
2161 events = []
2162
2163 class Foo(LoggingTestCase):
2164 def defaultTestResult(self):
2165 return LoggingResult(self.events)
2166
2167 def setUp(self):
2168 super(Foo, self).setUp()
2169 raise RuntimeError('raised by Foo.setUp')
2170
2171 Foo(events).run()
2172 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2173 'stopTest', 'stopTestRun']
2174 self.assertEqual(events, expected)
2175
Georg Brandl15c5ce92007-03-07 09:09:40 +00002176 # "When a setUp() method is defined, the test runner will run that method
2177 # prior to each test. Likewise, if a tearDown() method is defined, the
2178 # test runner will invoke that method after each test. In the example,
2179 # setUp() was used to create a fresh sequence for each test."
2180 #
2181 # Make sure the proper call order is maintained, even if the test raises
2182 # an error (as opposed to a failure).
2183 def test_run_call_order__error_in_test(self):
2184 events = []
2185 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002186
Michael Foord07ef4872009-05-02 22:43:34 +00002187 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002188 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002189 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002190 raise RuntimeError('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002191
Georg Brandl15c5ce92007-03-07 09:09:40 +00002192 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2193 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002194 Foo(events).run(result)
2195 self.assertEqual(events, expected)
2196
2197 # "With a default result, an error in the test still results in stopTestRun
2198 # being called."
2199 def test_run_call_order__error_in_test_default_result(self):
2200 events = []
2201
2202 class Foo(LoggingTestCase):
2203 def defaultTestResult(self):
2204 return LoggingResult(self.events)
2205
2206 def test(self):
2207 super(Foo, self).test()
2208 raise RuntimeError('raised by Foo.test')
2209
2210 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2211 'tearDown', 'stopTest', 'stopTestRun']
2212 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002213 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002214
Georg Brandl15c5ce92007-03-07 09:09:40 +00002215 # "When a setUp() method is defined, the test runner will run that method
2216 # prior to each test. Likewise, if a tearDown() method is defined, the
2217 # test runner will invoke that method after each test. In the example,
2218 # setUp() was used to create a fresh sequence for each test."
2219 #
2220 # Make sure the proper call order is maintained, even if the test signals
2221 # a failure (as opposed to an error).
2222 def test_run_call_order__failure_in_test(self):
2223 events = []
2224 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002225
Michael Foord07ef4872009-05-02 22:43:34 +00002226 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002227 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002228 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002229 self.fail('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002230
Georg Brandl15c5ce92007-03-07 09:09:40 +00002231 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2232 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002233 Foo(events).run(result)
2234 self.assertEqual(events, expected)
2235
2236 # "When a test fails with a default result stopTestRun is still called."
2237 def test_run_call_order__failure_in_test_default_result(self):
2238
2239 class Foo(LoggingTestCase):
2240 def defaultTestResult(self):
2241 return LoggingResult(self.events)
2242 def test(self):
2243 super(Foo, self).test()
2244 self.fail('raised by Foo.test')
2245
2246 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2247 'tearDown', 'stopTest', 'stopTestRun']
2248 events = []
2249 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002250 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002251
Georg Brandl15c5ce92007-03-07 09:09:40 +00002252 # "When a setUp() method is defined, the test runner will run that method
2253 # prior to each test. Likewise, if a tearDown() method is defined, the
2254 # test runner will invoke that method after each test. In the example,
2255 # setUp() was used to create a fresh sequence for each test."
2256 #
2257 # Make sure the proper call order is maintained, even if tearDown() raises
2258 # an exception.
2259 def test_run_call_order__error_in_tearDown(self):
2260 events = []
2261 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002262
Michael Foord07ef4872009-05-02 22:43:34 +00002263 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002264 def tearDown(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002265 super(Foo, self).tearDown()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002266 raise RuntimeError('raised by Foo.tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002267
Michael Foord07ef4872009-05-02 22:43:34 +00002268 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002269 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2270 'stopTest']
2271 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002272
Michael Foord07ef4872009-05-02 22:43:34 +00002273 # "When tearDown errors with a default result stopTestRun is still called."
2274 def test_run_call_order__error_in_tearDown_default_result(self):
2275
2276 class Foo(LoggingTestCase):
2277 def defaultTestResult(self):
2278 return LoggingResult(self.events)
2279 def tearDown(self):
2280 super(Foo, self).tearDown()
2281 raise RuntimeError('raised by Foo.tearDown')
2282
2283 events = []
2284 Foo(events).run()
2285 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2286 'addError', 'stopTest', 'stopTestRun']
2287 self.assertEqual(events, expected)
2288
2289 # "TestCase.run() still works when the defaultTestResult is a TestResult
2290 # that does not support startTestRun and stopTestRun.
2291 def test_run_call_order_default_result(self):
2292
2293 class Foo(unittest.TestCase):
2294 def defaultTestResult(self):
2295 return ResultWithNoStartTestRunStopTestRun()
2296 def test(self):
2297 pass
2298
2299 Foo('test').run()
2300
Georg Brandl15c5ce92007-03-07 09:09:40 +00002301 # "This class attribute gives the exception raised by the test() method.
2302 # If a test framework needs to use a specialized exception, possibly to
2303 # carry additional information, it must subclass this exception in
2304 # order to ``play fair'' with the framework. The initial value of this
2305 # attribute is AssertionError"
2306 def test_failureException__default(self):
2307 class Foo(unittest.TestCase):
2308 def test(self):
2309 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002310
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002311 self.assertTrue(Foo('test').failureException is AssertionError)
Tim Petersea5962f2007-03-12 18:07:52 +00002312
Georg Brandl15c5ce92007-03-07 09:09:40 +00002313 # "This class attribute gives the exception raised by the test() method.
2314 # If a test framework needs to use a specialized exception, possibly to
2315 # carry additional information, it must subclass this exception in
2316 # order to ``play fair'' with the framework."
2317 #
2318 # Make sure TestCase.run() respects the designated failureException
2319 def test_failureException__subclassing__explicit_raise(self):
2320 events = []
2321 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002322
Georg Brandl15c5ce92007-03-07 09:09:40 +00002323 class Foo(unittest.TestCase):
2324 def test(self):
2325 raise RuntimeError()
Tim Petersea5962f2007-03-12 18:07:52 +00002326
Georg Brandl15c5ce92007-03-07 09:09:40 +00002327 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002328
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002329 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002330
2331
Georg Brandl15c5ce92007-03-07 09:09:40 +00002332 Foo('test').run(result)
2333 expected = ['startTest', 'addFailure', 'stopTest']
2334 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002335
Georg Brandl15c5ce92007-03-07 09:09:40 +00002336 # "This class attribute gives the exception raised by the test() method.
2337 # If a test framework needs to use a specialized exception, possibly to
2338 # carry additional information, it must subclass this exception in
2339 # order to ``play fair'' with the framework."
2340 #
2341 # Make sure TestCase.run() respects the designated failureException
2342 def test_failureException__subclassing__implicit_raise(self):
2343 events = []
2344 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002345
Georg Brandl15c5ce92007-03-07 09:09:40 +00002346 class Foo(unittest.TestCase):
2347 def test(self):
2348 self.fail("foo")
Tim Petersea5962f2007-03-12 18:07:52 +00002349
Georg Brandl15c5ce92007-03-07 09:09:40 +00002350 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002351
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002352 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002353
2354
Georg Brandl15c5ce92007-03-07 09:09:40 +00002355 Foo('test').run(result)
2356 expected = ['startTest', 'addFailure', 'stopTest']
2357 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002358
2359 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002360 def test_setUp(self):
2361 class Foo(unittest.TestCase):
2362 def runTest(self):
2363 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002364
Georg Brandl15c5ce92007-03-07 09:09:40 +00002365 # ... and nothing should happen
2366 Foo().setUp()
Tim Petersea5962f2007-03-12 18:07:52 +00002367
2368 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002369 def test_tearDown(self):
2370 class Foo(unittest.TestCase):
2371 def runTest(self):
2372 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002373
Georg Brandl15c5ce92007-03-07 09:09:40 +00002374 # ... and nothing should happen
2375 Foo().tearDown()
Tim Petersea5962f2007-03-12 18:07:52 +00002376
Georg Brandl15c5ce92007-03-07 09:09:40 +00002377 # "Return a string identifying the specific test case."
2378 #
2379 # Because of the vague nature of the docs, I'm not going to lock this
2380 # test down too much. Really all that can be asserted is that the id()
2381 # will be a string (either 8-byte or unicode -- again, because the docs
2382 # just say "string")
2383 def test_id(self):
2384 class Foo(unittest.TestCase):
2385 def runTest(self):
2386 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002387
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002388 self.assertTrue(isinstance(Foo().id(), basestring))
Tim Petersea5962f2007-03-12 18:07:52 +00002389
Georg Brandl15c5ce92007-03-07 09:09:40 +00002390 # "If result is omitted or None, a temporary result object is created
Michael Foord07ef4872009-05-02 22:43:34 +00002391 # and used, but is not made available to the caller. As TestCase owns the
2392 # temporary result startTestRun and stopTestRun are called.
2393
Georg Brandl15c5ce92007-03-07 09:09:40 +00002394 def test_run__uses_defaultTestResult(self):
2395 events = []
Tim Petersea5962f2007-03-12 18:07:52 +00002396
Georg Brandl15c5ce92007-03-07 09:09:40 +00002397 class Foo(unittest.TestCase):
2398 def test(self):
2399 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002400
Georg Brandl15c5ce92007-03-07 09:09:40 +00002401 def defaultTestResult(self):
2402 return LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002403
2404 # Make run() find a result object on its own
Georg Brandl15c5ce92007-03-07 09:09:40 +00002405 Foo('test').run()
Tim Petersea5962f2007-03-12 18:07:52 +00002406
Michael Foord07ef4872009-05-02 22:43:34 +00002407 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2408 'stopTest', 'stopTestRun']
Georg Brandl15c5ce92007-03-07 09:09:40 +00002409 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002410
Gregory P. Smith28399852009-03-31 16:54:10 +00002411 def testShortDescriptionWithoutDocstring(self):
2412 self.assertEqual(
2413 self.shortDescription(),
2414 'testShortDescriptionWithoutDocstring (' + __name__ +
2415 '.Test_TestCase)')
2416
2417 def testShortDescriptionWithOneLineDocstring(self):
2418 """Tests shortDescription() for a method with a docstring."""
2419 self.assertEqual(
2420 self.shortDescription(),
2421 ('testShortDescriptionWithOneLineDocstring '
2422 '(' + __name__ + '.Test_TestCase)\n'
2423 'Tests shortDescription() for a method with a docstring.'))
2424
2425 def testShortDescriptionWithMultiLineDocstring(self):
2426 """Tests shortDescription() for a method with a longer docstring.
2427
2428 This method ensures that only the first line of a docstring is
2429 returned used in the short description, no matter how long the
2430 whole thing is.
2431 """
2432 self.assertEqual(
2433 self.shortDescription(),
2434 ('testShortDescriptionWithMultiLineDocstring '
2435 '(' + __name__ + '.Test_TestCase)\n'
2436 'Tests shortDescription() for a method with a longer '
2437 'docstring.'))
2438
Gregory P. Smith28399852009-03-31 16:54:10 +00002439 def testAddTypeEqualityFunc(self):
2440 class SadSnake(object):
2441 """Dummy class for test_addTypeEqualityFunc."""
2442 s1, s2 = SadSnake(), SadSnake()
2443 self.assertFalse(s1 == s2)
2444 def AllSnakesCreatedEqual(a, b, msg=None):
2445 return type(a) == type(b) == SadSnake
2446 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2447 self.assertEqual(s1, s2)
2448 # No this doesn't clean up and remove the SadSnake equality func
2449 # from this TestCase instance but since its a local nothing else
2450 # will ever notice that.
2451
Michael Foordf2dfef12009-04-05 19:19:28 +00002452 def testAssertIs(self):
2453 thing = object()
2454 self.assertIs(thing, thing)
2455 self.assertRaises(self.failureException, self.assertIs, thing, object())
2456
2457 def testAssertIsNot(self):
2458 thing = object()
2459 self.assertIsNot(thing, object())
2460 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2461
Gregory P. Smith28399852009-03-31 16:54:10 +00002462 def testAssertIn(self):
2463 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2464
2465 self.assertIn('a', 'abc')
2466 self.assertIn(2, [1, 2, 3])
2467 self.assertIn('monkey', animals)
2468
2469 self.assertNotIn('d', 'abc')
2470 self.assertNotIn(0, [1, 2, 3])
2471 self.assertNotIn('otter', animals)
2472
2473 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2474 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2475 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2476 animals)
2477
2478 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2479 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2480 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2481 animals)
2482
2483 def testAssertDictContainsSubset(self):
2484 self.assertDictContainsSubset({}, {})
2485 self.assertDictContainsSubset({}, {'a': 1})
2486 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2487 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2488 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2489
2490 self.assertRaises(unittest.TestCase.failureException,
2491 self.assertDictContainsSubset, {'a': 2}, {'a': 1},
2492 '.*Mismatched values:.*')
2493
2494 self.assertRaises(unittest.TestCase.failureException,
2495 self.assertDictContainsSubset, {'c': 1}, {'a': 1},
2496 '.*Missing:.*')
2497
2498 self.assertRaises(unittest.TestCase.failureException,
2499 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2500 {'a': 1}, '.*Missing:.*')
2501
2502 self.assertRaises(unittest.TestCase.failureException,
2503 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2504 {'a': 1}, '.*Missing:.*Mismatched values:.*')
2505
2506 def testAssertEqual(self):
2507 equal_pairs = [
2508 ((), ()),
2509 ({}, {}),
2510 ([], []),
2511 (set(), set()),
2512 (frozenset(), frozenset())]
2513 for a, b in equal_pairs:
2514 # This mess of try excepts is to test the assertEqual behavior
2515 # itself.
2516 try:
2517 self.assertEqual(a, b)
2518 except self.failureException:
2519 self.fail('assertEqual(%r, %r) failed' % (a, b))
2520 try:
2521 self.assertEqual(a, b, msg='foo')
2522 except self.failureException:
2523 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2524 try:
2525 self.assertEqual(a, b, 'foo')
2526 except self.failureException:
2527 self.fail('assertEqual(%r, %r) with third parameter failed' %
2528 (a, b))
2529
2530 unequal_pairs = [
2531 ((), []),
2532 ({}, set()),
2533 (set([4,1]), frozenset([4,2])),
2534 (frozenset([4,5]), set([2,3])),
2535 (set([3,4]), set([5,4]))]
2536 for a, b in unequal_pairs:
2537 self.assertRaises(self.failureException, self.assertEqual, a, b)
2538 self.assertRaises(self.failureException, self.assertEqual, a, b,
2539 'foo')
2540 self.assertRaises(self.failureException, self.assertEqual, a, b,
2541 msg='foo')
2542
2543 def testEquality(self):
2544 self.assertListEqual([], [])
2545 self.assertTupleEqual((), ())
2546 self.assertSequenceEqual([], ())
2547
2548 a = [0, 'a', []]
2549 b = []
2550 self.assertRaises(unittest.TestCase.failureException,
2551 self.assertListEqual, a, b)
2552 self.assertRaises(unittest.TestCase.failureException,
2553 self.assertListEqual, tuple(a), tuple(b))
2554 self.assertRaises(unittest.TestCase.failureException,
2555 self.assertSequenceEqual, a, tuple(b))
2556
2557 b.extend(a)
2558 self.assertListEqual(a, b)
2559 self.assertTupleEqual(tuple(a), tuple(b))
2560 self.assertSequenceEqual(a, tuple(b))
2561 self.assertSequenceEqual(tuple(a), b)
2562
2563 self.assertRaises(self.failureException, self.assertListEqual,
2564 a, tuple(b))
2565 self.assertRaises(self.failureException, self.assertTupleEqual,
2566 tuple(a), b)
2567 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2568 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2569 tuple(b))
2570 self.assertRaises(self.failureException, self.assertSequenceEqual,
2571 None, tuple(b))
2572 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2573 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2574 self.assertRaises(self.failureException, self.assertSequenceEqual,
2575 1, 1)
2576
2577 self.assertDictEqual({}, {})
2578
2579 c = { 'x': 1 }
2580 d = {}
2581 self.assertRaises(unittest.TestCase.failureException,
2582 self.assertDictEqual, c, d)
2583
2584 d.update(c)
2585 self.assertDictEqual(c, d)
2586
2587 d['x'] = 0
2588 self.assertRaises(unittest.TestCase.failureException,
2589 self.assertDictEqual, c, d, 'These are unequal')
2590
2591 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2592 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2593 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2594
2595 self.assertSameElements([1, 2, 3], [3, 2, 1])
2596 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2597 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2598 self.assertRaises(self.failureException, self.assertSameElements,
2599 [10], [10, 11])
2600 self.assertRaises(self.failureException, self.assertSameElements,
2601 [10, 11], [10])
2602
2603 # Test that sequences of unhashable objects can be tested for sameness:
2604 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Michael Foordf2dfef12009-04-05 19:19:28 +00002605
Gregory P. Smith28399852009-03-31 16:54:10 +00002606 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2607 self.assertRaises(self.failureException, self.assertSameElements,
2608 [[1]], [[2]])
2609
2610 def testAssertSetEqual(self):
2611 set1 = set()
2612 set2 = set()
2613 self.assertSetEqual(set1, set2)
2614
2615 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2616 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2617 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2618 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2619
2620 set1 = set(['a'])
2621 set2 = set()
2622 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2623
2624 set1 = set(['a'])
2625 set2 = set(['a'])
2626 self.assertSetEqual(set1, set2)
2627
2628 set1 = set(['a'])
2629 set2 = set(['a', 'b'])
2630 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2631
2632 set1 = set(['a'])
2633 set2 = frozenset(['a', 'b'])
2634 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2635
2636 set1 = set(['a', 'b'])
2637 set2 = frozenset(['a', 'b'])
2638 self.assertSetEqual(set1, set2)
2639
2640 set1 = set()
2641 set2 = "foo"
2642 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2643 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2644
2645 # make sure any string formatting is tuple-safe
2646 set1 = set([(0, 1), (2, 3)])
2647 set2 = set([(4, 5)])
2648 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2649
2650 def testInequality(self):
2651 # Try ints
2652 self.assertGreater(2, 1)
2653 self.assertGreaterEqual(2, 1)
2654 self.assertGreaterEqual(1, 1)
2655 self.assertLess(1, 2)
2656 self.assertLessEqual(1, 2)
2657 self.assertLessEqual(1, 1)
2658 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2659 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2660 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2661 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2662 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2663 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2664
2665 # Try Floats
2666 self.assertGreater(1.1, 1.0)
2667 self.assertGreaterEqual(1.1, 1.0)
2668 self.assertGreaterEqual(1.0, 1.0)
2669 self.assertLess(1.0, 1.1)
2670 self.assertLessEqual(1.0, 1.1)
2671 self.assertLessEqual(1.0, 1.0)
2672 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2673 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2674 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2675 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2676 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2677 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2678
2679 # Try Strings
2680 self.assertGreater('bug', 'ant')
2681 self.assertGreaterEqual('bug', 'ant')
2682 self.assertGreaterEqual('ant', 'ant')
2683 self.assertLess('ant', 'bug')
2684 self.assertLessEqual('ant', 'bug')
2685 self.assertLessEqual('ant', 'ant')
2686 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2687 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2688 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2689 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2690 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2691 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2692
2693 # Try Unicode
2694 self.assertGreater(u'bug', u'ant')
2695 self.assertGreaterEqual(u'bug', u'ant')
2696 self.assertGreaterEqual(u'ant', u'ant')
2697 self.assertLess(u'ant', u'bug')
2698 self.assertLessEqual(u'ant', u'bug')
2699 self.assertLessEqual(u'ant', u'ant')
2700 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug')
2701 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant')
2702 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2703 u'bug')
2704 self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant')
2705 self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant')
2706 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant')
2707
2708 # Try Mixed String/Unicode
2709 self.assertGreater('bug', u'ant')
2710 self.assertGreater(u'bug', 'ant')
2711 self.assertGreaterEqual('bug', u'ant')
2712 self.assertGreaterEqual(u'bug', 'ant')
2713 self.assertGreaterEqual('ant', u'ant')
2714 self.assertGreaterEqual(u'ant', 'ant')
2715 self.assertLess('ant', u'bug')
2716 self.assertLess(u'ant', 'bug')
2717 self.assertLessEqual('ant', u'bug')
2718 self.assertLessEqual(u'ant', 'bug')
2719 self.assertLessEqual('ant', u'ant')
2720 self.assertLessEqual(u'ant', 'ant')
2721 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug')
2722 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug')
2723 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant')
2724 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant')
2725 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant',
2726 u'bug')
2727 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2728 'bug')
2729 self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant')
2730 self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant')
2731 self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant')
2732 self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant')
2733 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant')
2734 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant')
2735
2736 def testAssertMultiLineEqual(self):
2737 sample_text = b"""\
2738http://www.python.org/doc/2.3/lib/module-unittest.html
2739test case
2740 A test case is the smallest unit of testing. [...]
2741"""
2742 revised_sample_text = b"""\
2743http://www.python.org/doc/2.4.1/lib/module-unittest.html
2744test case
2745 A test case is the smallest unit of testing. [...] You may provide your
2746 own implementation that does not subclass from TestCase, of course.
2747"""
2748 sample_text_error = b"""
2749- http://www.python.org/doc/2.3/lib/module-unittest.html
2750? ^
2751+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2752? ^^^
2753 test case
2754- A test case is the smallest unit of testing. [...]
2755+ A test case is the smallest unit of testing. [...] You may provide your
2756? +++++++++++++++++++++
2757+ own implementation that does not subclass from TestCase, of course.
2758"""
2759
2760 for type_changer in (lambda x: x, lambda x: x.decode('utf8')):
2761 try:
2762 self.assertMultiLineEqual(type_changer(sample_text),
2763 type_changer(revised_sample_text))
2764 except self.failureException, e:
2765 # no fair testing ourself with ourself, use assertEqual..
2766 self.assertEqual(sample_text_error, str(e).encode('utf8'))
2767
2768 def testAssertIsNone(self):
2769 self.assertIsNone(None)
2770 self.assertRaises(self.failureException, self.assertIsNone, False)
2771 self.assertIsNotNone('DjZoPloGears on Rails')
2772 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2773
2774 def testAssertRegexpMatches(self):
2775 self.assertRegexpMatches('asdfabasdf', r'ab+')
2776 self.assertRaises(self.failureException, self.assertRegexpMatches,
2777 'saaas', r'aaaa')
2778
2779 def testAssertRaisesRegexp(self):
2780 class ExceptionMock(Exception):
2781 pass
2782
2783 def Stub():
2784 raise ExceptionMock('We expect')
2785
2786 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2787 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2788 self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
2789
2790 def testAssertNotRaisesRegexp(self):
2791 self.assertRaisesRegexp(
2792 self.failureException, '^Exception not raised$',
2793 self.assertRaisesRegexp, Exception, re.compile('x'),
2794 lambda: None)
2795 self.assertRaisesRegexp(
2796 self.failureException, '^Exception not raised$',
2797 self.assertRaisesRegexp, Exception, 'x',
2798 lambda: None)
2799 self.assertRaisesRegexp(
2800 self.failureException, '^Exception not raised$',
2801 self.assertRaisesRegexp, Exception, u'x',
2802 lambda: None)
2803
2804 def testAssertRaisesRegexpMismatch(self):
2805 def Stub():
2806 raise Exception('Unexpected')
2807
2808 self.assertRaisesRegexp(
2809 self.failureException,
2810 r'"\^Expected\$" does not match "Unexpected"',
2811 self.assertRaisesRegexp, Exception, '^Expected$',
2812 Stub)
2813 self.assertRaisesRegexp(
2814 self.failureException,
2815 r'"\^Expected\$" does not match "Unexpected"',
2816 self.assertRaisesRegexp, Exception, u'^Expected$',
2817 Stub)
2818 self.assertRaisesRegexp(
2819 self.failureException,
2820 r'"\^Expected\$" does not match "Unexpected"',
2821 self.assertRaisesRegexp, Exception,
2822 re.compile('^Expected$'), Stub)
2823
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00002824 def testAssertRaisesExcValue(self):
2825 class ExceptionMock(Exception):
2826 pass
2827
2828 def Stub(foo):
2829 raise ExceptionMock(foo)
2830 v = "particular value"
2831
2832 ctx = self.assertRaises(ExceptionMock)
2833 with ctx:
2834 Stub(v)
2835 e = ctx.exc_value
2836 self.assertTrue(isinstance(e, ExceptionMock))
2837 self.assertEqual(e.args[0], v)
2838
Gregory P. Smith7558d572009-03-31 19:03:28 +00002839 def testSynonymAssertMethodNames(self):
2840 """Test undocumented method name synonyms.
2841
2842 Please do not use these methods names in your own code.
2843
2844 This test confirms their continued existence and functionality
2845 in order to avoid breaking existing code.
2846 """
2847 self.assertNotEquals(3, 5)
2848 self.assertEquals(3, 3)
2849 self.assertAlmostEquals(2.0, 2.0)
2850 self.assertNotAlmostEquals(3.0, 5.0)
2851 self.assert_(True)
2852
2853 def testPendingDeprecationMethodNames(self):
2854 """Test fail* methods pending deprecation, they will warn in 3.2.
2855
2856 Do not use these methods. They will go away in 3.3.
2857 """
2858 self.failIfEqual(3, 5)
2859 self.failUnlessEqual(3, 3)
2860 self.failUnlessAlmostEqual(2.0, 2.0)
2861 self.failIfAlmostEqual(3.0, 5.0)
2862 self.failUnless(True)
2863 self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam')
2864 self.failIf(False)
2865
Michael Foorde2942d02009-04-02 05:51:54 +00002866 def testDeepcopy(self):
2867 # Issue: 5660
2868 class TestableTest(TestCase):
2869 def testNothing(self):
2870 pass
2871
2872 test = TestableTest('testNothing')
2873
2874 # This shouldn't blow up
2875 deepcopy(test)
2876
Benjamin Peterson692428e2009-03-23 21:50:21 +00002877
2878class Test_TestSkipping(TestCase):
2879
2880 def test_skipping(self):
2881 class Foo(unittest.TestCase):
2882 def test_skip_me(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002883 self.skipTest("skip")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002884 events = []
2885 result = LoggingResult(events)
2886 test = Foo("test_skip_me")
2887 test.run(result)
2888 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2889 self.assertEqual(result.skipped, [(test, "skip")])
2890
2891 # Try letting setUp skip the test now.
2892 class Foo(unittest.TestCase):
2893 def setUp(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002894 self.skipTest("testing")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002895 def test_nothing(self): pass
2896 events = []
2897 result = LoggingResult(events)
2898 test = Foo("test_nothing")
2899 test.run(result)
2900 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2901 self.assertEqual(result.skipped, [(test, "testing")])
2902 self.assertEqual(result.testsRun, 1)
2903
2904 def test_skipping_decorators(self):
2905 op_table = ((unittest.skipUnless, False, True),
2906 (unittest.skipIf, True, False))
2907 for deco, do_skip, dont_skip in op_table:
2908 class Foo(unittest.TestCase):
2909 @deco(do_skip, "testing")
2910 def test_skip(self): pass
2911
2912 @deco(dont_skip, "testing")
2913 def test_dont_skip(self): pass
2914 test_do_skip = Foo("test_skip")
2915 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002916 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002917 events = []
2918 result = LoggingResult(events)
2919 suite.run(result)
2920 self.assertEqual(len(result.skipped), 1)
2921 expected = ['startTest', 'addSkip', 'stopTest',
2922 'startTest', 'addSuccess', 'stopTest']
2923 self.assertEqual(events, expected)
2924 self.assertEqual(result.testsRun, 2)
2925 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
2926 self.assertTrue(result.wasSuccessful())
2927
2928 def test_skip_class(self):
2929 @unittest.skip("testing")
2930 class Foo(unittest.TestCase):
2931 def test_1(self):
2932 record.append(1)
2933 record = []
2934 result = unittest.TestResult()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002935 test = Foo("test_1")
2936 suite = unittest.TestSuite([test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002937 suite.run(result)
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002938 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002939 self.assertEqual(record, [])
2940
2941 def test_expected_failure(self):
2942 class Foo(unittest.TestCase):
2943 @unittest.expectedFailure
2944 def test_die(self):
2945 self.fail("help me!")
2946 events = []
2947 result = LoggingResult(events)
2948 test = Foo("test_die")
2949 test.run(result)
2950 self.assertEqual(events,
2951 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00002952 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00002953 self.assertTrue(result.wasSuccessful())
2954
2955 def test_unexpected_success(self):
2956 class Foo(unittest.TestCase):
2957 @unittest.expectedFailure
2958 def test_die(self):
2959 pass
2960 events = []
2961 result = LoggingResult(events)
2962 test = Foo("test_die")
2963 test.run(result)
2964 self.assertEqual(events,
2965 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
2966 self.assertFalse(result.failures)
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00002967 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002968 self.assertTrue(result.wasSuccessful())
2969
2970
2971
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002972class Test_Assertions(TestCase):
2973 def test_AlmostEqual(self):
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002974 self.assertAlmostEqual(1.00000001, 1.0)
2975 self.assertNotAlmostEqual(1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00002976 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002977 self.assertAlmostEqual, 1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00002978 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002979 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002980
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002981 self.assertAlmostEqual(1.1, 1.0, places=0)
Gregory P. Smith28399852009-03-31 16:54:10 +00002982 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002983 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002984
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002985 self.assertAlmostEqual(0, .1+.1j, places=0)
2986 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00002987 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002988 self.assertAlmostEqual, 0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00002989 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002990 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002991
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00002992 def test_assertRaises(self):
2993 def _raise(e):
2994 raise e
2995 self.assertRaises(KeyError, _raise, KeyError)
2996 self.assertRaises(KeyError, _raise, KeyError("key"))
2997 try:
2998 self.assertRaises(KeyError, lambda: None)
Gregory P. Smith28399852009-03-31 16:54:10 +00002999 except self.failureException as e:
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003000 self.assert_("KeyError not raised" in e, str(e))
3001 else:
3002 self.fail("assertRaises() didn't fail")
3003 try:
3004 self.assertRaises(KeyError, _raise, ValueError)
3005 except ValueError:
3006 pass
3007 else:
3008 self.fail("assertRaises() didn't let exception pass through")
3009 with self.assertRaises(KeyError):
3010 raise KeyError
3011 with self.assertRaises(KeyError):
3012 raise KeyError("key")
3013 try:
3014 with self.assertRaises(KeyError):
3015 pass
Gregory P. Smith28399852009-03-31 16:54:10 +00003016 except self.failureException as e:
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003017 self.assert_("KeyError not raised" in e, str(e))
3018 else:
3019 self.fail("assertRaises() didn't fail")
3020 try:
3021 with self.assertRaises(KeyError):
3022 raise ValueError
3023 except ValueError:
3024 pass
3025 else:
3026 self.fail("assertRaises() didn't let exception pass through")
3027
3028
Michael Foord345b2fe2009-04-02 03:20:38 +00003029class TestLongMessage(TestCase):
3030 """Test that the individual asserts honour longMessage.
3031 This actually tests all the message behaviour for
3032 asserts that use longMessage."""
3033
3034 def setUp(self):
3035 class TestableTestFalse(TestCase):
3036 longMessage = False
3037 failureException = self.failureException
3038
3039 def testTest(self):
3040 pass
3041
3042 class TestableTestTrue(TestCase):
3043 longMessage = True
3044 failureException = self.failureException
3045
3046 def testTest(self):
3047 pass
3048
3049 self.testableTrue = TestableTestTrue('testTest')
3050 self.testableFalse = TestableTestFalse('testTest')
3051
3052 def testDefault(self):
3053 self.assertFalse(TestCase.longMessage)
3054
3055 def test_formatMsg(self):
3056 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3057 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3058
3059 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3060 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3061
3062 def assertMessages(self, methodName, args, errors):
3063 def getMethod(i):
3064 useTestableFalse = i < 2
3065 if useTestableFalse:
3066 test = self.testableFalse
3067 else:
3068 test = self.testableTrue
3069 return getattr(test, methodName)
3070
3071 for i, expected_regexp in enumerate(errors):
3072 testMethod = getMethod(i)
3073 kwargs = {}
3074 withMsg = i % 2
3075 if withMsg:
3076 kwargs = {"msg": "oops"}
3077
3078 with self.assertRaisesRegexp(self.failureException,
3079 expected_regexp=expected_regexp):
3080 testMethod(*args, **kwargs)
3081
3082 def testAssertTrue(self):
3083 self.assertMessages('assertTrue', (False,),
3084 ["^False is not True$", "^oops$", "^False is not True$",
3085 "^False is not True : oops$"])
3086
3087 def testAssertFalse(self):
3088 self.assertMessages('assertFalse', (True,),
3089 ["^True is not False$", "^oops$", "^True is not False$",
3090 "^True is not False : oops$"])
3091
3092 def testNotEqual(self):
3093 self.assertMessages('assertNotEqual', (1, 1),
3094 ["^1 == 1$", "^oops$", "^1 == 1$",
3095 "^1 == 1 : oops$"])
3096
3097 def testAlmostEqual(self):
3098 self.assertMessages('assertAlmostEqual', (1, 2),
3099 ["^1 != 2 within 7 places$", "^oops$",
3100 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3101
3102 def testNotAlmostEqual(self):
3103 self.assertMessages('assertNotAlmostEqual', (1, 1),
3104 ["^1 == 1 within 7 places$", "^oops$",
3105 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3106
3107 def test_baseAssertEqual(self):
3108 self.assertMessages('_baseAssertEqual', (1, 2),
3109 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3110
3111 def testAssertSequenceEqual(self):
3112 # Error messages are multiline so not testing on full message
3113 # assertTupleEqual and assertListEqual delegate to this method
3114 self.assertMessages('assertSequenceEqual', ([], [None]),
3115 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3116 r"\+ \[None\] : oops$"])
3117
3118 def testAssertSetEqual(self):
3119 self.assertMessages('assertSetEqual', (set(), set([None])),
3120 ["None$", "^oops$", "None$",
3121 "None : oops$"])
3122
3123 def testAssertIn(self):
3124 self.assertMessages('assertIn', (None, []),
3125 ['^None not found in \[\]$', "^oops$",
3126 '^None not found in \[\]$',
3127 '^None not found in \[\] : oops$'])
3128
3129 def testAssertNotIn(self):
3130 self.assertMessages('assertNotIn', (None, [None]),
3131 ['^None unexpectedly found in \[None\]$', "^oops$",
3132 '^None unexpectedly found in \[None\]$',
3133 '^None unexpectedly found in \[None\] : oops$'])
3134
3135 def testAssertDictEqual(self):
3136 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3137 [r"\+ \{'key': 'value'\}$", "^oops$",
3138 "\+ \{'key': 'value'\}$",
3139 "\+ \{'key': 'value'\} : oops$"])
3140
3141 def testAssertDictContainsSubset(self):
3142 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3143 ["^Missing: 'key'$", "^oops$",
3144 "^Missing: 'key'$",
3145 "^Missing: 'key' : oops$"])
3146
3147 def testAssertSameElements(self):
3148 self.assertMessages('assertSameElements', ([], [None]),
3149 [r"\[None\]$", "^oops$",
3150 r"\[None\]$",
3151 r"\[None\] : oops$"])
3152
3153 def testAssertMultiLineEqual(self):
3154 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3155 [r"\+ foo$", "^oops$",
3156 r"\+ foo$",
3157 r"\+ foo : oops$"])
3158
3159 def testAssertLess(self):
3160 self.assertMessages('assertLess', (2, 1),
3161 ["^2 not less than 1$", "^oops$",
3162 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3163
3164 def testAssertLessEqual(self):
3165 self.assertMessages('assertLessEqual', (2, 1),
3166 ["^2 not less than or equal to 1$", "^oops$",
3167 "^2 not less than or equal to 1$",
3168 "^2 not less than or equal to 1 : oops$"])
3169
3170 def testAssertGreater(self):
3171 self.assertMessages('assertGreater', (1, 2),
3172 ["^1 not greater than 2$", "^oops$",
3173 "^1 not greater than 2$",
3174 "^1 not greater than 2 : oops$"])
3175
3176 def testAssertGreaterEqual(self):
3177 self.assertMessages('assertGreaterEqual', (1, 2),
3178 ["^1 not greater than or equal to 2$", "^oops$",
3179 "^1 not greater than or equal to 2$",
3180 "^1 not greater than or equal to 2 : oops$"])
3181
3182 def testAssertIsNone(self):
3183 self.assertMessages('assertIsNone', ('not None',),
3184 ["^'not None' is not None$", "^oops$",
3185 "^'not None' is not None$",
3186 "^'not None' is not None : oops$"])
3187
3188 def testAssertIsNotNone(self):
3189 self.assertMessages('assertIsNotNone', (None,),
3190 ["^unexpectedly None$", "^oops$",
3191 "^unexpectedly None$",
3192 "^unexpectedly None : oops$"])
3193
Michael Foordf2dfef12009-04-05 19:19:28 +00003194 def testAssertIs(self):
3195 self.assertMessages('assertIs', (None, 'foo'),
3196 ["^None is not 'foo'$", "^oops$",
3197 "^None is not 'foo'$",
3198 "^None is not 'foo' : oops$"])
3199
3200 def testAssertIsNot(self):
3201 self.assertMessages('assertIsNot', (None, None),
3202 ["^unexpectedly identical: None$", "^oops$",
3203 "^unexpectedly identical: None$",
3204 "^unexpectedly identical: None : oops$"])
3205
Michael Foord345b2fe2009-04-02 03:20:38 +00003206
Michael Foorde2fb98f2009-05-02 20:15:05 +00003207class TestCleanUp(TestCase):
3208
3209 def testCleanUp(self):
3210 class TestableTest(TestCase):
3211 def testNothing(self):
3212 pass
3213
3214 test = TestableTest('testNothing')
3215 self.assertEqual(test._cleanups, [])
3216
3217 cleanups = []
3218
3219 def cleanup1(*args, **kwargs):
3220 cleanups.append((1, args, kwargs))
3221
3222 def cleanup2(*args, **kwargs):
3223 cleanups.append((2, args, kwargs))
3224
3225 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3226 test.addCleanup(cleanup2)
3227
3228 self.assertEqual(test._cleanups,
3229 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3230 (cleanup2, (), {})])
3231
3232 result = test.doCleanups()
3233 self.assertTrue(result)
3234
3235 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3236
3237 def testCleanUpWithErrors(self):
3238 class TestableTest(TestCase):
3239 def testNothing(self):
3240 pass
3241
3242 class MockResult(object):
3243 errors = []
3244 def addError(self, test, exc_info):
3245 self.errors.append((test, exc_info))
3246
3247 result = MockResult()
3248 test = TestableTest('testNothing')
Michael Foorda50af062009-05-21 22:57:02 +00003249 test._resultForDoCleanups = result
Michael Foorde2fb98f2009-05-02 20:15:05 +00003250
3251 exc1 = Exception('foo')
3252 exc2 = Exception('bar')
3253 def cleanup1():
3254 raise exc1
3255
3256 def cleanup2():
3257 raise exc2
3258
3259 test.addCleanup(cleanup1)
3260 test.addCleanup(cleanup2)
3261
3262 self.assertFalse(test.doCleanups())
3263
3264 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3265 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3266 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3267
3268 def testCleanupInRun(self):
3269 blowUp = False
3270 ordering = []
3271
3272 class TestableTest(TestCase):
3273 def setUp(self):
3274 ordering.append('setUp')
3275 if blowUp:
3276 raise Exception('foo')
3277
3278 def testNothing(self):
3279 ordering.append('test')
3280
3281 def tearDown(self):
3282 ordering.append('tearDown')
3283
3284 test = TestableTest('testNothing')
3285
3286 def cleanup1():
3287 ordering.append('cleanup1')
3288 def cleanup2():
3289 ordering.append('cleanup2')
3290 test.addCleanup(cleanup1)
3291 test.addCleanup(cleanup2)
3292
3293 def success(some_test):
3294 self.assertEqual(some_test, test)
3295 ordering.append('success')
3296
3297 result = unittest.TestResult()
3298 result.addSuccess = success
3299
3300 test.run(result)
3301 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3302 'cleanup2', 'cleanup1', 'success'])
3303
3304 blowUp = True
3305 ordering = []
3306 test = TestableTest('testNothing')
3307 test.addCleanup(cleanup1)
3308 test.run(result)
3309 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3310
3311
Michael Foord829f6b82009-05-02 11:43:06 +00003312class Test_TestProgram(TestCase):
3313
3314 # Horrible white box test
3315 def testNoExit(self):
3316 result = object()
3317 test = object()
3318
3319 class FakeRunner(object):
3320 def run(self, test):
3321 self.test = test
3322 return result
3323
3324 runner = FakeRunner()
3325
Michael Foord5d31e052009-05-11 17:59:43 +00003326 oldParseArgs = TestProgram.parseArgs
3327 def restoreParseArgs():
Michael Foord829f6b82009-05-02 11:43:06 +00003328 TestProgram.parseArgs = oldParseArgs
Michael Foord5d31e052009-05-11 17:59:43 +00003329 TestProgram.parseArgs = lambda *args: None
3330 self.addCleanup(restoreParseArgs)
3331
3332 def removeTest():
Michael Foord829f6b82009-05-02 11:43:06 +00003333 del TestProgram.test
Michael Foord5d31e052009-05-11 17:59:43 +00003334 TestProgram.test = test
3335 self.addCleanup(removeTest)
3336
3337 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3338
3339 self.assertEqual(program.result, result)
3340 self.assertEqual(runner.test, test)
3341 self.assertEqual(program.verbosity, 2)
Michael Foord829f6b82009-05-02 11:43:06 +00003342
Michael Foord829f6b82009-05-02 11:43:06 +00003343 class FooBar(unittest.TestCase):
3344 def testPass(self):
3345 assert True
3346 def testFail(self):
3347 assert False
3348
3349 class FooBarLoader(unittest.TestLoader):
3350 """Test loader that returns a suite containing FooBar."""
3351 def loadTestsFromModule(self, module):
3352 return self.suiteClass(
3353 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3354
3355
3356 def test_NonExit(self):
3357 program = unittest.main(exit=False,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003358 argv=["foobar"],
3359 testRunner=unittest.TextTestRunner(stream=StringIO()),
3360 testLoader=self.FooBarLoader())
Michael Foord829f6b82009-05-02 11:43:06 +00003361 self.assertTrue(hasattr(program, 'result'))
3362
3363
3364 def test_Exit(self):
3365 self.assertRaises(
3366 SystemExit,
3367 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003368 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003369 testRunner=unittest.TextTestRunner(stream=StringIO()),
3370 exit=True,
3371 testLoader=self.FooBarLoader())
3372
3373
3374 def test_ExitAsDefault(self):
3375 self.assertRaises(
3376 SystemExit,
3377 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003378 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003379 testRunner=unittest.TextTestRunner(stream=StringIO()),
3380 testLoader=self.FooBarLoader())
3381
3382
Michael Foord07ef4872009-05-02 22:43:34 +00003383class Test_TextTestRunner(TestCase):
3384 """Tests for TextTestRunner."""
3385
3386 def test_works_with_result_without_startTestRun_stopTestRun(self):
3387 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3388 separator2 = ''
3389 def printErrors(self):
3390 pass
3391
3392 class Runner(unittest.TextTestRunner):
3393 def __init__(self):
3394 super(Runner, self).__init__(StringIO())
3395
3396 def _makeResult(self):
3397 return OldTextResult()
3398
3399 runner = Runner()
3400 runner.run(unittest.TestSuite())
3401
3402 def test_startTestRun_stopTestRun_called(self):
3403 class LoggingTextResult(LoggingResult):
3404 separator2 = ''
3405 def printErrors(self):
3406 pass
3407
3408 class LoggingRunner(unittest.TextTestRunner):
3409 def __init__(self, events):
3410 super(LoggingRunner, self).__init__(StringIO())
3411 self._events = events
3412
3413 def _makeResult(self):
3414 return LoggingTextResult(self._events)
3415
3416 events = []
3417 runner = LoggingRunner(events)
3418 runner.run(unittest.TestSuite())
3419 expected = ['startTestRun', 'stopTestRun']
3420 self.assertEqual(events, expected)
3421
3422
Michael Foordb4a81c82009-05-29 20:33:46 +00003423class TestDiscovery(TestCase):
3424
3425 # Heavily mocked tests so I can avoid hitting the filesystem
3426 def test_get_module_from_path(self):
3427 loader = unittest.TestLoader()
3428
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00003429 old_import = __import__
Michael Foordb4a81c82009-05-29 20:33:46 +00003430 def restore_import():
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00003431 __builtin__.__import__ = old_import
3432 __builtin__.__import__ = lambda *_: None
Michael Foordb4a81c82009-05-29 20:33:46 +00003433 self.addCleanup(restore_import)
3434
3435 expected_module = object()
3436 def del_module():
3437 del sys.modules['bar.baz']
3438 sys.modules['bar.baz'] = expected_module
3439 self.addCleanup(del_module)
3440
3441 loader._top_level_dir = '/foo'
3442 module = loader._get_module_from_path('/foo/bar/baz.py')
3443 self.assertEqual(module, expected_module)
3444
3445 if not __debug__:
3446 # asserts are off
3447 return
3448
3449 with self.assertRaises(AssertionError):
3450 loader._get_module_from_path('/bar/baz.py')
3451
3452 def test_find_tests(self):
3453 loader = unittest.TestLoader()
3454
3455 original_listdir = os.listdir
3456 def restore_listdir():
3457 os.listdir = original_listdir
3458 original_isfile = os.path.isfile
3459 def restore_isfile():
3460 os.path.isfile = original_isfile
3461 original_isdir = os.path.isdir
3462 def restore_isdir():
3463 os.path.isdir = original_isdir
3464
3465 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
3466 'test.foo', 'another_dir'],
3467 ['test3.py', 'test4.py', ]]
3468 os.listdir = lambda path: path_lists.pop(0)
3469 self.addCleanup(restore_listdir)
3470
3471 def isdir(path):
3472 return path.endswith('dir')
3473 os.path.isdir = isdir
3474 self.addCleanup(restore_isdir)
3475
3476 def isfile(path):
3477 # another_dir is not a package and so shouldn't be recursed into
3478 return not path.endswith('dir') and not 'another_dir' in path
3479 os.path.isfile = isfile
3480 self.addCleanup(restore_isfile)
3481
3482 loader._get_module_from_path = lambda path: path + ' module'
3483 loader.loadTestsFromModule = lambda module: module + ' tests'
3484
3485 loader._top_level_dir = '/foo'
3486 suite = list(loader._find_tests('/foo', 'test*.py'))
3487
3488 expected = [os.path.join('/foo', name) + ' module tests' for name in
3489 ('test1.py', 'test2.py')]
3490 expected.extend([os.path.join('/foo', 'test_dir', name) + ' module tests' for name in
3491 ('test3.py', 'test4.py')])
3492 self.assertEqual(suite, expected)
3493
3494 def test_find_tests_with_package(self):
3495 loader = unittest.TestLoader()
3496
3497 original_listdir = os.listdir
3498 def restore_listdir():
3499 os.listdir = original_listdir
3500 original_isfile = os.path.isfile
3501 def restore_isfile():
3502 os.path.isfile = original_isfile
3503 original_isdir = os.path.isdir
3504 def restore_isdir():
3505 os.path.isdir = original_isdir
3506
3507 directories = ['a_directory', 'test_directory', 'test_directory2']
3508 path_lists = [directories, [], [], []]
3509 os.listdir = lambda path: path_lists.pop(0)
3510 self.addCleanup(restore_listdir)
3511
3512 os.path.isdir = lambda path: True
3513 self.addCleanup(restore_isdir)
3514
3515 os.path.isfile = lambda path: os.path.basename(path) not in directories
3516 self.addCleanup(restore_isfile)
3517
3518 class Module(object):
3519 paths = []
3520 load_tests_args = []
3521
3522 def __init__(self, path):
3523 self.path = path
3524 self.paths.append(path)
3525 if os.path.basename(path) == 'test_directory':
3526 def load_tests(loader, tests, pattern):
3527 self.load_tests_args.append((loader, tests, pattern))
3528 return 'load_tests'
3529 self.load_tests = load_tests
3530
3531 def __eq__(self, other):
3532 return self.path == other.path
3533
3534 loader._get_module_from_path = lambda path: Module(path)
3535 def loadTestsFromModule(module, use_load_tests):
3536 if use_load_tests:
3537 raise self.failureException('use_load_tests should be False for packages')
3538 return module.path + ' module tests'
3539 loader.loadTestsFromModule = loadTestsFromModule
3540
3541 loader._top_level_dir = '/foo'
3542 # this time no '.py' on the pattern so that it can match
3543 # a test package
3544 suite = list(loader._find_tests('/foo', 'test*'))
3545
3546 # We should have loaded tests from the test_directory package by calling load_tests
3547 # and directly from the test_directory2 package
Michael Foordd53d0852009-06-05 14:14:34 +00003548 self.assertEqual(suite,
3549 ['load_tests',
3550 os.path.join('/foo', 'test_directory2') + ' module tests'])
Michael Foordb4a81c82009-05-29 20:33:46 +00003551 self.assertEqual(Module.paths, [os.path.join('/foo', 'test_directory'),
3552 os.path.join('/foo', 'test_directory2')])
3553
3554 # load_tests should have been called once with loader, tests and pattern
3555 self.assertEqual(Module.load_tests_args,
3556 [(loader, os.path.join('/foo', 'test_directory') + ' module tests',
3557 'test*')])
3558
3559 def test_discover(self):
3560 loader = unittest.TestLoader()
3561
3562 original_isfile = os.path.isfile
3563 def restore_isfile():
3564 os.path.isfile = original_isfile
3565
3566 os.path.isfile = lambda path: False
3567 self.addCleanup(restore_isfile)
3568
3569 full_path = os.path.abspath(os.path.normpath('/foo'))
3570 def clean_path():
3571 if sys.path[-1] == full_path:
3572 sys.path.pop(-1)
3573 self.addCleanup(clean_path)
3574
3575 with self.assertRaises(ImportError):
3576 loader.discover('/foo/bar', top_level_dir='/foo')
3577
3578 self.assertEqual(loader._top_level_dir, full_path)
3579 self.assertIn(full_path, sys.path)
3580
3581 os.path.isfile = lambda path: True
3582 _find_tests_args = []
3583 def _find_tests(start_dir, pattern):
3584 _find_tests_args.append((start_dir, pattern))
3585 return ['tests']
3586 loader._find_tests = _find_tests
3587 loader.suiteClass = str
3588
3589 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3590
3591 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3592 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3593 self.assertEqual(suite, "['tests']")
3594 self.assertEqual(loader._top_level_dir, top_level_dir)
3595 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
3596
3597 def test_command_line_handling_parseArgs(self):
3598 # Haha - take that uninstantiable class
3599 program = object.__new__(TestProgram)
3600
3601 args = []
3602 def do_discovery(argv):
3603 args.extend(argv)
3604 program._do_discovery = do_discovery
3605 program.parseArgs(['something', 'discover'])
3606 self.assertEqual(args, [])
3607
3608 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3609 self.assertEqual(args, ['foo', 'bar'])
3610
3611 def test_command_line_handling_do_discovery_too_many_arguments(self):
3612 class Stop(Exception):
3613 pass
3614 def usageExit():
3615 raise Stop
3616
3617 program = object.__new__(TestProgram)
3618 program.usageExit = usageExit
3619
3620 with self.assertRaises(Stop):
3621 # too many args
3622 program._do_discovery(['one', 'two', 'three', 'four'])
3623
3624
3625 def test_command_line_handling_do_discovery_calls_loader(self):
3626 program = object.__new__(TestProgram)
3627
3628 class Loader(object):
3629 args = []
3630 def discover(self, start_dir, pattern, top_level_dir):
3631 self.args.append((start_dir, pattern, top_level_dir))
3632 return 'tests'
3633
3634 program._do_discovery(['-v'], Loader=Loader)
3635 self.assertEqual(program.verbosity, 2)
3636 self.assertEqual(program.test, 'tests')
3637 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3638
3639 Loader.args = []
3640 program = object.__new__(TestProgram)
3641 program._do_discovery(['--verbose'], Loader=Loader)
3642 self.assertEqual(program.test, 'tests')
3643 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3644
3645 Loader.args = []
3646 program = object.__new__(TestProgram)
3647 program._do_discovery([], Loader=Loader)
3648 self.assertEqual(program.test, 'tests')
3649 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3650
3651 Loader.args = []
3652 program = object.__new__(TestProgram)
3653 program._do_discovery(['fish'], Loader=Loader)
3654 self.assertEqual(program.test, 'tests')
3655 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3656
3657 Loader.args = []
3658 program = object.__new__(TestProgram)
3659 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3660 self.assertEqual(program.test, 'tests')
3661 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3662
3663 Loader.args = []
3664 program = object.__new__(TestProgram)
3665 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3666 self.assertEqual(program.test, 'tests')
3667 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3668
3669 Loader.args = []
3670 program = object.__new__(TestProgram)
3671 program._do_discovery(['-s', 'fish'], Loader=Loader)
3672 self.assertEqual(program.test, 'tests')
3673 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3674
3675 Loader.args = []
3676 program = object.__new__(TestProgram)
3677 program._do_discovery(['-t', 'fish'], Loader=Loader)
3678 self.assertEqual(program.test, 'tests')
3679 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3680
3681 Loader.args = []
3682 program = object.__new__(TestProgram)
3683 program._do_discovery(['-p', 'fish'], Loader=Loader)
3684 self.assertEqual(program.test, 'tests')
3685 self.assertEqual(Loader.args, [('.', 'fish', None)])
3686
3687 Loader.args = []
3688 program = object.__new__(TestProgram)
3689 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3690 self.assertEqual(program.test, 'tests')
3691 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3692 self.assertEqual(program.verbosity, 2)
3693
3694
Jim Fultonfafd8742004-08-28 15:22:12 +00003695######################################################################
3696## Main
3697######################################################################
3698
3699def test_main():
Georg Brandl15c5ce92007-03-07 09:09:40 +00003700 test_support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003701 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Michael Foord829f6b82009-05-02 11:43:06 +00003702 Test_TestSkipping, Test_Assertions, TestLongMessage,
Michael Foordb4a81c82009-05-29 20:33:46 +00003703 Test_TestProgram, TestCleanUp, TestDiscovery)
Jim Fultonfafd8742004-08-28 15:22:12 +00003704
Georg Brandl15c5ce92007-03-07 09:09:40 +00003705if __name__ == "__main__":
Tim Petersea5962f2007-03-12 18:07:52 +00003706 test_main()