blob: 5228e764fc07ab9da161bdda6e36dc737a425eac [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()
Michael Foord98e7b762010-03-20 03:00:34 +00002578 self.assertNotEqual(s1, s2)
Gregory P. Smith28399852009-03-31 16:54:10 +00002579 def AllSnakesCreatedEqual(a, b, msg=None):
Michael Foord98e7b762010-03-20 03:00:34 +00002580 return type(a) is type(b) is SadSnake
Gregory P. Smith28399852009-03-31 16:54:10 +00002581 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
Michael Foord98e7b762010-03-20 03:00:34 +00002748 def testAssertItemsEqual(self):
2749 a = object()
2750 self.assertItemsEqual([1, 2, 3], [3, 2, 1])
2751 self.assertItemsEqual(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2752 self.assertItemsEqual([a, a, 2, 2, 3], (a, 2, 3, a, 2))
2753 self.assertItemsEqual([1, "2", "a", "a"], ["a", "2", True, "a"])
2754 self.assertRaises(self.failureException, self.assertItemsEqual,
2755 [1, 2] + [3] * 100, [1] * 100 + [2, 3])
2756 self.assertRaises(self.failureException, self.assertItemsEqual,
2757 [1, "2", "a", "a"], ["a", "2", True, 1])
2758 self.assertRaises(self.failureException, self.assertItemsEqual,
Gregory P. Smith28399852009-03-31 16:54:10 +00002759 [10], [10, 11])
Michael Foord98e7b762010-03-20 03:00:34 +00002760 self.assertRaises(self.failureException, self.assertItemsEqual,
Gregory P. Smith28399852009-03-31 16:54:10 +00002761 [10, 11], [10])
Michael Foord98e7b762010-03-20 03:00:34 +00002762 self.assertRaises(self.failureException, self.assertItemsEqual,
2763 [10, 11, 10], [10, 11])
Gregory P. Smith28399852009-03-31 16:54:10 +00002764
2765 # Test that sequences of unhashable objects can be tested for sameness:
Michael Foord98e7b762010-03-20 03:00:34 +00002766 self.assertItemsEqual([[1, 2], [3, 4], 0], [False, [3, 4], [1, 2]])
2767 with test_support.check_warnings(quiet=True) as w:
2768 # hashable types, but not orderable
2769 self.assertRaises(self.failureException, self.assertItemsEqual,
2770 [], [divmod, 'x', 1, 5j, 2j, frozenset()])
2771 # comparing dicts raises a py3k warning
2772 self.assertItemsEqual([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2773 # comparing heterogenous non-hashable sequences raises a py3k warning
2774 self.assertItemsEqual([1, 'x', divmod, []], [divmod, [], 'x', 1])
2775 self.assertRaises(self.failureException, self.assertItemsEqual,
2776 [], [divmod, [], 'x', 1, 5j, 2j, set()])
2777 # fail the test if warnings are not silenced
2778 if w.warnings:
2779 self.fail('assertItemsEqual raised a warning: ' +
2780 str(w.warnings[0]))
2781 self.assertRaises(self.failureException, self.assertItemsEqual,
Gregory P. Smith28399852009-03-31 16:54:10 +00002782 [[1]], [[2]])
2783
Michael Foord98e7b762010-03-20 03:00:34 +00002784 # Same elements, but not same sequence length
2785 self.assertRaises(self.failureException, self.assertItemsEqual,
2786 [1, 1, 2], [2, 1])
2787 self.assertRaises(self.failureException, self.assertItemsEqual,
2788 [1, 1, "2", "a", "a"], ["2", "2", True, "a"])
2789 self.assertRaises(self.failureException, self.assertItemsEqual,
2790 [1, {'b': 2}, None, True], [{'b': 2}, True, None])
2791
2792
Gregory P. Smith28399852009-03-31 16:54:10 +00002793 def testAssertSetEqual(self):
2794 set1 = set()
2795 set2 = set()
2796 self.assertSetEqual(set1, set2)
2797
2798 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2799 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2800 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2801 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2802
2803 set1 = set(['a'])
2804 set2 = set()
2805 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2806
2807 set1 = set(['a'])
2808 set2 = set(['a'])
2809 self.assertSetEqual(set1, set2)
2810
2811 set1 = set(['a'])
2812 set2 = set(['a', 'b'])
2813 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2814
2815 set1 = set(['a'])
2816 set2 = frozenset(['a', 'b'])
2817 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2818
2819 set1 = set(['a', 'b'])
2820 set2 = frozenset(['a', 'b'])
2821 self.assertSetEqual(set1, set2)
2822
2823 set1 = set()
2824 set2 = "foo"
2825 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2826 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2827
2828 # make sure any string formatting is tuple-safe
2829 set1 = set([(0, 1), (2, 3)])
2830 set2 = set([(4, 5)])
2831 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2832
2833 def testInequality(self):
2834 # Try ints
2835 self.assertGreater(2, 1)
2836 self.assertGreaterEqual(2, 1)
2837 self.assertGreaterEqual(1, 1)
2838 self.assertLess(1, 2)
2839 self.assertLessEqual(1, 2)
2840 self.assertLessEqual(1, 1)
2841 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2842 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2843 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2844 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2845 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2846 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2847
2848 # Try Floats
2849 self.assertGreater(1.1, 1.0)
2850 self.assertGreaterEqual(1.1, 1.0)
2851 self.assertGreaterEqual(1.0, 1.0)
2852 self.assertLess(1.0, 1.1)
2853 self.assertLessEqual(1.0, 1.1)
2854 self.assertLessEqual(1.0, 1.0)
2855 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2856 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2857 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2858 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2859 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2860 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2861
2862 # Try Strings
2863 self.assertGreater('bug', 'ant')
2864 self.assertGreaterEqual('bug', 'ant')
2865 self.assertGreaterEqual('ant', 'ant')
2866 self.assertLess('ant', 'bug')
2867 self.assertLessEqual('ant', 'bug')
2868 self.assertLessEqual('ant', 'ant')
2869 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2870 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2871 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2872 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2873 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2874 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2875
2876 # Try Unicode
2877 self.assertGreater(u'bug', u'ant')
2878 self.assertGreaterEqual(u'bug', u'ant')
2879 self.assertGreaterEqual(u'ant', u'ant')
2880 self.assertLess(u'ant', u'bug')
2881 self.assertLessEqual(u'ant', u'bug')
2882 self.assertLessEqual(u'ant', u'ant')
2883 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug')
2884 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant')
2885 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2886 u'bug')
2887 self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant')
2888 self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant')
2889 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant')
2890
2891 # Try Mixed String/Unicode
2892 self.assertGreater('bug', u'ant')
2893 self.assertGreater(u'bug', 'ant')
2894 self.assertGreaterEqual('bug', u'ant')
2895 self.assertGreaterEqual(u'bug', 'ant')
2896 self.assertGreaterEqual('ant', u'ant')
2897 self.assertGreaterEqual(u'ant', 'ant')
2898 self.assertLess('ant', u'bug')
2899 self.assertLess(u'ant', 'bug')
2900 self.assertLessEqual('ant', u'bug')
2901 self.assertLessEqual(u'ant', 'bug')
2902 self.assertLessEqual('ant', u'ant')
2903 self.assertLessEqual(u'ant', 'ant')
2904 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug')
2905 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug')
2906 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant')
2907 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant')
2908 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant',
2909 u'bug')
2910 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2911 'bug')
2912 self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant')
2913 self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant')
2914 self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant')
2915 self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant')
2916 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant')
2917 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant')
2918
2919 def testAssertMultiLineEqual(self):
2920 sample_text = b"""\
2921http://www.python.org/doc/2.3/lib/module-unittest.html
2922test case
2923 A test case is the smallest unit of testing. [...]
2924"""
2925 revised_sample_text = b"""\
2926http://www.python.org/doc/2.4.1/lib/module-unittest.html
2927test case
2928 A test case is the smallest unit of testing. [...] You may provide your
2929 own implementation that does not subclass from TestCase, of course.
2930"""
2931 sample_text_error = b"""
2932- http://www.python.org/doc/2.3/lib/module-unittest.html
2933? ^
2934+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2935? ^^^
2936 test case
2937- A test case is the smallest unit of testing. [...]
2938+ A test case is the smallest unit of testing. [...] You may provide your
2939? +++++++++++++++++++++
2940+ own implementation that does not subclass from TestCase, of course.
2941"""
2942
2943 for type_changer in (lambda x: x, lambda x: x.decode('utf8')):
2944 try:
2945 self.assertMultiLineEqual(type_changer(sample_text),
2946 type_changer(revised_sample_text))
2947 except self.failureException, e:
Michael Foordfe6349c2010-02-08 22:41:16 +00002948 # assertMultiLineEqual is hooked up as the default for
2949 # unicode strings - so we can't use it for this check
2950 self.assertTrue(sample_text_error == str(e).encode('utf8'))
Gregory P. Smith28399852009-03-31 16:54:10 +00002951
2952 def testAssertIsNone(self):
2953 self.assertIsNone(None)
2954 self.assertRaises(self.failureException, self.assertIsNone, False)
2955 self.assertIsNotNone('DjZoPloGears on Rails')
2956 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2957
2958 def testAssertRegexpMatches(self):
2959 self.assertRegexpMatches('asdfabasdf', r'ab+')
2960 self.assertRaises(self.failureException, self.assertRegexpMatches,
2961 'saaas', r'aaaa')
2962
2963 def testAssertRaisesRegexp(self):
2964 class ExceptionMock(Exception):
2965 pass
2966
2967 def Stub():
2968 raise ExceptionMock('We expect')
2969
2970 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2971 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2972 self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
2973
2974 def testAssertNotRaisesRegexp(self):
2975 self.assertRaisesRegexp(
2976 self.failureException, '^Exception not raised$',
2977 self.assertRaisesRegexp, Exception, re.compile('x'),
2978 lambda: None)
2979 self.assertRaisesRegexp(
2980 self.failureException, '^Exception not raised$',
2981 self.assertRaisesRegexp, Exception, 'x',
2982 lambda: None)
2983 self.assertRaisesRegexp(
2984 self.failureException, '^Exception not raised$',
2985 self.assertRaisesRegexp, Exception, u'x',
2986 lambda: None)
2987
2988 def testAssertRaisesRegexpMismatch(self):
2989 def Stub():
2990 raise Exception('Unexpected')
2991
2992 self.assertRaisesRegexp(
2993 self.failureException,
2994 r'"\^Expected\$" does not match "Unexpected"',
2995 self.assertRaisesRegexp, Exception, '^Expected$',
2996 Stub)
2997 self.assertRaisesRegexp(
2998 self.failureException,
2999 r'"\^Expected\$" does not match "Unexpected"',
3000 self.assertRaisesRegexp, Exception, u'^Expected$',
3001 Stub)
3002 self.assertRaisesRegexp(
3003 self.failureException,
3004 r'"\^Expected\$" does not match "Unexpected"',
3005 self.assertRaisesRegexp, Exception,
3006 re.compile('^Expected$'), Stub)
3007
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00003008 def testAssertRaisesExcValue(self):
3009 class ExceptionMock(Exception):
3010 pass
3011
3012 def Stub(foo):
3013 raise ExceptionMock(foo)
3014 v = "particular value"
3015
3016 ctx = self.assertRaises(ExceptionMock)
3017 with ctx:
3018 Stub(v)
Georg Brandldc3694b2010-02-07 17:02:22 +00003019 e = ctx.exception
Ezio Melottib0f5adc2010-01-24 16:58:36 +00003020 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00003021 self.assertEqual(e.args[0], v)
3022
Gregory P. Smith7558d572009-03-31 19:03:28 +00003023 def testSynonymAssertMethodNames(self):
3024 """Test undocumented method name synonyms.
3025
3026 Please do not use these methods names in your own code.
3027
3028 This test confirms their continued existence and functionality
3029 in order to avoid breaking existing code.
3030 """
3031 self.assertNotEquals(3, 5)
3032 self.assertEquals(3, 3)
3033 self.assertAlmostEquals(2.0, 2.0)
3034 self.assertNotAlmostEquals(3.0, 5.0)
3035 self.assert_(True)
3036
3037 def testPendingDeprecationMethodNames(self):
3038 """Test fail* methods pending deprecation, they will warn in 3.2.
3039
3040 Do not use these methods. They will go away in 3.3.
3041 """
Michael Foord98e7b762010-03-20 03:00:34 +00003042 with test_support.check_warnings():
3043 self.failIfEqual(3, 5)
3044 self.failUnlessEqual(3, 3)
3045 self.failUnlessAlmostEqual(2.0, 2.0)
3046 self.failIfAlmostEqual(3.0, 5.0)
3047 self.failUnless(True)
3048 self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam')
3049 self.failIf(False)
Gregory P. Smith7558d572009-03-31 19:03:28 +00003050
Michael Foorde2942d02009-04-02 05:51:54 +00003051 def testDeepcopy(self):
3052 # Issue: 5660
3053 class TestableTest(TestCase):
3054 def testNothing(self):
3055 pass
3056
3057 test = TestableTest('testNothing')
3058
3059 # This shouldn't blow up
3060 deepcopy(test)
3061
Benjamin Peterson692428e2009-03-23 21:50:21 +00003062
3063class Test_TestSkipping(TestCase):
3064
3065 def test_skipping(self):
3066 class Foo(unittest.TestCase):
3067 def test_skip_me(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00003068 self.skipTest("skip")
Benjamin Peterson692428e2009-03-23 21:50:21 +00003069 events = []
3070 result = LoggingResult(events)
3071 test = Foo("test_skip_me")
3072 test.run(result)
3073 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3074 self.assertEqual(result.skipped, [(test, "skip")])
3075
3076 # Try letting setUp skip the test now.
3077 class Foo(unittest.TestCase):
3078 def setUp(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00003079 self.skipTest("testing")
Benjamin Peterson692428e2009-03-23 21:50:21 +00003080 def test_nothing(self): pass
3081 events = []
3082 result = LoggingResult(events)
3083 test = Foo("test_nothing")
3084 test.run(result)
3085 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3086 self.assertEqual(result.skipped, [(test, "testing")])
3087 self.assertEqual(result.testsRun, 1)
3088
3089 def test_skipping_decorators(self):
3090 op_table = ((unittest.skipUnless, False, True),
3091 (unittest.skipIf, True, False))
3092 for deco, do_skip, dont_skip in op_table:
3093 class Foo(unittest.TestCase):
3094 @deco(do_skip, "testing")
3095 def test_skip(self): pass
3096
3097 @deco(dont_skip, "testing")
3098 def test_dont_skip(self): pass
3099 test_do_skip = Foo("test_skip")
3100 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003101 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003102 events = []
3103 result = LoggingResult(events)
3104 suite.run(result)
3105 self.assertEqual(len(result.skipped), 1)
3106 expected = ['startTest', 'addSkip', 'stopTest',
3107 'startTest', 'addSuccess', 'stopTest']
3108 self.assertEqual(events, expected)
3109 self.assertEqual(result.testsRun, 2)
3110 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
3111 self.assertTrue(result.wasSuccessful())
3112
3113 def test_skip_class(self):
3114 @unittest.skip("testing")
3115 class Foo(unittest.TestCase):
3116 def test_1(self):
3117 record.append(1)
3118 record = []
3119 result = unittest.TestResult()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003120 test = Foo("test_1")
3121 suite = unittest.TestSuite([test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003122 suite.run(result)
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003123 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003124 self.assertEqual(record, [])
3125
3126 def test_expected_failure(self):
3127 class Foo(unittest.TestCase):
3128 @unittest.expectedFailure
3129 def test_die(self):
3130 self.fail("help me!")
3131 events = []
3132 result = LoggingResult(events)
3133 test = Foo("test_die")
3134 test.run(result)
3135 self.assertEqual(events,
3136 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003137 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00003138 self.assertTrue(result.wasSuccessful())
3139
3140 def test_unexpected_success(self):
3141 class Foo(unittest.TestCase):
3142 @unittest.expectedFailure
3143 def test_die(self):
3144 pass
3145 events = []
3146 result = LoggingResult(events)
3147 test = Foo("test_die")
3148 test.run(result)
3149 self.assertEqual(events,
3150 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3151 self.assertFalse(result.failures)
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003152 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003153 self.assertTrue(result.wasSuccessful())
3154
Michael Foord53e8eea2010-03-07 20:22:12 +00003155 def test_skip_doesnt_run_setup(self):
3156 class Foo(unittest.TestCase):
3157 wasSetUp = False
3158 wasTornDown = False
3159 def setUp(self):
3160 Foo.wasSetUp = True
3161 def tornDown(self):
3162 Foo.wasTornDown = True
3163 @unittest.skip('testing')
3164 def test_1(self):
3165 pass
3166
3167 result = unittest.TestResult()
3168 test = Foo("test_1")
3169 suite = unittest.TestSuite([test])
3170 suite.run(result)
3171 self.assertEqual(result.skipped, [(test, "testing")])
3172 self.assertFalse(Foo.wasSetUp)
3173 self.assertFalse(Foo.wasTornDown)
3174
3175 def test_decorated_skip(self):
3176 def decorator(func):
3177 def inner(*a):
3178 return func(*a)
3179 return inner
3180
3181 class Foo(unittest.TestCase):
3182 @decorator
3183 @unittest.skip('testing')
3184 def test_1(self):
3185 pass
3186
3187 result = unittest.TestResult()
3188 test = Foo("test_1")
3189 suite = unittest.TestSuite([test])
3190 suite.run(result)
3191 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003192
3193
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003194class Test_Assertions(TestCase):
3195 def test_AlmostEqual(self):
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003196 self.assertAlmostEqual(1.00000001, 1.0)
3197 self.assertNotAlmostEqual(1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003198 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003199 self.assertAlmostEqual, 1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003200 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003201 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003202
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003203 self.assertAlmostEqual(1.1, 1.0, places=0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003204 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003205 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003206
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003207 self.assertAlmostEqual(0, .1+.1j, places=0)
3208 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003209 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003210 self.assertAlmostEqual, 0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003211 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003212 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003213
Michael Foordc3f79372009-09-13 16:40:02 +00003214 self.assertAlmostEqual(float('inf'), float('inf'))
3215 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3216 float('inf'), float('inf'))
3217
3218
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003219 def test_assertRaises(self):
3220 def _raise(e):
3221 raise e
3222 self.assertRaises(KeyError, _raise, KeyError)
3223 self.assertRaises(KeyError, _raise, KeyError("key"))
3224 try:
3225 self.assertRaises(KeyError, lambda: None)
Gregory P. Smith28399852009-03-31 16:54:10 +00003226 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003227 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003228 else:
3229 self.fail("assertRaises() didn't fail")
3230 try:
3231 self.assertRaises(KeyError, _raise, ValueError)
3232 except ValueError:
3233 pass
3234 else:
3235 self.fail("assertRaises() didn't let exception pass through")
Michael Foord2bd52dc2010-02-07 18:44:12 +00003236 with self.assertRaises(KeyError) as cm:
3237 try:
3238 raise KeyError
3239 except Exception, e:
3240 raise
3241 self.assertIs(cm.exception, e)
3242
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003243 with self.assertRaises(KeyError):
3244 raise KeyError("key")
3245 try:
3246 with self.assertRaises(KeyError):
3247 pass
Gregory P. Smith28399852009-03-31 16:54:10 +00003248 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003249 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003250 else:
3251 self.fail("assertRaises() didn't fail")
3252 try:
3253 with self.assertRaises(KeyError):
3254 raise ValueError
3255 except ValueError:
3256 pass
3257 else:
3258 self.fail("assertRaises() didn't let exception pass through")
3259
3260
Michael Foord345b2fe2009-04-02 03:20:38 +00003261class TestLongMessage(TestCase):
3262 """Test that the individual asserts honour longMessage.
3263 This actually tests all the message behaviour for
3264 asserts that use longMessage."""
3265
3266 def setUp(self):
3267 class TestableTestFalse(TestCase):
3268 longMessage = False
3269 failureException = self.failureException
3270
3271 def testTest(self):
3272 pass
3273
3274 class TestableTestTrue(TestCase):
3275 longMessage = True
3276 failureException = self.failureException
3277
3278 def testTest(self):
3279 pass
3280
3281 self.testableTrue = TestableTestTrue('testTest')
3282 self.testableFalse = TestableTestFalse('testTest')
3283
3284 def testDefault(self):
3285 self.assertFalse(TestCase.longMessage)
3286
3287 def test_formatMsg(self):
3288 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3289 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3290
3291 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3292 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3293
Michael Foord53e8eea2010-03-07 20:22:12 +00003294 # This blows up if _formatMessage uses string concatenation
3295 self.testableTrue._formatMessage(object(), 'foo')
3296
3297 def test_formatMessage_unicode_error(self):
3298 with warnings.catch_warnings(record=True):
3299 # This causes a UnicodeWarning due to its craziness
3300 one = ''.join(chr(i) for i in range(255))
3301 # this used to cause a UnicodeDecodeError constructing msg
3302 self.testableTrue._formatMessage(one, u'\uFFFD')
3303
Michael Foord345b2fe2009-04-02 03:20:38 +00003304 def assertMessages(self, methodName, args, errors):
3305 def getMethod(i):
3306 useTestableFalse = i < 2
3307 if useTestableFalse:
3308 test = self.testableFalse
3309 else:
3310 test = self.testableTrue
3311 return getattr(test, methodName)
3312
3313 for i, expected_regexp in enumerate(errors):
3314 testMethod = getMethod(i)
3315 kwargs = {}
3316 withMsg = i % 2
3317 if withMsg:
3318 kwargs = {"msg": "oops"}
3319
3320 with self.assertRaisesRegexp(self.failureException,
3321 expected_regexp=expected_regexp):
3322 testMethod(*args, **kwargs)
3323
3324 def testAssertTrue(self):
3325 self.assertMessages('assertTrue', (False,),
3326 ["^False is not True$", "^oops$", "^False is not True$",
3327 "^False is not True : oops$"])
3328
3329 def testAssertFalse(self):
3330 self.assertMessages('assertFalse', (True,),
3331 ["^True is not False$", "^oops$", "^True is not False$",
3332 "^True is not False : oops$"])
3333
3334 def testNotEqual(self):
3335 self.assertMessages('assertNotEqual', (1, 1),
3336 ["^1 == 1$", "^oops$", "^1 == 1$",
3337 "^1 == 1 : oops$"])
3338
3339 def testAlmostEqual(self):
3340 self.assertMessages('assertAlmostEqual', (1, 2),
3341 ["^1 != 2 within 7 places$", "^oops$",
3342 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3343
3344 def testNotAlmostEqual(self):
3345 self.assertMessages('assertNotAlmostEqual', (1, 1),
3346 ["^1 == 1 within 7 places$", "^oops$",
3347 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3348
3349 def test_baseAssertEqual(self):
3350 self.assertMessages('_baseAssertEqual', (1, 2),
3351 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3352
3353 def testAssertSequenceEqual(self):
3354 # Error messages are multiline so not testing on full message
3355 # assertTupleEqual and assertListEqual delegate to this method
3356 self.assertMessages('assertSequenceEqual', ([], [None]),
3357 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3358 r"\+ \[None\] : oops$"])
3359
3360 def testAssertSetEqual(self):
3361 self.assertMessages('assertSetEqual', (set(), set([None])),
3362 ["None$", "^oops$", "None$",
3363 "None : oops$"])
3364
3365 def testAssertIn(self):
3366 self.assertMessages('assertIn', (None, []),
3367 ['^None not found in \[\]$', "^oops$",
3368 '^None not found in \[\]$',
3369 '^None not found in \[\] : oops$'])
3370
3371 def testAssertNotIn(self):
3372 self.assertMessages('assertNotIn', (None, [None]),
3373 ['^None unexpectedly found in \[None\]$', "^oops$",
3374 '^None unexpectedly found in \[None\]$',
3375 '^None unexpectedly found in \[None\] : oops$'])
3376
3377 def testAssertDictEqual(self):
3378 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3379 [r"\+ \{'key': 'value'\}$", "^oops$",
3380 "\+ \{'key': 'value'\}$",
3381 "\+ \{'key': 'value'\} : oops$"])
3382
3383 def testAssertDictContainsSubset(self):
3384 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3385 ["^Missing: 'key'$", "^oops$",
3386 "^Missing: 'key'$",
3387 "^Missing: 'key' : oops$"])
3388
Michael Foord98e7b762010-03-20 03:00:34 +00003389 def testAssertItemsEqual(self):
3390 self.assertMessages('assertItemsEqual', ([], [None]),
Michael Foord345b2fe2009-04-02 03:20:38 +00003391 [r"\[None\]$", "^oops$",
3392 r"\[None\]$",
3393 r"\[None\] : oops$"])
3394
3395 def testAssertMultiLineEqual(self):
3396 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3397 [r"\+ foo$", "^oops$",
3398 r"\+ foo$",
3399 r"\+ foo : oops$"])
3400
3401 def testAssertLess(self):
3402 self.assertMessages('assertLess', (2, 1),
3403 ["^2 not less than 1$", "^oops$",
3404 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3405
3406 def testAssertLessEqual(self):
3407 self.assertMessages('assertLessEqual', (2, 1),
3408 ["^2 not less than or equal to 1$", "^oops$",
3409 "^2 not less than or equal to 1$",
3410 "^2 not less than or equal to 1 : oops$"])
3411
3412 def testAssertGreater(self):
3413 self.assertMessages('assertGreater', (1, 2),
3414 ["^1 not greater than 2$", "^oops$",
3415 "^1 not greater than 2$",
3416 "^1 not greater than 2 : oops$"])
3417
3418 def testAssertGreaterEqual(self):
3419 self.assertMessages('assertGreaterEqual', (1, 2),
3420 ["^1 not greater than or equal to 2$", "^oops$",
3421 "^1 not greater than or equal to 2$",
3422 "^1 not greater than or equal to 2 : oops$"])
3423
3424 def testAssertIsNone(self):
3425 self.assertMessages('assertIsNone', ('not None',),
3426 ["^'not None' is not None$", "^oops$",
3427 "^'not None' is not None$",
3428 "^'not None' is not None : oops$"])
3429
3430 def testAssertIsNotNone(self):
3431 self.assertMessages('assertIsNotNone', (None,),
3432 ["^unexpectedly None$", "^oops$",
3433 "^unexpectedly None$",
3434 "^unexpectedly None : oops$"])
3435
Michael Foordf2dfef12009-04-05 19:19:28 +00003436 def testAssertIs(self):
3437 self.assertMessages('assertIs', (None, 'foo'),
3438 ["^None is not 'foo'$", "^oops$",
3439 "^None is not 'foo'$",
3440 "^None is not 'foo' : oops$"])
3441
3442 def testAssertIsNot(self):
3443 self.assertMessages('assertIsNot', (None, None),
3444 ["^unexpectedly identical: None$", "^oops$",
3445 "^unexpectedly identical: None$",
3446 "^unexpectedly identical: None : oops$"])
3447
Michael Foord345b2fe2009-04-02 03:20:38 +00003448
Michael Foorde2fb98f2009-05-02 20:15:05 +00003449class TestCleanUp(TestCase):
3450
3451 def testCleanUp(self):
3452 class TestableTest(TestCase):
3453 def testNothing(self):
3454 pass
3455
3456 test = TestableTest('testNothing')
3457 self.assertEqual(test._cleanups, [])
3458
3459 cleanups = []
3460
3461 def cleanup1(*args, **kwargs):
3462 cleanups.append((1, args, kwargs))
3463
3464 def cleanup2(*args, **kwargs):
3465 cleanups.append((2, args, kwargs))
3466
3467 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3468 test.addCleanup(cleanup2)
3469
3470 self.assertEqual(test._cleanups,
3471 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3472 (cleanup2, (), {})])
3473
3474 result = test.doCleanups()
3475 self.assertTrue(result)
3476
3477 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3478
3479 def testCleanUpWithErrors(self):
3480 class TestableTest(TestCase):
3481 def testNothing(self):
3482 pass
3483
3484 class MockResult(object):
3485 errors = []
3486 def addError(self, test, exc_info):
3487 self.errors.append((test, exc_info))
3488
3489 result = MockResult()
3490 test = TestableTest('testNothing')
Michael Foorda50af062009-05-21 22:57:02 +00003491 test._resultForDoCleanups = result
Michael Foorde2fb98f2009-05-02 20:15:05 +00003492
3493 exc1 = Exception('foo')
3494 exc2 = Exception('bar')
3495 def cleanup1():
3496 raise exc1
3497
3498 def cleanup2():
3499 raise exc2
3500
3501 test.addCleanup(cleanup1)
3502 test.addCleanup(cleanup2)
3503
3504 self.assertFalse(test.doCleanups())
3505
3506 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3507 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3508 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3509
3510 def testCleanupInRun(self):
3511 blowUp = False
3512 ordering = []
3513
3514 class TestableTest(TestCase):
3515 def setUp(self):
3516 ordering.append('setUp')
3517 if blowUp:
3518 raise Exception('foo')
3519
3520 def testNothing(self):
3521 ordering.append('test')
3522
3523 def tearDown(self):
3524 ordering.append('tearDown')
3525
3526 test = TestableTest('testNothing')
3527
3528 def cleanup1():
3529 ordering.append('cleanup1')
3530 def cleanup2():
3531 ordering.append('cleanup2')
3532 test.addCleanup(cleanup1)
3533 test.addCleanup(cleanup2)
3534
3535 def success(some_test):
3536 self.assertEqual(some_test, test)
3537 ordering.append('success')
3538
3539 result = unittest.TestResult()
3540 result.addSuccess = success
3541
3542 test.run(result)
3543 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3544 'cleanup2', 'cleanup1', 'success'])
3545
3546 blowUp = True
3547 ordering = []
3548 test = TestableTest('testNothing')
3549 test.addCleanup(cleanup1)
3550 test.run(result)
3551 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3552
3553
Michael Foord829f6b82009-05-02 11:43:06 +00003554class Test_TestProgram(TestCase):
3555
3556 # Horrible white box test
3557 def testNoExit(self):
3558 result = object()
3559 test = object()
3560
3561 class FakeRunner(object):
3562 def run(self, test):
3563 self.test = test
3564 return result
3565
3566 runner = FakeRunner()
3567
Michael Foord5d31e052009-05-11 17:59:43 +00003568 oldParseArgs = TestProgram.parseArgs
3569 def restoreParseArgs():
Michael Foord829f6b82009-05-02 11:43:06 +00003570 TestProgram.parseArgs = oldParseArgs
Michael Foord5d31e052009-05-11 17:59:43 +00003571 TestProgram.parseArgs = lambda *args: None
3572 self.addCleanup(restoreParseArgs)
3573
3574 def removeTest():
Michael Foord829f6b82009-05-02 11:43:06 +00003575 del TestProgram.test
Michael Foord5d31e052009-05-11 17:59:43 +00003576 TestProgram.test = test
3577 self.addCleanup(removeTest)
3578
3579 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3580
3581 self.assertEqual(program.result, result)
3582 self.assertEqual(runner.test, test)
3583 self.assertEqual(program.verbosity, 2)
Michael Foord829f6b82009-05-02 11:43:06 +00003584
Michael Foord829f6b82009-05-02 11:43:06 +00003585 class FooBar(unittest.TestCase):
3586 def testPass(self):
3587 assert True
3588 def testFail(self):
3589 assert False
3590
3591 class FooBarLoader(unittest.TestLoader):
3592 """Test loader that returns a suite containing FooBar."""
3593 def loadTestsFromModule(self, module):
3594 return self.suiteClass(
3595 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3596
3597
3598 def test_NonExit(self):
3599 program = unittest.main(exit=False,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003600 argv=["foobar"],
3601 testRunner=unittest.TextTestRunner(stream=StringIO()),
3602 testLoader=self.FooBarLoader())
Michael Foord829f6b82009-05-02 11:43:06 +00003603 self.assertTrue(hasattr(program, 'result'))
3604
3605
3606 def test_Exit(self):
3607 self.assertRaises(
3608 SystemExit,
3609 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003610 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003611 testRunner=unittest.TextTestRunner(stream=StringIO()),
3612 exit=True,
3613 testLoader=self.FooBarLoader())
3614
3615
3616 def test_ExitAsDefault(self):
3617 self.assertRaises(
3618 SystemExit,
3619 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003620 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003621 testRunner=unittest.TextTestRunner(stream=StringIO()),
3622 testLoader=self.FooBarLoader())
3623
3624
Michael Foord07ef4872009-05-02 22:43:34 +00003625class Test_TextTestRunner(TestCase):
3626 """Tests for TextTestRunner."""
3627
3628 def test_works_with_result_without_startTestRun_stopTestRun(self):
3629 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3630 separator2 = ''
3631 def printErrors(self):
3632 pass
3633
3634 class Runner(unittest.TextTestRunner):
3635 def __init__(self):
3636 super(Runner, self).__init__(StringIO())
3637
3638 def _makeResult(self):
3639 return OldTextResult()
3640
3641 runner = Runner()
3642 runner.run(unittest.TestSuite())
3643
3644 def test_startTestRun_stopTestRun_called(self):
3645 class LoggingTextResult(LoggingResult):
3646 separator2 = ''
3647 def printErrors(self):
3648 pass
3649
3650 class LoggingRunner(unittest.TextTestRunner):
3651 def __init__(self, events):
3652 super(LoggingRunner, self).__init__(StringIO())
3653 self._events = events
3654
3655 def _makeResult(self):
3656 return LoggingTextResult(self._events)
3657
3658 events = []
3659 runner = LoggingRunner(events)
3660 runner.run(unittest.TestSuite())
3661 expected = ['startTestRun', 'stopTestRun']
3662 self.assertEqual(events, expected)
3663
Antoine Pitrou0734c632009-11-10 20:49:30 +00003664 def test_pickle_unpickle(self):
3665 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3666 # required by test_multiprocessing under Windows (in verbose mode).
3667 import StringIO
3668 # cStringIO objects are not pickleable, but StringIO objects are.
3669 stream = StringIO.StringIO("foo")
3670 runner = unittest.TextTestRunner(stream)
3671 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
3672 s = pickle.dumps(runner, protocol=protocol)
3673 obj = pickle.loads(s)
3674 # StringIO objects never compare equal, a cheap test instead.
3675 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3676
Michael Foorddb43b5a2010-02-10 14:25:12 +00003677 def test_resultclass(self):
3678 def MockResultClass(*args):
3679 return args
3680 STREAM = object()
3681 DESCRIPTIONS = object()
3682 VERBOSITY = object()
3683 runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY,
3684 resultclass=MockResultClass)
3685 self.assertEqual(runner.resultclass, MockResultClass)
3686
3687 expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY)
3688 self.assertEqual(runner._makeResult(), expectedresult)
3689
Michael Foord07ef4872009-05-02 22:43:34 +00003690
Michael Foordb4a81c82009-05-29 20:33:46 +00003691class TestDiscovery(TestCase):
3692
3693 # Heavily mocked tests so I can avoid hitting the filesystem
Michael Foorde91ea562009-09-13 19:07:03 +00003694 def test_get_name_from_path(self):
Michael Foordb4a81c82009-05-29 20:33:46 +00003695 loader = unittest.TestLoader()
3696
Michael Foordb4a81c82009-05-29 20:33:46 +00003697 loader._top_level_dir = '/foo'
Michael Foorde91ea562009-09-13 19:07:03 +00003698 name = loader._get_name_from_path('/foo/bar/baz.py')
3699 self.assertEqual(name, 'bar.baz')
Michael Foordb4a81c82009-05-29 20:33:46 +00003700
3701 if not __debug__:
3702 # asserts are off
3703 return
3704
3705 with self.assertRaises(AssertionError):
Michael Foorde91ea562009-09-13 19:07:03 +00003706 loader._get_name_from_path('/bar/baz.py')
Michael Foordb4a81c82009-05-29 20:33:46 +00003707
3708 def test_find_tests(self):
3709 loader = unittest.TestLoader()
3710
3711 original_listdir = os.listdir
3712 def restore_listdir():
3713 os.listdir = original_listdir
3714 original_isfile = os.path.isfile
3715 def restore_isfile():
3716 os.path.isfile = original_isfile
3717 original_isdir = os.path.isdir
3718 def restore_isdir():
3719 os.path.isdir = original_isdir
3720
3721 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Michael Foorde91ea562009-09-13 19:07:03 +00003722 'test.foo', 'test-not-a-module.py', 'another_dir'],
Michael Foordb4a81c82009-05-29 20:33:46 +00003723 ['test3.py', 'test4.py', ]]
3724 os.listdir = lambda path: path_lists.pop(0)
3725 self.addCleanup(restore_listdir)
3726
3727 def isdir(path):
3728 return path.endswith('dir')
3729 os.path.isdir = isdir
3730 self.addCleanup(restore_isdir)
3731
3732 def isfile(path):
3733 # another_dir is not a package and so shouldn't be recursed into
3734 return not path.endswith('dir') and not 'another_dir' in path
3735 os.path.isfile = isfile
3736 self.addCleanup(restore_isfile)
3737
Michael Foorde91ea562009-09-13 19:07:03 +00003738 loader._get_module_from_name = lambda path: path + ' module'
Michael Foordb4a81c82009-05-29 20:33:46 +00003739 loader.loadTestsFromModule = lambda module: module + ' tests'
3740
3741 loader._top_level_dir = '/foo'
3742 suite = list(loader._find_tests('/foo', 'test*.py'))
3743
Michael Foorde91ea562009-09-13 19:07:03 +00003744 expected = [name + ' module tests' for name in
3745 ('test1', 'test2')]
3746 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3747 ('test3', 'test4')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003748 self.assertEqual(suite, expected)
3749
3750 def test_find_tests_with_package(self):
3751 loader = unittest.TestLoader()
3752
3753 original_listdir = os.listdir
3754 def restore_listdir():
3755 os.listdir = original_listdir
3756 original_isfile = os.path.isfile
3757 def restore_isfile():
3758 os.path.isfile = original_isfile
3759 original_isdir = os.path.isdir
3760 def restore_isdir():
3761 os.path.isdir = original_isdir
3762
3763 directories = ['a_directory', 'test_directory', 'test_directory2']
3764 path_lists = [directories, [], [], []]
3765 os.listdir = lambda path: path_lists.pop(0)
3766 self.addCleanup(restore_listdir)
3767
3768 os.path.isdir = lambda path: True
3769 self.addCleanup(restore_isdir)
3770
3771 os.path.isfile = lambda path: os.path.basename(path) not in directories
3772 self.addCleanup(restore_isfile)
3773
3774 class Module(object):
3775 paths = []
3776 load_tests_args = []
3777
3778 def __init__(self, path):
3779 self.path = path
3780 self.paths.append(path)
3781 if os.path.basename(path) == 'test_directory':
3782 def load_tests(loader, tests, pattern):
3783 self.load_tests_args.append((loader, tests, pattern))
3784 return 'load_tests'
3785 self.load_tests = load_tests
3786
3787 def __eq__(self, other):
3788 return self.path == other.path
3789
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003790 # Silence py3k warning
3791 __hash__ = None
3792
Michael Foorde91ea562009-09-13 19:07:03 +00003793 loader._get_module_from_name = lambda name: Module(name)
Michael Foordb4a81c82009-05-29 20:33:46 +00003794 def loadTestsFromModule(module, use_load_tests):
3795 if use_load_tests:
3796 raise self.failureException('use_load_tests should be False for packages')
3797 return module.path + ' module tests'
3798 loader.loadTestsFromModule = loadTestsFromModule
3799
3800 loader._top_level_dir = '/foo'
3801 # this time no '.py' on the pattern so that it can match
3802 # a test package
3803 suite = list(loader._find_tests('/foo', 'test*'))
3804
3805 # We should have loaded tests from the test_directory package by calling load_tests
3806 # and directly from the test_directory2 package
Michael Foordd53d0852009-06-05 14:14:34 +00003807 self.assertEqual(suite,
Michael Foorde91ea562009-09-13 19:07:03 +00003808 ['load_tests', 'test_directory2' + ' module tests'])
3809 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Michael Foordb4a81c82009-05-29 20:33:46 +00003810
3811 # load_tests should have been called once with loader, tests and pattern
3812 self.assertEqual(Module.load_tests_args,
Michael Foorde91ea562009-09-13 19:07:03 +00003813 [(loader, 'test_directory' + ' module tests', 'test*')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003814
3815 def test_discover(self):
3816 loader = unittest.TestLoader()
3817
3818 original_isfile = os.path.isfile
3819 def restore_isfile():
3820 os.path.isfile = original_isfile
3821
3822 os.path.isfile = lambda path: False
3823 self.addCleanup(restore_isfile)
3824
Nick Coghlanb6edf192009-10-17 08:21:21 +00003825 orig_sys_path = sys.path[:]
3826 def restore_path():
3827 sys.path[:] = orig_sys_path
3828 self.addCleanup(restore_path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003829
Nick Coghlanb6edf192009-10-17 08:21:21 +00003830 full_path = os.path.abspath(os.path.normpath('/foo'))
Michael Foordb4a81c82009-05-29 20:33:46 +00003831 with self.assertRaises(ImportError):
3832 loader.discover('/foo/bar', top_level_dir='/foo')
3833
3834 self.assertEqual(loader._top_level_dir, full_path)
3835 self.assertIn(full_path, sys.path)
3836
3837 os.path.isfile = lambda path: True
3838 _find_tests_args = []
3839 def _find_tests(start_dir, pattern):
3840 _find_tests_args.append((start_dir, pattern))
3841 return ['tests']
3842 loader._find_tests = _find_tests
3843 loader.suiteClass = str
3844
3845 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3846
3847 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3848 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3849 self.assertEqual(suite, "['tests']")
3850 self.assertEqual(loader._top_level_dir, top_level_dir)
3851 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlanb6edf192009-10-17 08:21:21 +00003852 self.assertIn(top_level_dir, sys.path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003853
Michael Foorde91ea562009-09-13 19:07:03 +00003854 def test_discover_with_modules_that_fail_to_import(self):
3855 loader = unittest.TestLoader()
3856
3857 listdir = os.listdir
3858 os.listdir = lambda _: ['test_this_does_not_exist.py']
3859 isfile = os.path.isfile
3860 os.path.isfile = lambda _: True
Nick Coghlanb6edf192009-10-17 08:21:21 +00003861 orig_sys_path = sys.path[:]
Michael Foorde91ea562009-09-13 19:07:03 +00003862 def restore():
3863 os.path.isfile = isfile
3864 os.listdir = listdir
Nick Coghlanb6edf192009-10-17 08:21:21 +00003865 sys.path[:] = orig_sys_path
Michael Foorde91ea562009-09-13 19:07:03 +00003866 self.addCleanup(restore)
3867
3868 suite = loader.discover('.')
Nick Coghlanb6edf192009-10-17 08:21:21 +00003869 self.assertIn(os.getcwd(), sys.path)
Michael Foorde91ea562009-09-13 19:07:03 +00003870 self.assertEqual(suite.countTestCases(), 1)
3871 test = list(list(suite)[0])[0] # extract test from suite
3872
3873 with self.assertRaises(ImportError):
3874 test.test_this_does_not_exist()
3875
Michael Foordb4a81c82009-05-29 20:33:46 +00003876 def test_command_line_handling_parseArgs(self):
3877 # Haha - take that uninstantiable class
3878 program = object.__new__(TestProgram)
3879
3880 args = []
3881 def do_discovery(argv):
3882 args.extend(argv)
3883 program._do_discovery = do_discovery
3884 program.parseArgs(['something', 'discover'])
3885 self.assertEqual(args, [])
3886
3887 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3888 self.assertEqual(args, ['foo', 'bar'])
3889
3890 def test_command_line_handling_do_discovery_too_many_arguments(self):
3891 class Stop(Exception):
3892 pass
3893 def usageExit():
3894 raise Stop
3895
3896 program = object.__new__(TestProgram)
3897 program.usageExit = usageExit
3898
3899 with self.assertRaises(Stop):
3900 # too many args
3901 program._do_discovery(['one', 'two', 'three', 'four'])
3902
3903
3904 def test_command_line_handling_do_discovery_calls_loader(self):
3905 program = object.__new__(TestProgram)
3906
3907 class Loader(object):
3908 args = []
3909 def discover(self, start_dir, pattern, top_level_dir):
3910 self.args.append((start_dir, pattern, top_level_dir))
3911 return 'tests'
3912
3913 program._do_discovery(['-v'], Loader=Loader)
3914 self.assertEqual(program.verbosity, 2)
3915 self.assertEqual(program.test, 'tests')
3916 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3917
3918 Loader.args = []
3919 program = object.__new__(TestProgram)
3920 program._do_discovery(['--verbose'], Loader=Loader)
3921 self.assertEqual(program.test, 'tests')
3922 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3923
3924 Loader.args = []
3925 program = object.__new__(TestProgram)
3926 program._do_discovery([], Loader=Loader)
3927 self.assertEqual(program.test, 'tests')
3928 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3929
3930 Loader.args = []
3931 program = object.__new__(TestProgram)
3932 program._do_discovery(['fish'], Loader=Loader)
3933 self.assertEqual(program.test, 'tests')
3934 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3935
3936 Loader.args = []
3937 program = object.__new__(TestProgram)
3938 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3939 self.assertEqual(program.test, 'tests')
3940 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3941
3942 Loader.args = []
3943 program = object.__new__(TestProgram)
3944 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3945 self.assertEqual(program.test, 'tests')
3946 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3947
3948 Loader.args = []
3949 program = object.__new__(TestProgram)
3950 program._do_discovery(['-s', 'fish'], Loader=Loader)
3951 self.assertEqual(program.test, 'tests')
3952 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3953
3954 Loader.args = []
3955 program = object.__new__(TestProgram)
3956 program._do_discovery(['-t', 'fish'], Loader=Loader)
3957 self.assertEqual(program.test, 'tests')
3958 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3959
3960 Loader.args = []
3961 program = object.__new__(TestProgram)
3962 program._do_discovery(['-p', 'fish'], Loader=Loader)
3963 self.assertEqual(program.test, 'tests')
3964 self.assertEqual(Loader.args, [('.', 'fish', None)])
3965
3966 Loader.args = []
3967 program = object.__new__(TestProgram)
3968 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3969 self.assertEqual(program.test, 'tests')
3970 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3971 self.assertEqual(program.verbosity, 2)
3972
3973
Michael Foord5ffa3252010-03-07 22:04:55 +00003974class TestSetups(unittest.TestCase):
3975
3976 def getRunner(self):
3977 return unittest.TextTestRunner(resultclass=resultFactory,
3978 stream=StringIO())
3979 def runTests(self, *cases):
3980 suite = unittest.TestSuite()
3981 for case in cases:
3982 tests = unittest.defaultTestLoader.loadTestsFromTestCase(case)
3983 suite.addTests(tests)
3984
3985 runner = self.getRunner()
3986
3987 # creating a nested suite exposes some potential bugs
3988 realSuite = unittest.TestSuite()
3989 realSuite.addTest(suite)
3990 # adding empty suites to the end exposes potential bugs
3991 suite.addTest(unittest.TestSuite())
3992 realSuite.addTest(unittest.TestSuite())
3993 return runner.run(realSuite)
3994
3995 def test_setup_class(self):
3996 class Test(unittest.TestCase):
3997 setUpCalled = 0
3998 @classmethod
3999 def setUpClass(cls):
4000 Test.setUpCalled += 1
4001 unittest.TestCase.setUpClass()
4002 def test_one(self):
4003 pass
4004 def test_two(self):
4005 pass
4006
4007 result = self.runTests(Test)
4008
4009 self.assertEqual(Test.setUpCalled, 1)
4010 self.assertEqual(result.testsRun, 2)
4011 self.assertEqual(len(result.errors), 0)
4012
4013 def test_teardown_class(self):
4014 class Test(unittest.TestCase):
4015 tearDownCalled = 0
4016 @classmethod
4017 def tearDownClass(cls):
4018 Test.tearDownCalled += 1
4019 unittest.TestCase.tearDownClass()
4020 def test_one(self):
4021 pass
4022 def test_two(self):
4023 pass
4024
4025 result = self.runTests(Test)
4026
4027 self.assertEqual(Test.tearDownCalled, 1)
4028 self.assertEqual(result.testsRun, 2)
4029 self.assertEqual(len(result.errors), 0)
4030
4031 def test_teardown_class_two_classes(self):
4032 class Test(unittest.TestCase):
4033 tearDownCalled = 0
4034 @classmethod
4035 def tearDownClass(cls):
4036 Test.tearDownCalled += 1
4037 unittest.TestCase.tearDownClass()
4038 def test_one(self):
4039 pass
4040 def test_two(self):
4041 pass
4042
4043 class Test2(unittest.TestCase):
4044 tearDownCalled = 0
4045 @classmethod
4046 def tearDownClass(cls):
4047 Test2.tearDownCalled += 1
4048 unittest.TestCase.tearDownClass()
4049 def test_one(self):
4050 pass
4051 def test_two(self):
4052 pass
4053
4054 result = self.runTests(Test, Test2)
4055
4056 self.assertEqual(Test.tearDownCalled, 1)
4057 self.assertEqual(Test2.tearDownCalled, 1)
4058 self.assertEqual(result.testsRun, 4)
4059 self.assertEqual(len(result.errors), 0)
4060
4061 def test_error_in_setupclass(self):
4062 class BrokenTest(unittest.TestCase):
4063 @classmethod
4064 def setUpClass(cls):
4065 raise TypeError('foo')
4066 def test_one(self):
4067 pass
4068 def test_two(self):
4069 pass
4070
4071 result = self.runTests(BrokenTest)
4072
4073 self.assertEqual(result.testsRun, 0)
4074 self.assertEqual(len(result.errors), 1)
4075 error, _ = result.errors[0]
4076 self.assertEqual(str(error),
4077 'classSetUp (%s.BrokenTest)' % __name__)
4078
4079 def test_error_in_teardown_class(self):
4080 class Test(unittest.TestCase):
4081 tornDown = 0
4082 @classmethod
4083 def tearDownClass(cls):
4084 Test.tornDown += 1
4085 raise TypeError('foo')
4086 def test_one(self):
4087 pass
4088 def test_two(self):
4089 pass
4090
4091 class Test2(unittest.TestCase):
4092 tornDown = 0
4093 @classmethod
4094 def tearDownClass(cls):
4095 Test2.tornDown += 1
4096 raise TypeError('foo')
4097 def test_one(self):
4098 pass
4099 def test_two(self):
4100 pass
4101
4102 result = self.runTests(Test, Test2)
4103 self.assertEqual(result.testsRun, 4)
4104 self.assertEqual(len(result.errors), 2)
4105 self.assertEqual(Test.tornDown, 1)
4106 self.assertEqual(Test2.tornDown, 1)
4107
4108 error, _ = result.errors[0]
4109 self.assertEqual(str(error),
4110 'classTearDown (%s.Test)' % __name__)
4111
4112 def test_class_not_torndown_when_setup_fails(self):
4113 class Test(unittest.TestCase):
4114 tornDown = False
4115 @classmethod
4116 def setUpClass(cls):
4117 raise TypeError
4118 @classmethod
4119 def tearDownClass(cls):
4120 Test.tornDown = True
4121 raise TypeError('foo')
4122 def test_one(self):
4123 pass
4124
4125 self.runTests(Test)
4126 self.assertFalse(Test.tornDown)
4127
4128 def test_class_not_setup_or_torndown_when_skipped(self):
4129 class Test(unittest.TestCase):
4130 classSetUp = False
4131 tornDown = False
4132 @classmethod
4133 def setUpClass(cls):
4134 Test.classSetUp = True
4135 @classmethod
4136 def tearDownClass(cls):
4137 Test.tornDown = True
4138 def test_one(self):
4139 pass
4140
4141 Test = unittest.skip("hop")(Test)
4142 self.runTests(Test)
4143 self.assertFalse(Test.classSetUp)
4144 self.assertFalse(Test.tornDown)
4145
4146 def test_setup_teardown_order_with_pathological_suite(self):
4147 results = []
4148
4149 class Module1(object):
4150 @staticmethod
4151 def setUpModule():
4152 results.append('Module1.setUpModule')
4153 @staticmethod
4154 def tearDownModule():
4155 results.append('Module1.tearDownModule')
4156
4157 class Module2(object):
4158 @staticmethod
4159 def setUpModule():
4160 results.append('Module2.setUpModule')
4161 @staticmethod
4162 def tearDownModule():
4163 results.append('Module2.tearDownModule')
4164
4165 class Test1(unittest.TestCase):
4166 @classmethod
4167 def setUpClass(cls):
4168 results.append('setup 1')
4169 @classmethod
4170 def tearDownClass(cls):
4171 results.append('teardown 1')
4172 def testOne(self):
4173 results.append('Test1.testOne')
4174 def testTwo(self):
4175 results.append('Test1.testTwo')
4176
4177 class Test2(unittest.TestCase):
4178 @classmethod
4179 def setUpClass(cls):
4180 results.append('setup 2')
4181 @classmethod
4182 def tearDownClass(cls):
4183 results.append('teardown 2')
4184 def testOne(self):
4185 results.append('Test2.testOne')
4186 def testTwo(self):
4187 results.append('Test2.testTwo')
4188
4189 class Test3(unittest.TestCase):
4190 @classmethod
4191 def setUpClass(cls):
4192 results.append('setup 3')
4193 @classmethod
4194 def tearDownClass(cls):
4195 results.append('teardown 3')
4196 def testOne(self):
4197 results.append('Test3.testOne')
4198 def testTwo(self):
4199 results.append('Test3.testTwo')
4200
4201 Test1.__module__ = Test2.__module__ = 'Module'
4202 Test3.__module__ = 'Module2'
4203 sys.modules['Module'] = Module1
4204 sys.modules['Module2'] = Module2
4205
4206 first = unittest.TestSuite((Test1('testOne'),))
4207 second = unittest.TestSuite((Test1('testTwo'),))
4208 third = unittest.TestSuite((Test2('testOne'),))
4209 fourth = unittest.TestSuite((Test2('testTwo'),))
4210 fifth = unittest.TestSuite((Test3('testOne'),))
4211 sixth = unittest.TestSuite((Test3('testTwo'),))
4212 suite = unittest.TestSuite((first, second, third, fourth, fifth, sixth))
4213
4214 runner = self.getRunner()
4215 result = runner.run(suite)
4216 self.assertEqual(result.testsRun, 6)
4217 self.assertEqual(len(result.errors), 0)
4218
4219 self.assertEqual(results,
4220 ['Module1.setUpModule', 'setup 1',
4221 'Test1.testOne', 'Test1.testTwo', 'teardown 1',
4222 'setup 2', 'Test2.testOne', 'Test2.testTwo',
4223 'teardown 2', 'Module1.tearDownModule',
4224 'Module2.setUpModule', 'setup 3',
4225 'Test3.testOne', 'Test3.testTwo',
4226 'teardown 3', 'Module2.tearDownModule'])
4227
4228 def test_setup_module(self):
4229 class Module(object):
4230 moduleSetup = 0
4231 @staticmethod
4232 def setUpModule():
4233 Module.moduleSetup += 1
4234
4235 class Test(unittest.TestCase):
4236 def test_one(self):
4237 pass
4238 def test_two(self):
4239 pass
4240 Test.__module__ = 'Module'
4241 sys.modules['Module'] = Module
4242
4243 result = self.runTests(Test)
4244 self.assertEqual(Module.moduleSetup, 1)
4245 self.assertEqual(result.testsRun, 2)
4246 self.assertEqual(len(result.errors), 0)
4247
4248 def test_error_in_setup_module(self):
4249 class Module(object):
4250 moduleSetup = 0
4251 moduleTornDown = 0
4252 @staticmethod
4253 def setUpModule():
4254 Module.moduleSetup += 1
4255 raise TypeError('foo')
4256 @staticmethod
4257 def tearDownModule():
4258 Module.moduleTornDown += 1
4259
4260 class Test(unittest.TestCase):
4261 classSetUp = False
4262 classTornDown = False
4263 @classmethod
4264 def setUpClass(cls):
4265 Test.classSetUp = True
4266 @classmethod
4267 def tearDownClass(cls):
4268 Test.classTornDown = True
4269 def test_one(self):
4270 pass
4271 def test_two(self):
4272 pass
4273
4274 class Test2(unittest.TestCase):
4275 def test_one(self):
4276 pass
4277 def test_two(self):
4278 pass
4279 Test.__module__ = 'Module'
4280 Test2.__module__ = 'Module'
4281 sys.modules['Module'] = Module
4282
4283 result = self.runTests(Test, Test2)
4284 self.assertEqual(Module.moduleSetup, 1)
4285 self.assertEqual(Module.moduleTornDown, 0)
4286 self.assertEqual(result.testsRun, 0)
4287 self.assertFalse(Test.classSetUp)
4288 self.assertFalse(Test.classTornDown)
4289 self.assertEqual(len(result.errors), 1)
4290 error, _ = result.errors[0]
4291 self.assertEqual(str(error), 'setUpModule (Module)')
4292
4293 def test_testcase_with_missing_module(self):
4294 class Test(unittest.TestCase):
4295 def test_one(self):
4296 pass
4297 def test_two(self):
4298 pass
4299 Test.__module__ = 'Module'
4300 sys.modules.pop('Module', None)
4301
4302 result = self.runTests(Test)
4303 self.assertEqual(result.testsRun, 2)
4304
4305 def test_teardown_module(self):
4306 class Module(object):
4307 moduleTornDown = 0
4308 @staticmethod
4309 def tearDownModule():
4310 Module.moduleTornDown += 1
4311
4312 class Test(unittest.TestCase):
4313 def test_one(self):
4314 pass
4315 def test_two(self):
4316 pass
4317 Test.__module__ = 'Module'
4318 sys.modules['Module'] = Module
4319
4320 result = self.runTests(Test)
4321 self.assertEqual(Module.moduleTornDown, 1)
4322 self.assertEqual(result.testsRun, 2)
4323 self.assertEqual(len(result.errors), 0)
4324
4325 def test_error_in_teardown_module(self):
4326 class Module(object):
4327 moduleTornDown = 0
4328 @staticmethod
4329 def tearDownModule():
4330 Module.moduleTornDown += 1
4331 raise TypeError('foo')
4332
4333 class Test(unittest.TestCase):
4334 classSetUp = False
4335 classTornDown = False
4336 @classmethod
4337 def setUpClass(cls):
4338 Test.classSetUp = True
4339 @classmethod
4340 def tearDownClass(cls):
4341 Test.classTornDown = True
4342 def test_one(self):
4343 pass
4344 def test_two(self):
4345 pass
4346
4347 class Test2(unittest.TestCase):
4348 def test_one(self):
4349 pass
4350 def test_two(self):
4351 pass
4352 Test.__module__ = 'Module'
4353 Test2.__module__ = 'Module'
4354 sys.modules['Module'] = Module
4355
4356 result = self.runTests(Test, Test2)
4357 self.assertEqual(Module.moduleTornDown, 1)
4358 self.assertEqual(result.testsRun, 4)
4359 self.assertTrue(Test.classSetUp)
4360 self.assertTrue(Test.classTornDown)
4361 self.assertEqual(len(result.errors), 1)
4362 error, _ = result.errors[0]
4363 self.assertEqual(str(error), 'tearDownModule (Module)')
4364
Jim Fultonfafd8742004-08-28 15:22:12 +00004365######################################################################
4366## Main
4367######################################################################
4368
4369def test_main():
Georg Brandl15c5ce92007-03-07 09:09:40 +00004370 test_support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00004371 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Michael Foord829f6b82009-05-02 11:43:06 +00004372 Test_TestSkipping, Test_Assertions, TestLongMessage,
Michael Foordae3db0a2010-02-22 23:28:32 +00004373 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner,
Michael Foord5ffa3252010-03-07 22:04:55 +00004374 Test_OldTestResult, TestSetups)
Jim Fultonfafd8742004-08-28 15:22:12 +00004375
Georg Brandl15c5ce92007-03-07 09:09:40 +00004376if __name__ == "__main__":
Tim Petersea5962f2007-03-12 18:07:52 +00004377 test_main()