blob: 1b486282e7afab37bbb1544bd6e74fc14aaca829 [file] [log] [blame]
Jim Fultonfafd8742004-08-28 15:22:12 +00001"""Test script for unittest.
2
Georg Brandl15c5ce92007-03-07 09:09:40 +00003By Collin Winter <collinw at gmail.com>
4
5Still need testing:
6 TestCase.{assert,fail}* methods (some are tested implicitly)
Jim Fultonfafd8742004-08-28 15:22:12 +00007"""
8
Michael Foordb4a81c82009-05-29 20:33:46 +00009import os
Gregory P. Smith28399852009-03-31 16:54:10 +000010import re
Michael Foordb4a81c82009-05-29 20:33:46 +000011import sys
Georg Brandl15c5ce92007-03-07 09:09:40 +000012from test import test_support
Jim Fultonfafd8742004-08-28 15:22:12 +000013import unittest
Michael Foord829f6b82009-05-02 11:43:06 +000014from unittest import TestCase, TestProgram
Christian Heimesc756d002007-11-27 21:34:01 +000015import types
Michael Foorde2942d02009-04-02 05:51:54 +000016from copy import deepcopy
Michael Foord829f6b82009-05-02 11:43:06 +000017from cStringIO import StringIO
Antoine Pitrou0734c632009-11-10 20:49:30 +000018import pickle
Michael Foord2f677562010-02-21 14:48:59 +000019import warnings
Jim Fultonfafd8742004-08-28 15:22:12 +000020
Michael Foord225a0992010-02-18 20:30:09 +000021
Georg Brandl15c5ce92007-03-07 09:09:40 +000022### Support code
23################################################################
Jim Fultonfafd8742004-08-28 15:22:12 +000024
Michael Foord5ffa3252010-03-07 22:04:55 +000025def resultFactory(*_):
26 return unittest.TestResult()
27
Georg Brandl15c5ce92007-03-07 09:09:40 +000028class LoggingResult(unittest.TestResult):
29 def __init__(self, log):
30 self._events = log
31 super(LoggingResult, self).__init__()
32
33 def startTest(self, test):
34 self._events.append('startTest')
35 super(LoggingResult, self).startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +000036
Michael Foord07ef4872009-05-02 22:43:34 +000037 def startTestRun(self):
38 self._events.append('startTestRun')
39 super(LoggingResult, self).startTestRun()
40
Georg Brandl15c5ce92007-03-07 09:09:40 +000041 def stopTest(self, test):
42 self._events.append('stopTest')
43 super(LoggingResult, self).stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +000044
Michael Foord07ef4872009-05-02 22:43:34 +000045 def stopTestRun(self):
46 self._events.append('stopTestRun')
47 super(LoggingResult, self).stopTestRun()
48
Georg Brandl15c5ce92007-03-07 09:09:40 +000049 def addFailure(self, *args):
50 self._events.append('addFailure')
51 super(LoggingResult, self).addFailure(*args)
Tim Petersea5962f2007-03-12 18:07:52 +000052
Benjamin Peterson692428e2009-03-23 21:50:21 +000053 def addSuccess(self, *args):
54 self._events.append('addSuccess')
55 super(LoggingResult, self).addSuccess(*args)
56
Georg Brandl15c5ce92007-03-07 09:09:40 +000057 def addError(self, *args):
58 self._events.append('addError')
59 super(LoggingResult, self).addError(*args)
60
Benjamin Peterson692428e2009-03-23 21:50:21 +000061 def addSkip(self, *args):
62 self._events.append('addSkip')
63 super(LoggingResult, self).addSkip(*args)
64
65 def addExpectedFailure(self, *args):
66 self._events.append('addExpectedFailure')
67 super(LoggingResult, self).addExpectedFailure(*args)
68
69 def addUnexpectedSuccess(self, *args):
70 self._events.append('addUnexpectedSuccess')
71 super(LoggingResult, self).addUnexpectedSuccess(*args)
72
73
Georg Brandl15c5ce92007-03-07 09:09:40 +000074class TestEquality(object):
Michael Foord345b2fe2009-04-02 03:20:38 +000075 """Used as a mixin for TestCase"""
76
Tim Petersea5962f2007-03-12 18:07:52 +000077 # Check for a valid __eq__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000078 def test_eq(self):
79 for obj_1, obj_2 in self.eq_pairs:
80 self.assertEqual(obj_1, obj_2)
81 self.assertEqual(obj_2, obj_1)
Tim Petersea5962f2007-03-12 18:07:52 +000082
83 # Check for a valid __ne__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000084 def test_ne(self):
85 for obj_1, obj_2 in self.ne_pairs:
Benjamin Peterson6b0032f2009-06-30 23:30:12 +000086 self.assertNotEqual(obj_1, obj_2)
87 self.assertNotEqual(obj_2, obj_1)
Tim Petersea5962f2007-03-12 18:07:52 +000088
Georg Brandl15c5ce92007-03-07 09:09:40 +000089class TestHashing(object):
Michael Foord345b2fe2009-04-02 03:20:38 +000090 """Used as a mixin for TestCase"""
91
Tim Petersea5962f2007-03-12 18:07:52 +000092 # Check for a valid __hash__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000093 def test_hash(self):
94 for obj_1, obj_2 in self.eq_pairs:
95 try:
Gregory P. Smith28399852009-03-31 16:54:10 +000096 if not hash(obj_1) == hash(obj_2):
97 self.fail("%r and %r do not hash equal" % (obj_1, obj_2))
Georg Brandl15c5ce92007-03-07 09:09:40 +000098 except KeyboardInterrupt:
99 raise
Georg Brandl15c5ce92007-03-07 09:09:40 +0000100 except Exception, e:
Gregory P. Smith28399852009-03-31 16:54:10 +0000101 self.fail("Problem hashing %r and %r: %s" % (obj_1, obj_2, e))
Tim Petersea5962f2007-03-12 18:07:52 +0000102
Georg Brandl15c5ce92007-03-07 09:09:40 +0000103 for obj_1, obj_2 in self.ne_pairs:
104 try:
Gregory P. Smith28399852009-03-31 16:54:10 +0000105 if hash(obj_1) == hash(obj_2):
106 self.fail("%s and %s hash equal, but shouldn't" %
107 (obj_1, obj_2))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000108 except KeyboardInterrupt:
109 raise
Georg Brandl15c5ce92007-03-07 09:09:40 +0000110 except Exception, e:
111 self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e))
Tim Petersea5962f2007-03-12 18:07:52 +0000112
Georg Brandl15c5ce92007-03-07 09:09:40 +0000113
Benjamin Peterson692428e2009-03-23 21:50:21 +0000114# List subclass we can add attributes to.
115class MyClassSuite(list):
116
Benjamin Peterson176a56c2009-05-25 00:48:58 +0000117 def __init__(self, tests):
Benjamin Peterson692428e2009-03-23 21:50:21 +0000118 super(MyClassSuite, self).__init__(tests)
119
120
Georg Brandl15c5ce92007-03-07 09:09:40 +0000121################################################################
122### /Support code
123
124class Test_TestLoader(TestCase):
125
126 ### Tests for TestLoader.loadTestsFromTestCase
127 ################################################################
128
129 # "Return a suite of all tests cases contained in the TestCase-derived
130 # class testCaseClass"
131 def test_loadTestsFromTestCase(self):
132 class Foo(unittest.TestCase):
133 def test_1(self): pass
134 def test_2(self): pass
135 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000136
Georg Brandl15c5ce92007-03-07 09:09:40 +0000137 tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +0000138
Georg Brandl15c5ce92007-03-07 09:09:40 +0000139 loader = unittest.TestLoader()
140 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +0000141
Georg Brandl15c5ce92007-03-07 09:09:40 +0000142 # "Return a suite of all tests cases contained in the TestCase-derived
143 # class testCaseClass"
144 #
Tim Petersea5962f2007-03-12 18:07:52 +0000145 # Make sure it does the right thing even if no tests were found
Georg Brandl15c5ce92007-03-07 09:09:40 +0000146 def test_loadTestsFromTestCase__no_matches(self):
147 class Foo(unittest.TestCase):
148 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000149
Georg Brandl15c5ce92007-03-07 09:09:40 +0000150 empty_suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +0000151
Georg Brandl15c5ce92007-03-07 09:09:40 +0000152 loader = unittest.TestLoader()
153 self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite)
Tim Petersea5962f2007-03-12 18:07:52 +0000154
Georg Brandl15c5ce92007-03-07 09:09:40 +0000155 # "Return a suite of all tests cases contained in the TestCase-derived
156 # class testCaseClass"
157 #
158 # What happens if loadTestsFromTestCase() is given an object
159 # that isn't a subclass of TestCase? Specifically, what happens
160 # if testCaseClass is a subclass of TestSuite?
161 #
162 # This is checked for specifically in the code, so we better add a
163 # test for it.
164 def test_loadTestsFromTestCase__TestSuite_subclass(self):
165 class NotATestCase(unittest.TestSuite):
166 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000167
Georg Brandl15c5ce92007-03-07 09:09:40 +0000168 loader = unittest.TestLoader()
169 try:
170 loader.loadTestsFromTestCase(NotATestCase)
171 except TypeError:
172 pass
173 else:
174 self.fail('Should raise TypeError')
Tim Petersea5962f2007-03-12 18:07:52 +0000175
Georg Brandl15c5ce92007-03-07 09:09:40 +0000176 # "Return a suite of all tests cases contained in the TestCase-derived
177 # class testCaseClass"
178 #
179 # Make sure loadTestsFromTestCase() picks up the default test method
180 # name (as specified by TestCase), even though the method name does
181 # not match the default TestLoader.testMethodPrefix string
182 def test_loadTestsFromTestCase__default_method_name(self):
183 class Foo(unittest.TestCase):
184 def runTest(self):
185 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000186
Georg Brandl15c5ce92007-03-07 09:09:40 +0000187 loader = unittest.TestLoader()
188 # This has to be false for the test to succeed
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000189 self.assertFalse('runTest'.startswith(loader.testMethodPrefix))
Tim Petersea5962f2007-03-12 18:07:52 +0000190
Georg Brandl15c5ce92007-03-07 09:09:40 +0000191 suite = loader.loadTestsFromTestCase(Foo)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000192 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000193 self.assertEqual(list(suite), [Foo('runTest')])
194
195 ################################################################
196 ### /Tests for TestLoader.loadTestsFromTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000197
Georg Brandl15c5ce92007-03-07 09:09:40 +0000198 ### Tests for TestLoader.loadTestsFromModule
199 ################################################################
200
201 # "This method searches `module` for classes derived from TestCase"
202 def test_loadTestsFromModule__TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000203 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000204 class MyTestCase(unittest.TestCase):
205 def test(self):
206 pass
207 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000208
Georg Brandl15c5ce92007-03-07 09:09:40 +0000209 loader = unittest.TestLoader()
210 suite = loader.loadTestsFromModule(m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000211 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000212
Georg Brandl15c5ce92007-03-07 09:09:40 +0000213 expected = [loader.suiteClass([MyTestCase('test')])]
214 self.assertEqual(list(suite), expected)
Tim Petersea5962f2007-03-12 18:07:52 +0000215
Georg Brandl15c5ce92007-03-07 09:09:40 +0000216 # "This method searches `module` for classes derived from TestCase"
Tim Petersea5962f2007-03-12 18:07:52 +0000217 #
Georg Brandl15c5ce92007-03-07 09:09:40 +0000218 # What happens if no tests are found (no TestCase instances)?
219 def test_loadTestsFromModule__no_TestCase_instances(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000220 m = types.ModuleType('m')
Tim Petersea5962f2007-03-12 18:07:52 +0000221
Georg Brandl15c5ce92007-03-07 09:09:40 +0000222 loader = unittest.TestLoader()
223 suite = loader.loadTestsFromModule(m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000224 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000225 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000226
Georg Brandl15c5ce92007-03-07 09:09:40 +0000227 # "This method searches `module` for classes derived from TestCase"
228 #
Tim Petersea5962f2007-03-12 18:07:52 +0000229 # What happens if no tests are found (TestCases instances, but no tests)?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000230 def test_loadTestsFromModule__no_TestCase_tests(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000231 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000232 class MyTestCase(unittest.TestCase):
233 pass
234 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000235
Georg Brandl15c5ce92007-03-07 09:09:40 +0000236 loader = unittest.TestLoader()
237 suite = loader.loadTestsFromModule(m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000238 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000239
Georg Brandl15c5ce92007-03-07 09:09:40 +0000240 self.assertEqual(list(suite), [loader.suiteClass()])
Tim Petersea5962f2007-03-12 18:07:52 +0000241
Georg Brandl15c5ce92007-03-07 09:09:40 +0000242 # "This method searches `module` for classes derived from TestCase"s
243 #
244 # What happens if loadTestsFromModule() is given something other
245 # than a module?
246 #
247 # XXX Currently, it succeeds anyway. This flexibility
248 # should either be documented or loadTestsFromModule() should
249 # raise a TypeError
250 #
251 # XXX Certain people are using this behaviour. We'll add a test for it
252 def test_loadTestsFromModule__not_a_module(self):
253 class MyTestCase(unittest.TestCase):
254 def test(self):
255 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000256
Georg Brandl15c5ce92007-03-07 09:09:40 +0000257 class NotAModule(object):
258 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000259
Georg Brandl15c5ce92007-03-07 09:09:40 +0000260 loader = unittest.TestLoader()
261 suite = loader.loadTestsFromModule(NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000262
Georg Brandl15c5ce92007-03-07 09:09:40 +0000263 reference = [unittest.TestSuite([MyTestCase('test')])]
264 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000265
Michael Foordb4a81c82009-05-29 20:33:46 +0000266
267 # Check that loadTestsFromModule honors (or not) a module
268 # with a load_tests function.
269 def test_loadTestsFromModule__load_tests(self):
270 m = types.ModuleType('m')
271 class MyTestCase(unittest.TestCase):
272 def test(self):
273 pass
274 m.testcase_1 = MyTestCase
275
276 load_tests_args = []
277 def load_tests(loader, tests, pattern):
Michael Foord08770602010-02-06 00:22:26 +0000278 self.assertIsInstance(tests, unittest.TestSuite)
Michael Foordb4a81c82009-05-29 20:33:46 +0000279 load_tests_args.extend((loader, tests, pattern))
280 return tests
281 m.load_tests = load_tests
282
283 loader = unittest.TestLoader()
284 suite = loader.loadTestsFromModule(m)
Michael Foord08770602010-02-06 00:22:26 +0000285 self.assertIsInstance(suite, unittest.TestSuite)
Michael Foordb4a81c82009-05-29 20:33:46 +0000286 self.assertEquals(load_tests_args, [loader, suite, None])
287
288 load_tests_args = []
289 suite = loader.loadTestsFromModule(m, use_load_tests=False)
290 self.assertEquals(load_tests_args, [])
291
Georg Brandl15c5ce92007-03-07 09:09:40 +0000292 ################################################################
293 ### /Tests for TestLoader.loadTestsFromModule()
Tim Petersea5962f2007-03-12 18:07:52 +0000294
Georg Brandl15c5ce92007-03-07 09:09:40 +0000295 ### Tests for TestLoader.loadTestsFromName()
296 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000297
Georg Brandl15c5ce92007-03-07 09:09:40 +0000298 # "The specifier name is a ``dotted name'' that may resolve either to
299 # a module, a test case class, a TestSuite instance, a test method
300 # within a test case class, or a callable object which returns a
301 # TestCase or TestSuite instance."
302 #
303 # Is ValueError raised in response to an empty name?
304 def test_loadTestsFromName__empty_name(self):
305 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000306
Georg Brandl15c5ce92007-03-07 09:09:40 +0000307 try:
308 loader.loadTestsFromName('')
309 except ValueError, e:
310 self.assertEqual(str(e), "Empty module name")
311 else:
312 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000313
Georg Brandl15c5ce92007-03-07 09:09:40 +0000314 # "The specifier name is a ``dotted name'' that may resolve either to
315 # a module, a test case class, a TestSuite instance, a test method
316 # within a test case class, or a callable object which returns a
317 # TestCase or TestSuite instance."
318 #
Tim Petersea5962f2007-03-12 18:07:52 +0000319 # What happens when the name contains invalid characters?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000320 def test_loadTestsFromName__malformed_name(self):
321 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000322
Georg Brandl15c5ce92007-03-07 09:09:40 +0000323 # XXX Should this raise ValueError or ImportError?
324 try:
325 loader.loadTestsFromName('abc () //')
326 except ValueError:
327 pass
328 except ImportError:
329 pass
330 else:
331 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000332
Georg Brandl15c5ce92007-03-07 09:09:40 +0000333 # "The specifier name is a ``dotted name'' that may resolve ... to a
334 # module"
335 #
Tim Petersea5962f2007-03-12 18:07:52 +0000336 # What happens when a module by that name can't be found?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000337 def test_loadTestsFromName__unknown_module_name(self):
338 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000339
Georg Brandl15c5ce92007-03-07 09:09:40 +0000340 try:
341 loader.loadTestsFromName('sdasfasfasdf')
342 except ImportError, e:
343 self.assertEqual(str(e), "No module named sdasfasfasdf")
344 else:
345 self.fail("TestLoader.loadTestsFromName failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000346
Georg Brandl15c5ce92007-03-07 09:09:40 +0000347 # "The specifier name is a ``dotted name'' that may resolve either to
348 # a module, a test case class, a TestSuite instance, a test method
349 # within a test case class, or a callable object which returns a
350 # TestCase or TestSuite instance."
351 #
Tim Petersea5962f2007-03-12 18:07:52 +0000352 # What happens when the module is found, but the attribute can't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000353 def test_loadTestsFromName__unknown_attr_name(self):
354 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000355
Georg Brandl15c5ce92007-03-07 09:09:40 +0000356 try:
357 loader.loadTestsFromName('unittest.sdasfasfasdf')
358 except AttributeError, e:
359 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
360 else:
361 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000362
Georg Brandl15c5ce92007-03-07 09:09:40 +0000363 # "The specifier name is a ``dotted name'' that may resolve either to
364 # a module, a test case class, a TestSuite instance, a test method
365 # within a test case class, or a callable object which returns a
366 # TestCase or TestSuite instance."
367 #
368 # What happens when we provide the module, but the attribute can't be
369 # found?
370 def test_loadTestsFromName__relative_unknown_name(self):
371 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000372
Georg Brandl15c5ce92007-03-07 09:09:40 +0000373 try:
374 loader.loadTestsFromName('sdasfasfasdf', unittest)
375 except AttributeError, e:
376 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
377 else:
378 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000379
Georg Brandl15c5ce92007-03-07 09:09:40 +0000380 # "The specifier name is a ``dotted name'' that may resolve either to
381 # a module, a test case class, a TestSuite instance, a test method
382 # within a test case class, or a callable object which returns a
383 # TestCase or TestSuite instance."
384 # ...
385 # "The method optionally resolves name relative to the given module"
386 #
387 # Does loadTestsFromName raise ValueError when passed an empty
388 # name relative to a provided module?
389 #
390 # XXX Should probably raise a ValueError instead of an AttributeError
391 def test_loadTestsFromName__relative_empty_name(self):
392 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000393
Georg Brandl15c5ce92007-03-07 09:09:40 +0000394 try:
395 loader.loadTestsFromName('', unittest)
396 except AttributeError, e:
397 pass
398 else:
399 self.fail("Failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000400
Georg Brandl15c5ce92007-03-07 09:09:40 +0000401 # "The specifier name is a ``dotted name'' that may resolve either to
402 # a module, a test case class, a TestSuite instance, a test method
403 # within a test case class, or a callable object which returns a
404 # TestCase or TestSuite instance."
405 # ...
406 # "The method optionally resolves name relative to the given module"
407 #
408 # What happens when an impossible name is given, relative to the provided
409 # `module`?
410 def test_loadTestsFromName__relative_malformed_name(self):
411 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000412
Georg Brandl15c5ce92007-03-07 09:09:40 +0000413 # XXX Should this raise AttributeError or ValueError?
414 try:
415 loader.loadTestsFromName('abc () //', unittest)
416 except ValueError:
417 pass
418 except AttributeError:
419 pass
420 else:
421 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
422
423 # "The method optionally resolves name relative to the given module"
424 #
425 # Does loadTestsFromName raise TypeError when the `module` argument
426 # isn't a module object?
427 #
428 # XXX Accepts the not-a-module object, ignorning the object's type
429 # This should raise an exception or the method name should be changed
430 #
431 # XXX Some people are relying on this, so keep it for now
432 def test_loadTestsFromName__relative_not_a_module(self):
433 class MyTestCase(unittest.TestCase):
434 def test(self):
435 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000436
Georg Brandl15c5ce92007-03-07 09:09:40 +0000437 class NotAModule(object):
438 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000439
Georg Brandl15c5ce92007-03-07 09:09:40 +0000440 loader = unittest.TestLoader()
441 suite = loader.loadTestsFromName('test_2', NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000442
Georg Brandl15c5ce92007-03-07 09:09:40 +0000443 reference = [MyTestCase('test')]
444 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000445
Georg Brandl15c5ce92007-03-07 09:09:40 +0000446 # "The specifier name is a ``dotted name'' that may resolve either to
447 # a module, a test case class, a TestSuite instance, a test method
448 # within a test case class, or a callable object which returns a
449 # TestCase or TestSuite instance."
450 #
451 # Does it raise an exception if the name resolves to an invalid
452 # object?
453 def test_loadTestsFromName__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000454 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000455 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000456
Georg Brandl15c5ce92007-03-07 09:09:40 +0000457 loader = unittest.TestLoader()
458 try:
459 loader.loadTestsFromName('testcase_1', m)
460 except TypeError:
461 pass
462 else:
463 self.fail("Should have raised TypeError")
464
465 # "The specifier name is a ``dotted name'' that may
466 # resolve either to ... a test case class"
467 def test_loadTestsFromName__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000468 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000469 class MyTestCase(unittest.TestCase):
470 def test(self):
471 pass
472 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000473
Georg Brandl15c5ce92007-03-07 09:09:40 +0000474 loader = unittest.TestLoader()
475 suite = loader.loadTestsFromName('testcase_1', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000476 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000477 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000478
Georg Brandl15c5ce92007-03-07 09:09:40 +0000479 # "The specifier name is a ``dotted name'' that may resolve either to
480 # a module, a test case class, a TestSuite instance, a test method
481 # within a test case class, or a callable object which returns a
482 # TestCase or TestSuite instance."
483 def test_loadTestsFromName__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000484 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000485 class MyTestCase(unittest.TestCase):
486 def test(self):
487 pass
488 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000489
Georg Brandl15c5ce92007-03-07 09:09:40 +0000490 loader = unittest.TestLoader()
491 suite = loader.loadTestsFromName('testsuite', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000492 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000493
Georg Brandl15c5ce92007-03-07 09:09:40 +0000494 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000495
Georg Brandl15c5ce92007-03-07 09:09:40 +0000496 # "The specifier name is a ``dotted name'' that may resolve ... to
497 # ... a test method within a test case class"
498 def test_loadTestsFromName__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000499 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000500 class MyTestCase(unittest.TestCase):
501 def test(self):
502 pass
503 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000504
Georg Brandl15c5ce92007-03-07 09:09:40 +0000505 loader = unittest.TestLoader()
506 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000507 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000508
Georg Brandl15c5ce92007-03-07 09:09:40 +0000509 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000510
Georg Brandl15c5ce92007-03-07 09:09:40 +0000511 # "The specifier name is a ``dotted name'' that may resolve either to
512 # a module, a test case class, a TestSuite instance, a test method
513 # within a test case class, or a callable object which returns a
514 # TestCase or TestSuite instance."
515 #
516 # Does loadTestsFromName() raise the proper exception when trying to
517 # resolve "a test method within a test case class" that doesn't exist
518 # for the given name (relative to a provided module)?
519 def test_loadTestsFromName__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000520 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000521 class MyTestCase(unittest.TestCase):
522 def test(self):
523 pass
524 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000525
Georg Brandl15c5ce92007-03-07 09:09:40 +0000526 loader = unittest.TestLoader()
527 try:
528 loader.loadTestsFromName('testcase_1.testfoo', m)
529 except AttributeError, e:
530 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
531 else:
532 self.fail("Failed to raise AttributeError")
533
534 # "The specifier name is a ``dotted name'' that may resolve ... to
535 # ... a callable object which returns a ... TestSuite instance"
536 def test_loadTestsFromName__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000537 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000538 testcase_1 = unittest.FunctionTestCase(lambda: None)
539 testcase_2 = unittest.FunctionTestCase(lambda: None)
540 def return_TestSuite():
541 return unittest.TestSuite([testcase_1, testcase_2])
542 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000543
Georg Brandl15c5ce92007-03-07 09:09:40 +0000544 loader = unittest.TestLoader()
545 suite = loader.loadTestsFromName('return_TestSuite', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000546 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000547 self.assertEqual(list(suite), [testcase_1, testcase_2])
Tim Petersea5962f2007-03-12 18:07:52 +0000548
Georg Brandl15c5ce92007-03-07 09:09:40 +0000549 # "The specifier name is a ``dotted name'' that may resolve ... to
550 # ... a callable object which returns a TestCase ... instance"
551 def test_loadTestsFromName__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000552 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000553 testcase_1 = unittest.FunctionTestCase(lambda: None)
554 def return_TestCase():
555 return testcase_1
556 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000557
Georg Brandl15c5ce92007-03-07 09:09:40 +0000558 loader = unittest.TestLoader()
559 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000560 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000561 self.assertEqual(list(suite), [testcase_1])
Tim Petersea5962f2007-03-12 18:07:52 +0000562
Georg Brandl15c5ce92007-03-07 09:09:40 +0000563 # "The specifier name is a ``dotted name'' that may resolve ... to
Michael Foord5a9719d2009-09-13 17:28:35 +0000564 # ... a callable object which returns a TestCase ... instance"
565 #*****************************************************************
566 #Override the suiteClass attribute to ensure that the suiteClass
567 #attribute is used
568 def test_loadTestsFromName__callable__TestCase_instance_ProperSuiteClass(self):
569 class SubTestSuite(unittest.TestSuite):
570 pass
571 m = types.ModuleType('m')
572 testcase_1 = unittest.FunctionTestCase(lambda: None)
573 def return_TestCase():
574 return testcase_1
575 m.return_TestCase = return_TestCase
576
577 loader = unittest.TestLoader()
578 loader.suiteClass = SubTestSuite
579 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000580 self.assertIsInstance(suite, loader.suiteClass)
Michael Foord5a9719d2009-09-13 17:28:35 +0000581 self.assertEqual(list(suite), [testcase_1])
582
583 # "The specifier name is a ``dotted name'' that may resolve ... to
584 # ... a test method within a test case class"
585 #*****************************************************************
586 #Override the suiteClass attribute to ensure that the suiteClass
587 #attribute is used
588 def test_loadTestsFromName__relative_testmethod_ProperSuiteClass(self):
589 class SubTestSuite(unittest.TestSuite):
590 pass
591 m = types.ModuleType('m')
592 class MyTestCase(unittest.TestCase):
593 def test(self):
594 pass
595 m.testcase_1 = MyTestCase
596
597 loader = unittest.TestLoader()
598 loader.suiteClass=SubTestSuite
599 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000600 self.assertIsInstance(suite, loader.suiteClass)
Michael Foord5a9719d2009-09-13 17:28:35 +0000601
602 self.assertEqual(list(suite), [MyTestCase('test')])
603
604 # "The specifier name is a ``dotted name'' that may resolve ... to
Georg Brandl15c5ce92007-03-07 09:09:40 +0000605 # ... a callable object which returns a TestCase or TestSuite instance"
606 #
607 # What happens if the callable returns something else?
608 def test_loadTestsFromName__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000609 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000610 def return_wrong():
611 return 6
612 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000613
Georg Brandl15c5ce92007-03-07 09:09:40 +0000614 loader = unittest.TestLoader()
615 try:
616 suite = loader.loadTestsFromName('return_wrong', m)
617 except TypeError:
618 pass
619 else:
620 self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000621
Georg Brandl15c5ce92007-03-07 09:09:40 +0000622 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +0000623 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +0000624 def test_loadTestsFromName__module_not_loaded(self):
625 # We're going to try to load this module as a side-effect, so it
626 # better not be loaded before we try.
627 #
628 # Why pick audioop? Google shows it isn't used very often, so there's
629 # a good chance that it won't be imported when this test is run
630 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +0000631
Georg Brandl15c5ce92007-03-07 09:09:40 +0000632 if module_name in sys.modules:
633 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000634
Georg Brandl15c5ce92007-03-07 09:09:40 +0000635 loader = unittest.TestLoader()
636 try:
637 suite = loader.loadTestsFromName(module_name)
638
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000639 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000640 self.assertEqual(list(suite), [])
641
642 # audioop should now be loaded, thanks to loadTestsFromName()
Ezio Melottiaa980582010-01-23 23:04:36 +0000643 self.assertIn(module_name, sys.modules)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000644 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000645 if module_name in sys.modules:
646 del sys.modules[module_name]
Georg Brandl15c5ce92007-03-07 09:09:40 +0000647
648 ################################################################
649 ### Tests for TestLoader.loadTestsFromName()
650
651 ### Tests for TestLoader.loadTestsFromNames()
652 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000653
Georg Brandl15c5ce92007-03-07 09:09:40 +0000654 # "Similar to loadTestsFromName(), but takes a sequence of names rather
655 # than a single name."
656 #
657 # What happens if that sequence of names is empty?
658 def test_loadTestsFromNames__empty_name_list(self):
659 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000660
Georg Brandl15c5ce92007-03-07 09:09:40 +0000661 suite = loader.loadTestsFromNames([])
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000662 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000663 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000664
Georg Brandl15c5ce92007-03-07 09:09:40 +0000665 # "Similar to loadTestsFromName(), but takes a sequence of names rather
666 # than a single name."
667 # ...
668 # "The method optionally resolves name relative to the given module"
669 #
670 # What happens if that sequence of names is empty?
671 #
672 # XXX Should this raise a ValueError or just return an empty TestSuite?
673 def test_loadTestsFromNames__relative_empty_name_list(self):
674 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000675
Georg Brandl15c5ce92007-03-07 09:09:40 +0000676 suite = loader.loadTestsFromNames([], unittest)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000677 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000678 self.assertEqual(list(suite), [])
679
680 # "The specifier name is a ``dotted name'' that may resolve either to
681 # a module, a test case class, a TestSuite instance, a test method
682 # within a test case class, or a callable object which returns a
683 # TestCase or TestSuite instance."
684 #
685 # Is ValueError raised in response to an empty name?
686 def test_loadTestsFromNames__empty_name(self):
687 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000688
Georg Brandl15c5ce92007-03-07 09:09:40 +0000689 try:
690 loader.loadTestsFromNames([''])
691 except ValueError, e:
692 self.assertEqual(str(e), "Empty module name")
693 else:
694 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000695
Georg Brandl15c5ce92007-03-07 09:09:40 +0000696 # "The specifier name is a ``dotted name'' that may resolve either to
697 # a module, a test case class, a TestSuite instance, a test method
698 # within a test case class, or a callable object which returns a
699 # TestCase or TestSuite instance."
700 #
Tim Petersea5962f2007-03-12 18:07:52 +0000701 # What happens when presented with an impossible module name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000702 def test_loadTestsFromNames__malformed_name(self):
703 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000704
Georg Brandl15c5ce92007-03-07 09:09:40 +0000705 # XXX Should this raise ValueError or ImportError?
706 try:
707 loader.loadTestsFromNames(['abc () //'])
708 except ValueError:
709 pass
710 except ImportError:
711 pass
712 else:
713 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000714
Georg Brandl15c5ce92007-03-07 09:09:40 +0000715 # "The specifier name is a ``dotted name'' that may resolve either to
716 # a module, a test case class, a TestSuite instance, a test method
717 # within a test case class, or a callable object which returns a
718 # TestCase or TestSuite instance."
719 #
Tim Petersea5962f2007-03-12 18:07:52 +0000720 # What happens when no module can be found for the given name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000721 def test_loadTestsFromNames__unknown_module_name(self):
722 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000723
Georg Brandl15c5ce92007-03-07 09:09:40 +0000724 try:
725 loader.loadTestsFromNames(['sdasfasfasdf'])
726 except ImportError, e:
727 self.assertEqual(str(e), "No module named sdasfasfasdf")
728 else:
729 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000730
Georg Brandl15c5ce92007-03-07 09:09:40 +0000731 # "The specifier name is a ``dotted name'' that may resolve either to
732 # a module, a test case class, a TestSuite instance, a test method
733 # within a test case class, or a callable object which returns a
734 # TestCase or TestSuite instance."
735 #
Tim Petersea5962f2007-03-12 18:07:52 +0000736 # What happens when the module can be found, but not the attribute?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000737 def test_loadTestsFromNames__unknown_attr_name(self):
738 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000739
Georg Brandl15c5ce92007-03-07 09:09:40 +0000740 try:
741 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
742 except AttributeError, e:
743 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
744 else:
745 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000746
Georg Brandl15c5ce92007-03-07 09:09:40 +0000747 # "The specifier name is a ``dotted name'' that may resolve either to
748 # a module, a test case class, a TestSuite instance, a test method
749 # within a test case class, or a callable object which returns a
750 # TestCase or TestSuite instance."
751 # ...
752 # "The method optionally resolves name relative to the given module"
753 #
754 # What happens when given an unknown attribute on a specified `module`
755 # argument?
756 def test_loadTestsFromNames__unknown_name_relative_1(self):
757 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000758
Georg Brandl15c5ce92007-03-07 09:09:40 +0000759 try:
760 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
761 except AttributeError, e:
762 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
763 else:
764 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000765
Georg Brandl15c5ce92007-03-07 09:09:40 +0000766 # "The specifier name is a ``dotted name'' that may resolve either to
767 # a module, a test case class, a TestSuite instance, a test method
768 # within a test case class, or a callable object which returns a
769 # TestCase or TestSuite instance."
770 # ...
771 # "The method optionally resolves name relative to the given module"
772 #
773 # Do unknown attributes (relative to a provided module) still raise an
Tim Petersea5962f2007-03-12 18:07:52 +0000774 # exception even in the presence of valid attribute names?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000775 def test_loadTestsFromNames__unknown_name_relative_2(self):
776 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000777
Georg Brandl15c5ce92007-03-07 09:09:40 +0000778 try:
779 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
780 except AttributeError, e:
781 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
782 else:
783 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
784
785 # "The specifier name is a ``dotted name'' that may resolve either to
786 # a module, a test case class, a TestSuite instance, a test method
787 # within a test case class, or a callable object which returns a
788 # TestCase or TestSuite instance."
789 # ...
790 # "The method optionally resolves name relative to the given module"
791 #
792 # What happens when faced with the empty string?
793 #
794 # XXX This currently raises AttributeError, though ValueError is probably
795 # more appropriate
796 def test_loadTestsFromNames__relative_empty_name(self):
797 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000798
Georg Brandl15c5ce92007-03-07 09:09:40 +0000799 try:
800 loader.loadTestsFromNames([''], unittest)
801 except AttributeError:
802 pass
803 else:
804 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000805
Georg Brandl15c5ce92007-03-07 09:09:40 +0000806 # "The specifier name is a ``dotted name'' that may resolve either to
807 # a module, a test case class, a TestSuite instance, a test method
808 # within a test case class, or a callable object which returns a
809 # TestCase or TestSuite instance."
810 # ...
811 # "The method optionally resolves name relative to the given module"
812 #
Tim Petersea5962f2007-03-12 18:07:52 +0000813 # What happens when presented with an impossible attribute name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000814 def test_loadTestsFromNames__relative_malformed_name(self):
815 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000816
Georg Brandl15c5ce92007-03-07 09:09:40 +0000817 # XXX Should this raise AttributeError or ValueError?
818 try:
819 loader.loadTestsFromNames(['abc () //'], unittest)
820 except AttributeError:
821 pass
822 except ValueError:
823 pass
824 else:
825 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
826
827 # "The method optionally resolves name relative to the given module"
828 #
829 # Does loadTestsFromNames() make sure the provided `module` is in fact
830 # a module?
831 #
832 # XXX This validation is currently not done. This flexibility should
833 # either be documented or a TypeError should be raised.
834 def test_loadTestsFromNames__relative_not_a_module(self):
835 class MyTestCase(unittest.TestCase):
836 def test(self):
837 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000838
Georg Brandl15c5ce92007-03-07 09:09:40 +0000839 class NotAModule(object):
840 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000841
Georg Brandl15c5ce92007-03-07 09:09:40 +0000842 loader = unittest.TestLoader()
843 suite = loader.loadTestsFromNames(['test_2'], NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000844
Georg Brandl15c5ce92007-03-07 09:09:40 +0000845 reference = [unittest.TestSuite([MyTestCase('test')])]
846 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000847
Georg Brandl15c5ce92007-03-07 09:09:40 +0000848 # "The specifier name is a ``dotted name'' that may resolve either to
849 # a module, a test case class, a TestSuite instance, a test method
850 # within a test case class, or a callable object which returns a
851 # TestCase or TestSuite instance."
852 #
853 # Does it raise an exception if the name resolves to an invalid
854 # object?
855 def test_loadTestsFromNames__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000856 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000857 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000858
Georg Brandl15c5ce92007-03-07 09:09:40 +0000859 loader = unittest.TestLoader()
860 try:
861 loader.loadTestsFromNames(['testcase_1'], m)
862 except TypeError:
863 pass
864 else:
865 self.fail("Should have raised TypeError")
866
867 # "The specifier name is a ``dotted name'' that may resolve ... to
868 # ... a test case class"
869 def test_loadTestsFromNames__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000870 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000871 class MyTestCase(unittest.TestCase):
872 def test(self):
873 pass
874 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000875
Georg Brandl15c5ce92007-03-07 09:09:40 +0000876 loader = unittest.TestLoader()
877 suite = loader.loadTestsFromNames(['testcase_1'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000878 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000879
Georg Brandl15c5ce92007-03-07 09:09:40 +0000880 expected = loader.suiteClass([MyTestCase('test')])
881 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000882
Georg Brandl15c5ce92007-03-07 09:09:40 +0000883 # "The specifier name is a ``dotted name'' that may resolve ... to
884 # ... a TestSuite instance"
885 def test_loadTestsFromNames__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000886 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000887 class MyTestCase(unittest.TestCase):
888 def test(self):
889 pass
890 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000891
Georg Brandl15c5ce92007-03-07 09:09:40 +0000892 loader = unittest.TestLoader()
893 suite = loader.loadTestsFromNames(['testsuite'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000894 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000895
Georg Brandl15c5ce92007-03-07 09:09:40 +0000896 self.assertEqual(list(suite), [m.testsuite])
Tim Petersea5962f2007-03-12 18:07:52 +0000897
Georg Brandl15c5ce92007-03-07 09:09:40 +0000898 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
899 # test method within a test case class"
900 def test_loadTestsFromNames__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000901 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000902 class MyTestCase(unittest.TestCase):
903 def test(self):
904 pass
905 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000906
Georg Brandl15c5ce92007-03-07 09:09:40 +0000907 loader = unittest.TestLoader()
908 suite = loader.loadTestsFromNames(['testcase_1.test'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000909 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000910
Georg Brandl15c5ce92007-03-07 09:09:40 +0000911 ref_suite = unittest.TestSuite([MyTestCase('test')])
912 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000913
Georg Brandl15c5ce92007-03-07 09:09:40 +0000914 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
915 # test method within a test case class"
916 #
917 # Does the method gracefully handle names that initially look like they
Tim Petersea5962f2007-03-12 18:07:52 +0000918 # resolve to "a test method within a test case class" but don't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000919 def test_loadTestsFromNames__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000920 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000921 class MyTestCase(unittest.TestCase):
922 def test(self):
923 pass
924 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000925
Georg Brandl15c5ce92007-03-07 09:09:40 +0000926 loader = unittest.TestLoader()
927 try:
928 loader.loadTestsFromNames(['testcase_1.testfoo'], m)
929 except AttributeError, e:
930 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
931 else:
932 self.fail("Failed to raise AttributeError")
933
934 # "The specifier name is a ``dotted name'' that may resolve ... to
935 # ... a callable object which returns a ... TestSuite instance"
936 def test_loadTestsFromNames__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000937 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000938 testcase_1 = unittest.FunctionTestCase(lambda: None)
939 testcase_2 = unittest.FunctionTestCase(lambda: None)
940 def return_TestSuite():
941 return unittest.TestSuite([testcase_1, testcase_2])
942 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000943
Georg Brandl15c5ce92007-03-07 09:09:40 +0000944 loader = unittest.TestLoader()
945 suite = loader.loadTestsFromNames(['return_TestSuite'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000946 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000947
Georg Brandl15c5ce92007-03-07 09:09:40 +0000948 expected = unittest.TestSuite([testcase_1, testcase_2])
949 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000950
Georg Brandl15c5ce92007-03-07 09:09:40 +0000951 # "The specifier name is a ``dotted name'' that may resolve ... to
952 # ... a callable object which returns a TestCase ... instance"
953 def test_loadTestsFromNames__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000954 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000955 testcase_1 = unittest.FunctionTestCase(lambda: None)
956 def return_TestCase():
957 return testcase_1
958 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000959
Georg Brandl15c5ce92007-03-07 09:09:40 +0000960 loader = unittest.TestLoader()
961 suite = loader.loadTestsFromNames(['return_TestCase'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000962 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000963
Georg Brandl15c5ce92007-03-07 09:09:40 +0000964 ref_suite = unittest.TestSuite([testcase_1])
965 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000966
Georg Brandl15c5ce92007-03-07 09:09:40 +0000967 # "The specifier name is a ``dotted name'' that may resolve ... to
968 # ... a callable object which returns a TestCase or TestSuite instance"
969 #
Tim Petersea5962f2007-03-12 18:07:52 +0000970 # Are staticmethods handled correctly?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000971 def test_loadTestsFromNames__callable__call_staticmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000972 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000973 class Test1(unittest.TestCase):
974 def test(self):
975 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000976
Georg Brandl15c5ce92007-03-07 09:09:40 +0000977 testcase_1 = Test1('test')
978 class Foo(unittest.TestCase):
979 @staticmethod
980 def foo():
981 return testcase_1
982 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +0000983
Georg Brandl15c5ce92007-03-07 09:09:40 +0000984 loader = unittest.TestLoader()
985 suite = loader.loadTestsFromNames(['Foo.foo'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000986 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000987
Georg Brandl15c5ce92007-03-07 09:09:40 +0000988 ref_suite = unittest.TestSuite([testcase_1])
989 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000990
Georg Brandl15c5ce92007-03-07 09:09:40 +0000991 # "The specifier name is a ``dotted name'' that may resolve ... to
992 # ... a callable object which returns a TestCase or TestSuite instance"
993 #
994 # What happens when the callable returns something else?
995 def test_loadTestsFromNames__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000996 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000997 def return_wrong():
998 return 6
999 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +00001000
Georg Brandl15c5ce92007-03-07 09:09:40 +00001001 loader = unittest.TestLoader()
1002 try:
1003 suite = loader.loadTestsFromNames(['return_wrong'], m)
1004 except TypeError:
1005 pass
1006 else:
1007 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +00001008
Georg Brandl15c5ce92007-03-07 09:09:40 +00001009 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +00001010 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001011 def test_loadTestsFromNames__module_not_loaded(self):
1012 # We're going to try to load this module as a side-effect, so it
1013 # better not be loaded before we try.
1014 #
1015 # Why pick audioop? Google shows it isn't used very often, so there's
1016 # a good chance that it won't be imported when this test is run
1017 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +00001018
Georg Brandl15c5ce92007-03-07 09:09:40 +00001019 if module_name in sys.modules:
1020 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +00001021
Georg Brandl15c5ce92007-03-07 09:09:40 +00001022 loader = unittest.TestLoader()
1023 try:
1024 suite = loader.loadTestsFromNames([module_name])
1025
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001026 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +00001027 self.assertEqual(list(suite), [unittest.TestSuite()])
1028
1029 # audioop should now be loaded, thanks to loadTestsFromName()
Ezio Melottiaa980582010-01-23 23:04:36 +00001030 self.assertIn(module_name, sys.modules)
Georg Brandl15c5ce92007-03-07 09:09:40 +00001031 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +00001032 if module_name in sys.modules:
1033 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +00001034
Georg Brandl15c5ce92007-03-07 09:09:40 +00001035 ################################################################
1036 ### /Tests for TestLoader.loadTestsFromNames()
1037
1038 ### Tests for TestLoader.getTestCaseNames()
1039 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001040
Georg Brandl15c5ce92007-03-07 09:09:40 +00001041 # "Return a sorted sequence of method names found within testCaseClass"
1042 #
1043 # Test.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(self):
1046 class Test(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 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001052
Georg Brandl15c5ce92007-03-07 09:09:40 +00001053 self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])
Tim Petersea5962f2007-03-12 18:07:52 +00001054
Georg Brandl15c5ce92007-03-07 09:09:40 +00001055 # "Return a sorted sequence of method names found within testCaseClass"
1056 #
Tim Petersea5962f2007-03-12 18:07:52 +00001057 # Does getTestCaseNames() behave appropriately if no tests are found?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001058 def test_getTestCaseNames__no_tests(self):
1059 class Test(unittest.TestCase):
1060 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001061
Georg Brandl15c5ce92007-03-07 09:09:40 +00001062 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001063
Georg Brandl15c5ce92007-03-07 09:09:40 +00001064 self.assertEqual(loader.getTestCaseNames(Test), [])
Tim Petersea5962f2007-03-12 18:07:52 +00001065
Georg Brandl15c5ce92007-03-07 09:09:40 +00001066 # "Return a sorted sequence of method names found within testCaseClass"
1067 #
1068 # Are not-TestCases handled gracefully?
1069 #
1070 # XXX This should raise a TypeError, not return a list
1071 #
1072 # XXX It's too late in the 2.5 release cycle to fix this, but it should
1073 # probably be revisited for 2.6
1074 def test_getTestCaseNames__not_a_TestCase(self):
1075 class BadCase(int):
1076 def test_foo(self):
1077 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001078
Georg Brandl15c5ce92007-03-07 09:09:40 +00001079 loader = unittest.TestLoader()
1080 names = loader.getTestCaseNames(BadCase)
Tim Petersea5962f2007-03-12 18:07:52 +00001081
Georg Brandl15c5ce92007-03-07 09:09:40 +00001082 self.assertEqual(names, ['test_foo'])
Tim Petersea5962f2007-03-12 18:07:52 +00001083
Georg Brandl15c5ce92007-03-07 09:09:40 +00001084 # "Return a sorted sequence of method names found within testCaseClass"
1085 #
1086 # Make sure inherited names are handled.
1087 #
1088 # TestP.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +00001089 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +00001090 def test_getTestCaseNames__inheritance(self):
1091 class TestP(unittest.TestCase):
1092 def test_1(self): pass
1093 def test_2(self): pass
1094 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001095
Georg Brandl15c5ce92007-03-07 09:09:40 +00001096 class TestC(TestP):
1097 def test_1(self): pass
1098 def test_3(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001099
Georg Brandl15c5ce92007-03-07 09:09:40 +00001100 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001101
Georg Brandl15c5ce92007-03-07 09:09:40 +00001102 names = ['test_1', 'test_2', 'test_3']
1103 self.assertEqual(loader.getTestCaseNames(TestC), names)
Tim Petersea5962f2007-03-12 18:07:52 +00001104
1105 ################################################################
Georg Brandl15c5ce92007-03-07 09:09:40 +00001106 ### /Tests for TestLoader.getTestCaseNames()
1107
1108 ### Tests for TestLoader.testMethodPrefix
1109 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001110
Georg Brandl15c5ce92007-03-07 09:09:40 +00001111 # "String giving the prefix of method names which will be interpreted as
1112 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001113 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001114 # Implicit in the documentation is that testMethodPrefix is respected by
1115 # all loadTestsFrom* methods.
1116 def test_testMethodPrefix__loadTestsFromTestCase(self):
1117 class Foo(unittest.TestCase):
1118 def test_1(self): pass
1119 def test_2(self): pass
1120 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001121
Georg Brandl15c5ce92007-03-07 09:09:40 +00001122 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1123 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001124
Georg Brandl15c5ce92007-03-07 09:09:40 +00001125 loader = unittest.TestLoader()
1126 loader.testMethodPrefix = 'foo'
1127 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
1128
1129 loader.testMethodPrefix = 'test'
1130 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001131
Georg Brandl15c5ce92007-03-07 09:09:40 +00001132 # "String giving the prefix of method names which will be interpreted as
1133 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001134 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001135 # Implicit in the documentation is that testMethodPrefix is respected by
1136 # all loadTestsFrom* methods.
1137 def test_testMethodPrefix__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001138 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001139 class Foo(unittest.TestCase):
1140 def test_1(self): pass
1141 def test_2(self): pass
1142 def foo_bar(self): pass
1143 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001144
Georg Brandl15c5ce92007-03-07 09:09:40 +00001145 tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
1146 tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]
Tim Petersea5962f2007-03-12 18:07:52 +00001147
Georg Brandl15c5ce92007-03-07 09:09:40 +00001148 loader = unittest.TestLoader()
1149 loader.testMethodPrefix = 'foo'
1150 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
1151
1152 loader.testMethodPrefix = 'test'
1153 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001154
Georg Brandl15c5ce92007-03-07 09:09:40 +00001155 # "String giving the prefix of method names which will be interpreted as
1156 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001157 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001158 # Implicit in the documentation is that testMethodPrefix is respected by
1159 # all loadTestsFrom* methods.
1160 def test_testMethodPrefix__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001161 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001162 class Foo(unittest.TestCase):
1163 def test_1(self): pass
1164 def test_2(self): pass
1165 def foo_bar(self): pass
1166 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001167
Georg Brandl15c5ce92007-03-07 09:09:40 +00001168 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1169 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001170
Georg Brandl15c5ce92007-03-07 09:09:40 +00001171 loader = unittest.TestLoader()
1172 loader.testMethodPrefix = 'foo'
1173 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
1174
1175 loader.testMethodPrefix = 'test'
1176 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001177
Georg Brandl15c5ce92007-03-07 09:09:40 +00001178 # "String giving the prefix of method names which will be interpreted as
1179 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001180 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001181 # Implicit in the documentation is that testMethodPrefix is respected by
1182 # all loadTestsFrom* methods.
1183 def test_testMethodPrefix__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001184 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001185 class Foo(unittest.TestCase):
1186 def test_1(self): pass
1187 def test_2(self): pass
1188 def foo_bar(self): pass
1189 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001190
Georg Brandl15c5ce92007-03-07 09:09:40 +00001191 tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
1192 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1193 tests_2 = unittest.TestSuite([tests_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001194
Georg Brandl15c5ce92007-03-07 09:09:40 +00001195 loader = unittest.TestLoader()
1196 loader.testMethodPrefix = 'foo'
1197 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)
1198
1199 loader.testMethodPrefix = 'test'
1200 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001201
Georg Brandl15c5ce92007-03-07 09:09:40 +00001202 # "The default value is 'test'"
1203 def test_testMethodPrefix__default_value(self):
1204 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001205 self.assertTrue(loader.testMethodPrefix == 'test')
Tim Petersea5962f2007-03-12 18:07:52 +00001206
Georg Brandl15c5ce92007-03-07 09:09:40 +00001207 ################################################################
1208 ### /Tests for TestLoader.testMethodPrefix
1209
Tim Petersea5962f2007-03-12 18:07:52 +00001210 ### Tests for TestLoader.sortTestMethodsUsing
Georg Brandl15c5ce92007-03-07 09:09:40 +00001211 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001212
Georg Brandl15c5ce92007-03-07 09:09:40 +00001213 # "Function to be used to compare method names when sorting them in
1214 # getTestCaseNames() and all the loadTestsFromX() methods"
1215 def test_sortTestMethodsUsing__loadTestsFromTestCase(self):
1216 def reversed_cmp(x, y):
1217 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001218
Georg Brandl15c5ce92007-03-07 09:09:40 +00001219 class Foo(unittest.TestCase):
1220 def test_1(self): pass
1221 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001222
Georg Brandl15c5ce92007-03-07 09:09:40 +00001223 loader = unittest.TestLoader()
1224 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001225
Georg Brandl15c5ce92007-03-07 09:09:40 +00001226 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1227 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001228
Georg Brandl15c5ce92007-03-07 09:09:40 +00001229 # "Function to be used to compare method names when sorting them in
1230 # getTestCaseNames() and all the loadTestsFromX() methods"
1231 def test_sortTestMethodsUsing__loadTestsFromModule(self):
1232 def reversed_cmp(x, y):
1233 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001234
Christian Heimesc756d002007-11-27 21:34:01 +00001235 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001236 class Foo(unittest.TestCase):
1237 def test_1(self): pass
1238 def test_2(self): pass
1239 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001240
Georg Brandl15c5ce92007-03-07 09:09:40 +00001241 loader = unittest.TestLoader()
1242 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001243
Georg Brandl15c5ce92007-03-07 09:09:40 +00001244 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1245 self.assertEqual(list(loader.loadTestsFromModule(m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001246
Georg Brandl15c5ce92007-03-07 09:09:40 +00001247 # "Function to be used to compare method names when sorting them in
1248 # getTestCaseNames() and all the loadTestsFromX() methods"
1249 def test_sortTestMethodsUsing__loadTestsFromName(self):
1250 def reversed_cmp(x, y):
1251 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001252
Christian Heimesc756d002007-11-27 21:34:01 +00001253 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001254 class Foo(unittest.TestCase):
1255 def test_1(self): pass
1256 def test_2(self): pass
1257 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001258
Georg Brandl15c5ce92007-03-07 09:09:40 +00001259 loader = unittest.TestLoader()
1260 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001261
Georg Brandl15c5ce92007-03-07 09:09:40 +00001262 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1263 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001264
Georg Brandl15c5ce92007-03-07 09:09:40 +00001265 # "Function to be used to compare method names when sorting them in
1266 # getTestCaseNames() and all the loadTestsFromX() methods"
1267 def test_sortTestMethodsUsing__loadTestsFromNames(self):
1268 def reversed_cmp(x, y):
1269 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001270
Christian Heimesc756d002007-11-27 21:34:01 +00001271 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001272 class Foo(unittest.TestCase):
1273 def test_1(self): pass
1274 def test_2(self): pass
1275 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001276
Georg Brandl15c5ce92007-03-07 09:09:40 +00001277 loader = unittest.TestLoader()
1278 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001279
Georg Brandl15c5ce92007-03-07 09:09:40 +00001280 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1281 self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001282
Georg Brandl15c5ce92007-03-07 09:09:40 +00001283 # "Function to be used to compare method names when sorting them in
1284 # getTestCaseNames()"
1285 #
1286 # Does it actually affect getTestCaseNames()?
1287 def test_sortTestMethodsUsing__getTestCaseNames(self):
1288 def reversed_cmp(x, y):
1289 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001290
Georg Brandl15c5ce92007-03-07 09:09:40 +00001291 class Foo(unittest.TestCase):
1292 def test_1(self): pass
1293 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001294
Georg Brandl15c5ce92007-03-07 09:09:40 +00001295 loader = unittest.TestLoader()
1296 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001297
Georg Brandl15c5ce92007-03-07 09:09:40 +00001298 test_names = ['test_2', 'test_1']
1299 self.assertEqual(loader.getTestCaseNames(Foo), test_names)
Tim Petersea5962f2007-03-12 18:07:52 +00001300
Georg Brandl15c5ce92007-03-07 09:09:40 +00001301 # "The default value is the built-in cmp() function"
1302 def test_sortTestMethodsUsing__default_value(self):
1303 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001304 self.assertTrue(loader.sortTestMethodsUsing is cmp)
Tim Petersea5962f2007-03-12 18:07:52 +00001305
Georg Brandl15c5ce92007-03-07 09:09:40 +00001306 # "it can be set to None to disable the sort."
1307 #
1308 # XXX How is this different from reassigning cmp? Are the tests returned
1309 # in a random order or something? This behaviour should die
1310 def test_sortTestMethodsUsing__None(self):
1311 class Foo(unittest.TestCase):
1312 def test_1(self): pass
1313 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001314
Georg Brandl15c5ce92007-03-07 09:09:40 +00001315 loader = unittest.TestLoader()
1316 loader.sortTestMethodsUsing = None
Tim Petersea5962f2007-03-12 18:07:52 +00001317
Georg Brandl15c5ce92007-03-07 09:09:40 +00001318 test_names = ['test_2', 'test_1']
1319 self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))
Tim Petersea5962f2007-03-12 18:07:52 +00001320
Georg Brandl15c5ce92007-03-07 09:09:40 +00001321 ################################################################
1322 ### /Tests for TestLoader.sortTestMethodsUsing
Tim Petersea5962f2007-03-12 18:07:52 +00001323
Georg Brandl15c5ce92007-03-07 09:09:40 +00001324 ### Tests for TestLoader.suiteClass
1325 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001326
Georg Brandl15c5ce92007-03-07 09:09:40 +00001327 # "Callable object that constructs a test suite from a list of tests."
1328 def test_suiteClass__loadTestsFromTestCase(self):
1329 class Foo(unittest.TestCase):
1330 def test_1(self): pass
1331 def test_2(self): pass
1332 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001333
Georg Brandl15c5ce92007-03-07 09:09:40 +00001334 tests = [Foo('test_1'), Foo('test_2')]
1335
1336 loader = unittest.TestLoader()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001337 loader.suiteClass = list
Georg Brandl15c5ce92007-03-07 09:09:40 +00001338 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001339
Georg Brandl15c5ce92007-03-07 09:09:40 +00001340 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001341 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001342 def test_suiteClass__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001343 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001344 class Foo(unittest.TestCase):
1345 def test_1(self): pass
1346 def test_2(self): pass
1347 def foo_bar(self): pass
1348 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001349
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001350 tests = [[Foo('test_1'), Foo('test_2')]]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001351
1352 loader = unittest.TestLoader()
1353 loader.suiteClass = list
1354 self.assertEqual(loader.loadTestsFromModule(m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001355
Georg Brandl15c5ce92007-03-07 09:09:40 +00001356 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001357 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001358 def test_suiteClass__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001359 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001360 class Foo(unittest.TestCase):
1361 def test_1(self): pass
1362 def test_2(self): pass
1363 def foo_bar(self): pass
1364 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001365
Georg Brandl15c5ce92007-03-07 09:09:40 +00001366 tests = [Foo('test_1'), Foo('test_2')]
1367
1368 loader = unittest.TestLoader()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001369 loader.suiteClass = list
Georg Brandl15c5ce92007-03-07 09:09:40 +00001370 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001371
Georg Brandl15c5ce92007-03-07 09:09:40 +00001372 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001373 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001374 def test_suiteClass__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001375 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001376 class Foo(unittest.TestCase):
1377 def test_1(self): pass
1378 def test_2(self): pass
1379 def foo_bar(self): pass
1380 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001381
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001382 tests = [[Foo('test_1'), Foo('test_2')]]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001383
1384 loader = unittest.TestLoader()
1385 loader.suiteClass = list
1386 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001387
Georg Brandl15c5ce92007-03-07 09:09:40 +00001388 # "The default value is the TestSuite class"
1389 def test_suiteClass__default_value(self):
1390 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001391 self.assertTrue(loader.suiteClass is unittest.TestSuite)
Tim Petersea5962f2007-03-12 18:07:52 +00001392
Georg Brandl15c5ce92007-03-07 09:09:40 +00001393 ################################################################
1394 ### /Tests for TestLoader.suiteClass
1395
1396### Support code for Test_TestSuite
1397################################################################
1398
1399class Foo(unittest.TestCase):
1400 def test_1(self): pass
1401 def test_2(self): pass
1402 def test_3(self): pass
1403 def runTest(self): pass
1404
1405def _mk_TestSuite(*names):
1406 return unittest.TestSuite(Foo(n) for n in names)
Tim Petersea5962f2007-03-12 18:07:52 +00001407
Georg Brandl15c5ce92007-03-07 09:09:40 +00001408################################################################
1409### /Support code for Test_TestSuite
1410
1411class Test_TestSuite(TestCase, TestEquality):
1412
1413 ### Set up attributes needed by inherited tests
1414 ################################################################
1415
1416 # Used by TestEquality.test_eq
1417 eq_pairs = [(unittest.TestSuite(), unittest.TestSuite())
1418 ,(unittest.TestSuite(), unittest.TestSuite([]))
1419 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001420
1421 # Used by TestEquality.test_ne
Georg Brandl15c5ce92007-03-07 09:09:40 +00001422 ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1'))
1423 ,(unittest.TestSuite([]), _mk_TestSuite('test_1'))
1424 ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3'))
1425 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001426
Georg Brandl15c5ce92007-03-07 09:09:40 +00001427 ################################################################
1428 ### /Set up attributes needed by inherited tests
1429
1430 ### Tests for TestSuite.__init__
1431 ################################################################
1432
1433 # "class TestSuite([tests])"
1434 #
1435 # The tests iterable should be optional
1436 def test_init__tests_optional(self):
1437 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001438
Georg Brandl15c5ce92007-03-07 09:09:40 +00001439 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001440
Georg Brandl15c5ce92007-03-07 09:09:40 +00001441 # "class TestSuite([tests])"
1442 # ...
1443 # "If tests is given, it must be an iterable of individual test cases
1444 # or other test suites that will be used to build the suite initially"
1445 #
1446 # TestSuite should deal with empty tests iterables by allowing the
Tim Petersea5962f2007-03-12 18:07:52 +00001447 # creation of an empty suite
Georg Brandl15c5ce92007-03-07 09:09:40 +00001448 def test_init__empty_tests(self):
1449 suite = unittest.TestSuite([])
Tim Petersea5962f2007-03-12 18:07:52 +00001450
Georg Brandl15c5ce92007-03-07 09:09:40 +00001451 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001452
Georg Brandl15c5ce92007-03-07 09:09:40 +00001453 # "class TestSuite([tests])"
1454 # ...
1455 # "If tests is given, it must be an iterable of individual test cases
1456 # or other test suites that will be used to build the suite initially"
1457 #
Tim Petersea5962f2007-03-12 18:07:52 +00001458 # TestSuite should allow any iterable to provide tests
Georg Brandl15c5ce92007-03-07 09:09:40 +00001459 def test_init__tests_from_any_iterable(self):
1460 def tests():
1461 yield unittest.FunctionTestCase(lambda: None)
1462 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001463
Georg Brandl15c5ce92007-03-07 09:09:40 +00001464 suite_1 = unittest.TestSuite(tests())
1465 self.assertEqual(suite_1.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001466
Georg Brandl15c5ce92007-03-07 09:09:40 +00001467 suite_2 = unittest.TestSuite(suite_1)
1468 self.assertEqual(suite_2.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001469
Georg Brandl15c5ce92007-03-07 09:09:40 +00001470 suite_3 = unittest.TestSuite(set(suite_1))
1471 self.assertEqual(suite_3.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001472
Georg Brandl15c5ce92007-03-07 09:09:40 +00001473 # "class TestSuite([tests])"
1474 # ...
1475 # "If tests is given, it must be an iterable of individual test cases
1476 # or other test suites that will be used to build the suite initially"
1477 #
1478 # Does TestSuite() also allow other TestSuite() instances to be present
1479 # in the tests iterable?
1480 def test_init__TestSuite_instances_in_tests(self):
1481 def tests():
1482 ftc = unittest.FunctionTestCase(lambda: None)
1483 yield unittest.TestSuite([ftc])
1484 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001485
Georg Brandl15c5ce92007-03-07 09:09:40 +00001486 suite = unittest.TestSuite(tests())
1487 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001488
Georg Brandl15c5ce92007-03-07 09:09:40 +00001489 ################################################################
1490 ### /Tests for TestSuite.__init__
1491
1492 # Container types should support the iter protocol
1493 def test_iter(self):
1494 test1 = unittest.FunctionTestCase(lambda: None)
1495 test2 = unittest.FunctionTestCase(lambda: None)
1496 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001497
Georg Brandl15c5ce92007-03-07 09:09:40 +00001498 self.assertEqual(list(suite), [test1, test2])
Tim Petersea5962f2007-03-12 18:07:52 +00001499
Georg Brandl15c5ce92007-03-07 09:09:40 +00001500 # "Return the number of tests represented by the this test object.
1501 # ...this method is also implemented by the TestSuite class, which can
1502 # return larger [greater than 1] values"
1503 #
Tim Petersea5962f2007-03-12 18:07:52 +00001504 # Presumably an empty TestSuite returns 0?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001505 def test_countTestCases_zero_simple(self):
1506 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001507
Georg Brandl15c5ce92007-03-07 09:09:40 +00001508 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001509
Georg Brandl15c5ce92007-03-07 09:09:40 +00001510 # "Return the number of tests represented by the this test object.
1511 # ...this method is also implemented by the TestSuite class, which can
1512 # return larger [greater than 1] values"
1513 #
1514 # Presumably an empty TestSuite (even if it contains other empty
1515 # TestSuite instances) returns 0?
1516 def test_countTestCases_zero_nested(self):
1517 class Test1(unittest.TestCase):
1518 def test(self):
1519 pass
1520
1521 suite = unittest.TestSuite([unittest.TestSuite()])
Tim Petersea5962f2007-03-12 18:07:52 +00001522
Georg Brandl15c5ce92007-03-07 09:09:40 +00001523 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001524
Georg Brandl15c5ce92007-03-07 09:09:40 +00001525 # "Return the number of tests represented by the this test object.
1526 # ...this method is also implemented by the TestSuite class, which can
1527 # return larger [greater than 1] values"
1528 def test_countTestCases_simple(self):
1529 test1 = unittest.FunctionTestCase(lambda: None)
1530 test2 = unittest.FunctionTestCase(lambda: None)
1531 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001532
Georg Brandl15c5ce92007-03-07 09:09:40 +00001533 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001534
Georg Brandl15c5ce92007-03-07 09:09:40 +00001535 # "Return the number of tests represented by the this test object.
1536 # ...this method is also implemented by the TestSuite class, which can
1537 # return larger [greater than 1] values"
1538 #
1539 # Make sure this holds for nested TestSuite instances, too
1540 def test_countTestCases_nested(self):
1541 class Test1(unittest.TestCase):
1542 def test1(self): pass
1543 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001544
Georg Brandl15c5ce92007-03-07 09:09:40 +00001545 test2 = unittest.FunctionTestCase(lambda: None)
1546 test3 = unittest.FunctionTestCase(lambda: None)
1547 child = unittest.TestSuite((Test1('test2'), test2))
1548 parent = unittest.TestSuite((test3, child, Test1('test1')))
Tim Petersea5962f2007-03-12 18:07:52 +00001549
Georg Brandl15c5ce92007-03-07 09:09:40 +00001550 self.assertEqual(parent.countTestCases(), 4)
Tim Petersea5962f2007-03-12 18:07:52 +00001551
Georg Brandl15c5ce92007-03-07 09:09:40 +00001552 # "Run the tests associated with this suite, collecting the result into
1553 # the test result object passed as result."
1554 #
1555 # And if there are no tests? What then?
1556 def test_run__empty_suite(self):
1557 events = []
1558 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001559
Georg Brandl15c5ce92007-03-07 09:09:40 +00001560 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001561
Georg Brandl15c5ce92007-03-07 09:09:40 +00001562 suite.run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001563
Georg Brandl15c5ce92007-03-07 09:09:40 +00001564 self.assertEqual(events, [])
Tim Petersea5962f2007-03-12 18:07:52 +00001565
Georg Brandl15c5ce92007-03-07 09:09:40 +00001566 # "Note that unlike TestCase.run(), TestSuite.run() requires the
1567 # "result object to be passed in."
1568 def test_run__requires_result(self):
1569 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001570
Georg Brandl15c5ce92007-03-07 09:09:40 +00001571 try:
1572 suite.run()
1573 except TypeError:
1574 pass
1575 else:
1576 self.fail("Failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +00001577
Georg Brandl15c5ce92007-03-07 09:09:40 +00001578 # "Run the tests associated with this suite, collecting the result into
Tim Petersea5962f2007-03-12 18:07:52 +00001579 # the test result object passed as result."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001580 def test_run(self):
1581 events = []
1582 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001583
Georg Brandl15c5ce92007-03-07 09:09:40 +00001584 class LoggingCase(unittest.TestCase):
1585 def run(self, result):
1586 events.append('run %s' % self._testMethodName)
Tim Petersea5962f2007-03-12 18:07:52 +00001587
Georg Brandl15c5ce92007-03-07 09:09:40 +00001588 def test1(self): pass
1589 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001590
1591 tests = [LoggingCase('test1'), LoggingCase('test2')]
1592
Georg Brandl15c5ce92007-03-07 09:09:40 +00001593 unittest.TestSuite(tests).run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001594
Georg Brandl15c5ce92007-03-07 09:09:40 +00001595 self.assertEqual(events, ['run test1', 'run test2'])
Tim Petersea5962f2007-03-12 18:07:52 +00001596
1597 # "Add a TestCase ... to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001598 def test_addTest__TestCase(self):
1599 class Foo(unittest.TestCase):
1600 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001601
Georg Brandl15c5ce92007-03-07 09:09:40 +00001602 test = Foo('test')
1603 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001604
Georg Brandl15c5ce92007-03-07 09:09:40 +00001605 suite.addTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001606
Georg Brandl15c5ce92007-03-07 09:09:40 +00001607 self.assertEqual(suite.countTestCases(), 1)
1608 self.assertEqual(list(suite), [test])
Tim Petersea5962f2007-03-12 18:07:52 +00001609
1610 # "Add a ... TestSuite to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001611 def test_addTest__TestSuite(self):
1612 class Foo(unittest.TestCase):
1613 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001614
Georg Brandl15c5ce92007-03-07 09:09:40 +00001615 suite_2 = unittest.TestSuite([Foo('test')])
Tim Petersea5962f2007-03-12 18:07:52 +00001616
Georg Brandl15c5ce92007-03-07 09:09:40 +00001617 suite = unittest.TestSuite()
1618 suite.addTest(suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001619
Georg Brandl15c5ce92007-03-07 09:09:40 +00001620 self.assertEqual(suite.countTestCases(), 1)
1621 self.assertEqual(list(suite), [suite_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001622
Georg Brandl15c5ce92007-03-07 09:09:40 +00001623 # "Add all the tests from an iterable of TestCase and TestSuite
1624 # instances to this test suite."
Tim Petersea5962f2007-03-12 18:07:52 +00001625 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001626 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001627 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001628 def test_addTests(self):
1629 class Foo(unittest.TestCase):
1630 def test_1(self): pass
1631 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001632
Georg Brandl15c5ce92007-03-07 09:09:40 +00001633 test_1 = Foo('test_1')
1634 test_2 = Foo('test_2')
1635 inner_suite = unittest.TestSuite([test_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001636
Georg Brandl15c5ce92007-03-07 09:09:40 +00001637 def gen():
1638 yield test_1
1639 yield test_2
1640 yield inner_suite
Tim Petersea5962f2007-03-12 18:07:52 +00001641
Georg Brandl15c5ce92007-03-07 09:09:40 +00001642 suite_1 = unittest.TestSuite()
1643 suite_1.addTests(gen())
Tim Petersea5962f2007-03-12 18:07:52 +00001644
Georg Brandl15c5ce92007-03-07 09:09:40 +00001645 self.assertEqual(list(suite_1), list(gen()))
Tim Petersea5962f2007-03-12 18:07:52 +00001646
Georg Brandl15c5ce92007-03-07 09:09:40 +00001647 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001648 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001649 suite_2 = unittest.TestSuite()
1650 for t in gen():
1651 suite_2.addTest(t)
Tim Petersea5962f2007-03-12 18:07:52 +00001652
Georg Brandl15c5ce92007-03-07 09:09:40 +00001653 self.assertEqual(suite_1, suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001654
Georg Brandl15c5ce92007-03-07 09:09:40 +00001655 # "Add all the tests from an iterable of TestCase and TestSuite
1656 # instances to this test suite."
1657 #
Tim Petersea5962f2007-03-12 18:07:52 +00001658 # What happens if it doesn't get an iterable?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001659 def test_addTest__noniterable(self):
1660 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001661
Georg Brandl15c5ce92007-03-07 09:09:40 +00001662 try:
1663 suite.addTests(5)
1664 except TypeError:
1665 pass
1666 else:
1667 self.fail("Failed to raise TypeError")
Georg Brandld9e50262007-03-07 11:54:49 +00001668
1669 def test_addTest__noncallable(self):
1670 suite = unittest.TestSuite()
1671 self.assertRaises(TypeError, suite.addTest, 5)
1672
1673 def test_addTest__casesuiteclass(self):
1674 suite = unittest.TestSuite()
1675 self.assertRaises(TypeError, suite.addTest, Test_TestSuite)
1676 self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)
1677
1678 def test_addTests__string(self):
1679 suite = unittest.TestSuite()
1680 self.assertRaises(TypeError, suite.addTests, "foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001681
1682
Georg Brandl15c5ce92007-03-07 09:09:40 +00001683class Test_FunctionTestCase(TestCase):
Tim Petersea5962f2007-03-12 18:07:52 +00001684
Georg Brandl15c5ce92007-03-07 09:09:40 +00001685 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00001686 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001687 def test_countTestCases(self):
1688 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001689
Georg Brandl15c5ce92007-03-07 09:09:40 +00001690 self.assertEqual(test.countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00001691
Georg Brandl15c5ce92007-03-07 09:09:40 +00001692 # "When a setUp() method is defined, the test runner will run that method
1693 # prior to each test. Likewise, if a tearDown() method is defined, the
1694 # test runner will invoke that method after each test. In the example,
1695 # setUp() was used to create a fresh sequence for each test."
1696 #
1697 # Make sure the proper call order is maintained, even if setUp() raises
1698 # an exception.
1699 def test_run_call_order__error_in_setUp(self):
1700 events = []
1701 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001702
Georg Brandl15c5ce92007-03-07 09:09:40 +00001703 def setUp():
1704 events.append('setUp')
1705 raise RuntimeError('raised by setUp')
1706
1707 def test():
1708 events.append('test')
1709
1710 def tearDown():
1711 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001712
1713 expected = ['startTest', 'setUp', 'addError', 'stopTest']
Georg Brandl15c5ce92007-03-07 09:09:40 +00001714 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1715 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001716
Georg Brandl15c5ce92007-03-07 09:09:40 +00001717 # "When a setUp() method is defined, the test runner will run that method
1718 # prior to each test. Likewise, if a tearDown() method is defined, the
1719 # test runner will invoke that method after each test. In the example,
1720 # setUp() was used to create a fresh sequence for each test."
1721 #
1722 # Make sure the proper call order is maintained, even if the test raises
1723 # an error (as opposed to a failure).
1724 def test_run_call_order__error_in_test(self):
1725 events = []
1726 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001727
Georg Brandl15c5ce92007-03-07 09:09:40 +00001728 def setUp():
1729 events.append('setUp')
1730
1731 def test():
1732 events.append('test')
1733 raise RuntimeError('raised by test')
1734
1735 def tearDown():
1736 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001737
Georg Brandl15c5ce92007-03-07 09:09:40 +00001738 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
1739 'stopTest']
1740 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1741 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001742
Georg Brandl15c5ce92007-03-07 09:09:40 +00001743 # "When a setUp() method is defined, the test runner will run that method
1744 # prior to each test. Likewise, if a tearDown() method is defined, the
1745 # test runner will invoke that method after each test. In the example,
1746 # setUp() was used to create a fresh sequence for each test."
1747 #
1748 # Make sure the proper call order is maintained, even if the test signals
1749 # a failure (as opposed to an error).
1750 def test_run_call_order__failure_in_test(self):
1751 events = []
1752 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001753
Georg Brandl15c5ce92007-03-07 09:09:40 +00001754 def setUp():
1755 events.append('setUp')
1756
1757 def test():
1758 events.append('test')
1759 self.fail('raised by test')
1760
1761 def tearDown():
1762 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001763
Georg Brandl15c5ce92007-03-07 09:09:40 +00001764 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
1765 'stopTest']
1766 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1767 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001768
Georg Brandl15c5ce92007-03-07 09:09:40 +00001769 # "When a setUp() method is defined, the test runner will run that method
1770 # prior to each test. Likewise, if a tearDown() method is defined, the
1771 # test runner will invoke that method after each test. In the example,
1772 # setUp() was used to create a fresh sequence for each test."
1773 #
1774 # Make sure the proper call order is maintained, even if tearDown() raises
1775 # an exception.
1776 def test_run_call_order__error_in_tearDown(self):
1777 events = []
1778 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001779
Georg Brandl15c5ce92007-03-07 09:09:40 +00001780 def setUp():
1781 events.append('setUp')
1782
1783 def test():
1784 events.append('test')
1785
1786 def tearDown():
1787 events.append('tearDown')
1788 raise RuntimeError('raised by tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001789
Georg Brandl15c5ce92007-03-07 09:09:40 +00001790 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
1791 'stopTest']
1792 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1793 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001794
Georg Brandl15c5ce92007-03-07 09:09:40 +00001795 # "Return a string identifying the specific test case."
1796 #
1797 # Because of the vague nature of the docs, I'm not going to lock this
1798 # test down too much. Really all that can be asserted is that the id()
1799 # will be a string (either 8-byte or unicode -- again, because the docs
1800 # just say "string")
1801 def test_id(self):
1802 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001803
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001804 self.assertIsInstance(test.id(), basestring)
Tim Petersea5962f2007-03-12 18:07:52 +00001805
Georg Brandl15c5ce92007-03-07 09:09:40 +00001806 # "Returns a one-line description of the test, or None if no description
1807 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001808 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001809 def test_shortDescription__no_docstring(self):
1810 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001811
Georg Brandl15c5ce92007-03-07 09:09:40 +00001812 self.assertEqual(test.shortDescription(), None)
Tim Petersea5962f2007-03-12 18:07:52 +00001813
Georg Brandl15c5ce92007-03-07 09:09:40 +00001814 # "Returns a one-line description of the test, or None if no description
1815 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001816 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001817 def test_shortDescription__singleline_docstring(self):
1818 desc = "this tests foo"
1819 test = unittest.FunctionTestCase(lambda: None, description=desc)
Tim Petersea5962f2007-03-12 18:07:52 +00001820
Georg Brandl15c5ce92007-03-07 09:09:40 +00001821 self.assertEqual(test.shortDescription(), "this tests foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001822
Georg Brandl15c5ce92007-03-07 09:09:40 +00001823class Test_TestResult(TestCase):
1824 # Note: there are not separate tests for TestResult.wasSuccessful(),
1825 # TestResult.errors, TestResult.failures, TestResult.testsRun or
1826 # TestResult.shouldStop because these only have meaning in terms of
1827 # other TestResult methods.
1828 #
1829 # Accordingly, tests for the aforenamed attributes are incorporated
1830 # in with the tests for the defining methods.
1831 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001832
Georg Brandl15c5ce92007-03-07 09:09:40 +00001833 def test_init(self):
1834 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001835
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001836 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001837 self.assertEqual(len(result.errors), 0)
1838 self.assertEqual(len(result.failures), 0)
1839 self.assertEqual(result.testsRun, 0)
1840 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001841
Georg Brandl15c5ce92007-03-07 09:09:40 +00001842 # "This method can be called to signal that the set of tests being
1843 # run should be aborted by setting the TestResult's shouldStop
Tim Petersea5962f2007-03-12 18:07:52 +00001844 # attribute to True."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001845 def test_stop(self):
1846 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001847
Georg Brandl15c5ce92007-03-07 09:09:40 +00001848 result.stop()
Tim Petersea5962f2007-03-12 18:07:52 +00001849
Georg Brandl15c5ce92007-03-07 09:09:40 +00001850 self.assertEqual(result.shouldStop, True)
Tim Petersea5962f2007-03-12 18:07:52 +00001851
Georg Brandl15c5ce92007-03-07 09:09:40 +00001852 # "Called when the test case test is about to be run. The default
1853 # implementation simply increments the instance's testsRun counter."
1854 def test_startTest(self):
1855 class Foo(unittest.TestCase):
1856 def test_1(self):
1857 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001858
Georg Brandl15c5ce92007-03-07 09:09:40 +00001859 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001860
Georg Brandl15c5ce92007-03-07 09:09:40 +00001861 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001862
Georg Brandl15c5ce92007-03-07 09:09:40 +00001863 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001864
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001865 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001866 self.assertEqual(len(result.errors), 0)
1867 self.assertEqual(len(result.failures), 0)
1868 self.assertEqual(result.testsRun, 1)
1869 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001870
Georg Brandl15c5ce92007-03-07 09:09:40 +00001871 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001872
Georg Brandl15c5ce92007-03-07 09:09:40 +00001873 # "Called after the test case test has been executed, regardless of
1874 # the outcome. The default implementation does nothing."
1875 def test_stopTest(self):
1876 class Foo(unittest.TestCase):
1877 def test_1(self):
1878 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001879
Georg Brandl15c5ce92007-03-07 09:09:40 +00001880 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001881
Georg Brandl15c5ce92007-03-07 09:09:40 +00001882 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001883
Georg Brandl15c5ce92007-03-07 09:09:40 +00001884 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001885
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001886 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001887 self.assertEqual(len(result.errors), 0)
1888 self.assertEqual(len(result.failures), 0)
1889 self.assertEqual(result.testsRun, 1)
1890 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001891
Georg Brandl15c5ce92007-03-07 09:09:40 +00001892 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001893
Georg Brandl15c5ce92007-03-07 09:09:40 +00001894 # Same tests as above; make sure nothing has changed
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001895 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001896 self.assertEqual(len(result.errors), 0)
1897 self.assertEqual(len(result.failures), 0)
1898 self.assertEqual(result.testsRun, 1)
1899 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001900
Michael Foord07ef4872009-05-02 22:43:34 +00001901 # "Called before and after tests are run. The default implementation does nothing."
1902 def test_startTestRun_stopTestRun(self):
1903 result = unittest.TestResult()
1904 result.startTestRun()
1905 result.stopTestRun()
1906
Georg Brandl15c5ce92007-03-07 09:09:40 +00001907 # "addSuccess(test)"
1908 # ...
1909 # "Called when the test case test succeeds"
1910 # ...
1911 # "wasSuccessful() - Returns True if all tests run so far have passed,
1912 # otherwise returns False"
1913 # ...
1914 # "testsRun - The total number of tests run so far."
1915 # ...
1916 # "errors - A list containing 2-tuples of TestCase instances and
1917 # formatted tracebacks. Each tuple represents a test which raised an
1918 # unexpected exception. Contains formatted
1919 # tracebacks instead of sys.exc_info() results."
1920 # ...
1921 # "failures - A list containing 2-tuples of TestCase instances and
1922 # formatted tracebacks. Each tuple represents a test where a failure was
1923 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1924 # methods. Contains formatted tracebacks instead
1925 # of sys.exc_info() results."
1926 def test_addSuccess(self):
1927 class Foo(unittest.TestCase):
1928 def test_1(self):
1929 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001930
Georg Brandl15c5ce92007-03-07 09:09:40 +00001931 test = Foo('test_1')
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.addSuccess(test)
1937 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001938
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001939 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001940 self.assertEqual(len(result.errors), 0)
1941 self.assertEqual(len(result.failures), 0)
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 # "addFailure(test, err)"
1946 # ...
1947 # "Called when the test case test signals a failure. err is a tuple of
1948 # the form returned by sys.exc_info(): (type, value, traceback)"
1949 # ...
1950 # "wasSuccessful() - Returns True if all tests run so far have passed,
1951 # otherwise returns False"
1952 # ...
1953 # "testsRun - The total number of tests run so far."
1954 # ...
1955 # "errors - A list containing 2-tuples of TestCase instances and
1956 # formatted tracebacks. Each tuple represents a test which raised an
1957 # unexpected exception. Contains formatted
1958 # tracebacks instead of sys.exc_info() results."
1959 # ...
1960 # "failures - A list containing 2-tuples of TestCase instances and
1961 # formatted tracebacks. Each tuple represents a test where a failure was
1962 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1963 # methods. Contains formatted tracebacks instead
1964 # of sys.exc_info() results."
1965 def test_addFailure(self):
Georg Brandl15c5ce92007-03-07 09:09:40 +00001966 class Foo(unittest.TestCase):
1967 def test_1(self):
1968 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001969
Georg Brandl15c5ce92007-03-07 09:09:40 +00001970 test = Foo('test_1')
1971 try:
1972 test.fail("foo")
1973 except:
1974 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00001975
Georg Brandl15c5ce92007-03-07 09:09:40 +00001976 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001977
Georg Brandl15c5ce92007-03-07 09:09:40 +00001978 result.startTest(test)
1979 result.addFailure(test, exc_info_tuple)
1980 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001981
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001982 self.assertFalse(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001983 self.assertEqual(len(result.errors), 0)
1984 self.assertEqual(len(result.failures), 1)
1985 self.assertEqual(result.testsRun, 1)
1986 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001987
Georg Brandl15c5ce92007-03-07 09:09:40 +00001988 test_case, formatted_exc = result.failures[0]
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001989 self.assertTrue(test_case is test)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001990 self.assertIsInstance(formatted_exc, str)
Tim Petersea5962f2007-03-12 18:07:52 +00001991
Georg Brandl15c5ce92007-03-07 09:09:40 +00001992 # "addError(test, err)"
1993 # ...
1994 # "Called when the test case test raises an unexpected exception err
1995 # is a tuple of the form returned by sys.exc_info():
1996 # (type, value, traceback)"
1997 # ...
1998 # "wasSuccessful() - Returns True if all tests run so far have passed,
1999 # otherwise returns False"
2000 # ...
2001 # "testsRun - The total number of tests run so far."
2002 # ...
2003 # "errors - A list containing 2-tuples of TestCase instances and
2004 # formatted tracebacks. Each tuple represents a test which raised an
2005 # unexpected exception. Contains formatted
2006 # tracebacks instead of sys.exc_info() results."
2007 # ...
2008 # "failures - A list containing 2-tuples of TestCase instances and
2009 # formatted tracebacks. Each tuple represents a test where a failure was
2010 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
2011 # methods. Contains formatted tracebacks instead
2012 # of sys.exc_info() results."
2013 def test_addError(self):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002014 class Foo(unittest.TestCase):
2015 def test_1(self):
2016 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002017
Georg Brandl15c5ce92007-03-07 09:09:40 +00002018 test = Foo('test_1')
2019 try:
2020 raise TypeError()
2021 except:
2022 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00002023
Georg Brandl15c5ce92007-03-07 09:09:40 +00002024 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00002025
Georg Brandl15c5ce92007-03-07 09:09:40 +00002026 result.startTest(test)
2027 result.addError(test, exc_info_tuple)
2028 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00002029
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002030 self.assertFalse(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00002031 self.assertEqual(len(result.errors), 1)
2032 self.assertEqual(len(result.failures), 0)
2033 self.assertEqual(result.testsRun, 1)
2034 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00002035
Georg Brandl15c5ce92007-03-07 09:09:40 +00002036 test_case, formatted_exc = result.errors[0]
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002037 self.assertTrue(test_case is test)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002038 self.assertIsInstance(formatted_exc, str)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002039
Michael Foorddb43b5a2010-02-10 14:25:12 +00002040 def testGetDescriptionWithoutDocstring(self):
Michael Foord1c3abf42010-02-10 15:50:58 +00002041 result = unittest.TextTestResult(None, True, 1)
Michael Foorddb43b5a2010-02-10 14:25:12 +00002042 self.assertEqual(
2043 result.getDescription(self),
2044 'testGetDescriptionWithoutDocstring (' + __name__ +
2045 '.Test_TestResult)')
2046
R. David Murrayf28fd242010-02-23 00:24:49 +00002047 @unittest.skipIf(sys.flags.optimize >= 2,
2048 "Docstrings are omitted with -O2 and above")
Michael Foorddb43b5a2010-02-10 14:25:12 +00002049 def testGetDescriptionWithOneLineDocstring(self):
2050 """Tests getDescription() for a method with a docstring."""
Michael Foord1c3abf42010-02-10 15:50:58 +00002051 result = unittest.TextTestResult(None, True, 1)
Michael Foorddb43b5a2010-02-10 14:25:12 +00002052 self.assertEqual(
2053 result.getDescription(self),
2054 ('testGetDescriptionWithOneLineDocstring '
2055 '(' + __name__ + '.Test_TestResult)\n'
2056 'Tests getDescription() for a method with a docstring.'))
2057
R. David Murrayf28fd242010-02-23 00:24:49 +00002058 @unittest.skipIf(sys.flags.optimize >= 2,
2059 "Docstrings are omitted with -O2 and above")
Michael Foorddb43b5a2010-02-10 14:25:12 +00002060 def testGetDescriptionWithMultiLineDocstring(self):
2061 """Tests getDescription() for a method with a longer docstring.
2062 The second line of the docstring.
2063 """
Michael Foord1c3abf42010-02-10 15:50:58 +00002064 result = unittest.TextTestResult(None, True, 1)
Michael Foorddb43b5a2010-02-10 14:25:12 +00002065 self.assertEqual(
2066 result.getDescription(self),
2067 ('testGetDescriptionWithMultiLineDocstring '
2068 '(' + __name__ + '.Test_TestResult)\n'
2069 'Tests getDescription() for a method with a longer '
2070 'docstring.'))
2071
Michael Foordae3db0a2010-02-22 23:28:32 +00002072classDict = dict(unittest.TestResult.__dict__)
Michael Foordd99ef9a2010-02-23 17:00:53 +00002073for m in ('addSkip', 'addExpectedFailure', 'addUnexpectedSuccess',
2074 '__init__'):
Michael Foordae3db0a2010-02-22 23:28:32 +00002075 del classDict[m]
Michael Foordd99ef9a2010-02-23 17:00:53 +00002076
2077def __init__(self, stream=None, descriptions=None, verbosity=None):
2078 self.failures = []
2079 self.errors = []
2080 self.testsRun = 0
2081 self.shouldStop = False
2082classDict['__init__'] = __init__
Michael Foordae3db0a2010-02-22 23:28:32 +00002083OldResult = type('OldResult', (object,), classDict)
2084
2085class Test_OldTestResult(unittest.TestCase):
2086
2087 def assertOldResultWarning(self, test, failures):
2088 with warnings.catch_warnings(record=True) as log:
2089 result = OldResult()
2090 test.run(result)
2091 self.assertEqual(len(result.failures), failures)
2092 warning, = log
2093 self.assertIs(warning.category, RuntimeWarning)
2094
2095 def testOldTestResult(self):
2096 class Test(unittest.TestCase):
2097 def testSkip(self):
2098 self.skipTest('foobar')
2099 @unittest.expectedFailure
2100 def testExpectedFail(self):
2101 raise TypeError
2102 @unittest.expectedFailure
2103 def testUnexpectedSuccess(self):
2104 pass
2105
2106 for test_name, should_pass in (('testSkip', True),
2107 ('testExpectedFail', True),
2108 ('testUnexpectedSuccess', False)):
2109 test = Test(test_name)
2110 self.assertOldResultWarning(test, int(not should_pass))
2111
2112 def testOldTestTesultSetup(self):
2113 class Test(unittest.TestCase):
2114 def setUp(self):
2115 self.skipTest('no reason')
2116 def testFoo(self):
2117 pass
2118 self.assertOldResultWarning(Test('testFoo'), 0)
2119
2120 def testOldTestResultClass(self):
2121 @unittest.skip('no reason')
2122 class Test(unittest.TestCase):
2123 def testFoo(self):
2124 pass
2125 self.assertOldResultWarning(Test('testFoo'), 0)
2126
Michael Foordd99ef9a2010-02-23 17:00:53 +00002127 def testOldResultWithRunner(self):
2128 class Test(unittest.TestCase):
2129 def testFoo(self):
2130 pass
2131 runner = unittest.TextTestRunner(resultclass=OldResult,
2132 stream=StringIO())
2133 # This will raise an exception if TextTestRunner can't handle old
2134 # test result objects
2135 runner.run(Test('testFoo'))
Michael Foorddb43b5a2010-02-10 14:25:12 +00002136
Georg Brandl15c5ce92007-03-07 09:09:40 +00002137### Support code for Test_TestCase
2138################################################################
2139
2140class Foo(unittest.TestCase):
2141 def runTest(self): pass
2142 def test1(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002143
Georg Brandl15c5ce92007-03-07 09:09:40 +00002144class Bar(Foo):
2145 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002146
Michael Foord07ef4872009-05-02 22:43:34 +00002147class LoggingTestCase(unittest.TestCase):
2148 """A test case which logs its calls."""
2149
2150 def __init__(self, events):
2151 super(LoggingTestCase, self).__init__('test')
2152 self.events = events
2153
2154 def setUp(self):
2155 self.events.append('setUp')
2156
2157 def test(self):
2158 self.events.append('test')
2159
2160 def tearDown(self):
2161 self.events.append('tearDown')
2162
2163class ResultWithNoStartTestRunStopTestRun(object):
2164 """An object honouring TestResult before startTestRun/stopTestRun."""
2165
2166 def __init__(self):
2167 self.failures = []
2168 self.errors = []
2169 self.testsRun = 0
2170 self.skipped = []
2171 self.expectedFailures = []
2172 self.unexpectedSuccesses = []
2173 self.shouldStop = False
2174
2175 def startTest(self, test):
2176 pass
2177
2178 def stopTest(self, test):
2179 pass
2180
2181 def addError(self, test):
2182 pass
2183
2184 def addFailure(self, test):
2185 pass
2186
2187 def addSuccess(self, test):
2188 pass
2189
2190 def wasSuccessful(self):
2191 return True
2192
2193
Georg Brandl15c5ce92007-03-07 09:09:40 +00002194################################################################
2195### /Support code for Test_TestCase
2196
2197class Test_TestCase(TestCase, TestEquality, TestHashing):
2198
2199 ### Set up attributes used by inherited tests
2200 ################################################################
2201
2202 # Used by TestHashing.test_hash and TestEquality.test_eq
2203 eq_pairs = [(Foo('test1'), Foo('test1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002204
Georg Brandl15c5ce92007-03-07 09:09:40 +00002205 # Used by TestEquality.test_ne
2206 ne_pairs = [(Foo('test1'), Foo('runTest'))
2207 ,(Foo('test1'), Bar('test1'))
2208 ,(Foo('test1'), Bar('test2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002209
Georg Brandl15c5ce92007-03-07 09:09:40 +00002210 ################################################################
2211 ### /Set up attributes used by inherited tests
Tim Petersea5962f2007-03-12 18:07:52 +00002212
Georg Brandl15c5ce92007-03-07 09:09:40 +00002213
2214 # "class TestCase([methodName])"
2215 # ...
2216 # "Each instance of TestCase will run a single test method: the
2217 # method named methodName."
2218 # ...
2219 # "methodName defaults to "runTest"."
2220 #
2221 # Make sure it really is optional, and that it defaults to the proper
2222 # thing.
2223 def test_init__no_test_name(self):
2224 class Test(unittest.TestCase):
2225 def runTest(self): raise MyException()
2226 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002227
Georg Brandl15c5ce92007-03-07 09:09:40 +00002228 self.assertEqual(Test().id()[-13:], '.Test.runTest')
Tim Petersea5962f2007-03-12 18:07:52 +00002229
Georg Brandl15c5ce92007-03-07 09:09:40 +00002230 # "class TestCase([methodName])"
2231 # ...
2232 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002233 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002234 def test_init__test_name__valid(self):
2235 class Test(unittest.TestCase):
2236 def runTest(self): raise MyException()
2237 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002238
Georg Brandl15c5ce92007-03-07 09:09:40 +00002239 self.assertEqual(Test('test').id()[-10:], '.Test.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002240
Georg Brandl15c5ce92007-03-07 09:09:40 +00002241 # "class TestCase([methodName])"
2242 # ...
2243 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002244 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002245 def test_init__test_name__invalid(self):
2246 class Test(unittest.TestCase):
2247 def runTest(self): raise MyException()
2248 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002249
Georg Brandl15c5ce92007-03-07 09:09:40 +00002250 try:
2251 Test('testfoo')
2252 except ValueError:
2253 pass
2254 else:
2255 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +00002256
Georg Brandl15c5ce92007-03-07 09:09:40 +00002257 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00002258 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00002259 def test_countTestCases(self):
2260 class Foo(unittest.TestCase):
2261 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002262
Georg Brandl15c5ce92007-03-07 09:09:40 +00002263 self.assertEqual(Foo('test').countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00002264
Georg Brandl15c5ce92007-03-07 09:09:40 +00002265 # "Return the default type of test result object to be used to run this
2266 # test. For TestCase instances, this will always be
2267 # unittest.TestResult; subclasses of TestCase should
2268 # override this as necessary."
2269 def test_defaultTestResult(self):
2270 class Foo(unittest.TestCase):
2271 def runTest(self):
2272 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002273
Georg Brandl15c5ce92007-03-07 09:09:40 +00002274 result = Foo().defaultTestResult()
2275 self.assertEqual(type(result), unittest.TestResult)
2276
2277 # "When a setUp() method is defined, the test runner will run that method
2278 # prior to each test. Likewise, if a tearDown() method is defined, the
2279 # test runner will invoke that method after each test. In the example,
2280 # setUp() was used to create a fresh sequence for each test."
2281 #
2282 # Make sure the proper call order is maintained, even if setUp() raises
2283 # an exception.
2284 def test_run_call_order__error_in_setUp(self):
2285 events = []
2286 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002287
Michael Foord07ef4872009-05-02 22:43:34 +00002288 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002289 def setUp(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002290 super(Foo, self).setUp()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002291 raise RuntimeError('raised by Foo.setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002292
Michael Foord07ef4872009-05-02 22:43:34 +00002293 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002294 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2295 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002296
Michael Foord07ef4872009-05-02 22:43:34 +00002297 # "With a temporary result stopTestRun is called when setUp errors.
2298 def test_run_call_order__error_in_setUp_default_result(self):
2299 events = []
2300
2301 class Foo(LoggingTestCase):
2302 def defaultTestResult(self):
2303 return LoggingResult(self.events)
2304
2305 def setUp(self):
2306 super(Foo, self).setUp()
2307 raise RuntimeError('raised by Foo.setUp')
2308
2309 Foo(events).run()
2310 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2311 'stopTest', 'stopTestRun']
2312 self.assertEqual(events, expected)
2313
Georg Brandl15c5ce92007-03-07 09:09:40 +00002314 # "When a setUp() method is defined, the test runner will run that method
2315 # prior to each test. Likewise, if a tearDown() method is defined, the
2316 # test runner will invoke that method after each test. In the example,
2317 # setUp() was used to create a fresh sequence for each test."
2318 #
2319 # Make sure the proper call order is maintained, even if the test raises
2320 # an error (as opposed to a failure).
2321 def test_run_call_order__error_in_test(self):
2322 events = []
2323 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002324
Michael Foord07ef4872009-05-02 22:43:34 +00002325 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002326 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002327 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002328 raise RuntimeError('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002329
Georg Brandl15c5ce92007-03-07 09:09:40 +00002330 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2331 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002332 Foo(events).run(result)
2333 self.assertEqual(events, expected)
2334
2335 # "With a default result, an error in the test still results in stopTestRun
2336 # being called."
2337 def test_run_call_order__error_in_test_default_result(self):
2338 events = []
2339
2340 class Foo(LoggingTestCase):
2341 def defaultTestResult(self):
2342 return LoggingResult(self.events)
2343
2344 def test(self):
2345 super(Foo, self).test()
2346 raise RuntimeError('raised by Foo.test')
2347
2348 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2349 'tearDown', 'stopTest', 'stopTestRun']
2350 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002351 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002352
Georg Brandl15c5ce92007-03-07 09:09:40 +00002353 # "When a setUp() method is defined, the test runner will run that method
2354 # prior to each test. Likewise, if a tearDown() method is defined, the
2355 # test runner will invoke that method after each test. In the example,
2356 # setUp() was used to create a fresh sequence for each test."
2357 #
2358 # Make sure the proper call order is maintained, even if the test signals
2359 # a failure (as opposed to an error).
2360 def test_run_call_order__failure_in_test(self):
2361 events = []
2362 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002363
Michael Foord07ef4872009-05-02 22:43:34 +00002364 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002365 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002366 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002367 self.fail('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002368
Georg Brandl15c5ce92007-03-07 09:09:40 +00002369 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2370 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002371 Foo(events).run(result)
2372 self.assertEqual(events, expected)
2373
2374 # "When a test fails with a default result stopTestRun is still called."
2375 def test_run_call_order__failure_in_test_default_result(self):
2376
2377 class Foo(LoggingTestCase):
2378 def defaultTestResult(self):
2379 return LoggingResult(self.events)
2380 def test(self):
2381 super(Foo, self).test()
2382 self.fail('raised by Foo.test')
2383
2384 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2385 'tearDown', 'stopTest', 'stopTestRun']
2386 events = []
2387 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002388 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002389
Georg Brandl15c5ce92007-03-07 09:09:40 +00002390 # "When a setUp() method is defined, the test runner will run that method
2391 # prior to each test. Likewise, if a tearDown() method is defined, the
2392 # test runner will invoke that method after each test. In the example,
2393 # setUp() was used to create a fresh sequence for each test."
2394 #
2395 # Make sure the proper call order is maintained, even if tearDown() raises
2396 # an exception.
2397 def test_run_call_order__error_in_tearDown(self):
2398 events = []
2399 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002400
Michael Foord07ef4872009-05-02 22:43:34 +00002401 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002402 def tearDown(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002403 super(Foo, self).tearDown()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002404 raise RuntimeError('raised by Foo.tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002405
Michael Foord07ef4872009-05-02 22:43:34 +00002406 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002407 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2408 'stopTest']
2409 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002410
Michael Foord07ef4872009-05-02 22:43:34 +00002411 # "When tearDown errors with a default result stopTestRun is still called."
2412 def test_run_call_order__error_in_tearDown_default_result(self):
2413
2414 class Foo(LoggingTestCase):
2415 def defaultTestResult(self):
2416 return LoggingResult(self.events)
2417 def tearDown(self):
2418 super(Foo, self).tearDown()
2419 raise RuntimeError('raised by Foo.tearDown')
2420
2421 events = []
2422 Foo(events).run()
2423 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2424 'addError', 'stopTest', 'stopTestRun']
2425 self.assertEqual(events, expected)
2426
2427 # "TestCase.run() still works when the defaultTestResult is a TestResult
2428 # that does not support startTestRun and stopTestRun.
2429 def test_run_call_order_default_result(self):
2430
2431 class Foo(unittest.TestCase):
2432 def defaultTestResult(self):
2433 return ResultWithNoStartTestRunStopTestRun()
2434 def test(self):
2435 pass
2436
2437 Foo('test').run()
2438
Georg Brandl15c5ce92007-03-07 09:09:40 +00002439 # "This class attribute gives the exception raised by the test() method.
2440 # If a test framework needs to use a specialized exception, possibly to
2441 # carry additional information, it must subclass this exception in
2442 # order to ``play fair'' with the framework. The initial value of this
2443 # attribute is AssertionError"
2444 def test_failureException__default(self):
2445 class Foo(unittest.TestCase):
2446 def test(self):
2447 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002448
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002449 self.assertTrue(Foo('test').failureException is AssertionError)
Tim Petersea5962f2007-03-12 18:07:52 +00002450
Georg Brandl15c5ce92007-03-07 09:09:40 +00002451 # "This class attribute gives the exception raised by the test() method.
2452 # If a test framework needs to use a specialized exception, possibly to
2453 # carry additional information, it must subclass this exception in
2454 # order to ``play fair'' with the framework."
2455 #
2456 # Make sure TestCase.run() respects the designated failureException
2457 def test_failureException__subclassing__explicit_raise(self):
2458 events = []
2459 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002460
Georg Brandl15c5ce92007-03-07 09:09:40 +00002461 class Foo(unittest.TestCase):
2462 def test(self):
2463 raise RuntimeError()
Tim Petersea5962f2007-03-12 18:07:52 +00002464
Georg Brandl15c5ce92007-03-07 09:09:40 +00002465 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002466
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002467 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002468
2469
Georg Brandl15c5ce92007-03-07 09:09:40 +00002470 Foo('test').run(result)
2471 expected = ['startTest', 'addFailure', 'stopTest']
2472 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002473
Georg Brandl15c5ce92007-03-07 09:09:40 +00002474 # "This class attribute gives the exception raised by the test() method.
2475 # If a test framework needs to use a specialized exception, possibly to
2476 # carry additional information, it must subclass this exception in
2477 # order to ``play fair'' with the framework."
2478 #
2479 # Make sure TestCase.run() respects the designated failureException
2480 def test_failureException__subclassing__implicit_raise(self):
2481 events = []
2482 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002483
Georg Brandl15c5ce92007-03-07 09:09:40 +00002484 class Foo(unittest.TestCase):
2485 def test(self):
2486 self.fail("foo")
Tim Petersea5962f2007-03-12 18:07:52 +00002487
Georg Brandl15c5ce92007-03-07 09:09:40 +00002488 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002489
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002490 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002491
2492
Georg Brandl15c5ce92007-03-07 09:09:40 +00002493 Foo('test').run(result)
2494 expected = ['startTest', 'addFailure', 'stopTest']
2495 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002496
2497 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002498 def test_setUp(self):
2499 class Foo(unittest.TestCase):
2500 def runTest(self):
2501 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002502
Georg Brandl15c5ce92007-03-07 09:09:40 +00002503 # ... and nothing should happen
2504 Foo().setUp()
Tim Petersea5962f2007-03-12 18:07:52 +00002505
2506 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002507 def test_tearDown(self):
2508 class Foo(unittest.TestCase):
2509 def runTest(self):
2510 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002511
Georg Brandl15c5ce92007-03-07 09:09:40 +00002512 # ... and nothing should happen
2513 Foo().tearDown()
Tim Petersea5962f2007-03-12 18:07:52 +00002514
Georg Brandl15c5ce92007-03-07 09:09:40 +00002515 # "Return a string identifying the specific test case."
2516 #
2517 # Because of the vague nature of the docs, I'm not going to lock this
2518 # test down too much. Really all that can be asserted is that the id()
2519 # will be a string (either 8-byte or unicode -- again, because the docs
2520 # just say "string")
2521 def test_id(self):
2522 class Foo(unittest.TestCase):
2523 def runTest(self):
2524 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002525
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002526 self.assertIsInstance(Foo().id(), basestring)
Tim Petersea5962f2007-03-12 18:07:52 +00002527
Georg Brandl15c5ce92007-03-07 09:09:40 +00002528 # "If result is omitted or None, a temporary result object is created
Michael Foord07ef4872009-05-02 22:43:34 +00002529 # and used, but is not made available to the caller. As TestCase owns the
2530 # temporary result startTestRun and stopTestRun are called.
2531
Georg Brandl15c5ce92007-03-07 09:09:40 +00002532 def test_run__uses_defaultTestResult(self):
2533 events = []
Tim Petersea5962f2007-03-12 18:07:52 +00002534
Georg Brandl15c5ce92007-03-07 09:09:40 +00002535 class Foo(unittest.TestCase):
2536 def test(self):
2537 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002538
Georg Brandl15c5ce92007-03-07 09:09:40 +00002539 def defaultTestResult(self):
2540 return LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002541
2542 # Make run() find a result object on its own
Georg Brandl15c5ce92007-03-07 09:09:40 +00002543 Foo('test').run()
Tim Petersea5962f2007-03-12 18:07:52 +00002544
Michael Foord07ef4872009-05-02 22:43:34 +00002545 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2546 'stopTest', 'stopTestRun']
Georg Brandl15c5ce92007-03-07 09:09:40 +00002547 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002548
Gregory P. Smith28399852009-03-31 16:54:10 +00002549 def testShortDescriptionWithoutDocstring(self):
Michael Foorddb43b5a2010-02-10 14:25:12 +00002550 self.assertIsNone(self.shortDescription())
Gregory P. Smith28399852009-03-31 16:54:10 +00002551
R. David Murrayf28fd242010-02-23 00:24:49 +00002552 @unittest.skipIf(sys.flags.optimize >= 2,
2553 "Docstrings are omitted with -O2 and above")
Gregory P. Smith28399852009-03-31 16:54:10 +00002554 def testShortDescriptionWithOneLineDocstring(self):
2555 """Tests shortDescription() for a method with a docstring."""
2556 self.assertEqual(
2557 self.shortDescription(),
Michael Foorddb43b5a2010-02-10 14:25:12 +00002558 'Tests shortDescription() for a method with a docstring.')
Gregory P. Smith28399852009-03-31 16:54:10 +00002559
R. David Murrayf28fd242010-02-23 00:24:49 +00002560 @unittest.skipIf(sys.flags.optimize >= 2,
2561 "Docstrings are omitted with -O2 and above")
Gregory P. Smith28399852009-03-31 16:54:10 +00002562 def testShortDescriptionWithMultiLineDocstring(self):
2563 """Tests shortDescription() for a method with a longer docstring.
2564
2565 This method ensures that only the first line of a docstring is
2566 returned used in the short description, no matter how long the
2567 whole thing is.
2568 """
2569 self.assertEqual(
2570 self.shortDescription(),
Gregory P. Smith28399852009-03-31 16:54:10 +00002571 'Tests shortDescription() for a method with a longer '
Michael Foorddb43b5a2010-02-10 14:25:12 +00002572 'docstring.')
Gregory P. Smith28399852009-03-31 16:54:10 +00002573
Gregory P. Smith28399852009-03-31 16:54:10 +00002574 def testAddTypeEqualityFunc(self):
2575 class SadSnake(object):
2576 """Dummy class for test_addTypeEqualityFunc."""
2577 s1, s2 = SadSnake(), SadSnake()
2578 self.assertFalse(s1 == s2)
2579 def AllSnakesCreatedEqual(a, b, msg=None):
2580 return type(a) == type(b) == SadSnake
2581 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2582 self.assertEqual(s1, s2)
2583 # No this doesn't clean up and remove the SadSnake equality func
2584 # from this TestCase instance but since its a local nothing else
2585 # will ever notice that.
2586
Michael Foordf2dfef12009-04-05 19:19:28 +00002587 def testAssertIs(self):
2588 thing = object()
2589 self.assertIs(thing, thing)
2590 self.assertRaises(self.failureException, self.assertIs, thing, object())
2591
2592 def testAssertIsNot(self):
2593 thing = object()
2594 self.assertIsNot(thing, object())
2595 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2596
Georg Brandlf895cf52009-10-01 20:59:31 +00002597 def testAssertIsInstance(self):
2598 thing = []
2599 self.assertIsInstance(thing, list)
2600 self.assertRaises(self.failureException, self.assertIsInstance,
2601 thing, dict)
2602
2603 def testAssertNotIsInstance(self):
2604 thing = []
2605 self.assertNotIsInstance(thing, dict)
2606 self.assertRaises(self.failureException, self.assertNotIsInstance,
2607 thing, list)
2608
Gregory P. Smith28399852009-03-31 16:54:10 +00002609 def testAssertIn(self):
2610 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2611
2612 self.assertIn('a', 'abc')
2613 self.assertIn(2, [1, 2, 3])
2614 self.assertIn('monkey', animals)
2615
2616 self.assertNotIn('d', 'abc')
2617 self.assertNotIn(0, [1, 2, 3])
2618 self.assertNotIn('otter', animals)
2619
2620 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2621 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2622 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2623 animals)
2624
2625 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2626 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2627 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2628 animals)
2629
2630 def testAssertDictContainsSubset(self):
2631 self.assertDictContainsSubset({}, {})
2632 self.assertDictContainsSubset({}, {'a': 1})
2633 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2634 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2635 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2636
Michael Foord225a0992010-02-18 20:30:09 +00002637 with self.assertRaises(self.failureException):
2638 self.assertDictContainsSubset({1: "one"}, {})
Gregory P. Smith28399852009-03-31 16:54:10 +00002639
Michael Foord225a0992010-02-18 20:30:09 +00002640 with self.assertRaises(self.failureException):
2641 self.assertDictContainsSubset({'a': 2}, {'a': 1})
Gregory P. Smith28399852009-03-31 16:54:10 +00002642
Michael Foord225a0992010-02-18 20:30:09 +00002643 with self.assertRaises(self.failureException):
2644 self.assertDictContainsSubset({'c': 1}, {'a': 1})
Gregory P. Smith28399852009-03-31 16:54:10 +00002645
Michael Foord225a0992010-02-18 20:30:09 +00002646 with self.assertRaises(self.failureException):
2647 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2648
2649 with self.assertRaises(self.failureException):
2650 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2651
Michael Foord2f677562010-02-21 14:48:59 +00002652 with warnings.catch_warnings(record=True):
2653 # silence the UnicodeWarning
2654 one = ''.join(chr(i) for i in range(255))
2655 # this used to cause a UnicodeDecodeError constructing the failure msg
2656 with self.assertRaises(self.failureException):
2657 self.assertDictContainsSubset({'foo': one}, {'foo': u'\uFFFD'})
Gregory P. Smith28399852009-03-31 16:54:10 +00002658
2659 def testAssertEqual(self):
2660 equal_pairs = [
2661 ((), ()),
2662 ({}, {}),
2663 ([], []),
2664 (set(), set()),
2665 (frozenset(), frozenset())]
2666 for a, b in equal_pairs:
2667 # This mess of try excepts is to test the assertEqual behavior
2668 # itself.
2669 try:
2670 self.assertEqual(a, b)
2671 except self.failureException:
2672 self.fail('assertEqual(%r, %r) failed' % (a, b))
2673 try:
2674 self.assertEqual(a, b, msg='foo')
2675 except self.failureException:
2676 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2677 try:
2678 self.assertEqual(a, b, 'foo')
2679 except self.failureException:
2680 self.fail('assertEqual(%r, %r) with third parameter failed' %
2681 (a, b))
2682
2683 unequal_pairs = [
2684 ((), []),
2685 ({}, set()),
2686 (set([4,1]), frozenset([4,2])),
2687 (frozenset([4,5]), set([2,3])),
2688 (set([3,4]), set([5,4]))]
2689 for a, b in unequal_pairs:
2690 self.assertRaises(self.failureException, self.assertEqual, a, b)
2691 self.assertRaises(self.failureException, self.assertEqual, a, b,
2692 'foo')
2693 self.assertRaises(self.failureException, self.assertEqual, a, b,
2694 msg='foo')
2695
2696 def testEquality(self):
2697 self.assertListEqual([], [])
2698 self.assertTupleEqual((), ())
2699 self.assertSequenceEqual([], ())
2700
2701 a = [0, 'a', []]
2702 b = []
2703 self.assertRaises(unittest.TestCase.failureException,
2704 self.assertListEqual, a, b)
2705 self.assertRaises(unittest.TestCase.failureException,
2706 self.assertListEqual, tuple(a), tuple(b))
2707 self.assertRaises(unittest.TestCase.failureException,
2708 self.assertSequenceEqual, a, tuple(b))
2709
2710 b.extend(a)
2711 self.assertListEqual(a, b)
2712 self.assertTupleEqual(tuple(a), tuple(b))
2713 self.assertSequenceEqual(a, tuple(b))
2714 self.assertSequenceEqual(tuple(a), b)
2715
2716 self.assertRaises(self.failureException, self.assertListEqual,
2717 a, tuple(b))
2718 self.assertRaises(self.failureException, self.assertTupleEqual,
2719 tuple(a), b)
2720 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2721 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2722 tuple(b))
2723 self.assertRaises(self.failureException, self.assertSequenceEqual,
2724 None, tuple(b))
2725 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2726 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2727 self.assertRaises(self.failureException, self.assertSequenceEqual,
2728 1, 1)
2729
2730 self.assertDictEqual({}, {})
2731
2732 c = { 'x': 1 }
2733 d = {}
2734 self.assertRaises(unittest.TestCase.failureException,
2735 self.assertDictEqual, c, d)
2736
2737 d.update(c)
2738 self.assertDictEqual(c, d)
2739
2740 d['x'] = 0
2741 self.assertRaises(unittest.TestCase.failureException,
2742 self.assertDictEqual, c, d, 'These are unequal')
2743
2744 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2745 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2746 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2747
2748 self.assertSameElements([1, 2, 3], [3, 2, 1])
2749 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2750 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2751 self.assertRaises(self.failureException, self.assertSameElements,
2752 [10], [10, 11])
2753 self.assertRaises(self.failureException, self.assertSameElements,
2754 [10, 11], [10])
2755
2756 # Test that sequences of unhashable objects can be tested for sameness:
2757 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Michael Foordf2dfef12009-04-05 19:19:28 +00002758
Gregory P. Smith28399852009-03-31 16:54:10 +00002759 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2760 self.assertRaises(self.failureException, self.assertSameElements,
2761 [[1]], [[2]])
2762
2763 def testAssertSetEqual(self):
2764 set1 = set()
2765 set2 = set()
2766 self.assertSetEqual(set1, set2)
2767
2768 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2769 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2770 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2771 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2772
2773 set1 = set(['a'])
2774 set2 = set()
2775 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2776
2777 set1 = set(['a'])
2778 set2 = set(['a'])
2779 self.assertSetEqual(set1, set2)
2780
2781 set1 = set(['a'])
2782 set2 = set(['a', 'b'])
2783 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2784
2785 set1 = set(['a'])
2786 set2 = frozenset(['a', 'b'])
2787 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2788
2789 set1 = set(['a', 'b'])
2790 set2 = frozenset(['a', 'b'])
2791 self.assertSetEqual(set1, set2)
2792
2793 set1 = set()
2794 set2 = "foo"
2795 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2796 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2797
2798 # make sure any string formatting is tuple-safe
2799 set1 = set([(0, 1), (2, 3)])
2800 set2 = set([(4, 5)])
2801 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2802
2803 def testInequality(self):
2804 # Try ints
2805 self.assertGreater(2, 1)
2806 self.assertGreaterEqual(2, 1)
2807 self.assertGreaterEqual(1, 1)
2808 self.assertLess(1, 2)
2809 self.assertLessEqual(1, 2)
2810 self.assertLessEqual(1, 1)
2811 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2812 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2813 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2814 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2815 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2816 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2817
2818 # Try Floats
2819 self.assertGreater(1.1, 1.0)
2820 self.assertGreaterEqual(1.1, 1.0)
2821 self.assertGreaterEqual(1.0, 1.0)
2822 self.assertLess(1.0, 1.1)
2823 self.assertLessEqual(1.0, 1.1)
2824 self.assertLessEqual(1.0, 1.0)
2825 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2826 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2827 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2828 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2829 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2830 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2831
2832 # Try Strings
2833 self.assertGreater('bug', 'ant')
2834 self.assertGreaterEqual('bug', 'ant')
2835 self.assertGreaterEqual('ant', 'ant')
2836 self.assertLess('ant', 'bug')
2837 self.assertLessEqual('ant', 'bug')
2838 self.assertLessEqual('ant', 'ant')
2839 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2840 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2841 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2842 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2843 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2844 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2845
2846 # Try Unicode
2847 self.assertGreater(u'bug', u'ant')
2848 self.assertGreaterEqual(u'bug', u'ant')
2849 self.assertGreaterEqual(u'ant', u'ant')
2850 self.assertLess(u'ant', u'bug')
2851 self.assertLessEqual(u'ant', u'bug')
2852 self.assertLessEqual(u'ant', u'ant')
2853 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug')
2854 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant')
2855 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2856 u'bug')
2857 self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant')
2858 self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant')
2859 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant')
2860
2861 # Try Mixed String/Unicode
2862 self.assertGreater('bug', u'ant')
2863 self.assertGreater(u'bug', 'ant')
2864 self.assertGreaterEqual('bug', u'ant')
2865 self.assertGreaterEqual(u'bug', 'ant')
2866 self.assertGreaterEqual('ant', u'ant')
2867 self.assertGreaterEqual(u'ant', 'ant')
2868 self.assertLess('ant', u'bug')
2869 self.assertLess(u'ant', 'bug')
2870 self.assertLessEqual('ant', u'bug')
2871 self.assertLessEqual(u'ant', 'bug')
2872 self.assertLessEqual('ant', u'ant')
2873 self.assertLessEqual(u'ant', 'ant')
2874 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug')
2875 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug')
2876 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant')
2877 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant')
2878 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant',
2879 u'bug')
2880 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2881 'bug')
2882 self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant')
2883 self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant')
2884 self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant')
2885 self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant')
2886 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant')
2887 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant')
2888
2889 def testAssertMultiLineEqual(self):
2890 sample_text = b"""\
2891http://www.python.org/doc/2.3/lib/module-unittest.html
2892test case
2893 A test case is the smallest unit of testing. [...]
2894"""
2895 revised_sample_text = b"""\
2896http://www.python.org/doc/2.4.1/lib/module-unittest.html
2897test case
2898 A test case is the smallest unit of testing. [...] You may provide your
2899 own implementation that does not subclass from TestCase, of course.
2900"""
2901 sample_text_error = b"""
2902- http://www.python.org/doc/2.3/lib/module-unittest.html
2903? ^
2904+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2905? ^^^
2906 test case
2907- A test case is the smallest unit of testing. [...]
2908+ A test case is the smallest unit of testing. [...] You may provide your
2909? +++++++++++++++++++++
2910+ own implementation that does not subclass from TestCase, of course.
2911"""
2912
2913 for type_changer in (lambda x: x, lambda x: x.decode('utf8')):
2914 try:
2915 self.assertMultiLineEqual(type_changer(sample_text),
2916 type_changer(revised_sample_text))
2917 except self.failureException, e:
Michael Foordfe6349c2010-02-08 22:41:16 +00002918 # assertMultiLineEqual is hooked up as the default for
2919 # unicode strings - so we can't use it for this check
2920 self.assertTrue(sample_text_error == str(e).encode('utf8'))
Gregory P. Smith28399852009-03-31 16:54:10 +00002921
2922 def testAssertIsNone(self):
2923 self.assertIsNone(None)
2924 self.assertRaises(self.failureException, self.assertIsNone, False)
2925 self.assertIsNotNone('DjZoPloGears on Rails')
2926 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2927
2928 def testAssertRegexpMatches(self):
2929 self.assertRegexpMatches('asdfabasdf', r'ab+')
2930 self.assertRaises(self.failureException, self.assertRegexpMatches,
2931 'saaas', r'aaaa')
2932
2933 def testAssertRaisesRegexp(self):
2934 class ExceptionMock(Exception):
2935 pass
2936
2937 def Stub():
2938 raise ExceptionMock('We expect')
2939
2940 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2941 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2942 self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
2943
2944 def testAssertNotRaisesRegexp(self):
2945 self.assertRaisesRegexp(
2946 self.failureException, '^Exception not raised$',
2947 self.assertRaisesRegexp, Exception, re.compile('x'),
2948 lambda: None)
2949 self.assertRaisesRegexp(
2950 self.failureException, '^Exception not raised$',
2951 self.assertRaisesRegexp, Exception, 'x',
2952 lambda: None)
2953 self.assertRaisesRegexp(
2954 self.failureException, '^Exception not raised$',
2955 self.assertRaisesRegexp, Exception, u'x',
2956 lambda: None)
2957
2958 def testAssertRaisesRegexpMismatch(self):
2959 def Stub():
2960 raise Exception('Unexpected')
2961
2962 self.assertRaisesRegexp(
2963 self.failureException,
2964 r'"\^Expected\$" does not match "Unexpected"',
2965 self.assertRaisesRegexp, Exception, '^Expected$',
2966 Stub)
2967 self.assertRaisesRegexp(
2968 self.failureException,
2969 r'"\^Expected\$" does not match "Unexpected"',
2970 self.assertRaisesRegexp, Exception, u'^Expected$',
2971 Stub)
2972 self.assertRaisesRegexp(
2973 self.failureException,
2974 r'"\^Expected\$" does not match "Unexpected"',
2975 self.assertRaisesRegexp, Exception,
2976 re.compile('^Expected$'), Stub)
2977
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00002978 def testAssertRaisesExcValue(self):
2979 class ExceptionMock(Exception):
2980 pass
2981
2982 def Stub(foo):
2983 raise ExceptionMock(foo)
2984 v = "particular value"
2985
2986 ctx = self.assertRaises(ExceptionMock)
2987 with ctx:
2988 Stub(v)
Georg Brandldc3694b2010-02-07 17:02:22 +00002989 e = ctx.exception
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002990 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00002991 self.assertEqual(e.args[0], v)
2992
Gregory P. Smith7558d572009-03-31 19:03:28 +00002993 def testSynonymAssertMethodNames(self):
2994 """Test undocumented method name synonyms.
2995
2996 Please do not use these methods names in your own code.
2997
2998 This test confirms their continued existence and functionality
2999 in order to avoid breaking existing code.
3000 """
3001 self.assertNotEquals(3, 5)
3002 self.assertEquals(3, 3)
3003 self.assertAlmostEquals(2.0, 2.0)
3004 self.assertNotAlmostEquals(3.0, 5.0)
3005 self.assert_(True)
3006
3007 def testPendingDeprecationMethodNames(self):
3008 """Test fail* methods pending deprecation, they will warn in 3.2.
3009
3010 Do not use these methods. They will go away in 3.3.
3011 """
3012 self.failIfEqual(3, 5)
3013 self.failUnlessEqual(3, 3)
3014 self.failUnlessAlmostEqual(2.0, 2.0)
3015 self.failIfAlmostEqual(3.0, 5.0)
3016 self.failUnless(True)
3017 self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam')
3018 self.failIf(False)
3019
Michael Foorde2942d02009-04-02 05:51:54 +00003020 def testDeepcopy(self):
3021 # Issue: 5660
3022 class TestableTest(TestCase):
3023 def testNothing(self):
3024 pass
3025
3026 test = TestableTest('testNothing')
3027
3028 # This shouldn't blow up
3029 deepcopy(test)
3030
Benjamin Peterson692428e2009-03-23 21:50:21 +00003031
3032class Test_TestSkipping(TestCase):
3033
3034 def test_skipping(self):
3035 class Foo(unittest.TestCase):
3036 def test_skip_me(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00003037 self.skipTest("skip")
Benjamin Peterson692428e2009-03-23 21:50:21 +00003038 events = []
3039 result = LoggingResult(events)
3040 test = Foo("test_skip_me")
3041 test.run(result)
3042 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3043 self.assertEqual(result.skipped, [(test, "skip")])
3044
3045 # Try letting setUp skip the test now.
3046 class Foo(unittest.TestCase):
3047 def setUp(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00003048 self.skipTest("testing")
Benjamin Peterson692428e2009-03-23 21:50:21 +00003049 def test_nothing(self): pass
3050 events = []
3051 result = LoggingResult(events)
3052 test = Foo("test_nothing")
3053 test.run(result)
3054 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3055 self.assertEqual(result.skipped, [(test, "testing")])
3056 self.assertEqual(result.testsRun, 1)
3057
3058 def test_skipping_decorators(self):
3059 op_table = ((unittest.skipUnless, False, True),
3060 (unittest.skipIf, True, False))
3061 for deco, do_skip, dont_skip in op_table:
3062 class Foo(unittest.TestCase):
3063 @deco(do_skip, "testing")
3064 def test_skip(self): pass
3065
3066 @deco(dont_skip, "testing")
3067 def test_dont_skip(self): pass
3068 test_do_skip = Foo("test_skip")
3069 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003070 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003071 events = []
3072 result = LoggingResult(events)
3073 suite.run(result)
3074 self.assertEqual(len(result.skipped), 1)
3075 expected = ['startTest', 'addSkip', 'stopTest',
3076 'startTest', 'addSuccess', 'stopTest']
3077 self.assertEqual(events, expected)
3078 self.assertEqual(result.testsRun, 2)
3079 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
3080 self.assertTrue(result.wasSuccessful())
3081
3082 def test_skip_class(self):
3083 @unittest.skip("testing")
3084 class Foo(unittest.TestCase):
3085 def test_1(self):
3086 record.append(1)
3087 record = []
3088 result = unittest.TestResult()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003089 test = Foo("test_1")
3090 suite = unittest.TestSuite([test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003091 suite.run(result)
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003092 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003093 self.assertEqual(record, [])
3094
3095 def test_expected_failure(self):
3096 class Foo(unittest.TestCase):
3097 @unittest.expectedFailure
3098 def test_die(self):
3099 self.fail("help me!")
3100 events = []
3101 result = LoggingResult(events)
3102 test = Foo("test_die")
3103 test.run(result)
3104 self.assertEqual(events,
3105 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003106 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00003107 self.assertTrue(result.wasSuccessful())
3108
3109 def test_unexpected_success(self):
3110 class Foo(unittest.TestCase):
3111 @unittest.expectedFailure
3112 def test_die(self):
3113 pass
3114 events = []
3115 result = LoggingResult(events)
3116 test = Foo("test_die")
3117 test.run(result)
3118 self.assertEqual(events,
3119 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3120 self.assertFalse(result.failures)
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003121 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003122 self.assertTrue(result.wasSuccessful())
3123
Michael Foord53e8eea2010-03-07 20:22:12 +00003124 def test_skip_doesnt_run_setup(self):
3125 class Foo(unittest.TestCase):
3126 wasSetUp = False
3127 wasTornDown = False
3128 def setUp(self):
3129 Foo.wasSetUp = True
3130 def tornDown(self):
3131 Foo.wasTornDown = True
3132 @unittest.skip('testing')
3133 def test_1(self):
3134 pass
3135
3136 result = unittest.TestResult()
3137 test = Foo("test_1")
3138 suite = unittest.TestSuite([test])
3139 suite.run(result)
3140 self.assertEqual(result.skipped, [(test, "testing")])
3141 self.assertFalse(Foo.wasSetUp)
3142 self.assertFalse(Foo.wasTornDown)
3143
3144 def test_decorated_skip(self):
3145 def decorator(func):
3146 def inner(*a):
3147 return func(*a)
3148 return inner
3149
3150 class Foo(unittest.TestCase):
3151 @decorator
3152 @unittest.skip('testing')
3153 def test_1(self):
3154 pass
3155
3156 result = unittest.TestResult()
3157 test = Foo("test_1")
3158 suite = unittest.TestSuite([test])
3159 suite.run(result)
3160 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003161
3162
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003163class Test_Assertions(TestCase):
3164 def test_AlmostEqual(self):
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003165 self.assertAlmostEqual(1.00000001, 1.0)
3166 self.assertNotAlmostEqual(1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003167 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003168 self.assertAlmostEqual, 1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003169 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003170 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003171
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003172 self.assertAlmostEqual(1.1, 1.0, places=0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003173 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003174 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003175
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003176 self.assertAlmostEqual(0, .1+.1j, places=0)
3177 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003178 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003179 self.assertAlmostEqual, 0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003180 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003181 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003182
Michael Foordc3f79372009-09-13 16:40:02 +00003183 self.assertAlmostEqual(float('inf'), float('inf'))
3184 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3185 float('inf'), float('inf'))
3186
3187
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003188 def test_assertRaises(self):
3189 def _raise(e):
3190 raise e
3191 self.assertRaises(KeyError, _raise, KeyError)
3192 self.assertRaises(KeyError, _raise, KeyError("key"))
3193 try:
3194 self.assertRaises(KeyError, lambda: None)
Gregory P. Smith28399852009-03-31 16:54:10 +00003195 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003196 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003197 else:
3198 self.fail("assertRaises() didn't fail")
3199 try:
3200 self.assertRaises(KeyError, _raise, ValueError)
3201 except ValueError:
3202 pass
3203 else:
3204 self.fail("assertRaises() didn't let exception pass through")
Michael Foord2bd52dc2010-02-07 18:44:12 +00003205 with self.assertRaises(KeyError) as cm:
3206 try:
3207 raise KeyError
3208 except Exception, e:
3209 raise
3210 self.assertIs(cm.exception, e)
3211
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003212 with self.assertRaises(KeyError):
3213 raise KeyError("key")
3214 try:
3215 with self.assertRaises(KeyError):
3216 pass
Gregory P. Smith28399852009-03-31 16:54:10 +00003217 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003218 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003219 else:
3220 self.fail("assertRaises() didn't fail")
3221 try:
3222 with self.assertRaises(KeyError):
3223 raise ValueError
3224 except ValueError:
3225 pass
3226 else:
3227 self.fail("assertRaises() didn't let exception pass through")
3228
3229
Michael Foord345b2fe2009-04-02 03:20:38 +00003230class TestLongMessage(TestCase):
3231 """Test that the individual asserts honour longMessage.
3232 This actually tests all the message behaviour for
3233 asserts that use longMessage."""
3234
3235 def setUp(self):
3236 class TestableTestFalse(TestCase):
3237 longMessage = False
3238 failureException = self.failureException
3239
3240 def testTest(self):
3241 pass
3242
3243 class TestableTestTrue(TestCase):
3244 longMessage = True
3245 failureException = self.failureException
3246
3247 def testTest(self):
3248 pass
3249
3250 self.testableTrue = TestableTestTrue('testTest')
3251 self.testableFalse = TestableTestFalse('testTest')
3252
3253 def testDefault(self):
3254 self.assertFalse(TestCase.longMessage)
3255
3256 def test_formatMsg(self):
3257 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3258 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3259
3260 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3261 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3262
Michael Foord53e8eea2010-03-07 20:22:12 +00003263 # This blows up if _formatMessage uses string concatenation
3264 self.testableTrue._formatMessage(object(), 'foo')
3265
3266 def test_formatMessage_unicode_error(self):
3267 with warnings.catch_warnings(record=True):
3268 # This causes a UnicodeWarning due to its craziness
3269 one = ''.join(chr(i) for i in range(255))
3270 # this used to cause a UnicodeDecodeError constructing msg
3271 self.testableTrue._formatMessage(one, u'\uFFFD')
3272
Michael Foord345b2fe2009-04-02 03:20:38 +00003273 def assertMessages(self, methodName, args, errors):
3274 def getMethod(i):
3275 useTestableFalse = i < 2
3276 if useTestableFalse:
3277 test = self.testableFalse
3278 else:
3279 test = self.testableTrue
3280 return getattr(test, methodName)
3281
3282 for i, expected_regexp in enumerate(errors):
3283 testMethod = getMethod(i)
3284 kwargs = {}
3285 withMsg = i % 2
3286 if withMsg:
3287 kwargs = {"msg": "oops"}
3288
3289 with self.assertRaisesRegexp(self.failureException,
3290 expected_regexp=expected_regexp):
3291 testMethod(*args, **kwargs)
3292
3293 def testAssertTrue(self):
3294 self.assertMessages('assertTrue', (False,),
3295 ["^False is not True$", "^oops$", "^False is not True$",
3296 "^False is not True : oops$"])
3297
3298 def testAssertFalse(self):
3299 self.assertMessages('assertFalse', (True,),
3300 ["^True is not False$", "^oops$", "^True is not False$",
3301 "^True is not False : oops$"])
3302
3303 def testNotEqual(self):
3304 self.assertMessages('assertNotEqual', (1, 1),
3305 ["^1 == 1$", "^oops$", "^1 == 1$",
3306 "^1 == 1 : oops$"])
3307
3308 def testAlmostEqual(self):
3309 self.assertMessages('assertAlmostEqual', (1, 2),
3310 ["^1 != 2 within 7 places$", "^oops$",
3311 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3312
3313 def testNotAlmostEqual(self):
3314 self.assertMessages('assertNotAlmostEqual', (1, 1),
3315 ["^1 == 1 within 7 places$", "^oops$",
3316 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3317
3318 def test_baseAssertEqual(self):
3319 self.assertMessages('_baseAssertEqual', (1, 2),
3320 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3321
3322 def testAssertSequenceEqual(self):
3323 # Error messages are multiline so not testing on full message
3324 # assertTupleEqual and assertListEqual delegate to this method
3325 self.assertMessages('assertSequenceEqual', ([], [None]),
3326 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3327 r"\+ \[None\] : oops$"])
3328
3329 def testAssertSetEqual(self):
3330 self.assertMessages('assertSetEqual', (set(), set([None])),
3331 ["None$", "^oops$", "None$",
3332 "None : oops$"])
3333
3334 def testAssertIn(self):
3335 self.assertMessages('assertIn', (None, []),
3336 ['^None not found in \[\]$', "^oops$",
3337 '^None not found in \[\]$',
3338 '^None not found in \[\] : oops$'])
3339
3340 def testAssertNotIn(self):
3341 self.assertMessages('assertNotIn', (None, [None]),
3342 ['^None unexpectedly found in \[None\]$', "^oops$",
3343 '^None unexpectedly found in \[None\]$',
3344 '^None unexpectedly found in \[None\] : oops$'])
3345
3346 def testAssertDictEqual(self):
3347 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3348 [r"\+ \{'key': 'value'\}$", "^oops$",
3349 "\+ \{'key': 'value'\}$",
3350 "\+ \{'key': 'value'\} : oops$"])
3351
3352 def testAssertDictContainsSubset(self):
3353 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3354 ["^Missing: 'key'$", "^oops$",
3355 "^Missing: 'key'$",
3356 "^Missing: 'key' : oops$"])
3357
3358 def testAssertSameElements(self):
3359 self.assertMessages('assertSameElements', ([], [None]),
3360 [r"\[None\]$", "^oops$",
3361 r"\[None\]$",
3362 r"\[None\] : oops$"])
3363
3364 def testAssertMultiLineEqual(self):
3365 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3366 [r"\+ foo$", "^oops$",
3367 r"\+ foo$",
3368 r"\+ foo : oops$"])
3369
3370 def testAssertLess(self):
3371 self.assertMessages('assertLess', (2, 1),
3372 ["^2 not less than 1$", "^oops$",
3373 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3374
3375 def testAssertLessEqual(self):
3376 self.assertMessages('assertLessEqual', (2, 1),
3377 ["^2 not less than or equal to 1$", "^oops$",
3378 "^2 not less than or equal to 1$",
3379 "^2 not less than or equal to 1 : oops$"])
3380
3381 def testAssertGreater(self):
3382 self.assertMessages('assertGreater', (1, 2),
3383 ["^1 not greater than 2$", "^oops$",
3384 "^1 not greater than 2$",
3385 "^1 not greater than 2 : oops$"])
3386
3387 def testAssertGreaterEqual(self):
3388 self.assertMessages('assertGreaterEqual', (1, 2),
3389 ["^1 not greater than or equal to 2$", "^oops$",
3390 "^1 not greater than or equal to 2$",
3391 "^1 not greater than or equal to 2 : oops$"])
3392
3393 def testAssertIsNone(self):
3394 self.assertMessages('assertIsNone', ('not None',),
3395 ["^'not None' is not None$", "^oops$",
3396 "^'not None' is not None$",
3397 "^'not None' is not None : oops$"])
3398
3399 def testAssertIsNotNone(self):
3400 self.assertMessages('assertIsNotNone', (None,),
3401 ["^unexpectedly None$", "^oops$",
3402 "^unexpectedly None$",
3403 "^unexpectedly None : oops$"])
3404
Michael Foordf2dfef12009-04-05 19:19:28 +00003405 def testAssertIs(self):
3406 self.assertMessages('assertIs', (None, 'foo'),
3407 ["^None is not 'foo'$", "^oops$",
3408 "^None is not 'foo'$",
3409 "^None is not 'foo' : oops$"])
3410
3411 def testAssertIsNot(self):
3412 self.assertMessages('assertIsNot', (None, None),
3413 ["^unexpectedly identical: None$", "^oops$",
3414 "^unexpectedly identical: None$",
3415 "^unexpectedly identical: None : oops$"])
3416
Michael Foord345b2fe2009-04-02 03:20:38 +00003417
Michael Foorde2fb98f2009-05-02 20:15:05 +00003418class TestCleanUp(TestCase):
3419
3420 def testCleanUp(self):
3421 class TestableTest(TestCase):
3422 def testNothing(self):
3423 pass
3424
3425 test = TestableTest('testNothing')
3426 self.assertEqual(test._cleanups, [])
3427
3428 cleanups = []
3429
3430 def cleanup1(*args, **kwargs):
3431 cleanups.append((1, args, kwargs))
3432
3433 def cleanup2(*args, **kwargs):
3434 cleanups.append((2, args, kwargs))
3435
3436 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3437 test.addCleanup(cleanup2)
3438
3439 self.assertEqual(test._cleanups,
3440 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3441 (cleanup2, (), {})])
3442
3443 result = test.doCleanups()
3444 self.assertTrue(result)
3445
3446 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3447
3448 def testCleanUpWithErrors(self):
3449 class TestableTest(TestCase):
3450 def testNothing(self):
3451 pass
3452
3453 class MockResult(object):
3454 errors = []
3455 def addError(self, test, exc_info):
3456 self.errors.append((test, exc_info))
3457
3458 result = MockResult()
3459 test = TestableTest('testNothing')
Michael Foorda50af062009-05-21 22:57:02 +00003460 test._resultForDoCleanups = result
Michael Foorde2fb98f2009-05-02 20:15:05 +00003461
3462 exc1 = Exception('foo')
3463 exc2 = Exception('bar')
3464 def cleanup1():
3465 raise exc1
3466
3467 def cleanup2():
3468 raise exc2
3469
3470 test.addCleanup(cleanup1)
3471 test.addCleanup(cleanup2)
3472
3473 self.assertFalse(test.doCleanups())
3474
3475 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3476 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3477 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3478
3479 def testCleanupInRun(self):
3480 blowUp = False
3481 ordering = []
3482
3483 class TestableTest(TestCase):
3484 def setUp(self):
3485 ordering.append('setUp')
3486 if blowUp:
3487 raise Exception('foo')
3488
3489 def testNothing(self):
3490 ordering.append('test')
3491
3492 def tearDown(self):
3493 ordering.append('tearDown')
3494
3495 test = TestableTest('testNothing')
3496
3497 def cleanup1():
3498 ordering.append('cleanup1')
3499 def cleanup2():
3500 ordering.append('cleanup2')
3501 test.addCleanup(cleanup1)
3502 test.addCleanup(cleanup2)
3503
3504 def success(some_test):
3505 self.assertEqual(some_test, test)
3506 ordering.append('success')
3507
3508 result = unittest.TestResult()
3509 result.addSuccess = success
3510
3511 test.run(result)
3512 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3513 'cleanup2', 'cleanup1', 'success'])
3514
3515 blowUp = True
3516 ordering = []
3517 test = TestableTest('testNothing')
3518 test.addCleanup(cleanup1)
3519 test.run(result)
3520 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3521
3522
Michael Foord829f6b82009-05-02 11:43:06 +00003523class Test_TestProgram(TestCase):
3524
3525 # Horrible white box test
3526 def testNoExit(self):
3527 result = object()
3528 test = object()
3529
3530 class FakeRunner(object):
3531 def run(self, test):
3532 self.test = test
3533 return result
3534
3535 runner = FakeRunner()
3536
Michael Foord5d31e052009-05-11 17:59:43 +00003537 oldParseArgs = TestProgram.parseArgs
3538 def restoreParseArgs():
Michael Foord829f6b82009-05-02 11:43:06 +00003539 TestProgram.parseArgs = oldParseArgs
Michael Foord5d31e052009-05-11 17:59:43 +00003540 TestProgram.parseArgs = lambda *args: None
3541 self.addCleanup(restoreParseArgs)
3542
3543 def removeTest():
Michael Foord829f6b82009-05-02 11:43:06 +00003544 del TestProgram.test
Michael Foord5d31e052009-05-11 17:59:43 +00003545 TestProgram.test = test
3546 self.addCleanup(removeTest)
3547
3548 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3549
3550 self.assertEqual(program.result, result)
3551 self.assertEqual(runner.test, test)
3552 self.assertEqual(program.verbosity, 2)
Michael Foord829f6b82009-05-02 11:43:06 +00003553
Michael Foord829f6b82009-05-02 11:43:06 +00003554 class FooBar(unittest.TestCase):
3555 def testPass(self):
3556 assert True
3557 def testFail(self):
3558 assert False
3559
3560 class FooBarLoader(unittest.TestLoader):
3561 """Test loader that returns a suite containing FooBar."""
3562 def loadTestsFromModule(self, module):
3563 return self.suiteClass(
3564 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3565
3566
3567 def test_NonExit(self):
3568 program = unittest.main(exit=False,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003569 argv=["foobar"],
3570 testRunner=unittest.TextTestRunner(stream=StringIO()),
3571 testLoader=self.FooBarLoader())
Michael Foord829f6b82009-05-02 11:43:06 +00003572 self.assertTrue(hasattr(program, 'result'))
3573
3574
3575 def test_Exit(self):
3576 self.assertRaises(
3577 SystemExit,
3578 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003579 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003580 testRunner=unittest.TextTestRunner(stream=StringIO()),
3581 exit=True,
3582 testLoader=self.FooBarLoader())
3583
3584
3585 def test_ExitAsDefault(self):
3586 self.assertRaises(
3587 SystemExit,
3588 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003589 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003590 testRunner=unittest.TextTestRunner(stream=StringIO()),
3591 testLoader=self.FooBarLoader())
3592
3593
Michael Foord07ef4872009-05-02 22:43:34 +00003594class Test_TextTestRunner(TestCase):
3595 """Tests for TextTestRunner."""
3596
3597 def test_works_with_result_without_startTestRun_stopTestRun(self):
3598 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3599 separator2 = ''
3600 def printErrors(self):
3601 pass
3602
3603 class Runner(unittest.TextTestRunner):
3604 def __init__(self):
3605 super(Runner, self).__init__(StringIO())
3606
3607 def _makeResult(self):
3608 return OldTextResult()
3609
3610 runner = Runner()
3611 runner.run(unittest.TestSuite())
3612
3613 def test_startTestRun_stopTestRun_called(self):
3614 class LoggingTextResult(LoggingResult):
3615 separator2 = ''
3616 def printErrors(self):
3617 pass
3618
3619 class LoggingRunner(unittest.TextTestRunner):
3620 def __init__(self, events):
3621 super(LoggingRunner, self).__init__(StringIO())
3622 self._events = events
3623
3624 def _makeResult(self):
3625 return LoggingTextResult(self._events)
3626
3627 events = []
3628 runner = LoggingRunner(events)
3629 runner.run(unittest.TestSuite())
3630 expected = ['startTestRun', 'stopTestRun']
3631 self.assertEqual(events, expected)
3632
Antoine Pitrou0734c632009-11-10 20:49:30 +00003633 def test_pickle_unpickle(self):
3634 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3635 # required by test_multiprocessing under Windows (in verbose mode).
3636 import StringIO
3637 # cStringIO objects are not pickleable, but StringIO objects are.
3638 stream = StringIO.StringIO("foo")
3639 runner = unittest.TextTestRunner(stream)
3640 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
3641 s = pickle.dumps(runner, protocol=protocol)
3642 obj = pickle.loads(s)
3643 # StringIO objects never compare equal, a cheap test instead.
3644 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3645
Michael Foorddb43b5a2010-02-10 14:25:12 +00003646 def test_resultclass(self):
3647 def MockResultClass(*args):
3648 return args
3649 STREAM = object()
3650 DESCRIPTIONS = object()
3651 VERBOSITY = object()
3652 runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY,
3653 resultclass=MockResultClass)
3654 self.assertEqual(runner.resultclass, MockResultClass)
3655
3656 expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY)
3657 self.assertEqual(runner._makeResult(), expectedresult)
3658
Michael Foord07ef4872009-05-02 22:43:34 +00003659
Michael Foordb4a81c82009-05-29 20:33:46 +00003660class TestDiscovery(TestCase):
3661
3662 # Heavily mocked tests so I can avoid hitting the filesystem
Michael Foorde91ea562009-09-13 19:07:03 +00003663 def test_get_name_from_path(self):
Michael Foordb4a81c82009-05-29 20:33:46 +00003664 loader = unittest.TestLoader()
3665
Michael Foordb4a81c82009-05-29 20:33:46 +00003666 loader._top_level_dir = '/foo'
Michael Foorde91ea562009-09-13 19:07:03 +00003667 name = loader._get_name_from_path('/foo/bar/baz.py')
3668 self.assertEqual(name, 'bar.baz')
Michael Foordb4a81c82009-05-29 20:33:46 +00003669
3670 if not __debug__:
3671 # asserts are off
3672 return
3673
3674 with self.assertRaises(AssertionError):
Michael Foorde91ea562009-09-13 19:07:03 +00003675 loader._get_name_from_path('/bar/baz.py')
Michael Foordb4a81c82009-05-29 20:33:46 +00003676
3677 def test_find_tests(self):
3678 loader = unittest.TestLoader()
3679
3680 original_listdir = os.listdir
3681 def restore_listdir():
3682 os.listdir = original_listdir
3683 original_isfile = os.path.isfile
3684 def restore_isfile():
3685 os.path.isfile = original_isfile
3686 original_isdir = os.path.isdir
3687 def restore_isdir():
3688 os.path.isdir = original_isdir
3689
3690 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Michael Foorde91ea562009-09-13 19:07:03 +00003691 'test.foo', 'test-not-a-module.py', 'another_dir'],
Michael Foordb4a81c82009-05-29 20:33:46 +00003692 ['test3.py', 'test4.py', ]]
3693 os.listdir = lambda path: path_lists.pop(0)
3694 self.addCleanup(restore_listdir)
3695
3696 def isdir(path):
3697 return path.endswith('dir')
3698 os.path.isdir = isdir
3699 self.addCleanup(restore_isdir)
3700
3701 def isfile(path):
3702 # another_dir is not a package and so shouldn't be recursed into
3703 return not path.endswith('dir') and not 'another_dir' in path
3704 os.path.isfile = isfile
3705 self.addCleanup(restore_isfile)
3706
Michael Foorde91ea562009-09-13 19:07:03 +00003707 loader._get_module_from_name = lambda path: path + ' module'
Michael Foordb4a81c82009-05-29 20:33:46 +00003708 loader.loadTestsFromModule = lambda module: module + ' tests'
3709
3710 loader._top_level_dir = '/foo'
3711 suite = list(loader._find_tests('/foo', 'test*.py'))
3712
Michael Foorde91ea562009-09-13 19:07:03 +00003713 expected = [name + ' module tests' for name in
3714 ('test1', 'test2')]
3715 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3716 ('test3', 'test4')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003717 self.assertEqual(suite, expected)
3718
3719 def test_find_tests_with_package(self):
3720 loader = unittest.TestLoader()
3721
3722 original_listdir = os.listdir
3723 def restore_listdir():
3724 os.listdir = original_listdir
3725 original_isfile = os.path.isfile
3726 def restore_isfile():
3727 os.path.isfile = original_isfile
3728 original_isdir = os.path.isdir
3729 def restore_isdir():
3730 os.path.isdir = original_isdir
3731
3732 directories = ['a_directory', 'test_directory', 'test_directory2']
3733 path_lists = [directories, [], [], []]
3734 os.listdir = lambda path: path_lists.pop(0)
3735 self.addCleanup(restore_listdir)
3736
3737 os.path.isdir = lambda path: True
3738 self.addCleanup(restore_isdir)
3739
3740 os.path.isfile = lambda path: os.path.basename(path) not in directories
3741 self.addCleanup(restore_isfile)
3742
3743 class Module(object):
3744 paths = []
3745 load_tests_args = []
3746
3747 def __init__(self, path):
3748 self.path = path
3749 self.paths.append(path)
3750 if os.path.basename(path) == 'test_directory':
3751 def load_tests(loader, tests, pattern):
3752 self.load_tests_args.append((loader, tests, pattern))
3753 return 'load_tests'
3754 self.load_tests = load_tests
3755
3756 def __eq__(self, other):
3757 return self.path == other.path
3758
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003759 # Silence py3k warning
3760 __hash__ = None
3761
Michael Foorde91ea562009-09-13 19:07:03 +00003762 loader._get_module_from_name = lambda name: Module(name)
Michael Foordb4a81c82009-05-29 20:33:46 +00003763 def loadTestsFromModule(module, use_load_tests):
3764 if use_load_tests:
3765 raise self.failureException('use_load_tests should be False for packages')
3766 return module.path + ' module tests'
3767 loader.loadTestsFromModule = loadTestsFromModule
3768
3769 loader._top_level_dir = '/foo'
3770 # this time no '.py' on the pattern so that it can match
3771 # a test package
3772 suite = list(loader._find_tests('/foo', 'test*'))
3773
3774 # We should have loaded tests from the test_directory package by calling load_tests
3775 # and directly from the test_directory2 package
Michael Foordd53d0852009-06-05 14:14:34 +00003776 self.assertEqual(suite,
Michael Foorde91ea562009-09-13 19:07:03 +00003777 ['load_tests', 'test_directory2' + ' module tests'])
3778 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Michael Foordb4a81c82009-05-29 20:33:46 +00003779
3780 # load_tests should have been called once with loader, tests and pattern
3781 self.assertEqual(Module.load_tests_args,
Michael Foorde91ea562009-09-13 19:07:03 +00003782 [(loader, 'test_directory' + ' module tests', 'test*')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003783
3784 def test_discover(self):
3785 loader = unittest.TestLoader()
3786
3787 original_isfile = os.path.isfile
3788 def restore_isfile():
3789 os.path.isfile = original_isfile
3790
3791 os.path.isfile = lambda path: False
3792 self.addCleanup(restore_isfile)
3793
Nick Coghlanb6edf192009-10-17 08:21:21 +00003794 orig_sys_path = sys.path[:]
3795 def restore_path():
3796 sys.path[:] = orig_sys_path
3797 self.addCleanup(restore_path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003798
Nick Coghlanb6edf192009-10-17 08:21:21 +00003799 full_path = os.path.abspath(os.path.normpath('/foo'))
Michael Foordb4a81c82009-05-29 20:33:46 +00003800 with self.assertRaises(ImportError):
3801 loader.discover('/foo/bar', top_level_dir='/foo')
3802
3803 self.assertEqual(loader._top_level_dir, full_path)
3804 self.assertIn(full_path, sys.path)
3805
3806 os.path.isfile = lambda path: True
3807 _find_tests_args = []
3808 def _find_tests(start_dir, pattern):
3809 _find_tests_args.append((start_dir, pattern))
3810 return ['tests']
3811 loader._find_tests = _find_tests
3812 loader.suiteClass = str
3813
3814 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3815
3816 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3817 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3818 self.assertEqual(suite, "['tests']")
3819 self.assertEqual(loader._top_level_dir, top_level_dir)
3820 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlanb6edf192009-10-17 08:21:21 +00003821 self.assertIn(top_level_dir, sys.path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003822
Michael Foorde91ea562009-09-13 19:07:03 +00003823 def test_discover_with_modules_that_fail_to_import(self):
3824 loader = unittest.TestLoader()
3825
3826 listdir = os.listdir
3827 os.listdir = lambda _: ['test_this_does_not_exist.py']
3828 isfile = os.path.isfile
3829 os.path.isfile = lambda _: True
Nick Coghlanb6edf192009-10-17 08:21:21 +00003830 orig_sys_path = sys.path[:]
Michael Foorde91ea562009-09-13 19:07:03 +00003831 def restore():
3832 os.path.isfile = isfile
3833 os.listdir = listdir
Nick Coghlanb6edf192009-10-17 08:21:21 +00003834 sys.path[:] = orig_sys_path
Michael Foorde91ea562009-09-13 19:07:03 +00003835 self.addCleanup(restore)
3836
3837 suite = loader.discover('.')
Nick Coghlanb6edf192009-10-17 08:21:21 +00003838 self.assertIn(os.getcwd(), sys.path)
Michael Foorde91ea562009-09-13 19:07:03 +00003839 self.assertEqual(suite.countTestCases(), 1)
3840 test = list(list(suite)[0])[0] # extract test from suite
3841
3842 with self.assertRaises(ImportError):
3843 test.test_this_does_not_exist()
3844
Michael Foordb4a81c82009-05-29 20:33:46 +00003845 def test_command_line_handling_parseArgs(self):
3846 # Haha - take that uninstantiable class
3847 program = object.__new__(TestProgram)
3848
3849 args = []
3850 def do_discovery(argv):
3851 args.extend(argv)
3852 program._do_discovery = do_discovery
3853 program.parseArgs(['something', 'discover'])
3854 self.assertEqual(args, [])
3855
3856 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3857 self.assertEqual(args, ['foo', 'bar'])
3858
3859 def test_command_line_handling_do_discovery_too_many_arguments(self):
3860 class Stop(Exception):
3861 pass
3862 def usageExit():
3863 raise Stop
3864
3865 program = object.__new__(TestProgram)
3866 program.usageExit = usageExit
3867
3868 with self.assertRaises(Stop):
3869 # too many args
3870 program._do_discovery(['one', 'two', 'three', 'four'])
3871
3872
3873 def test_command_line_handling_do_discovery_calls_loader(self):
3874 program = object.__new__(TestProgram)
3875
3876 class Loader(object):
3877 args = []
3878 def discover(self, start_dir, pattern, top_level_dir):
3879 self.args.append((start_dir, pattern, top_level_dir))
3880 return 'tests'
3881
3882 program._do_discovery(['-v'], Loader=Loader)
3883 self.assertEqual(program.verbosity, 2)
3884 self.assertEqual(program.test, 'tests')
3885 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3886
3887 Loader.args = []
3888 program = object.__new__(TestProgram)
3889 program._do_discovery(['--verbose'], Loader=Loader)
3890 self.assertEqual(program.test, 'tests')
3891 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3892
3893 Loader.args = []
3894 program = object.__new__(TestProgram)
3895 program._do_discovery([], Loader=Loader)
3896 self.assertEqual(program.test, 'tests')
3897 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3898
3899 Loader.args = []
3900 program = object.__new__(TestProgram)
3901 program._do_discovery(['fish'], Loader=Loader)
3902 self.assertEqual(program.test, 'tests')
3903 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3904
3905 Loader.args = []
3906 program = object.__new__(TestProgram)
3907 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3908 self.assertEqual(program.test, 'tests')
3909 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3910
3911 Loader.args = []
3912 program = object.__new__(TestProgram)
3913 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3914 self.assertEqual(program.test, 'tests')
3915 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3916
3917 Loader.args = []
3918 program = object.__new__(TestProgram)
3919 program._do_discovery(['-s', 'fish'], Loader=Loader)
3920 self.assertEqual(program.test, 'tests')
3921 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3922
3923 Loader.args = []
3924 program = object.__new__(TestProgram)
3925 program._do_discovery(['-t', 'fish'], Loader=Loader)
3926 self.assertEqual(program.test, 'tests')
3927 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3928
3929 Loader.args = []
3930 program = object.__new__(TestProgram)
3931 program._do_discovery(['-p', 'fish'], Loader=Loader)
3932 self.assertEqual(program.test, 'tests')
3933 self.assertEqual(Loader.args, [('.', 'fish', None)])
3934
3935 Loader.args = []
3936 program = object.__new__(TestProgram)
3937 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3938 self.assertEqual(program.test, 'tests')
3939 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3940 self.assertEqual(program.verbosity, 2)
3941
3942
Michael Foord5ffa3252010-03-07 22:04:55 +00003943class TestSetups(unittest.TestCase):
3944
3945 def getRunner(self):
3946 return unittest.TextTestRunner(resultclass=resultFactory,
3947 stream=StringIO())
3948 def runTests(self, *cases):
3949 suite = unittest.TestSuite()
3950 for case in cases:
3951 tests = unittest.defaultTestLoader.loadTestsFromTestCase(case)
3952 suite.addTests(tests)
3953
3954 runner = self.getRunner()
3955
3956 # creating a nested suite exposes some potential bugs
3957 realSuite = unittest.TestSuite()
3958 realSuite.addTest(suite)
3959 # adding empty suites to the end exposes potential bugs
3960 suite.addTest(unittest.TestSuite())
3961 realSuite.addTest(unittest.TestSuite())
3962 return runner.run(realSuite)
3963
3964 def test_setup_class(self):
3965 class Test(unittest.TestCase):
3966 setUpCalled = 0
3967 @classmethod
3968 def setUpClass(cls):
3969 Test.setUpCalled += 1
3970 unittest.TestCase.setUpClass()
3971 def test_one(self):
3972 pass
3973 def test_two(self):
3974 pass
3975
3976 result = self.runTests(Test)
3977
3978 self.assertEqual(Test.setUpCalled, 1)
3979 self.assertEqual(result.testsRun, 2)
3980 self.assertEqual(len(result.errors), 0)
3981
3982 def test_teardown_class(self):
3983 class Test(unittest.TestCase):
3984 tearDownCalled = 0
3985 @classmethod
3986 def tearDownClass(cls):
3987 Test.tearDownCalled += 1
3988 unittest.TestCase.tearDownClass()
3989 def test_one(self):
3990 pass
3991 def test_two(self):
3992 pass
3993
3994 result = self.runTests(Test)
3995
3996 self.assertEqual(Test.tearDownCalled, 1)
3997 self.assertEqual(result.testsRun, 2)
3998 self.assertEqual(len(result.errors), 0)
3999
4000 def test_teardown_class_two_classes(self):
4001 class Test(unittest.TestCase):
4002 tearDownCalled = 0
4003 @classmethod
4004 def tearDownClass(cls):
4005 Test.tearDownCalled += 1
4006 unittest.TestCase.tearDownClass()
4007 def test_one(self):
4008 pass
4009 def test_two(self):
4010 pass
4011
4012 class Test2(unittest.TestCase):
4013 tearDownCalled = 0
4014 @classmethod
4015 def tearDownClass(cls):
4016 Test2.tearDownCalled += 1
4017 unittest.TestCase.tearDownClass()
4018 def test_one(self):
4019 pass
4020 def test_two(self):
4021 pass
4022
4023 result = self.runTests(Test, Test2)
4024
4025 self.assertEqual(Test.tearDownCalled, 1)
4026 self.assertEqual(Test2.tearDownCalled, 1)
4027 self.assertEqual(result.testsRun, 4)
4028 self.assertEqual(len(result.errors), 0)
4029
4030 def test_error_in_setupclass(self):
4031 class BrokenTest(unittest.TestCase):
4032 @classmethod
4033 def setUpClass(cls):
4034 raise TypeError('foo')
4035 def test_one(self):
4036 pass
4037 def test_two(self):
4038 pass
4039
4040 result = self.runTests(BrokenTest)
4041
4042 self.assertEqual(result.testsRun, 0)
4043 self.assertEqual(len(result.errors), 1)
4044 error, _ = result.errors[0]
4045 self.assertEqual(str(error),
4046 'classSetUp (%s.BrokenTest)' % __name__)
4047
4048 def test_error_in_teardown_class(self):
4049 class Test(unittest.TestCase):
4050 tornDown = 0
4051 @classmethod
4052 def tearDownClass(cls):
4053 Test.tornDown += 1
4054 raise TypeError('foo')
4055 def test_one(self):
4056 pass
4057 def test_two(self):
4058 pass
4059
4060 class Test2(unittest.TestCase):
4061 tornDown = 0
4062 @classmethod
4063 def tearDownClass(cls):
4064 Test2.tornDown += 1
4065 raise TypeError('foo')
4066 def test_one(self):
4067 pass
4068 def test_two(self):
4069 pass
4070
4071 result = self.runTests(Test, Test2)
4072 self.assertEqual(result.testsRun, 4)
4073 self.assertEqual(len(result.errors), 2)
4074 self.assertEqual(Test.tornDown, 1)
4075 self.assertEqual(Test2.tornDown, 1)
4076
4077 error, _ = result.errors[0]
4078 self.assertEqual(str(error),
4079 'classTearDown (%s.Test)' % __name__)
4080
4081 def test_class_not_torndown_when_setup_fails(self):
4082 class Test(unittest.TestCase):
4083 tornDown = False
4084 @classmethod
4085 def setUpClass(cls):
4086 raise TypeError
4087 @classmethod
4088 def tearDownClass(cls):
4089 Test.tornDown = True
4090 raise TypeError('foo')
4091 def test_one(self):
4092 pass
4093
4094 self.runTests(Test)
4095 self.assertFalse(Test.tornDown)
4096
4097 def test_class_not_setup_or_torndown_when_skipped(self):
4098 class Test(unittest.TestCase):
4099 classSetUp = False
4100 tornDown = False
4101 @classmethod
4102 def setUpClass(cls):
4103 Test.classSetUp = True
4104 @classmethod
4105 def tearDownClass(cls):
4106 Test.tornDown = True
4107 def test_one(self):
4108 pass
4109
4110 Test = unittest.skip("hop")(Test)
4111 self.runTests(Test)
4112 self.assertFalse(Test.classSetUp)
4113 self.assertFalse(Test.tornDown)
4114
4115 def test_setup_teardown_order_with_pathological_suite(self):
4116 results = []
4117
4118 class Module1(object):
4119 @staticmethod
4120 def setUpModule():
4121 results.append('Module1.setUpModule')
4122 @staticmethod
4123 def tearDownModule():
4124 results.append('Module1.tearDownModule')
4125
4126 class Module2(object):
4127 @staticmethod
4128 def setUpModule():
4129 results.append('Module2.setUpModule')
4130 @staticmethod
4131 def tearDownModule():
4132 results.append('Module2.tearDownModule')
4133
4134 class Test1(unittest.TestCase):
4135 @classmethod
4136 def setUpClass(cls):
4137 results.append('setup 1')
4138 @classmethod
4139 def tearDownClass(cls):
4140 results.append('teardown 1')
4141 def testOne(self):
4142 results.append('Test1.testOne')
4143 def testTwo(self):
4144 results.append('Test1.testTwo')
4145
4146 class Test2(unittest.TestCase):
4147 @classmethod
4148 def setUpClass(cls):
4149 results.append('setup 2')
4150 @classmethod
4151 def tearDownClass(cls):
4152 results.append('teardown 2')
4153 def testOne(self):
4154 results.append('Test2.testOne')
4155 def testTwo(self):
4156 results.append('Test2.testTwo')
4157
4158 class Test3(unittest.TestCase):
4159 @classmethod
4160 def setUpClass(cls):
4161 results.append('setup 3')
4162 @classmethod
4163 def tearDownClass(cls):
4164 results.append('teardown 3')
4165 def testOne(self):
4166 results.append('Test3.testOne')
4167 def testTwo(self):
4168 results.append('Test3.testTwo')
4169
4170 Test1.__module__ = Test2.__module__ = 'Module'
4171 Test3.__module__ = 'Module2'
4172 sys.modules['Module'] = Module1
4173 sys.modules['Module2'] = Module2
4174
4175 first = unittest.TestSuite((Test1('testOne'),))
4176 second = unittest.TestSuite((Test1('testTwo'),))
4177 third = unittest.TestSuite((Test2('testOne'),))
4178 fourth = unittest.TestSuite((Test2('testTwo'),))
4179 fifth = unittest.TestSuite((Test3('testOne'),))
4180 sixth = unittest.TestSuite((Test3('testTwo'),))
4181 suite = unittest.TestSuite((first, second, third, fourth, fifth, sixth))
4182
4183 runner = self.getRunner()
4184 result = runner.run(suite)
4185 self.assertEqual(result.testsRun, 6)
4186 self.assertEqual(len(result.errors), 0)
4187
4188 self.assertEqual(results,
4189 ['Module1.setUpModule', 'setup 1',
4190 'Test1.testOne', 'Test1.testTwo', 'teardown 1',
4191 'setup 2', 'Test2.testOne', 'Test2.testTwo',
4192 'teardown 2', 'Module1.tearDownModule',
4193 'Module2.setUpModule', 'setup 3',
4194 'Test3.testOne', 'Test3.testTwo',
4195 'teardown 3', 'Module2.tearDownModule'])
4196
4197 def test_setup_module(self):
4198 class Module(object):
4199 moduleSetup = 0
4200 @staticmethod
4201 def setUpModule():
4202 Module.moduleSetup += 1
4203
4204 class Test(unittest.TestCase):
4205 def test_one(self):
4206 pass
4207 def test_two(self):
4208 pass
4209 Test.__module__ = 'Module'
4210 sys.modules['Module'] = Module
4211
4212 result = self.runTests(Test)
4213 self.assertEqual(Module.moduleSetup, 1)
4214 self.assertEqual(result.testsRun, 2)
4215 self.assertEqual(len(result.errors), 0)
4216
4217 def test_error_in_setup_module(self):
4218 class Module(object):
4219 moduleSetup = 0
4220 moduleTornDown = 0
4221 @staticmethod
4222 def setUpModule():
4223 Module.moduleSetup += 1
4224 raise TypeError('foo')
4225 @staticmethod
4226 def tearDownModule():
4227 Module.moduleTornDown += 1
4228
4229 class Test(unittest.TestCase):
4230 classSetUp = False
4231 classTornDown = False
4232 @classmethod
4233 def setUpClass(cls):
4234 Test.classSetUp = True
4235 @classmethod
4236 def tearDownClass(cls):
4237 Test.classTornDown = True
4238 def test_one(self):
4239 pass
4240 def test_two(self):
4241 pass
4242
4243 class Test2(unittest.TestCase):
4244 def test_one(self):
4245 pass
4246 def test_two(self):
4247 pass
4248 Test.__module__ = 'Module'
4249 Test2.__module__ = 'Module'
4250 sys.modules['Module'] = Module
4251
4252 result = self.runTests(Test, Test2)
4253 self.assertEqual(Module.moduleSetup, 1)
4254 self.assertEqual(Module.moduleTornDown, 0)
4255 self.assertEqual(result.testsRun, 0)
4256 self.assertFalse(Test.classSetUp)
4257 self.assertFalse(Test.classTornDown)
4258 self.assertEqual(len(result.errors), 1)
4259 error, _ = result.errors[0]
4260 self.assertEqual(str(error), 'setUpModule (Module)')
4261
4262 def test_testcase_with_missing_module(self):
4263 class Test(unittest.TestCase):
4264 def test_one(self):
4265 pass
4266 def test_two(self):
4267 pass
4268 Test.__module__ = 'Module'
4269 sys.modules.pop('Module', None)
4270
4271 result = self.runTests(Test)
4272 self.assertEqual(result.testsRun, 2)
4273
4274 def test_teardown_module(self):
4275 class Module(object):
4276 moduleTornDown = 0
4277 @staticmethod
4278 def tearDownModule():
4279 Module.moduleTornDown += 1
4280
4281 class Test(unittest.TestCase):
4282 def test_one(self):
4283 pass
4284 def test_two(self):
4285 pass
4286 Test.__module__ = 'Module'
4287 sys.modules['Module'] = Module
4288
4289 result = self.runTests(Test)
4290 self.assertEqual(Module.moduleTornDown, 1)
4291 self.assertEqual(result.testsRun, 2)
4292 self.assertEqual(len(result.errors), 0)
4293
4294 def test_error_in_teardown_module(self):
4295 class Module(object):
4296 moduleTornDown = 0
4297 @staticmethod
4298 def tearDownModule():
4299 Module.moduleTornDown += 1
4300 raise TypeError('foo')
4301
4302 class Test(unittest.TestCase):
4303 classSetUp = False
4304 classTornDown = False
4305 @classmethod
4306 def setUpClass(cls):
4307 Test.classSetUp = True
4308 @classmethod
4309 def tearDownClass(cls):
4310 Test.classTornDown = True
4311 def test_one(self):
4312 pass
4313 def test_two(self):
4314 pass
4315
4316 class Test2(unittest.TestCase):
4317 def test_one(self):
4318 pass
4319 def test_two(self):
4320 pass
4321 Test.__module__ = 'Module'
4322 Test2.__module__ = 'Module'
4323 sys.modules['Module'] = Module
4324
4325 result = self.runTests(Test, Test2)
4326 self.assertEqual(Module.moduleTornDown, 1)
4327 self.assertEqual(result.testsRun, 4)
4328 self.assertTrue(Test.classSetUp)
4329 self.assertTrue(Test.classTornDown)
4330 self.assertEqual(len(result.errors), 1)
4331 error, _ = result.errors[0]
4332 self.assertEqual(str(error), 'tearDownModule (Module)')
4333
Jim Fultonfafd8742004-08-28 15:22:12 +00004334######################################################################
4335## Main
4336######################################################################
4337
4338def test_main():
Georg Brandl15c5ce92007-03-07 09:09:40 +00004339 test_support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004340 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Michael Foord829f6b82009-05-02 11:43:06 +00004341 Test_TestSkipping, Test_Assertions, TestLongMessage,
Michael Foordae3db0a2010-02-22 23:28:32 +00004342 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner,
Michael Foord5ffa3252010-03-07 22:04:55 +00004343 Test_OldTestResult, TestSetups)
Jim Fultonfafd8742004-08-28 15:22:12 +00004344
Georg Brandl15c5ce92007-03-07 09:09:40 +00004345if __name__ == "__main__":
Tim Petersea5962f2007-03-12 18:07:52 +00004346 test_main()