blob: 4e1582cde844cac7cfcf91de1d3a6aa66c656f38 [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
Jim Fultonfafd8742004-08-28 15:22:12 +000019
Georg Brandl15c5ce92007-03-07 09:09:40 +000020### Support code
21################################################################
Jim Fultonfafd8742004-08-28 15:22:12 +000022
Georg Brandl15c5ce92007-03-07 09:09:40 +000023class LoggingResult(unittest.TestResult):
24 def __init__(self, log):
25 self._events = log
26 super(LoggingResult, self).__init__()
27
28 def startTest(self, test):
29 self._events.append('startTest')
30 super(LoggingResult, self).startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +000031
Michael Foord07ef4872009-05-02 22:43:34 +000032 def startTestRun(self):
33 self._events.append('startTestRun')
34 super(LoggingResult, self).startTestRun()
35
Georg Brandl15c5ce92007-03-07 09:09:40 +000036 def stopTest(self, test):
37 self._events.append('stopTest')
38 super(LoggingResult, self).stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +000039
Michael Foord07ef4872009-05-02 22:43:34 +000040 def stopTestRun(self):
41 self._events.append('stopTestRun')
42 super(LoggingResult, self).stopTestRun()
43
Georg Brandl15c5ce92007-03-07 09:09:40 +000044 def addFailure(self, *args):
45 self._events.append('addFailure')
46 super(LoggingResult, self).addFailure(*args)
Tim Petersea5962f2007-03-12 18:07:52 +000047
Benjamin Peterson692428e2009-03-23 21:50:21 +000048 def addSuccess(self, *args):
49 self._events.append('addSuccess')
50 super(LoggingResult, self).addSuccess(*args)
51
Georg Brandl15c5ce92007-03-07 09:09:40 +000052 def addError(self, *args):
53 self._events.append('addError')
54 super(LoggingResult, self).addError(*args)
55
Benjamin Peterson692428e2009-03-23 21:50:21 +000056 def addSkip(self, *args):
57 self._events.append('addSkip')
58 super(LoggingResult, self).addSkip(*args)
59
60 def addExpectedFailure(self, *args):
61 self._events.append('addExpectedFailure')
62 super(LoggingResult, self).addExpectedFailure(*args)
63
64 def addUnexpectedSuccess(self, *args):
65 self._events.append('addUnexpectedSuccess')
66 super(LoggingResult, self).addUnexpectedSuccess(*args)
67
68
Georg Brandl15c5ce92007-03-07 09:09:40 +000069class TestEquality(object):
Michael Foord345b2fe2009-04-02 03:20:38 +000070 """Used as a mixin for TestCase"""
71
Tim Petersea5962f2007-03-12 18:07:52 +000072 # Check for a valid __eq__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000073 def test_eq(self):
74 for obj_1, obj_2 in self.eq_pairs:
75 self.assertEqual(obj_1, obj_2)
76 self.assertEqual(obj_2, obj_1)
Tim Petersea5962f2007-03-12 18:07:52 +000077
78 # Check for a valid __ne__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000079 def test_ne(self):
80 for obj_1, obj_2 in self.ne_pairs:
Benjamin Peterson6b0032f2009-06-30 23:30:12 +000081 self.assertNotEqual(obj_1, obj_2)
82 self.assertNotEqual(obj_2, obj_1)
Tim Petersea5962f2007-03-12 18:07:52 +000083
Georg Brandl15c5ce92007-03-07 09:09:40 +000084class TestHashing(object):
Michael Foord345b2fe2009-04-02 03:20:38 +000085 """Used as a mixin for TestCase"""
86
Tim Petersea5962f2007-03-12 18:07:52 +000087 # Check for a valid __hash__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000088 def test_hash(self):
89 for obj_1, obj_2 in self.eq_pairs:
90 try:
Gregory P. Smith28399852009-03-31 16:54:10 +000091 if not hash(obj_1) == hash(obj_2):
92 self.fail("%r and %r do not hash equal" % (obj_1, obj_2))
Georg Brandl15c5ce92007-03-07 09:09:40 +000093 except KeyboardInterrupt:
94 raise
Georg Brandl15c5ce92007-03-07 09:09:40 +000095 except Exception, e:
Gregory P. Smith28399852009-03-31 16:54:10 +000096 self.fail("Problem hashing %r and %r: %s" % (obj_1, obj_2, e))
Tim Petersea5962f2007-03-12 18:07:52 +000097
Georg Brandl15c5ce92007-03-07 09:09:40 +000098 for obj_1, obj_2 in self.ne_pairs:
99 try:
Gregory P. Smith28399852009-03-31 16:54:10 +0000100 if hash(obj_1) == hash(obj_2):
101 self.fail("%s and %s hash equal, but shouldn't" %
102 (obj_1, obj_2))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000103 except KeyboardInterrupt:
104 raise
Georg Brandl15c5ce92007-03-07 09:09:40 +0000105 except Exception, e:
106 self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e))
Tim Petersea5962f2007-03-12 18:07:52 +0000107
Georg Brandl15c5ce92007-03-07 09:09:40 +0000108
Benjamin Peterson692428e2009-03-23 21:50:21 +0000109# List subclass we can add attributes to.
110class MyClassSuite(list):
111
Benjamin Peterson176a56c2009-05-25 00:48:58 +0000112 def __init__(self, tests):
Benjamin Peterson692428e2009-03-23 21:50:21 +0000113 super(MyClassSuite, self).__init__(tests)
114
115
Georg Brandl15c5ce92007-03-07 09:09:40 +0000116################################################################
117### /Support code
118
119class Test_TestLoader(TestCase):
120
121 ### Tests for TestLoader.loadTestsFromTestCase
122 ################################################################
123
124 # "Return a suite of all tests cases contained in the TestCase-derived
125 # class testCaseClass"
126 def test_loadTestsFromTestCase(self):
127 class Foo(unittest.TestCase):
128 def test_1(self): pass
129 def test_2(self): pass
130 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000131
Georg Brandl15c5ce92007-03-07 09:09:40 +0000132 tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +0000133
Georg Brandl15c5ce92007-03-07 09:09:40 +0000134 loader = unittest.TestLoader()
135 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +0000136
Georg Brandl15c5ce92007-03-07 09:09:40 +0000137 # "Return a suite of all tests cases contained in the TestCase-derived
138 # class testCaseClass"
139 #
Tim Petersea5962f2007-03-12 18:07:52 +0000140 # Make sure it does the right thing even if no tests were found
Georg Brandl15c5ce92007-03-07 09:09:40 +0000141 def test_loadTestsFromTestCase__no_matches(self):
142 class Foo(unittest.TestCase):
143 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000144
Georg Brandl15c5ce92007-03-07 09:09:40 +0000145 empty_suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +0000146
Georg Brandl15c5ce92007-03-07 09:09:40 +0000147 loader = unittest.TestLoader()
148 self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite)
Tim Petersea5962f2007-03-12 18:07:52 +0000149
Georg Brandl15c5ce92007-03-07 09:09:40 +0000150 # "Return a suite of all tests cases contained in the TestCase-derived
151 # class testCaseClass"
152 #
153 # What happens if loadTestsFromTestCase() is given an object
154 # that isn't a subclass of TestCase? Specifically, what happens
155 # if testCaseClass is a subclass of TestSuite?
156 #
157 # This is checked for specifically in the code, so we better add a
158 # test for it.
159 def test_loadTestsFromTestCase__TestSuite_subclass(self):
160 class NotATestCase(unittest.TestSuite):
161 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000162
Georg Brandl15c5ce92007-03-07 09:09:40 +0000163 loader = unittest.TestLoader()
164 try:
165 loader.loadTestsFromTestCase(NotATestCase)
166 except TypeError:
167 pass
168 else:
169 self.fail('Should raise TypeError')
Tim Petersea5962f2007-03-12 18:07:52 +0000170
Georg Brandl15c5ce92007-03-07 09:09:40 +0000171 # "Return a suite of all tests cases contained in the TestCase-derived
172 # class testCaseClass"
173 #
174 # Make sure loadTestsFromTestCase() picks up the default test method
175 # name (as specified by TestCase), even though the method name does
176 # not match the default TestLoader.testMethodPrefix string
177 def test_loadTestsFromTestCase__default_method_name(self):
178 class Foo(unittest.TestCase):
179 def runTest(self):
180 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000181
Georg Brandl15c5ce92007-03-07 09:09:40 +0000182 loader = unittest.TestLoader()
183 # This has to be false for the test to succeed
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000184 self.assertFalse('runTest'.startswith(loader.testMethodPrefix))
Tim Petersea5962f2007-03-12 18:07:52 +0000185
Georg Brandl15c5ce92007-03-07 09:09:40 +0000186 suite = loader.loadTestsFromTestCase(Foo)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000187 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000188 self.assertEqual(list(suite), [Foo('runTest')])
189
190 ################################################################
191 ### /Tests for TestLoader.loadTestsFromTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000192
Georg Brandl15c5ce92007-03-07 09:09:40 +0000193 ### Tests for TestLoader.loadTestsFromModule
194 ################################################################
195
196 # "This method searches `module` for classes derived from TestCase"
197 def test_loadTestsFromModule__TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000198 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000199 class MyTestCase(unittest.TestCase):
200 def test(self):
201 pass
202 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000203
Georg Brandl15c5ce92007-03-07 09:09:40 +0000204 loader = unittest.TestLoader()
205 suite = loader.loadTestsFromModule(m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000206 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000207
Georg Brandl15c5ce92007-03-07 09:09:40 +0000208 expected = [loader.suiteClass([MyTestCase('test')])]
209 self.assertEqual(list(suite), expected)
Tim Petersea5962f2007-03-12 18:07:52 +0000210
Georg Brandl15c5ce92007-03-07 09:09:40 +0000211 # "This method searches `module` for classes derived from TestCase"
Tim Petersea5962f2007-03-12 18:07:52 +0000212 #
Georg Brandl15c5ce92007-03-07 09:09:40 +0000213 # What happens if no tests are found (no TestCase instances)?
214 def test_loadTestsFromModule__no_TestCase_instances(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000215 m = types.ModuleType('m')
Tim Petersea5962f2007-03-12 18:07:52 +0000216
Georg Brandl15c5ce92007-03-07 09:09:40 +0000217 loader = unittest.TestLoader()
218 suite = loader.loadTestsFromModule(m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000219 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000220 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000221
Georg Brandl15c5ce92007-03-07 09:09:40 +0000222 # "This method searches `module` for classes derived from TestCase"
223 #
Tim Petersea5962f2007-03-12 18:07:52 +0000224 # What happens if no tests are found (TestCases instances, but no tests)?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000225 def test_loadTestsFromModule__no_TestCase_tests(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000226 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000227 class MyTestCase(unittest.TestCase):
228 pass
229 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000230
Georg Brandl15c5ce92007-03-07 09:09:40 +0000231 loader = unittest.TestLoader()
232 suite = loader.loadTestsFromModule(m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000233 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000234
Georg Brandl15c5ce92007-03-07 09:09:40 +0000235 self.assertEqual(list(suite), [loader.suiteClass()])
Tim Petersea5962f2007-03-12 18:07:52 +0000236
Georg Brandl15c5ce92007-03-07 09:09:40 +0000237 # "This method searches `module` for classes derived from TestCase"s
238 #
239 # What happens if loadTestsFromModule() is given something other
240 # than a module?
241 #
242 # XXX Currently, it succeeds anyway. This flexibility
243 # should either be documented or loadTestsFromModule() should
244 # raise a TypeError
245 #
246 # XXX Certain people are using this behaviour. We'll add a test for it
247 def test_loadTestsFromModule__not_a_module(self):
248 class MyTestCase(unittest.TestCase):
249 def test(self):
250 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000251
Georg Brandl15c5ce92007-03-07 09:09:40 +0000252 class NotAModule(object):
253 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000254
Georg Brandl15c5ce92007-03-07 09:09:40 +0000255 loader = unittest.TestLoader()
256 suite = loader.loadTestsFromModule(NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000257
Georg Brandl15c5ce92007-03-07 09:09:40 +0000258 reference = [unittest.TestSuite([MyTestCase('test')])]
259 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000260
Michael Foordb4a81c82009-05-29 20:33:46 +0000261
262 # Check that loadTestsFromModule honors (or not) a module
263 # with a load_tests function.
264 def test_loadTestsFromModule__load_tests(self):
265 m = types.ModuleType('m')
266 class MyTestCase(unittest.TestCase):
267 def test(self):
268 pass
269 m.testcase_1 = MyTestCase
270
271 load_tests_args = []
272 def load_tests(loader, tests, pattern):
Michael Foord08770602010-02-06 00:22:26 +0000273 self.assertIsInstance(tests, unittest.TestSuite)
Michael Foordb4a81c82009-05-29 20:33:46 +0000274 load_tests_args.extend((loader, tests, pattern))
275 return tests
276 m.load_tests = load_tests
277
278 loader = unittest.TestLoader()
279 suite = loader.loadTestsFromModule(m)
Michael Foord08770602010-02-06 00:22:26 +0000280 self.assertIsInstance(suite, unittest.TestSuite)
Michael Foordb4a81c82009-05-29 20:33:46 +0000281 self.assertEquals(load_tests_args, [loader, suite, None])
282
283 load_tests_args = []
284 suite = loader.loadTestsFromModule(m, use_load_tests=False)
285 self.assertEquals(load_tests_args, [])
286
Georg Brandl15c5ce92007-03-07 09:09:40 +0000287 ################################################################
288 ### /Tests for TestLoader.loadTestsFromModule()
Tim Petersea5962f2007-03-12 18:07:52 +0000289
Georg Brandl15c5ce92007-03-07 09:09:40 +0000290 ### Tests for TestLoader.loadTestsFromName()
291 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000292
Georg Brandl15c5ce92007-03-07 09:09:40 +0000293 # "The specifier name is a ``dotted name'' that may resolve either to
294 # a module, a test case class, a TestSuite instance, a test method
295 # within a test case class, or a callable object which returns a
296 # TestCase or TestSuite instance."
297 #
298 # Is ValueError raised in response to an empty name?
299 def test_loadTestsFromName__empty_name(self):
300 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000301
Georg Brandl15c5ce92007-03-07 09:09:40 +0000302 try:
303 loader.loadTestsFromName('')
304 except ValueError, e:
305 self.assertEqual(str(e), "Empty module name")
306 else:
307 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000308
Georg Brandl15c5ce92007-03-07 09:09:40 +0000309 # "The specifier name is a ``dotted name'' that may resolve either to
310 # a module, a test case class, a TestSuite instance, a test method
311 # within a test case class, or a callable object which returns a
312 # TestCase or TestSuite instance."
313 #
Tim Petersea5962f2007-03-12 18:07:52 +0000314 # What happens when the name contains invalid characters?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000315 def test_loadTestsFromName__malformed_name(self):
316 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000317
Georg Brandl15c5ce92007-03-07 09:09:40 +0000318 # XXX Should this raise ValueError or ImportError?
319 try:
320 loader.loadTestsFromName('abc () //')
321 except ValueError:
322 pass
323 except ImportError:
324 pass
325 else:
326 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000327
Georg Brandl15c5ce92007-03-07 09:09:40 +0000328 # "The specifier name is a ``dotted name'' that may resolve ... to a
329 # module"
330 #
Tim Petersea5962f2007-03-12 18:07:52 +0000331 # What happens when a module by that name can't be found?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000332 def test_loadTestsFromName__unknown_module_name(self):
333 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000334
Georg Brandl15c5ce92007-03-07 09:09:40 +0000335 try:
336 loader.loadTestsFromName('sdasfasfasdf')
337 except ImportError, e:
338 self.assertEqual(str(e), "No module named sdasfasfasdf")
339 else:
340 self.fail("TestLoader.loadTestsFromName failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000341
Georg Brandl15c5ce92007-03-07 09:09:40 +0000342 # "The specifier name is a ``dotted name'' that may resolve either to
343 # a module, a test case class, a TestSuite instance, a test method
344 # within a test case class, or a callable object which returns a
345 # TestCase or TestSuite instance."
346 #
Tim Petersea5962f2007-03-12 18:07:52 +0000347 # What happens when the module is found, but the attribute can't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000348 def test_loadTestsFromName__unknown_attr_name(self):
349 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000350
Georg Brandl15c5ce92007-03-07 09:09:40 +0000351 try:
352 loader.loadTestsFromName('unittest.sdasfasfasdf')
353 except AttributeError, e:
354 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
355 else:
356 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000357
Georg Brandl15c5ce92007-03-07 09:09:40 +0000358 # "The specifier name is a ``dotted name'' that may resolve either to
359 # a module, a test case class, a TestSuite instance, a test method
360 # within a test case class, or a callable object which returns a
361 # TestCase or TestSuite instance."
362 #
363 # What happens when we provide the module, but the attribute can't be
364 # found?
365 def test_loadTestsFromName__relative_unknown_name(self):
366 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000367
Georg Brandl15c5ce92007-03-07 09:09:40 +0000368 try:
369 loader.loadTestsFromName('sdasfasfasdf', unittest)
370 except AttributeError, e:
371 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
372 else:
373 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000374
Georg Brandl15c5ce92007-03-07 09:09:40 +0000375 # "The specifier name is a ``dotted name'' that may resolve either to
376 # a module, a test case class, a TestSuite instance, a test method
377 # within a test case class, or a callable object which returns a
378 # TestCase or TestSuite instance."
379 # ...
380 # "The method optionally resolves name relative to the given module"
381 #
382 # Does loadTestsFromName raise ValueError when passed an empty
383 # name relative to a provided module?
384 #
385 # XXX Should probably raise a ValueError instead of an AttributeError
386 def test_loadTestsFromName__relative_empty_name(self):
387 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000388
Georg Brandl15c5ce92007-03-07 09:09:40 +0000389 try:
390 loader.loadTestsFromName('', unittest)
391 except AttributeError, e:
392 pass
393 else:
394 self.fail("Failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000395
Georg Brandl15c5ce92007-03-07 09:09:40 +0000396 # "The specifier name is a ``dotted name'' that may resolve either to
397 # a module, a test case class, a TestSuite instance, a test method
398 # within a test case class, or a callable object which returns a
399 # TestCase or TestSuite instance."
400 # ...
401 # "The method optionally resolves name relative to the given module"
402 #
403 # What happens when an impossible name is given, relative to the provided
404 # `module`?
405 def test_loadTestsFromName__relative_malformed_name(self):
406 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000407
Georg Brandl15c5ce92007-03-07 09:09:40 +0000408 # XXX Should this raise AttributeError or ValueError?
409 try:
410 loader.loadTestsFromName('abc () //', unittest)
411 except ValueError:
412 pass
413 except AttributeError:
414 pass
415 else:
416 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
417
418 # "The method optionally resolves name relative to the given module"
419 #
420 # Does loadTestsFromName raise TypeError when the `module` argument
421 # isn't a module object?
422 #
423 # XXX Accepts the not-a-module object, ignorning the object's type
424 # This should raise an exception or the method name should be changed
425 #
426 # XXX Some people are relying on this, so keep it for now
427 def test_loadTestsFromName__relative_not_a_module(self):
428 class MyTestCase(unittest.TestCase):
429 def test(self):
430 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000431
Georg Brandl15c5ce92007-03-07 09:09:40 +0000432 class NotAModule(object):
433 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000434
Georg Brandl15c5ce92007-03-07 09:09:40 +0000435 loader = unittest.TestLoader()
436 suite = loader.loadTestsFromName('test_2', NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000437
Georg Brandl15c5ce92007-03-07 09:09:40 +0000438 reference = [MyTestCase('test')]
439 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000440
Georg Brandl15c5ce92007-03-07 09:09:40 +0000441 # "The specifier name is a ``dotted name'' that may resolve either to
442 # a module, a test case class, a TestSuite instance, a test method
443 # within a test case class, or a callable object which returns a
444 # TestCase or TestSuite instance."
445 #
446 # Does it raise an exception if the name resolves to an invalid
447 # object?
448 def test_loadTestsFromName__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000449 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000450 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000451
Georg Brandl15c5ce92007-03-07 09:09:40 +0000452 loader = unittest.TestLoader()
453 try:
454 loader.loadTestsFromName('testcase_1', m)
455 except TypeError:
456 pass
457 else:
458 self.fail("Should have raised TypeError")
459
460 # "The specifier name is a ``dotted name'' that may
461 # resolve either to ... a test case class"
462 def test_loadTestsFromName__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000463 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000464 class MyTestCase(unittest.TestCase):
465 def test(self):
466 pass
467 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000468
Georg Brandl15c5ce92007-03-07 09:09:40 +0000469 loader = unittest.TestLoader()
470 suite = loader.loadTestsFromName('testcase_1', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000471 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000472 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000473
Georg Brandl15c5ce92007-03-07 09:09:40 +0000474 # "The specifier name is a ``dotted name'' that may resolve either to
475 # a module, a test case class, a TestSuite instance, a test method
476 # within a test case class, or a callable object which returns a
477 # TestCase or TestSuite instance."
478 def test_loadTestsFromName__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000479 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000480 class MyTestCase(unittest.TestCase):
481 def test(self):
482 pass
483 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000484
Georg Brandl15c5ce92007-03-07 09:09:40 +0000485 loader = unittest.TestLoader()
486 suite = loader.loadTestsFromName('testsuite', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000487 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000488
Georg Brandl15c5ce92007-03-07 09:09:40 +0000489 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000490
Georg Brandl15c5ce92007-03-07 09:09:40 +0000491 # "The specifier name is a ``dotted name'' that may resolve ... to
492 # ... a test method within a test case class"
493 def test_loadTestsFromName__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000494 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000495 class MyTestCase(unittest.TestCase):
496 def test(self):
497 pass
498 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000499
Georg Brandl15c5ce92007-03-07 09:09:40 +0000500 loader = unittest.TestLoader()
501 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000502 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000503
Georg Brandl15c5ce92007-03-07 09:09:40 +0000504 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000505
Georg Brandl15c5ce92007-03-07 09:09:40 +0000506 # "The specifier name is a ``dotted name'' that may resolve either to
507 # a module, a test case class, a TestSuite instance, a test method
508 # within a test case class, or a callable object which returns a
509 # TestCase or TestSuite instance."
510 #
511 # Does loadTestsFromName() raise the proper exception when trying to
512 # resolve "a test method within a test case class" that doesn't exist
513 # for the given name (relative to a provided module)?
514 def test_loadTestsFromName__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000515 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000516 class MyTestCase(unittest.TestCase):
517 def test(self):
518 pass
519 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000520
Georg Brandl15c5ce92007-03-07 09:09:40 +0000521 loader = unittest.TestLoader()
522 try:
523 loader.loadTestsFromName('testcase_1.testfoo', m)
524 except AttributeError, e:
525 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
526 else:
527 self.fail("Failed to raise AttributeError")
528
529 # "The specifier name is a ``dotted name'' that may resolve ... to
530 # ... a callable object which returns a ... TestSuite instance"
531 def test_loadTestsFromName__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000532 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000533 testcase_1 = unittest.FunctionTestCase(lambda: None)
534 testcase_2 = unittest.FunctionTestCase(lambda: None)
535 def return_TestSuite():
536 return unittest.TestSuite([testcase_1, testcase_2])
537 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000538
Georg Brandl15c5ce92007-03-07 09:09:40 +0000539 loader = unittest.TestLoader()
540 suite = loader.loadTestsFromName('return_TestSuite', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000541 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000542 self.assertEqual(list(suite), [testcase_1, testcase_2])
Tim Petersea5962f2007-03-12 18:07:52 +0000543
Georg Brandl15c5ce92007-03-07 09:09:40 +0000544 # "The specifier name is a ``dotted name'' that may resolve ... to
545 # ... a callable object which returns a TestCase ... instance"
546 def test_loadTestsFromName__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000547 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000548 testcase_1 = unittest.FunctionTestCase(lambda: None)
549 def return_TestCase():
550 return testcase_1
551 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000552
Georg Brandl15c5ce92007-03-07 09:09:40 +0000553 loader = unittest.TestLoader()
554 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000555 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000556 self.assertEqual(list(suite), [testcase_1])
Tim Petersea5962f2007-03-12 18:07:52 +0000557
Georg Brandl15c5ce92007-03-07 09:09:40 +0000558 # "The specifier name is a ``dotted name'' that may resolve ... to
Michael Foord5a9719d2009-09-13 17:28:35 +0000559 # ... a callable object which returns a TestCase ... instance"
560 #*****************************************************************
561 #Override the suiteClass attribute to ensure that the suiteClass
562 #attribute is used
563 def test_loadTestsFromName__callable__TestCase_instance_ProperSuiteClass(self):
564 class SubTestSuite(unittest.TestSuite):
565 pass
566 m = types.ModuleType('m')
567 testcase_1 = unittest.FunctionTestCase(lambda: None)
568 def return_TestCase():
569 return testcase_1
570 m.return_TestCase = return_TestCase
571
572 loader = unittest.TestLoader()
573 loader.suiteClass = SubTestSuite
574 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000575 self.assertIsInstance(suite, loader.suiteClass)
Michael Foord5a9719d2009-09-13 17:28:35 +0000576 self.assertEqual(list(suite), [testcase_1])
577
578 # "The specifier name is a ``dotted name'' that may resolve ... to
579 # ... a test method within a test case class"
580 #*****************************************************************
581 #Override the suiteClass attribute to ensure that the suiteClass
582 #attribute is used
583 def test_loadTestsFromName__relative_testmethod_ProperSuiteClass(self):
584 class SubTestSuite(unittest.TestSuite):
585 pass
586 m = types.ModuleType('m')
587 class MyTestCase(unittest.TestCase):
588 def test(self):
589 pass
590 m.testcase_1 = MyTestCase
591
592 loader = unittest.TestLoader()
593 loader.suiteClass=SubTestSuite
594 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000595 self.assertIsInstance(suite, loader.suiteClass)
Michael Foord5a9719d2009-09-13 17:28:35 +0000596
597 self.assertEqual(list(suite), [MyTestCase('test')])
598
599 # "The specifier name is a ``dotted name'' that may resolve ... to
Georg Brandl15c5ce92007-03-07 09:09:40 +0000600 # ... a callable object which returns a TestCase or TestSuite instance"
601 #
602 # What happens if the callable returns something else?
603 def test_loadTestsFromName__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000604 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000605 def return_wrong():
606 return 6
607 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000608
Georg Brandl15c5ce92007-03-07 09:09:40 +0000609 loader = unittest.TestLoader()
610 try:
611 suite = loader.loadTestsFromName('return_wrong', m)
612 except TypeError:
613 pass
614 else:
615 self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000616
Georg Brandl15c5ce92007-03-07 09:09:40 +0000617 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +0000618 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +0000619 def test_loadTestsFromName__module_not_loaded(self):
620 # We're going to try to load this module as a side-effect, so it
621 # better not be loaded before we try.
622 #
623 # Why pick audioop? Google shows it isn't used very often, so there's
624 # a good chance that it won't be imported when this test is run
625 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +0000626
Georg Brandl15c5ce92007-03-07 09:09:40 +0000627 if module_name in sys.modules:
628 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000629
Georg Brandl15c5ce92007-03-07 09:09:40 +0000630 loader = unittest.TestLoader()
631 try:
632 suite = loader.loadTestsFromName(module_name)
633
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000634 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000635 self.assertEqual(list(suite), [])
636
637 # audioop should now be loaded, thanks to loadTestsFromName()
Ezio Melottiaa980582010-01-23 23:04:36 +0000638 self.assertIn(module_name, sys.modules)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000639 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000640 if module_name in sys.modules:
641 del sys.modules[module_name]
Georg Brandl15c5ce92007-03-07 09:09:40 +0000642
643 ################################################################
644 ### Tests for TestLoader.loadTestsFromName()
645
646 ### Tests for TestLoader.loadTestsFromNames()
647 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000648
Georg Brandl15c5ce92007-03-07 09:09:40 +0000649 # "Similar to loadTestsFromName(), but takes a sequence of names rather
650 # than a single name."
651 #
652 # What happens if that sequence of names is empty?
653 def test_loadTestsFromNames__empty_name_list(self):
654 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000655
Georg Brandl15c5ce92007-03-07 09:09:40 +0000656 suite = loader.loadTestsFromNames([])
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000657 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000658 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000659
Georg Brandl15c5ce92007-03-07 09:09:40 +0000660 # "Similar to loadTestsFromName(), but takes a sequence of names rather
661 # than a single name."
662 # ...
663 # "The method optionally resolves name relative to the given module"
664 #
665 # What happens if that sequence of names is empty?
666 #
667 # XXX Should this raise a ValueError or just return an empty TestSuite?
668 def test_loadTestsFromNames__relative_empty_name_list(self):
669 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000670
Georg Brandl15c5ce92007-03-07 09:09:40 +0000671 suite = loader.loadTestsFromNames([], unittest)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000672 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000673 self.assertEqual(list(suite), [])
674
675 # "The specifier name is a ``dotted name'' that may resolve either to
676 # a module, a test case class, a TestSuite instance, a test method
677 # within a test case class, or a callable object which returns a
678 # TestCase or TestSuite instance."
679 #
680 # Is ValueError raised in response to an empty name?
681 def test_loadTestsFromNames__empty_name(self):
682 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000683
Georg Brandl15c5ce92007-03-07 09:09:40 +0000684 try:
685 loader.loadTestsFromNames([''])
686 except ValueError, e:
687 self.assertEqual(str(e), "Empty module name")
688 else:
689 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000690
Georg Brandl15c5ce92007-03-07 09:09:40 +0000691 # "The specifier name is a ``dotted name'' that may resolve either to
692 # a module, a test case class, a TestSuite instance, a test method
693 # within a test case class, or a callable object which returns a
694 # TestCase or TestSuite instance."
695 #
Tim Petersea5962f2007-03-12 18:07:52 +0000696 # What happens when presented with an impossible module name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000697 def test_loadTestsFromNames__malformed_name(self):
698 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000699
Georg Brandl15c5ce92007-03-07 09:09:40 +0000700 # XXX Should this raise ValueError or ImportError?
701 try:
702 loader.loadTestsFromNames(['abc () //'])
703 except ValueError:
704 pass
705 except ImportError:
706 pass
707 else:
708 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000709
Georg Brandl15c5ce92007-03-07 09:09:40 +0000710 # "The specifier name is a ``dotted name'' that may resolve either to
711 # a module, a test case class, a TestSuite instance, a test method
712 # within a test case class, or a callable object which returns a
713 # TestCase or TestSuite instance."
714 #
Tim Petersea5962f2007-03-12 18:07:52 +0000715 # What happens when no module can be found for the given name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000716 def test_loadTestsFromNames__unknown_module_name(self):
717 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000718
Georg Brandl15c5ce92007-03-07 09:09:40 +0000719 try:
720 loader.loadTestsFromNames(['sdasfasfasdf'])
721 except ImportError, e:
722 self.assertEqual(str(e), "No module named sdasfasfasdf")
723 else:
724 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000725
Georg Brandl15c5ce92007-03-07 09:09:40 +0000726 # "The specifier name is a ``dotted name'' that may resolve either to
727 # a module, a test case class, a TestSuite instance, a test method
728 # within a test case class, or a callable object which returns a
729 # TestCase or TestSuite instance."
730 #
Tim Petersea5962f2007-03-12 18:07:52 +0000731 # What happens when the module can be found, but not the attribute?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000732 def test_loadTestsFromNames__unknown_attr_name(self):
733 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000734
Georg Brandl15c5ce92007-03-07 09:09:40 +0000735 try:
736 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
737 except AttributeError, e:
738 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
739 else:
740 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000741
Georg Brandl15c5ce92007-03-07 09:09:40 +0000742 # "The specifier name is a ``dotted name'' that may resolve either to
743 # a module, a test case class, a TestSuite instance, a test method
744 # within a test case class, or a callable object which returns a
745 # TestCase or TestSuite instance."
746 # ...
747 # "The method optionally resolves name relative to the given module"
748 #
749 # What happens when given an unknown attribute on a specified `module`
750 # argument?
751 def test_loadTestsFromNames__unknown_name_relative_1(self):
752 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000753
Georg Brandl15c5ce92007-03-07 09:09:40 +0000754 try:
755 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
756 except AttributeError, e:
757 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
758 else:
759 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000760
Georg Brandl15c5ce92007-03-07 09:09:40 +0000761 # "The specifier name is a ``dotted name'' that may resolve either to
762 # a module, a test case class, a TestSuite instance, a test method
763 # within a test case class, or a callable object which returns a
764 # TestCase or TestSuite instance."
765 # ...
766 # "The method optionally resolves name relative to the given module"
767 #
768 # Do unknown attributes (relative to a provided module) still raise an
Tim Petersea5962f2007-03-12 18:07:52 +0000769 # exception even in the presence of valid attribute names?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000770 def test_loadTestsFromNames__unknown_name_relative_2(self):
771 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000772
Georg Brandl15c5ce92007-03-07 09:09:40 +0000773 try:
774 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
775 except AttributeError, e:
776 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
777 else:
778 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
779
780 # "The specifier name is a ``dotted name'' that may resolve either to
781 # a module, a test case class, a TestSuite instance, a test method
782 # within a test case class, or a callable object which returns a
783 # TestCase or TestSuite instance."
784 # ...
785 # "The method optionally resolves name relative to the given module"
786 #
787 # What happens when faced with the empty string?
788 #
789 # XXX This currently raises AttributeError, though ValueError is probably
790 # more appropriate
791 def test_loadTestsFromNames__relative_empty_name(self):
792 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000793
Georg Brandl15c5ce92007-03-07 09:09:40 +0000794 try:
795 loader.loadTestsFromNames([''], unittest)
796 except AttributeError:
797 pass
798 else:
799 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000800
Georg Brandl15c5ce92007-03-07 09:09:40 +0000801 # "The specifier name is a ``dotted name'' that may resolve either to
802 # a module, a test case class, a TestSuite instance, a test method
803 # within a test case class, or a callable object which returns a
804 # TestCase or TestSuite instance."
805 # ...
806 # "The method optionally resolves name relative to the given module"
807 #
Tim Petersea5962f2007-03-12 18:07:52 +0000808 # What happens when presented with an impossible attribute name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000809 def test_loadTestsFromNames__relative_malformed_name(self):
810 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000811
Georg Brandl15c5ce92007-03-07 09:09:40 +0000812 # XXX Should this raise AttributeError or ValueError?
813 try:
814 loader.loadTestsFromNames(['abc () //'], unittest)
815 except AttributeError:
816 pass
817 except ValueError:
818 pass
819 else:
820 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
821
822 # "The method optionally resolves name relative to the given module"
823 #
824 # Does loadTestsFromNames() make sure the provided `module` is in fact
825 # a module?
826 #
827 # XXX This validation is currently not done. This flexibility should
828 # either be documented or a TypeError should be raised.
829 def test_loadTestsFromNames__relative_not_a_module(self):
830 class MyTestCase(unittest.TestCase):
831 def test(self):
832 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000833
Georg Brandl15c5ce92007-03-07 09:09:40 +0000834 class NotAModule(object):
835 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000836
Georg Brandl15c5ce92007-03-07 09:09:40 +0000837 loader = unittest.TestLoader()
838 suite = loader.loadTestsFromNames(['test_2'], NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000839
Georg Brandl15c5ce92007-03-07 09:09:40 +0000840 reference = [unittest.TestSuite([MyTestCase('test')])]
841 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000842
Georg Brandl15c5ce92007-03-07 09:09:40 +0000843 # "The specifier name is a ``dotted name'' that may resolve either to
844 # a module, a test case class, a TestSuite instance, a test method
845 # within a test case class, or a callable object which returns a
846 # TestCase or TestSuite instance."
847 #
848 # Does it raise an exception if the name resolves to an invalid
849 # object?
850 def test_loadTestsFromNames__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000851 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000852 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000853
Georg Brandl15c5ce92007-03-07 09:09:40 +0000854 loader = unittest.TestLoader()
855 try:
856 loader.loadTestsFromNames(['testcase_1'], m)
857 except TypeError:
858 pass
859 else:
860 self.fail("Should have raised TypeError")
861
862 # "The specifier name is a ``dotted name'' that may resolve ... to
863 # ... a test case class"
864 def test_loadTestsFromNames__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000865 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000866 class MyTestCase(unittest.TestCase):
867 def test(self):
868 pass
869 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000870
Georg Brandl15c5ce92007-03-07 09:09:40 +0000871 loader = unittest.TestLoader()
872 suite = loader.loadTestsFromNames(['testcase_1'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000873 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000874
Georg Brandl15c5ce92007-03-07 09:09:40 +0000875 expected = loader.suiteClass([MyTestCase('test')])
876 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000877
Georg Brandl15c5ce92007-03-07 09:09:40 +0000878 # "The specifier name is a ``dotted name'' that may resolve ... to
879 # ... a TestSuite instance"
880 def test_loadTestsFromNames__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000881 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000882 class MyTestCase(unittest.TestCase):
883 def test(self):
884 pass
885 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000886
Georg Brandl15c5ce92007-03-07 09:09:40 +0000887 loader = unittest.TestLoader()
888 suite = loader.loadTestsFromNames(['testsuite'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000889 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000890
Georg Brandl15c5ce92007-03-07 09:09:40 +0000891 self.assertEqual(list(suite), [m.testsuite])
Tim Petersea5962f2007-03-12 18:07:52 +0000892
Georg Brandl15c5ce92007-03-07 09:09:40 +0000893 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
894 # test method within a test case class"
895 def test_loadTestsFromNames__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000896 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000897 class MyTestCase(unittest.TestCase):
898 def test(self):
899 pass
900 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000901
Georg Brandl15c5ce92007-03-07 09:09:40 +0000902 loader = unittest.TestLoader()
903 suite = loader.loadTestsFromNames(['testcase_1.test'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000904 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000905
Georg Brandl15c5ce92007-03-07 09:09:40 +0000906 ref_suite = unittest.TestSuite([MyTestCase('test')])
907 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000908
Georg Brandl15c5ce92007-03-07 09:09:40 +0000909 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
910 # test method within a test case class"
911 #
912 # Does the method gracefully handle names that initially look like they
Tim Petersea5962f2007-03-12 18:07:52 +0000913 # resolve to "a test method within a test case class" but don't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000914 def test_loadTestsFromNames__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000915 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000916 class MyTestCase(unittest.TestCase):
917 def test(self):
918 pass
919 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000920
Georg Brandl15c5ce92007-03-07 09:09:40 +0000921 loader = unittest.TestLoader()
922 try:
923 loader.loadTestsFromNames(['testcase_1.testfoo'], m)
924 except AttributeError, e:
925 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
926 else:
927 self.fail("Failed to raise AttributeError")
928
929 # "The specifier name is a ``dotted name'' that may resolve ... to
930 # ... a callable object which returns a ... TestSuite instance"
931 def test_loadTestsFromNames__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000932 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000933 testcase_1 = unittest.FunctionTestCase(lambda: None)
934 testcase_2 = unittest.FunctionTestCase(lambda: None)
935 def return_TestSuite():
936 return unittest.TestSuite([testcase_1, testcase_2])
937 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000938
Georg Brandl15c5ce92007-03-07 09:09:40 +0000939 loader = unittest.TestLoader()
940 suite = loader.loadTestsFromNames(['return_TestSuite'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000941 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000942
Georg Brandl15c5ce92007-03-07 09:09:40 +0000943 expected = unittest.TestSuite([testcase_1, testcase_2])
944 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000945
Georg Brandl15c5ce92007-03-07 09:09:40 +0000946 # "The specifier name is a ``dotted name'' that may resolve ... to
947 # ... a callable object which returns a TestCase ... instance"
948 def test_loadTestsFromNames__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000949 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000950 testcase_1 = unittest.FunctionTestCase(lambda: None)
951 def return_TestCase():
952 return testcase_1
953 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000954
Georg Brandl15c5ce92007-03-07 09:09:40 +0000955 loader = unittest.TestLoader()
956 suite = loader.loadTestsFromNames(['return_TestCase'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000957 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000958
Georg Brandl15c5ce92007-03-07 09:09:40 +0000959 ref_suite = unittest.TestSuite([testcase_1])
960 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000961
Georg Brandl15c5ce92007-03-07 09:09:40 +0000962 # "The specifier name is a ``dotted name'' that may resolve ... to
963 # ... a callable object which returns a TestCase or TestSuite instance"
964 #
Tim Petersea5962f2007-03-12 18:07:52 +0000965 # Are staticmethods handled correctly?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000966 def test_loadTestsFromNames__callable__call_staticmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000967 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000968 class Test1(unittest.TestCase):
969 def test(self):
970 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000971
Georg Brandl15c5ce92007-03-07 09:09:40 +0000972 testcase_1 = Test1('test')
973 class Foo(unittest.TestCase):
974 @staticmethod
975 def foo():
976 return testcase_1
977 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +0000978
Georg Brandl15c5ce92007-03-07 09:09:40 +0000979 loader = unittest.TestLoader()
980 suite = loader.loadTestsFromNames(['Foo.foo'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000981 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000982
Georg Brandl15c5ce92007-03-07 09:09:40 +0000983 ref_suite = unittest.TestSuite([testcase_1])
984 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000985
Georg Brandl15c5ce92007-03-07 09:09:40 +0000986 # "The specifier name is a ``dotted name'' that may resolve ... to
987 # ... a callable object which returns a TestCase or TestSuite instance"
988 #
989 # What happens when the callable returns something else?
990 def test_loadTestsFromNames__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000991 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000992 def return_wrong():
993 return 6
994 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000995
Georg Brandl15c5ce92007-03-07 09:09:40 +0000996 loader = unittest.TestLoader()
997 try:
998 suite = loader.loadTestsFromNames(['return_wrong'], m)
999 except TypeError:
1000 pass
1001 else:
1002 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +00001003
Georg Brandl15c5ce92007-03-07 09:09:40 +00001004 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +00001005 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001006 def test_loadTestsFromNames__module_not_loaded(self):
1007 # We're going to try to load this module as a side-effect, so it
1008 # better not be loaded before we try.
1009 #
1010 # Why pick audioop? Google shows it isn't used very often, so there's
1011 # a good chance that it won't be imported when this test is run
1012 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +00001013
Georg Brandl15c5ce92007-03-07 09:09:40 +00001014 if module_name in sys.modules:
1015 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +00001016
Georg Brandl15c5ce92007-03-07 09:09:40 +00001017 loader = unittest.TestLoader()
1018 try:
1019 suite = loader.loadTestsFromNames([module_name])
1020
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001021 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +00001022 self.assertEqual(list(suite), [unittest.TestSuite()])
1023
1024 # audioop should now be loaded, thanks to loadTestsFromName()
Ezio Melottiaa980582010-01-23 23:04:36 +00001025 self.assertIn(module_name, sys.modules)
Georg Brandl15c5ce92007-03-07 09:09:40 +00001026 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +00001027 if module_name in sys.modules:
1028 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +00001029
Georg Brandl15c5ce92007-03-07 09:09:40 +00001030 ################################################################
1031 ### /Tests for TestLoader.loadTestsFromNames()
1032
1033 ### Tests for TestLoader.getTestCaseNames()
1034 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001035
Georg Brandl15c5ce92007-03-07 09:09:40 +00001036 # "Return a sorted sequence of method names found within testCaseClass"
1037 #
1038 # Test.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +00001039 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +00001040 def test_getTestCaseNames(self):
1041 class Test(unittest.TestCase):
1042 def test_1(self): pass
1043 def test_2(self): pass
1044 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001045
Georg Brandl15c5ce92007-03-07 09:09:40 +00001046 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001047
Georg Brandl15c5ce92007-03-07 09:09:40 +00001048 self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])
Tim Petersea5962f2007-03-12 18:07:52 +00001049
Georg Brandl15c5ce92007-03-07 09:09:40 +00001050 # "Return a sorted sequence of method names found within testCaseClass"
1051 #
Tim Petersea5962f2007-03-12 18:07:52 +00001052 # Does getTestCaseNames() behave appropriately if no tests are found?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001053 def test_getTestCaseNames__no_tests(self):
1054 class Test(unittest.TestCase):
1055 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001056
Georg Brandl15c5ce92007-03-07 09:09:40 +00001057 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001058
Georg Brandl15c5ce92007-03-07 09:09:40 +00001059 self.assertEqual(loader.getTestCaseNames(Test), [])
Tim Petersea5962f2007-03-12 18:07:52 +00001060
Georg Brandl15c5ce92007-03-07 09:09:40 +00001061 # "Return a sorted sequence of method names found within testCaseClass"
1062 #
1063 # Are not-TestCases handled gracefully?
1064 #
1065 # XXX This should raise a TypeError, not return a list
1066 #
1067 # XXX It's too late in the 2.5 release cycle to fix this, but it should
1068 # probably be revisited for 2.6
1069 def test_getTestCaseNames__not_a_TestCase(self):
1070 class BadCase(int):
1071 def test_foo(self):
1072 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001073
Georg Brandl15c5ce92007-03-07 09:09:40 +00001074 loader = unittest.TestLoader()
1075 names = loader.getTestCaseNames(BadCase)
Tim Petersea5962f2007-03-12 18:07:52 +00001076
Georg Brandl15c5ce92007-03-07 09:09:40 +00001077 self.assertEqual(names, ['test_foo'])
Tim Petersea5962f2007-03-12 18:07:52 +00001078
Georg Brandl15c5ce92007-03-07 09:09:40 +00001079 # "Return a sorted sequence of method names found within testCaseClass"
1080 #
1081 # Make sure inherited names are handled.
1082 #
1083 # TestP.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +00001084 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +00001085 def test_getTestCaseNames__inheritance(self):
1086 class TestP(unittest.TestCase):
1087 def test_1(self): pass
1088 def test_2(self): pass
1089 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001090
Georg Brandl15c5ce92007-03-07 09:09:40 +00001091 class TestC(TestP):
1092 def test_1(self): pass
1093 def test_3(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001094
Georg Brandl15c5ce92007-03-07 09:09:40 +00001095 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001096
Georg Brandl15c5ce92007-03-07 09:09:40 +00001097 names = ['test_1', 'test_2', 'test_3']
1098 self.assertEqual(loader.getTestCaseNames(TestC), names)
Tim Petersea5962f2007-03-12 18:07:52 +00001099
1100 ################################################################
Georg Brandl15c5ce92007-03-07 09:09:40 +00001101 ### /Tests for TestLoader.getTestCaseNames()
1102
1103 ### Tests for TestLoader.testMethodPrefix
1104 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001105
Georg Brandl15c5ce92007-03-07 09:09:40 +00001106 # "String giving the prefix of method names which will be interpreted as
1107 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001108 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001109 # Implicit in the documentation is that testMethodPrefix is respected by
1110 # all loadTestsFrom* methods.
1111 def test_testMethodPrefix__loadTestsFromTestCase(self):
1112 class Foo(unittest.TestCase):
1113 def test_1(self): pass
1114 def test_2(self): pass
1115 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001116
Georg Brandl15c5ce92007-03-07 09:09:40 +00001117 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1118 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001119
Georg Brandl15c5ce92007-03-07 09:09:40 +00001120 loader = unittest.TestLoader()
1121 loader.testMethodPrefix = 'foo'
1122 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
1123
1124 loader.testMethodPrefix = 'test'
1125 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001126
Georg Brandl15c5ce92007-03-07 09:09:40 +00001127 # "String giving the prefix of method names which will be interpreted as
1128 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001129 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001130 # Implicit in the documentation is that testMethodPrefix is respected by
1131 # all loadTestsFrom* methods.
1132 def test_testMethodPrefix__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001133 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001134 class Foo(unittest.TestCase):
1135 def test_1(self): pass
1136 def test_2(self): pass
1137 def foo_bar(self): pass
1138 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001139
Georg Brandl15c5ce92007-03-07 09:09:40 +00001140 tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
1141 tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]
Tim Petersea5962f2007-03-12 18:07:52 +00001142
Georg Brandl15c5ce92007-03-07 09:09:40 +00001143 loader = unittest.TestLoader()
1144 loader.testMethodPrefix = 'foo'
1145 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
1146
1147 loader.testMethodPrefix = 'test'
1148 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001149
Georg Brandl15c5ce92007-03-07 09:09:40 +00001150 # "String giving the prefix of method names which will be interpreted as
1151 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001152 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001153 # Implicit in the documentation is that testMethodPrefix is respected by
1154 # all loadTestsFrom* methods.
1155 def test_testMethodPrefix__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001156 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001157 class Foo(unittest.TestCase):
1158 def test_1(self): pass
1159 def test_2(self): pass
1160 def foo_bar(self): pass
1161 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001162
Georg Brandl15c5ce92007-03-07 09:09:40 +00001163 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1164 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001165
Georg Brandl15c5ce92007-03-07 09:09:40 +00001166 loader = unittest.TestLoader()
1167 loader.testMethodPrefix = 'foo'
1168 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
1169
1170 loader.testMethodPrefix = 'test'
1171 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001172
Georg Brandl15c5ce92007-03-07 09:09:40 +00001173 # "String giving the prefix of method names which will be interpreted as
1174 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001175 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001176 # Implicit in the documentation is that testMethodPrefix is respected by
1177 # all loadTestsFrom* methods.
1178 def test_testMethodPrefix__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001179 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001180 class Foo(unittest.TestCase):
1181 def test_1(self): pass
1182 def test_2(self): pass
1183 def foo_bar(self): pass
1184 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001185
Georg Brandl15c5ce92007-03-07 09:09:40 +00001186 tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
1187 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1188 tests_2 = unittest.TestSuite([tests_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001189
Georg Brandl15c5ce92007-03-07 09:09:40 +00001190 loader = unittest.TestLoader()
1191 loader.testMethodPrefix = 'foo'
1192 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)
1193
1194 loader.testMethodPrefix = 'test'
1195 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001196
Georg Brandl15c5ce92007-03-07 09:09:40 +00001197 # "The default value is 'test'"
1198 def test_testMethodPrefix__default_value(self):
1199 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001200 self.assertTrue(loader.testMethodPrefix == 'test')
Tim Petersea5962f2007-03-12 18:07:52 +00001201
Georg Brandl15c5ce92007-03-07 09:09:40 +00001202 ################################################################
1203 ### /Tests for TestLoader.testMethodPrefix
1204
Tim Petersea5962f2007-03-12 18:07:52 +00001205 ### Tests for TestLoader.sortTestMethodsUsing
Georg Brandl15c5ce92007-03-07 09:09:40 +00001206 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001207
Georg Brandl15c5ce92007-03-07 09:09:40 +00001208 # "Function to be used to compare method names when sorting them in
1209 # getTestCaseNames() and all the loadTestsFromX() methods"
1210 def test_sortTestMethodsUsing__loadTestsFromTestCase(self):
1211 def reversed_cmp(x, y):
1212 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001213
Georg Brandl15c5ce92007-03-07 09:09:40 +00001214 class Foo(unittest.TestCase):
1215 def test_1(self): pass
1216 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001217
Georg Brandl15c5ce92007-03-07 09:09:40 +00001218 loader = unittest.TestLoader()
1219 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001220
Georg Brandl15c5ce92007-03-07 09:09:40 +00001221 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1222 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001223
Georg Brandl15c5ce92007-03-07 09:09:40 +00001224 # "Function to be used to compare method names when sorting them in
1225 # getTestCaseNames() and all the loadTestsFromX() methods"
1226 def test_sortTestMethodsUsing__loadTestsFromModule(self):
1227 def reversed_cmp(x, y):
1228 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001229
Christian Heimesc756d002007-11-27 21:34:01 +00001230 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001231 class Foo(unittest.TestCase):
1232 def test_1(self): pass
1233 def test_2(self): pass
1234 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001235
Georg Brandl15c5ce92007-03-07 09:09:40 +00001236 loader = unittest.TestLoader()
1237 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001238
Georg Brandl15c5ce92007-03-07 09:09:40 +00001239 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1240 self.assertEqual(list(loader.loadTestsFromModule(m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001241
Georg Brandl15c5ce92007-03-07 09:09:40 +00001242 # "Function to be used to compare method names when sorting them in
1243 # getTestCaseNames() and all the loadTestsFromX() methods"
1244 def test_sortTestMethodsUsing__loadTestsFromName(self):
1245 def reversed_cmp(x, y):
1246 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001247
Christian Heimesc756d002007-11-27 21:34:01 +00001248 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001249 class Foo(unittest.TestCase):
1250 def test_1(self): pass
1251 def test_2(self): pass
1252 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001253
Georg Brandl15c5ce92007-03-07 09:09:40 +00001254 loader = unittest.TestLoader()
1255 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001256
Georg Brandl15c5ce92007-03-07 09:09:40 +00001257 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1258 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001259
Georg Brandl15c5ce92007-03-07 09:09:40 +00001260 # "Function to be used to compare method names when sorting them in
1261 # getTestCaseNames() and all the loadTestsFromX() methods"
1262 def test_sortTestMethodsUsing__loadTestsFromNames(self):
1263 def reversed_cmp(x, y):
1264 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001265
Christian Heimesc756d002007-11-27 21:34:01 +00001266 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001267 class Foo(unittest.TestCase):
1268 def test_1(self): pass
1269 def test_2(self): pass
1270 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001271
Georg Brandl15c5ce92007-03-07 09:09:40 +00001272 loader = unittest.TestLoader()
1273 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001274
Georg Brandl15c5ce92007-03-07 09:09:40 +00001275 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1276 self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001277
Georg Brandl15c5ce92007-03-07 09:09:40 +00001278 # "Function to be used to compare method names when sorting them in
1279 # getTestCaseNames()"
1280 #
1281 # Does it actually affect getTestCaseNames()?
1282 def test_sortTestMethodsUsing__getTestCaseNames(self):
1283 def reversed_cmp(x, y):
1284 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001285
Georg Brandl15c5ce92007-03-07 09:09:40 +00001286 class Foo(unittest.TestCase):
1287 def test_1(self): pass
1288 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001289
Georg Brandl15c5ce92007-03-07 09:09:40 +00001290 loader = unittest.TestLoader()
1291 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001292
Georg Brandl15c5ce92007-03-07 09:09:40 +00001293 test_names = ['test_2', 'test_1']
1294 self.assertEqual(loader.getTestCaseNames(Foo), test_names)
Tim Petersea5962f2007-03-12 18:07:52 +00001295
Georg Brandl15c5ce92007-03-07 09:09:40 +00001296 # "The default value is the built-in cmp() function"
1297 def test_sortTestMethodsUsing__default_value(self):
1298 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001299 self.assertTrue(loader.sortTestMethodsUsing is cmp)
Tim Petersea5962f2007-03-12 18:07:52 +00001300
Georg Brandl15c5ce92007-03-07 09:09:40 +00001301 # "it can be set to None to disable the sort."
1302 #
1303 # XXX How is this different from reassigning cmp? Are the tests returned
1304 # in a random order or something? This behaviour should die
1305 def test_sortTestMethodsUsing__None(self):
1306 class Foo(unittest.TestCase):
1307 def test_1(self): pass
1308 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001309
Georg Brandl15c5ce92007-03-07 09:09:40 +00001310 loader = unittest.TestLoader()
1311 loader.sortTestMethodsUsing = None
Tim Petersea5962f2007-03-12 18:07:52 +00001312
Georg Brandl15c5ce92007-03-07 09:09:40 +00001313 test_names = ['test_2', 'test_1']
1314 self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))
Tim Petersea5962f2007-03-12 18:07:52 +00001315
Georg Brandl15c5ce92007-03-07 09:09:40 +00001316 ################################################################
1317 ### /Tests for TestLoader.sortTestMethodsUsing
Tim Petersea5962f2007-03-12 18:07:52 +00001318
Georg Brandl15c5ce92007-03-07 09:09:40 +00001319 ### Tests for TestLoader.suiteClass
1320 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001321
Georg Brandl15c5ce92007-03-07 09:09:40 +00001322 # "Callable object that constructs a test suite from a list of tests."
1323 def test_suiteClass__loadTestsFromTestCase(self):
1324 class Foo(unittest.TestCase):
1325 def test_1(self): pass
1326 def test_2(self): pass
1327 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001328
Georg Brandl15c5ce92007-03-07 09:09:40 +00001329 tests = [Foo('test_1'), Foo('test_2')]
1330
1331 loader = unittest.TestLoader()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001332 loader.suiteClass = list
Georg Brandl15c5ce92007-03-07 09:09:40 +00001333 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001334
Georg Brandl15c5ce92007-03-07 09:09:40 +00001335 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001336 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001337 def test_suiteClass__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001338 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001339 class Foo(unittest.TestCase):
1340 def test_1(self): pass
1341 def test_2(self): pass
1342 def foo_bar(self): pass
1343 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001344
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001345 tests = [[Foo('test_1'), Foo('test_2')]]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001346
1347 loader = unittest.TestLoader()
1348 loader.suiteClass = list
1349 self.assertEqual(loader.loadTestsFromModule(m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001350
Georg Brandl15c5ce92007-03-07 09:09:40 +00001351 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001352 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001353 def test_suiteClass__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001354 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001355 class Foo(unittest.TestCase):
1356 def test_1(self): pass
1357 def test_2(self): pass
1358 def foo_bar(self): pass
1359 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001360
Georg Brandl15c5ce92007-03-07 09:09:40 +00001361 tests = [Foo('test_1'), Foo('test_2')]
1362
1363 loader = unittest.TestLoader()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001364 loader.suiteClass = list
Georg Brandl15c5ce92007-03-07 09:09:40 +00001365 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001366
Georg Brandl15c5ce92007-03-07 09:09:40 +00001367 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001368 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001369 def test_suiteClass__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001370 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001371 class Foo(unittest.TestCase):
1372 def test_1(self): pass
1373 def test_2(self): pass
1374 def foo_bar(self): pass
1375 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001376
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001377 tests = [[Foo('test_1'), Foo('test_2')]]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001378
1379 loader = unittest.TestLoader()
1380 loader.suiteClass = list
1381 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001382
Georg Brandl15c5ce92007-03-07 09:09:40 +00001383 # "The default value is the TestSuite class"
1384 def test_suiteClass__default_value(self):
1385 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001386 self.assertTrue(loader.suiteClass is unittest.TestSuite)
Tim Petersea5962f2007-03-12 18:07:52 +00001387
Georg Brandl15c5ce92007-03-07 09:09:40 +00001388 ################################################################
1389 ### /Tests for TestLoader.suiteClass
1390
1391### Support code for Test_TestSuite
1392################################################################
1393
1394class Foo(unittest.TestCase):
1395 def test_1(self): pass
1396 def test_2(self): pass
1397 def test_3(self): pass
1398 def runTest(self): pass
1399
1400def _mk_TestSuite(*names):
1401 return unittest.TestSuite(Foo(n) for n in names)
Tim Petersea5962f2007-03-12 18:07:52 +00001402
Georg Brandl15c5ce92007-03-07 09:09:40 +00001403################################################################
1404### /Support code for Test_TestSuite
1405
1406class Test_TestSuite(TestCase, TestEquality):
1407
1408 ### Set up attributes needed by inherited tests
1409 ################################################################
1410
1411 # Used by TestEquality.test_eq
1412 eq_pairs = [(unittest.TestSuite(), unittest.TestSuite())
1413 ,(unittest.TestSuite(), unittest.TestSuite([]))
1414 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001415
1416 # Used by TestEquality.test_ne
Georg Brandl15c5ce92007-03-07 09:09:40 +00001417 ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1'))
1418 ,(unittest.TestSuite([]), _mk_TestSuite('test_1'))
1419 ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3'))
1420 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001421
Georg Brandl15c5ce92007-03-07 09:09:40 +00001422 ################################################################
1423 ### /Set up attributes needed by inherited tests
1424
1425 ### Tests for TestSuite.__init__
1426 ################################################################
1427
1428 # "class TestSuite([tests])"
1429 #
1430 # The tests iterable should be optional
1431 def test_init__tests_optional(self):
1432 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001433
Georg Brandl15c5ce92007-03-07 09:09:40 +00001434 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001435
Georg Brandl15c5ce92007-03-07 09:09:40 +00001436 # "class TestSuite([tests])"
1437 # ...
1438 # "If tests is given, it must be an iterable of individual test cases
1439 # or other test suites that will be used to build the suite initially"
1440 #
1441 # TestSuite should deal with empty tests iterables by allowing the
Tim Petersea5962f2007-03-12 18:07:52 +00001442 # creation of an empty suite
Georg Brandl15c5ce92007-03-07 09:09:40 +00001443 def test_init__empty_tests(self):
1444 suite = unittest.TestSuite([])
Tim Petersea5962f2007-03-12 18:07:52 +00001445
Georg Brandl15c5ce92007-03-07 09:09:40 +00001446 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001447
Georg Brandl15c5ce92007-03-07 09:09:40 +00001448 # "class TestSuite([tests])"
1449 # ...
1450 # "If tests is given, it must be an iterable of individual test cases
1451 # or other test suites that will be used to build the suite initially"
1452 #
Tim Petersea5962f2007-03-12 18:07:52 +00001453 # TestSuite should allow any iterable to provide tests
Georg Brandl15c5ce92007-03-07 09:09:40 +00001454 def test_init__tests_from_any_iterable(self):
1455 def tests():
1456 yield unittest.FunctionTestCase(lambda: None)
1457 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001458
Georg Brandl15c5ce92007-03-07 09:09:40 +00001459 suite_1 = unittest.TestSuite(tests())
1460 self.assertEqual(suite_1.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001461
Georg Brandl15c5ce92007-03-07 09:09:40 +00001462 suite_2 = unittest.TestSuite(suite_1)
1463 self.assertEqual(suite_2.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001464
Georg Brandl15c5ce92007-03-07 09:09:40 +00001465 suite_3 = unittest.TestSuite(set(suite_1))
1466 self.assertEqual(suite_3.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001467
Georg Brandl15c5ce92007-03-07 09:09:40 +00001468 # "class TestSuite([tests])"
1469 # ...
1470 # "If tests is given, it must be an iterable of individual test cases
1471 # or other test suites that will be used to build the suite initially"
1472 #
1473 # Does TestSuite() also allow other TestSuite() instances to be present
1474 # in the tests iterable?
1475 def test_init__TestSuite_instances_in_tests(self):
1476 def tests():
1477 ftc = unittest.FunctionTestCase(lambda: None)
1478 yield unittest.TestSuite([ftc])
1479 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001480
Georg Brandl15c5ce92007-03-07 09:09:40 +00001481 suite = unittest.TestSuite(tests())
1482 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001483
Georg Brandl15c5ce92007-03-07 09:09:40 +00001484 ################################################################
1485 ### /Tests for TestSuite.__init__
1486
1487 # Container types should support the iter protocol
1488 def test_iter(self):
1489 test1 = unittest.FunctionTestCase(lambda: None)
1490 test2 = unittest.FunctionTestCase(lambda: None)
1491 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001492
Georg Brandl15c5ce92007-03-07 09:09:40 +00001493 self.assertEqual(list(suite), [test1, test2])
Tim Petersea5962f2007-03-12 18:07:52 +00001494
Georg Brandl15c5ce92007-03-07 09:09:40 +00001495 # "Return the number of tests represented by the this test object.
1496 # ...this method is also implemented by the TestSuite class, which can
1497 # return larger [greater than 1] values"
1498 #
Tim Petersea5962f2007-03-12 18:07:52 +00001499 # Presumably an empty TestSuite returns 0?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001500 def test_countTestCases_zero_simple(self):
1501 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001502
Georg Brandl15c5ce92007-03-07 09:09:40 +00001503 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001504
Georg Brandl15c5ce92007-03-07 09:09:40 +00001505 # "Return the number of tests represented by the this test object.
1506 # ...this method is also implemented by the TestSuite class, which can
1507 # return larger [greater than 1] values"
1508 #
1509 # Presumably an empty TestSuite (even if it contains other empty
1510 # TestSuite instances) returns 0?
1511 def test_countTestCases_zero_nested(self):
1512 class Test1(unittest.TestCase):
1513 def test(self):
1514 pass
1515
1516 suite = unittest.TestSuite([unittest.TestSuite()])
Tim Petersea5962f2007-03-12 18:07:52 +00001517
Georg Brandl15c5ce92007-03-07 09:09:40 +00001518 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001519
Georg Brandl15c5ce92007-03-07 09:09:40 +00001520 # "Return the number of tests represented by the this test object.
1521 # ...this method is also implemented by the TestSuite class, which can
1522 # return larger [greater than 1] values"
1523 def test_countTestCases_simple(self):
1524 test1 = unittest.FunctionTestCase(lambda: None)
1525 test2 = unittest.FunctionTestCase(lambda: None)
1526 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001527
Georg Brandl15c5ce92007-03-07 09:09:40 +00001528 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001529
Georg Brandl15c5ce92007-03-07 09:09:40 +00001530 # "Return the number of tests represented by the this test object.
1531 # ...this method is also implemented by the TestSuite class, which can
1532 # return larger [greater than 1] values"
1533 #
1534 # Make sure this holds for nested TestSuite instances, too
1535 def test_countTestCases_nested(self):
1536 class Test1(unittest.TestCase):
1537 def test1(self): pass
1538 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001539
Georg Brandl15c5ce92007-03-07 09:09:40 +00001540 test2 = unittest.FunctionTestCase(lambda: None)
1541 test3 = unittest.FunctionTestCase(lambda: None)
1542 child = unittest.TestSuite((Test1('test2'), test2))
1543 parent = unittest.TestSuite((test3, child, Test1('test1')))
Tim Petersea5962f2007-03-12 18:07:52 +00001544
Georg Brandl15c5ce92007-03-07 09:09:40 +00001545 self.assertEqual(parent.countTestCases(), 4)
Tim Petersea5962f2007-03-12 18:07:52 +00001546
Georg Brandl15c5ce92007-03-07 09:09:40 +00001547 # "Run the tests associated with this suite, collecting the result into
1548 # the test result object passed as result."
1549 #
1550 # And if there are no tests? What then?
1551 def test_run__empty_suite(self):
1552 events = []
1553 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001554
Georg Brandl15c5ce92007-03-07 09:09:40 +00001555 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001556
Georg Brandl15c5ce92007-03-07 09:09:40 +00001557 suite.run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001558
Georg Brandl15c5ce92007-03-07 09:09:40 +00001559 self.assertEqual(events, [])
Tim Petersea5962f2007-03-12 18:07:52 +00001560
Georg Brandl15c5ce92007-03-07 09:09:40 +00001561 # "Note that unlike TestCase.run(), TestSuite.run() requires the
1562 # "result object to be passed in."
1563 def test_run__requires_result(self):
1564 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001565
Georg Brandl15c5ce92007-03-07 09:09:40 +00001566 try:
1567 suite.run()
1568 except TypeError:
1569 pass
1570 else:
1571 self.fail("Failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +00001572
Georg Brandl15c5ce92007-03-07 09:09:40 +00001573 # "Run the tests associated with this suite, collecting the result into
Tim Petersea5962f2007-03-12 18:07:52 +00001574 # the test result object passed as result."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001575 def test_run(self):
1576 events = []
1577 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001578
Georg Brandl15c5ce92007-03-07 09:09:40 +00001579 class LoggingCase(unittest.TestCase):
1580 def run(self, result):
1581 events.append('run %s' % self._testMethodName)
Tim Petersea5962f2007-03-12 18:07:52 +00001582
Georg Brandl15c5ce92007-03-07 09:09:40 +00001583 def test1(self): pass
1584 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001585
1586 tests = [LoggingCase('test1'), LoggingCase('test2')]
1587
Georg Brandl15c5ce92007-03-07 09:09:40 +00001588 unittest.TestSuite(tests).run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001589
Georg Brandl15c5ce92007-03-07 09:09:40 +00001590 self.assertEqual(events, ['run test1', 'run test2'])
Tim Petersea5962f2007-03-12 18:07:52 +00001591
1592 # "Add a TestCase ... to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001593 def test_addTest__TestCase(self):
1594 class Foo(unittest.TestCase):
1595 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001596
Georg Brandl15c5ce92007-03-07 09:09:40 +00001597 test = Foo('test')
1598 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001599
Georg Brandl15c5ce92007-03-07 09:09:40 +00001600 suite.addTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001601
Georg Brandl15c5ce92007-03-07 09:09:40 +00001602 self.assertEqual(suite.countTestCases(), 1)
1603 self.assertEqual(list(suite), [test])
Tim Petersea5962f2007-03-12 18:07:52 +00001604
1605 # "Add a ... TestSuite to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001606 def test_addTest__TestSuite(self):
1607 class Foo(unittest.TestCase):
1608 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001609
Georg Brandl15c5ce92007-03-07 09:09:40 +00001610 suite_2 = unittest.TestSuite([Foo('test')])
Tim Petersea5962f2007-03-12 18:07:52 +00001611
Georg Brandl15c5ce92007-03-07 09:09:40 +00001612 suite = unittest.TestSuite()
1613 suite.addTest(suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001614
Georg Brandl15c5ce92007-03-07 09:09:40 +00001615 self.assertEqual(suite.countTestCases(), 1)
1616 self.assertEqual(list(suite), [suite_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001617
Georg Brandl15c5ce92007-03-07 09:09:40 +00001618 # "Add all the tests from an iterable of TestCase and TestSuite
1619 # instances to this test suite."
Tim Petersea5962f2007-03-12 18:07:52 +00001620 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001621 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001622 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001623 def test_addTests(self):
1624 class Foo(unittest.TestCase):
1625 def test_1(self): pass
1626 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001627
Georg Brandl15c5ce92007-03-07 09:09:40 +00001628 test_1 = Foo('test_1')
1629 test_2 = Foo('test_2')
1630 inner_suite = unittest.TestSuite([test_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001631
Georg Brandl15c5ce92007-03-07 09:09:40 +00001632 def gen():
1633 yield test_1
1634 yield test_2
1635 yield inner_suite
Tim Petersea5962f2007-03-12 18:07:52 +00001636
Georg Brandl15c5ce92007-03-07 09:09:40 +00001637 suite_1 = unittest.TestSuite()
1638 suite_1.addTests(gen())
Tim Petersea5962f2007-03-12 18:07:52 +00001639
Georg Brandl15c5ce92007-03-07 09:09:40 +00001640 self.assertEqual(list(suite_1), list(gen()))
Tim Petersea5962f2007-03-12 18:07:52 +00001641
Georg Brandl15c5ce92007-03-07 09:09:40 +00001642 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001643 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001644 suite_2 = unittest.TestSuite()
1645 for t in gen():
1646 suite_2.addTest(t)
Tim Petersea5962f2007-03-12 18:07:52 +00001647
Georg Brandl15c5ce92007-03-07 09:09:40 +00001648 self.assertEqual(suite_1, suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001649
Georg Brandl15c5ce92007-03-07 09:09:40 +00001650 # "Add all the tests from an iterable of TestCase and TestSuite
1651 # instances to this test suite."
1652 #
Tim Petersea5962f2007-03-12 18:07:52 +00001653 # What happens if it doesn't get an iterable?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001654 def test_addTest__noniterable(self):
1655 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001656
Georg Brandl15c5ce92007-03-07 09:09:40 +00001657 try:
1658 suite.addTests(5)
1659 except TypeError:
1660 pass
1661 else:
1662 self.fail("Failed to raise TypeError")
Georg Brandld9e50262007-03-07 11:54:49 +00001663
1664 def test_addTest__noncallable(self):
1665 suite = unittest.TestSuite()
1666 self.assertRaises(TypeError, suite.addTest, 5)
1667
1668 def test_addTest__casesuiteclass(self):
1669 suite = unittest.TestSuite()
1670 self.assertRaises(TypeError, suite.addTest, Test_TestSuite)
1671 self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)
1672
1673 def test_addTests__string(self):
1674 suite = unittest.TestSuite()
1675 self.assertRaises(TypeError, suite.addTests, "foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001676
1677
Georg Brandl15c5ce92007-03-07 09:09:40 +00001678class Test_FunctionTestCase(TestCase):
Tim Petersea5962f2007-03-12 18:07:52 +00001679
Georg Brandl15c5ce92007-03-07 09:09:40 +00001680 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00001681 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001682 def test_countTestCases(self):
1683 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001684
Georg Brandl15c5ce92007-03-07 09:09:40 +00001685 self.assertEqual(test.countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00001686
Georg Brandl15c5ce92007-03-07 09:09:40 +00001687 # "When a setUp() method is defined, the test runner will run that method
1688 # prior to each test. Likewise, if a tearDown() method is defined, the
1689 # test runner will invoke that method after each test. In the example,
1690 # setUp() was used to create a fresh sequence for each test."
1691 #
1692 # Make sure the proper call order is maintained, even if setUp() raises
1693 # an exception.
1694 def test_run_call_order__error_in_setUp(self):
1695 events = []
1696 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001697
Georg Brandl15c5ce92007-03-07 09:09:40 +00001698 def setUp():
1699 events.append('setUp')
1700 raise RuntimeError('raised by setUp')
1701
1702 def test():
1703 events.append('test')
1704
1705 def tearDown():
1706 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001707
1708 expected = ['startTest', 'setUp', 'addError', 'stopTest']
Georg Brandl15c5ce92007-03-07 09:09:40 +00001709 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1710 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001711
Georg Brandl15c5ce92007-03-07 09:09:40 +00001712 # "When a setUp() method is defined, the test runner will run that method
1713 # prior to each test. Likewise, if a tearDown() method is defined, the
1714 # test runner will invoke that method after each test. In the example,
1715 # setUp() was used to create a fresh sequence for each test."
1716 #
1717 # Make sure the proper call order is maintained, even if the test raises
1718 # an error (as opposed to a failure).
1719 def test_run_call_order__error_in_test(self):
1720 events = []
1721 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001722
Georg Brandl15c5ce92007-03-07 09:09:40 +00001723 def setUp():
1724 events.append('setUp')
1725
1726 def test():
1727 events.append('test')
1728 raise RuntimeError('raised by test')
1729
1730 def tearDown():
1731 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001732
Georg Brandl15c5ce92007-03-07 09:09:40 +00001733 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
1734 'stopTest']
1735 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1736 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001737
Georg Brandl15c5ce92007-03-07 09:09:40 +00001738 # "When a setUp() method is defined, the test runner will run that method
1739 # prior to each test. Likewise, if a tearDown() method is defined, the
1740 # test runner will invoke that method after each test. In the example,
1741 # setUp() was used to create a fresh sequence for each test."
1742 #
1743 # Make sure the proper call order is maintained, even if the test signals
1744 # a failure (as opposed to an error).
1745 def test_run_call_order__failure_in_test(self):
1746 events = []
1747 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001748
Georg Brandl15c5ce92007-03-07 09:09:40 +00001749 def setUp():
1750 events.append('setUp')
1751
1752 def test():
1753 events.append('test')
1754 self.fail('raised by test')
1755
1756 def tearDown():
1757 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001758
Georg Brandl15c5ce92007-03-07 09:09:40 +00001759 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
1760 'stopTest']
1761 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1762 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001763
Georg Brandl15c5ce92007-03-07 09:09:40 +00001764 # "When a setUp() method is defined, the test runner will run that method
1765 # prior to each test. Likewise, if a tearDown() method is defined, the
1766 # test runner will invoke that method after each test. In the example,
1767 # setUp() was used to create a fresh sequence for each test."
1768 #
1769 # Make sure the proper call order is maintained, even if tearDown() raises
1770 # an exception.
1771 def test_run_call_order__error_in_tearDown(self):
1772 events = []
1773 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001774
Georg Brandl15c5ce92007-03-07 09:09:40 +00001775 def setUp():
1776 events.append('setUp')
1777
1778 def test():
1779 events.append('test')
1780
1781 def tearDown():
1782 events.append('tearDown')
1783 raise RuntimeError('raised by tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001784
Georg Brandl15c5ce92007-03-07 09:09:40 +00001785 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
1786 'stopTest']
1787 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1788 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001789
Georg Brandl15c5ce92007-03-07 09:09:40 +00001790 # "Return a string identifying the specific test case."
1791 #
1792 # Because of the vague nature of the docs, I'm not going to lock this
1793 # test down too much. Really all that can be asserted is that the id()
1794 # will be a string (either 8-byte or unicode -- again, because the docs
1795 # just say "string")
1796 def test_id(self):
1797 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001798
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001799 self.assertIsInstance(test.id(), basestring)
Tim Petersea5962f2007-03-12 18:07:52 +00001800
Georg Brandl15c5ce92007-03-07 09:09:40 +00001801 # "Returns a one-line description of the test, or None if no description
1802 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001803 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001804 def test_shortDescription__no_docstring(self):
1805 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001806
Georg Brandl15c5ce92007-03-07 09:09:40 +00001807 self.assertEqual(test.shortDescription(), None)
Tim Petersea5962f2007-03-12 18:07:52 +00001808
Georg Brandl15c5ce92007-03-07 09:09:40 +00001809 # "Returns a one-line description of the test, or None if no description
1810 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001811 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001812 def test_shortDescription__singleline_docstring(self):
1813 desc = "this tests foo"
1814 test = unittest.FunctionTestCase(lambda: None, description=desc)
Tim Petersea5962f2007-03-12 18:07:52 +00001815
Georg Brandl15c5ce92007-03-07 09:09:40 +00001816 self.assertEqual(test.shortDescription(), "this tests foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001817
Georg Brandl15c5ce92007-03-07 09:09:40 +00001818class Test_TestResult(TestCase):
1819 # Note: there are not separate tests for TestResult.wasSuccessful(),
1820 # TestResult.errors, TestResult.failures, TestResult.testsRun or
1821 # TestResult.shouldStop because these only have meaning in terms of
1822 # other TestResult methods.
1823 #
1824 # Accordingly, tests for the aforenamed attributes are incorporated
1825 # in with the tests for the defining methods.
1826 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001827
Georg Brandl15c5ce92007-03-07 09:09:40 +00001828 def test_init(self):
1829 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001830
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001831 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001832 self.assertEqual(len(result.errors), 0)
1833 self.assertEqual(len(result.failures), 0)
1834 self.assertEqual(result.testsRun, 0)
1835 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001836
Georg Brandl15c5ce92007-03-07 09:09:40 +00001837 # "This method can be called to signal that the set of tests being
1838 # run should be aborted by setting the TestResult's shouldStop
Tim Petersea5962f2007-03-12 18:07:52 +00001839 # attribute to True."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001840 def test_stop(self):
1841 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001842
Georg Brandl15c5ce92007-03-07 09:09:40 +00001843 result.stop()
Tim Petersea5962f2007-03-12 18:07:52 +00001844
Georg Brandl15c5ce92007-03-07 09:09:40 +00001845 self.assertEqual(result.shouldStop, True)
Tim Petersea5962f2007-03-12 18:07:52 +00001846
Georg Brandl15c5ce92007-03-07 09:09:40 +00001847 # "Called when the test case test is about to be run. The default
1848 # implementation simply increments the instance's testsRun counter."
1849 def test_startTest(self):
1850 class Foo(unittest.TestCase):
1851 def test_1(self):
1852 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001853
Georg Brandl15c5ce92007-03-07 09:09:40 +00001854 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001855
Georg Brandl15c5ce92007-03-07 09:09:40 +00001856 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001857
Georg Brandl15c5ce92007-03-07 09:09:40 +00001858 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001859
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001860 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001861 self.assertEqual(len(result.errors), 0)
1862 self.assertEqual(len(result.failures), 0)
1863 self.assertEqual(result.testsRun, 1)
1864 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001865
Georg Brandl15c5ce92007-03-07 09:09:40 +00001866 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001867
Georg Brandl15c5ce92007-03-07 09:09:40 +00001868 # "Called after the test case test has been executed, regardless of
1869 # the outcome. The default implementation does nothing."
1870 def test_stopTest(self):
1871 class Foo(unittest.TestCase):
1872 def test_1(self):
1873 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001874
Georg Brandl15c5ce92007-03-07 09:09:40 +00001875 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001876
Georg Brandl15c5ce92007-03-07 09:09:40 +00001877 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001878
Georg Brandl15c5ce92007-03-07 09:09:40 +00001879 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001880
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001881 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001882 self.assertEqual(len(result.errors), 0)
1883 self.assertEqual(len(result.failures), 0)
1884 self.assertEqual(result.testsRun, 1)
1885 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001886
Georg Brandl15c5ce92007-03-07 09:09:40 +00001887 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001888
Georg Brandl15c5ce92007-03-07 09:09:40 +00001889 # Same tests as above; make sure nothing has changed
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001890 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001891 self.assertEqual(len(result.errors), 0)
1892 self.assertEqual(len(result.failures), 0)
1893 self.assertEqual(result.testsRun, 1)
1894 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001895
Michael Foord07ef4872009-05-02 22:43:34 +00001896 # "Called before and after tests are run. The default implementation does nothing."
1897 def test_startTestRun_stopTestRun(self):
1898 result = unittest.TestResult()
1899 result.startTestRun()
1900 result.stopTestRun()
1901
Georg Brandl15c5ce92007-03-07 09:09:40 +00001902 # "addSuccess(test)"
1903 # ...
1904 # "Called when the test case test succeeds"
1905 # ...
1906 # "wasSuccessful() - Returns True if all tests run so far have passed,
1907 # otherwise returns False"
1908 # ...
1909 # "testsRun - The total number of tests run so far."
1910 # ...
1911 # "errors - A list containing 2-tuples of TestCase instances and
1912 # formatted tracebacks. Each tuple represents a test which raised an
1913 # unexpected exception. Contains formatted
1914 # tracebacks instead of sys.exc_info() results."
1915 # ...
1916 # "failures - A list containing 2-tuples of TestCase instances and
1917 # formatted tracebacks. Each tuple represents a test where a failure was
1918 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1919 # methods. Contains formatted tracebacks instead
1920 # of sys.exc_info() results."
1921 def test_addSuccess(self):
1922 class Foo(unittest.TestCase):
1923 def test_1(self):
1924 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001925
Georg Brandl15c5ce92007-03-07 09:09:40 +00001926 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001927
Georg Brandl15c5ce92007-03-07 09:09:40 +00001928 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001929
Georg Brandl15c5ce92007-03-07 09:09:40 +00001930 result.startTest(test)
1931 result.addSuccess(test)
1932 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001933
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001934 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001935 self.assertEqual(len(result.errors), 0)
1936 self.assertEqual(len(result.failures), 0)
1937 self.assertEqual(result.testsRun, 1)
1938 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001939
Georg Brandl15c5ce92007-03-07 09:09:40 +00001940 # "addFailure(test, err)"
1941 # ...
1942 # "Called when the test case test signals a failure. err is a tuple of
1943 # the form returned by sys.exc_info(): (type, value, traceback)"
1944 # ...
1945 # "wasSuccessful() - Returns True if all tests run so far have passed,
1946 # otherwise returns False"
1947 # ...
1948 # "testsRun - The total number of tests run so far."
1949 # ...
1950 # "errors - A list containing 2-tuples of TestCase instances and
1951 # formatted tracebacks. Each tuple represents a test which raised an
1952 # unexpected exception. Contains formatted
1953 # tracebacks instead of sys.exc_info() results."
1954 # ...
1955 # "failures - A list containing 2-tuples of TestCase instances and
1956 # formatted tracebacks. Each tuple represents a test where a failure was
1957 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1958 # methods. Contains formatted tracebacks instead
1959 # of sys.exc_info() results."
1960 def test_addFailure(self):
Georg Brandl15c5ce92007-03-07 09:09:40 +00001961 class Foo(unittest.TestCase):
1962 def test_1(self):
1963 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001964
Georg Brandl15c5ce92007-03-07 09:09:40 +00001965 test = Foo('test_1')
1966 try:
1967 test.fail("foo")
1968 except:
1969 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00001970
Georg Brandl15c5ce92007-03-07 09:09:40 +00001971 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001972
Georg Brandl15c5ce92007-03-07 09:09:40 +00001973 result.startTest(test)
1974 result.addFailure(test, exc_info_tuple)
1975 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001976
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001977 self.assertFalse(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001978 self.assertEqual(len(result.errors), 0)
1979 self.assertEqual(len(result.failures), 1)
1980 self.assertEqual(result.testsRun, 1)
1981 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001982
Georg Brandl15c5ce92007-03-07 09:09:40 +00001983 test_case, formatted_exc = result.failures[0]
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001984 self.assertTrue(test_case is test)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001985 self.assertIsInstance(formatted_exc, str)
Tim Petersea5962f2007-03-12 18:07:52 +00001986
Georg Brandl15c5ce92007-03-07 09:09:40 +00001987 # "addError(test, err)"
1988 # ...
1989 # "Called when the test case test raises an unexpected exception err
1990 # is a tuple of the form returned by sys.exc_info():
1991 # (type, value, traceback)"
1992 # ...
1993 # "wasSuccessful() - Returns True if all tests run so far have passed,
1994 # otherwise returns False"
1995 # ...
1996 # "testsRun - The total number of tests run so far."
1997 # ...
1998 # "errors - A list containing 2-tuples of TestCase instances and
1999 # formatted tracebacks. Each tuple represents a test which raised an
2000 # unexpected exception. Contains formatted
2001 # tracebacks instead of sys.exc_info() results."
2002 # ...
2003 # "failures - A list containing 2-tuples of TestCase instances and
2004 # formatted tracebacks. Each tuple represents a test where a failure was
2005 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
2006 # methods. Contains formatted tracebacks instead
2007 # of sys.exc_info() results."
2008 def test_addError(self):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002009 class Foo(unittest.TestCase):
2010 def test_1(self):
2011 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002012
Georg Brandl15c5ce92007-03-07 09:09:40 +00002013 test = Foo('test_1')
2014 try:
2015 raise TypeError()
2016 except:
2017 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00002018
Georg Brandl15c5ce92007-03-07 09:09:40 +00002019 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00002020
Georg Brandl15c5ce92007-03-07 09:09:40 +00002021 result.startTest(test)
2022 result.addError(test, exc_info_tuple)
2023 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00002024
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002025 self.assertFalse(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00002026 self.assertEqual(len(result.errors), 1)
2027 self.assertEqual(len(result.failures), 0)
2028 self.assertEqual(result.testsRun, 1)
2029 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00002030
Georg Brandl15c5ce92007-03-07 09:09:40 +00002031 test_case, formatted_exc = result.errors[0]
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002032 self.assertTrue(test_case is test)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002033 self.assertIsInstance(formatted_exc, str)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002034
Michael Foorddb43b5a2010-02-10 14:25:12 +00002035 def testGetDescriptionWithoutDocstring(self):
Michael Foord1c3abf42010-02-10 15:50:58 +00002036 result = unittest.TextTestResult(None, True, 1)
Michael Foorddb43b5a2010-02-10 14:25:12 +00002037 self.assertEqual(
2038 result.getDescription(self),
2039 'testGetDescriptionWithoutDocstring (' + __name__ +
2040 '.Test_TestResult)')
2041
2042 def testGetDescriptionWithOneLineDocstring(self):
2043 """Tests getDescription() for a method with a docstring."""
Michael Foord1c3abf42010-02-10 15:50:58 +00002044 result = unittest.TextTestResult(None, True, 1)
Michael Foorddb43b5a2010-02-10 14:25:12 +00002045 self.assertEqual(
2046 result.getDescription(self),
2047 ('testGetDescriptionWithOneLineDocstring '
2048 '(' + __name__ + '.Test_TestResult)\n'
2049 'Tests getDescription() for a method with a docstring.'))
2050
2051 def testGetDescriptionWithMultiLineDocstring(self):
2052 """Tests getDescription() for a method with a longer docstring.
2053 The second line of the docstring.
2054 """
Michael Foord1c3abf42010-02-10 15:50:58 +00002055 result = unittest.TextTestResult(None, True, 1)
Michael Foorddb43b5a2010-02-10 14:25:12 +00002056 self.assertEqual(
2057 result.getDescription(self),
2058 ('testGetDescriptionWithMultiLineDocstring '
2059 '(' + __name__ + '.Test_TestResult)\n'
2060 'Tests getDescription() for a method with a longer '
2061 'docstring.'))
2062
2063
Georg Brandl15c5ce92007-03-07 09:09:40 +00002064### Support code for Test_TestCase
2065################################################################
2066
2067class Foo(unittest.TestCase):
2068 def runTest(self): pass
2069 def test1(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002070
Georg Brandl15c5ce92007-03-07 09:09:40 +00002071class Bar(Foo):
2072 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002073
Michael Foord07ef4872009-05-02 22:43:34 +00002074class LoggingTestCase(unittest.TestCase):
2075 """A test case which logs its calls."""
2076
2077 def __init__(self, events):
2078 super(LoggingTestCase, self).__init__('test')
2079 self.events = events
2080
2081 def setUp(self):
2082 self.events.append('setUp')
2083
2084 def test(self):
2085 self.events.append('test')
2086
2087 def tearDown(self):
2088 self.events.append('tearDown')
2089
2090class ResultWithNoStartTestRunStopTestRun(object):
2091 """An object honouring TestResult before startTestRun/stopTestRun."""
2092
2093 def __init__(self):
2094 self.failures = []
2095 self.errors = []
2096 self.testsRun = 0
2097 self.skipped = []
2098 self.expectedFailures = []
2099 self.unexpectedSuccesses = []
2100 self.shouldStop = False
2101
2102 def startTest(self, test):
2103 pass
2104
2105 def stopTest(self, test):
2106 pass
2107
2108 def addError(self, test):
2109 pass
2110
2111 def addFailure(self, test):
2112 pass
2113
2114 def addSuccess(self, test):
2115 pass
2116
2117 def wasSuccessful(self):
2118 return True
2119
2120
Georg Brandl15c5ce92007-03-07 09:09:40 +00002121################################################################
2122### /Support code for Test_TestCase
2123
2124class Test_TestCase(TestCase, TestEquality, TestHashing):
2125
2126 ### Set up attributes used by inherited tests
2127 ################################################################
2128
2129 # Used by TestHashing.test_hash and TestEquality.test_eq
2130 eq_pairs = [(Foo('test1'), Foo('test1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002131
Georg Brandl15c5ce92007-03-07 09:09:40 +00002132 # Used by TestEquality.test_ne
2133 ne_pairs = [(Foo('test1'), Foo('runTest'))
2134 ,(Foo('test1'), Bar('test1'))
2135 ,(Foo('test1'), Bar('test2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002136
Georg Brandl15c5ce92007-03-07 09:09:40 +00002137 ################################################################
2138 ### /Set up attributes used by inherited tests
Tim Petersea5962f2007-03-12 18:07:52 +00002139
Georg Brandl15c5ce92007-03-07 09:09:40 +00002140
2141 # "class TestCase([methodName])"
2142 # ...
2143 # "Each instance of TestCase will run a single test method: the
2144 # method named methodName."
2145 # ...
2146 # "methodName defaults to "runTest"."
2147 #
2148 # Make sure it really is optional, and that it defaults to the proper
2149 # thing.
2150 def test_init__no_test_name(self):
2151 class Test(unittest.TestCase):
2152 def runTest(self): raise MyException()
2153 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002154
Georg Brandl15c5ce92007-03-07 09:09:40 +00002155 self.assertEqual(Test().id()[-13:], '.Test.runTest')
Tim Petersea5962f2007-03-12 18:07:52 +00002156
Georg Brandl15c5ce92007-03-07 09:09:40 +00002157 # "class TestCase([methodName])"
2158 # ...
2159 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002160 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002161 def test_init__test_name__valid(self):
2162 class Test(unittest.TestCase):
2163 def runTest(self): raise MyException()
2164 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002165
Georg Brandl15c5ce92007-03-07 09:09:40 +00002166 self.assertEqual(Test('test').id()[-10:], '.Test.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002167
Georg Brandl15c5ce92007-03-07 09:09:40 +00002168 # "class TestCase([methodName])"
2169 # ...
2170 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002171 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002172 def test_init__test_name__invalid(self):
2173 class Test(unittest.TestCase):
2174 def runTest(self): raise MyException()
2175 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002176
Georg Brandl15c5ce92007-03-07 09:09:40 +00002177 try:
2178 Test('testfoo')
2179 except ValueError:
2180 pass
2181 else:
2182 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +00002183
Georg Brandl15c5ce92007-03-07 09:09:40 +00002184 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00002185 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00002186 def test_countTestCases(self):
2187 class Foo(unittest.TestCase):
2188 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002189
Georg Brandl15c5ce92007-03-07 09:09:40 +00002190 self.assertEqual(Foo('test').countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00002191
Georg Brandl15c5ce92007-03-07 09:09:40 +00002192 # "Return the default type of test result object to be used to run this
2193 # test. For TestCase instances, this will always be
2194 # unittest.TestResult; subclasses of TestCase should
2195 # override this as necessary."
2196 def test_defaultTestResult(self):
2197 class Foo(unittest.TestCase):
2198 def runTest(self):
2199 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002200
Georg Brandl15c5ce92007-03-07 09:09:40 +00002201 result = Foo().defaultTestResult()
2202 self.assertEqual(type(result), unittest.TestResult)
2203
2204 # "When a setUp() method is defined, the test runner will run that method
2205 # prior to each test. Likewise, if a tearDown() method is defined, the
2206 # test runner will invoke that method after each test. In the example,
2207 # setUp() was used to create a fresh sequence for each test."
2208 #
2209 # Make sure the proper call order is maintained, even if setUp() raises
2210 # an exception.
2211 def test_run_call_order__error_in_setUp(self):
2212 events = []
2213 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002214
Michael Foord07ef4872009-05-02 22:43:34 +00002215 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002216 def setUp(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002217 super(Foo, self).setUp()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002218 raise RuntimeError('raised by Foo.setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002219
Michael Foord07ef4872009-05-02 22:43:34 +00002220 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002221 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2222 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002223
Michael Foord07ef4872009-05-02 22:43:34 +00002224 # "With a temporary result stopTestRun is called when setUp errors.
2225 def test_run_call_order__error_in_setUp_default_result(self):
2226 events = []
2227
2228 class Foo(LoggingTestCase):
2229 def defaultTestResult(self):
2230 return LoggingResult(self.events)
2231
2232 def setUp(self):
2233 super(Foo, self).setUp()
2234 raise RuntimeError('raised by Foo.setUp')
2235
2236 Foo(events).run()
2237 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2238 'stopTest', 'stopTestRun']
2239 self.assertEqual(events, expected)
2240
Georg Brandl15c5ce92007-03-07 09:09:40 +00002241 # "When a setUp() method is defined, the test runner will run that method
2242 # prior to each test. Likewise, if a tearDown() method is defined, the
2243 # test runner will invoke that method after each test. In the example,
2244 # setUp() was used to create a fresh sequence for each test."
2245 #
2246 # Make sure the proper call order is maintained, even if the test raises
2247 # an error (as opposed to a failure).
2248 def test_run_call_order__error_in_test(self):
2249 events = []
2250 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002251
Michael Foord07ef4872009-05-02 22:43:34 +00002252 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002253 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002254 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002255 raise RuntimeError('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002256
Georg Brandl15c5ce92007-03-07 09:09:40 +00002257 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2258 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002259 Foo(events).run(result)
2260 self.assertEqual(events, expected)
2261
2262 # "With a default result, an error in the test still results in stopTestRun
2263 # being called."
2264 def test_run_call_order__error_in_test_default_result(self):
2265 events = []
2266
2267 class Foo(LoggingTestCase):
2268 def defaultTestResult(self):
2269 return LoggingResult(self.events)
2270
2271 def test(self):
2272 super(Foo, self).test()
2273 raise RuntimeError('raised by Foo.test')
2274
2275 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2276 'tearDown', 'stopTest', 'stopTestRun']
2277 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002278 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002279
Georg Brandl15c5ce92007-03-07 09:09:40 +00002280 # "When a setUp() method is defined, the test runner will run that method
2281 # prior to each test. Likewise, if a tearDown() method is defined, the
2282 # test runner will invoke that method after each test. In the example,
2283 # setUp() was used to create a fresh sequence for each test."
2284 #
2285 # Make sure the proper call order is maintained, even if the test signals
2286 # a failure (as opposed to an error).
2287 def test_run_call_order__failure_in_test(self):
2288 events = []
2289 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002290
Michael Foord07ef4872009-05-02 22:43:34 +00002291 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002292 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002293 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002294 self.fail('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002295
Georg Brandl15c5ce92007-03-07 09:09:40 +00002296 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2297 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002298 Foo(events).run(result)
2299 self.assertEqual(events, expected)
2300
2301 # "When a test fails with a default result stopTestRun is still called."
2302 def test_run_call_order__failure_in_test_default_result(self):
2303
2304 class Foo(LoggingTestCase):
2305 def defaultTestResult(self):
2306 return LoggingResult(self.events)
2307 def test(self):
2308 super(Foo, self).test()
2309 self.fail('raised by Foo.test')
2310
2311 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2312 'tearDown', 'stopTest', 'stopTestRun']
2313 events = []
2314 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002315 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002316
Georg Brandl15c5ce92007-03-07 09:09:40 +00002317 # "When a setUp() method is defined, the test runner will run that method
2318 # prior to each test. Likewise, if a tearDown() method is defined, the
2319 # test runner will invoke that method after each test. In the example,
2320 # setUp() was used to create a fresh sequence for each test."
2321 #
2322 # Make sure the proper call order is maintained, even if tearDown() raises
2323 # an exception.
2324 def test_run_call_order__error_in_tearDown(self):
2325 events = []
2326 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002327
Michael Foord07ef4872009-05-02 22:43:34 +00002328 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002329 def tearDown(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002330 super(Foo, self).tearDown()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002331 raise RuntimeError('raised by Foo.tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002332
Michael Foord07ef4872009-05-02 22:43:34 +00002333 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002334 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2335 'stopTest']
2336 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002337
Michael Foord07ef4872009-05-02 22:43:34 +00002338 # "When tearDown errors with a default result stopTestRun is still called."
2339 def test_run_call_order__error_in_tearDown_default_result(self):
2340
2341 class Foo(LoggingTestCase):
2342 def defaultTestResult(self):
2343 return LoggingResult(self.events)
2344 def tearDown(self):
2345 super(Foo, self).tearDown()
2346 raise RuntimeError('raised by Foo.tearDown')
2347
2348 events = []
2349 Foo(events).run()
2350 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2351 'addError', 'stopTest', 'stopTestRun']
2352 self.assertEqual(events, expected)
2353
2354 # "TestCase.run() still works when the defaultTestResult is a TestResult
2355 # that does not support startTestRun and stopTestRun.
2356 def test_run_call_order_default_result(self):
2357
2358 class Foo(unittest.TestCase):
2359 def defaultTestResult(self):
2360 return ResultWithNoStartTestRunStopTestRun()
2361 def test(self):
2362 pass
2363
2364 Foo('test').run()
2365
Georg Brandl15c5ce92007-03-07 09:09:40 +00002366 # "This class attribute gives the exception raised by the test() method.
2367 # If a test framework needs to use a specialized exception, possibly to
2368 # carry additional information, it must subclass this exception in
2369 # order to ``play fair'' with the framework. The initial value of this
2370 # attribute is AssertionError"
2371 def test_failureException__default(self):
2372 class Foo(unittest.TestCase):
2373 def test(self):
2374 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002375
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002376 self.assertTrue(Foo('test').failureException is AssertionError)
Tim Petersea5962f2007-03-12 18:07:52 +00002377
Georg Brandl15c5ce92007-03-07 09:09:40 +00002378 # "This class attribute gives the exception raised by the test() method.
2379 # If a test framework needs to use a specialized exception, possibly to
2380 # carry additional information, it must subclass this exception in
2381 # order to ``play fair'' with the framework."
2382 #
2383 # Make sure TestCase.run() respects the designated failureException
2384 def test_failureException__subclassing__explicit_raise(self):
2385 events = []
2386 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002387
Georg Brandl15c5ce92007-03-07 09:09:40 +00002388 class Foo(unittest.TestCase):
2389 def test(self):
2390 raise RuntimeError()
Tim Petersea5962f2007-03-12 18:07:52 +00002391
Georg Brandl15c5ce92007-03-07 09:09:40 +00002392 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002393
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002394 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002395
2396
Georg Brandl15c5ce92007-03-07 09:09:40 +00002397 Foo('test').run(result)
2398 expected = ['startTest', 'addFailure', 'stopTest']
2399 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002400
Georg Brandl15c5ce92007-03-07 09:09:40 +00002401 # "This class attribute gives the exception raised by the test() method.
2402 # If a test framework needs to use a specialized exception, possibly to
2403 # carry additional information, it must subclass this exception in
2404 # order to ``play fair'' with the framework."
2405 #
2406 # Make sure TestCase.run() respects the designated failureException
2407 def test_failureException__subclassing__implicit_raise(self):
2408 events = []
2409 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002410
Georg Brandl15c5ce92007-03-07 09:09:40 +00002411 class Foo(unittest.TestCase):
2412 def test(self):
2413 self.fail("foo")
Tim Petersea5962f2007-03-12 18:07:52 +00002414
Georg Brandl15c5ce92007-03-07 09:09:40 +00002415 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002416
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002417 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002418
2419
Georg Brandl15c5ce92007-03-07 09:09:40 +00002420 Foo('test').run(result)
2421 expected = ['startTest', 'addFailure', 'stopTest']
2422 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002423
2424 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002425 def test_setUp(self):
2426 class Foo(unittest.TestCase):
2427 def runTest(self):
2428 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002429
Georg Brandl15c5ce92007-03-07 09:09:40 +00002430 # ... and nothing should happen
2431 Foo().setUp()
Tim Petersea5962f2007-03-12 18:07:52 +00002432
2433 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002434 def test_tearDown(self):
2435 class Foo(unittest.TestCase):
2436 def runTest(self):
2437 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002438
Georg Brandl15c5ce92007-03-07 09:09:40 +00002439 # ... and nothing should happen
2440 Foo().tearDown()
Tim Petersea5962f2007-03-12 18:07:52 +00002441
Georg Brandl15c5ce92007-03-07 09:09:40 +00002442 # "Return a string identifying the specific test case."
2443 #
2444 # Because of the vague nature of the docs, I'm not going to lock this
2445 # test down too much. Really all that can be asserted is that the id()
2446 # will be a string (either 8-byte or unicode -- again, because the docs
2447 # just say "string")
2448 def test_id(self):
2449 class Foo(unittest.TestCase):
2450 def runTest(self):
2451 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002452
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002453 self.assertIsInstance(Foo().id(), basestring)
Tim Petersea5962f2007-03-12 18:07:52 +00002454
Georg Brandl15c5ce92007-03-07 09:09:40 +00002455 # "If result is omitted or None, a temporary result object is created
Michael Foord07ef4872009-05-02 22:43:34 +00002456 # and used, but is not made available to the caller. As TestCase owns the
2457 # temporary result startTestRun and stopTestRun are called.
2458
Georg Brandl15c5ce92007-03-07 09:09:40 +00002459 def test_run__uses_defaultTestResult(self):
2460 events = []
Tim Petersea5962f2007-03-12 18:07:52 +00002461
Georg Brandl15c5ce92007-03-07 09:09:40 +00002462 class Foo(unittest.TestCase):
2463 def test(self):
2464 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002465
Georg Brandl15c5ce92007-03-07 09:09:40 +00002466 def defaultTestResult(self):
2467 return LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002468
2469 # Make run() find a result object on its own
Georg Brandl15c5ce92007-03-07 09:09:40 +00002470 Foo('test').run()
Tim Petersea5962f2007-03-12 18:07:52 +00002471
Michael Foord07ef4872009-05-02 22:43:34 +00002472 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2473 'stopTest', 'stopTestRun']
Georg Brandl15c5ce92007-03-07 09:09:40 +00002474 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002475
Gregory P. Smith28399852009-03-31 16:54:10 +00002476 def testShortDescriptionWithoutDocstring(self):
Michael Foorddb43b5a2010-02-10 14:25:12 +00002477 self.assertIsNone(self.shortDescription())
Gregory P. Smith28399852009-03-31 16:54:10 +00002478
2479 def testShortDescriptionWithOneLineDocstring(self):
2480 """Tests shortDescription() for a method with a docstring."""
2481 self.assertEqual(
2482 self.shortDescription(),
Michael Foorddb43b5a2010-02-10 14:25:12 +00002483 'Tests shortDescription() for a method with a docstring.')
Gregory P. Smith28399852009-03-31 16:54:10 +00002484
2485 def testShortDescriptionWithMultiLineDocstring(self):
2486 """Tests shortDescription() for a method with a longer docstring.
2487
2488 This method ensures that only the first line of a docstring is
2489 returned used in the short description, no matter how long the
2490 whole thing is.
2491 """
2492 self.assertEqual(
2493 self.shortDescription(),
Gregory P. Smith28399852009-03-31 16:54:10 +00002494 'Tests shortDescription() for a method with a longer '
Michael Foorddb43b5a2010-02-10 14:25:12 +00002495 'docstring.')
Gregory P. Smith28399852009-03-31 16:54:10 +00002496
Gregory P. Smith28399852009-03-31 16:54:10 +00002497 def testAddTypeEqualityFunc(self):
2498 class SadSnake(object):
2499 """Dummy class for test_addTypeEqualityFunc."""
2500 s1, s2 = SadSnake(), SadSnake()
2501 self.assertFalse(s1 == s2)
2502 def AllSnakesCreatedEqual(a, b, msg=None):
2503 return type(a) == type(b) == SadSnake
2504 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2505 self.assertEqual(s1, s2)
2506 # No this doesn't clean up and remove the SadSnake equality func
2507 # from this TestCase instance but since its a local nothing else
2508 # will ever notice that.
2509
Michael Foordf2dfef12009-04-05 19:19:28 +00002510 def testAssertIs(self):
2511 thing = object()
2512 self.assertIs(thing, thing)
2513 self.assertRaises(self.failureException, self.assertIs, thing, object())
2514
2515 def testAssertIsNot(self):
2516 thing = object()
2517 self.assertIsNot(thing, object())
2518 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2519
Georg Brandlf895cf52009-10-01 20:59:31 +00002520 def testAssertIsInstance(self):
2521 thing = []
2522 self.assertIsInstance(thing, list)
2523 self.assertRaises(self.failureException, self.assertIsInstance,
2524 thing, dict)
2525
2526 def testAssertNotIsInstance(self):
2527 thing = []
2528 self.assertNotIsInstance(thing, dict)
2529 self.assertRaises(self.failureException, self.assertNotIsInstance,
2530 thing, list)
2531
Gregory P. Smith28399852009-03-31 16:54:10 +00002532 def testAssertIn(self):
2533 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2534
2535 self.assertIn('a', 'abc')
2536 self.assertIn(2, [1, 2, 3])
2537 self.assertIn('monkey', animals)
2538
2539 self.assertNotIn('d', 'abc')
2540 self.assertNotIn(0, [1, 2, 3])
2541 self.assertNotIn('otter', animals)
2542
2543 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2544 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2545 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2546 animals)
2547
2548 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2549 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2550 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2551 animals)
2552
2553 def testAssertDictContainsSubset(self):
2554 self.assertDictContainsSubset({}, {})
2555 self.assertDictContainsSubset({}, {'a': 1})
2556 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2557 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2558 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2559
2560 self.assertRaises(unittest.TestCase.failureException,
2561 self.assertDictContainsSubset, {'a': 2}, {'a': 1},
2562 '.*Mismatched values:.*')
2563
2564 self.assertRaises(unittest.TestCase.failureException,
2565 self.assertDictContainsSubset, {'c': 1}, {'a': 1},
2566 '.*Missing:.*')
2567
2568 self.assertRaises(unittest.TestCase.failureException,
2569 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2570 {'a': 1}, '.*Missing:.*')
2571
2572 self.assertRaises(unittest.TestCase.failureException,
2573 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2574 {'a': 1}, '.*Missing:.*Mismatched values:.*')
2575
2576 def testAssertEqual(self):
2577 equal_pairs = [
2578 ((), ()),
2579 ({}, {}),
2580 ([], []),
2581 (set(), set()),
2582 (frozenset(), frozenset())]
2583 for a, b in equal_pairs:
2584 # This mess of try excepts is to test the assertEqual behavior
2585 # itself.
2586 try:
2587 self.assertEqual(a, b)
2588 except self.failureException:
2589 self.fail('assertEqual(%r, %r) failed' % (a, b))
2590 try:
2591 self.assertEqual(a, b, msg='foo')
2592 except self.failureException:
2593 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2594 try:
2595 self.assertEqual(a, b, 'foo')
2596 except self.failureException:
2597 self.fail('assertEqual(%r, %r) with third parameter failed' %
2598 (a, b))
2599
2600 unequal_pairs = [
2601 ((), []),
2602 ({}, set()),
2603 (set([4,1]), frozenset([4,2])),
2604 (frozenset([4,5]), set([2,3])),
2605 (set([3,4]), set([5,4]))]
2606 for a, b in unequal_pairs:
2607 self.assertRaises(self.failureException, self.assertEqual, a, b)
2608 self.assertRaises(self.failureException, self.assertEqual, a, b,
2609 'foo')
2610 self.assertRaises(self.failureException, self.assertEqual, a, b,
2611 msg='foo')
2612
2613 def testEquality(self):
2614 self.assertListEqual([], [])
2615 self.assertTupleEqual((), ())
2616 self.assertSequenceEqual([], ())
2617
2618 a = [0, 'a', []]
2619 b = []
2620 self.assertRaises(unittest.TestCase.failureException,
2621 self.assertListEqual, a, b)
2622 self.assertRaises(unittest.TestCase.failureException,
2623 self.assertListEqual, tuple(a), tuple(b))
2624 self.assertRaises(unittest.TestCase.failureException,
2625 self.assertSequenceEqual, a, tuple(b))
2626
2627 b.extend(a)
2628 self.assertListEqual(a, b)
2629 self.assertTupleEqual(tuple(a), tuple(b))
2630 self.assertSequenceEqual(a, tuple(b))
2631 self.assertSequenceEqual(tuple(a), b)
2632
2633 self.assertRaises(self.failureException, self.assertListEqual,
2634 a, tuple(b))
2635 self.assertRaises(self.failureException, self.assertTupleEqual,
2636 tuple(a), b)
2637 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2638 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2639 tuple(b))
2640 self.assertRaises(self.failureException, self.assertSequenceEqual,
2641 None, tuple(b))
2642 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2643 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2644 self.assertRaises(self.failureException, self.assertSequenceEqual,
2645 1, 1)
2646
2647 self.assertDictEqual({}, {})
2648
2649 c = { 'x': 1 }
2650 d = {}
2651 self.assertRaises(unittest.TestCase.failureException,
2652 self.assertDictEqual, c, d)
2653
2654 d.update(c)
2655 self.assertDictEqual(c, d)
2656
2657 d['x'] = 0
2658 self.assertRaises(unittest.TestCase.failureException,
2659 self.assertDictEqual, c, d, 'These are unequal')
2660
2661 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2662 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2663 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2664
2665 self.assertSameElements([1, 2, 3], [3, 2, 1])
2666 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2667 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2668 self.assertRaises(self.failureException, self.assertSameElements,
2669 [10], [10, 11])
2670 self.assertRaises(self.failureException, self.assertSameElements,
2671 [10, 11], [10])
2672
2673 # Test that sequences of unhashable objects can be tested for sameness:
2674 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Michael Foordf2dfef12009-04-05 19:19:28 +00002675
Gregory P. Smith28399852009-03-31 16:54:10 +00002676 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2677 self.assertRaises(self.failureException, self.assertSameElements,
2678 [[1]], [[2]])
2679
2680 def testAssertSetEqual(self):
2681 set1 = set()
2682 set2 = set()
2683 self.assertSetEqual(set1, set2)
2684
2685 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2686 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2687 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2688 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2689
2690 set1 = set(['a'])
2691 set2 = set()
2692 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2693
2694 set1 = set(['a'])
2695 set2 = set(['a'])
2696 self.assertSetEqual(set1, set2)
2697
2698 set1 = set(['a'])
2699 set2 = set(['a', 'b'])
2700 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2701
2702 set1 = set(['a'])
2703 set2 = frozenset(['a', 'b'])
2704 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2705
2706 set1 = set(['a', 'b'])
2707 set2 = frozenset(['a', 'b'])
2708 self.assertSetEqual(set1, set2)
2709
2710 set1 = set()
2711 set2 = "foo"
2712 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2713 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2714
2715 # make sure any string formatting is tuple-safe
2716 set1 = set([(0, 1), (2, 3)])
2717 set2 = set([(4, 5)])
2718 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2719
2720 def testInequality(self):
2721 # Try ints
2722 self.assertGreater(2, 1)
2723 self.assertGreaterEqual(2, 1)
2724 self.assertGreaterEqual(1, 1)
2725 self.assertLess(1, 2)
2726 self.assertLessEqual(1, 2)
2727 self.assertLessEqual(1, 1)
2728 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2729 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2730 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2731 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2732 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2733 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2734
2735 # Try Floats
2736 self.assertGreater(1.1, 1.0)
2737 self.assertGreaterEqual(1.1, 1.0)
2738 self.assertGreaterEqual(1.0, 1.0)
2739 self.assertLess(1.0, 1.1)
2740 self.assertLessEqual(1.0, 1.1)
2741 self.assertLessEqual(1.0, 1.0)
2742 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2743 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2744 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2745 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2746 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2747 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2748
2749 # Try Strings
2750 self.assertGreater('bug', 'ant')
2751 self.assertGreaterEqual('bug', 'ant')
2752 self.assertGreaterEqual('ant', 'ant')
2753 self.assertLess('ant', 'bug')
2754 self.assertLessEqual('ant', 'bug')
2755 self.assertLessEqual('ant', 'ant')
2756 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2757 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2758 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2759 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2760 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2761 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2762
2763 # Try Unicode
2764 self.assertGreater(u'bug', u'ant')
2765 self.assertGreaterEqual(u'bug', u'ant')
2766 self.assertGreaterEqual(u'ant', u'ant')
2767 self.assertLess(u'ant', u'bug')
2768 self.assertLessEqual(u'ant', u'bug')
2769 self.assertLessEqual(u'ant', u'ant')
2770 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug')
2771 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant')
2772 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2773 u'bug')
2774 self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant')
2775 self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant')
2776 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant')
2777
2778 # Try Mixed String/Unicode
2779 self.assertGreater('bug', u'ant')
2780 self.assertGreater(u'bug', 'ant')
2781 self.assertGreaterEqual('bug', u'ant')
2782 self.assertGreaterEqual(u'bug', 'ant')
2783 self.assertGreaterEqual('ant', u'ant')
2784 self.assertGreaterEqual(u'ant', 'ant')
2785 self.assertLess('ant', u'bug')
2786 self.assertLess(u'ant', 'bug')
2787 self.assertLessEqual('ant', u'bug')
2788 self.assertLessEqual(u'ant', 'bug')
2789 self.assertLessEqual('ant', u'ant')
2790 self.assertLessEqual(u'ant', 'ant')
2791 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug')
2792 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug')
2793 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant')
2794 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant')
2795 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant',
2796 u'bug')
2797 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2798 'bug')
2799 self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant')
2800 self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant')
2801 self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant')
2802 self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant')
2803 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant')
2804 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant')
2805
2806 def testAssertMultiLineEqual(self):
2807 sample_text = b"""\
2808http://www.python.org/doc/2.3/lib/module-unittest.html
2809test case
2810 A test case is the smallest unit of testing. [...]
2811"""
2812 revised_sample_text = b"""\
2813http://www.python.org/doc/2.4.1/lib/module-unittest.html
2814test case
2815 A test case is the smallest unit of testing. [...] You may provide your
2816 own implementation that does not subclass from TestCase, of course.
2817"""
2818 sample_text_error = b"""
2819- http://www.python.org/doc/2.3/lib/module-unittest.html
2820? ^
2821+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2822? ^^^
2823 test case
2824- A test case is the smallest unit of testing. [...]
2825+ A test case is the smallest unit of testing. [...] You may provide your
2826? +++++++++++++++++++++
2827+ own implementation that does not subclass from TestCase, of course.
2828"""
2829
2830 for type_changer in (lambda x: x, lambda x: x.decode('utf8')):
2831 try:
2832 self.assertMultiLineEqual(type_changer(sample_text),
2833 type_changer(revised_sample_text))
2834 except self.failureException, e:
Michael Foordfe6349c2010-02-08 22:41:16 +00002835 # assertMultiLineEqual is hooked up as the default for
2836 # unicode strings - so we can't use it for this check
2837 self.assertTrue(sample_text_error == str(e).encode('utf8'))
Gregory P. Smith28399852009-03-31 16:54:10 +00002838
2839 def testAssertIsNone(self):
2840 self.assertIsNone(None)
2841 self.assertRaises(self.failureException, self.assertIsNone, False)
2842 self.assertIsNotNone('DjZoPloGears on Rails')
2843 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2844
2845 def testAssertRegexpMatches(self):
2846 self.assertRegexpMatches('asdfabasdf', r'ab+')
2847 self.assertRaises(self.failureException, self.assertRegexpMatches,
2848 'saaas', r'aaaa')
2849
2850 def testAssertRaisesRegexp(self):
2851 class ExceptionMock(Exception):
2852 pass
2853
2854 def Stub():
2855 raise ExceptionMock('We expect')
2856
2857 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2858 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2859 self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
2860
2861 def testAssertNotRaisesRegexp(self):
2862 self.assertRaisesRegexp(
2863 self.failureException, '^Exception not raised$',
2864 self.assertRaisesRegexp, Exception, re.compile('x'),
2865 lambda: None)
2866 self.assertRaisesRegexp(
2867 self.failureException, '^Exception not raised$',
2868 self.assertRaisesRegexp, Exception, 'x',
2869 lambda: None)
2870 self.assertRaisesRegexp(
2871 self.failureException, '^Exception not raised$',
2872 self.assertRaisesRegexp, Exception, u'x',
2873 lambda: None)
2874
2875 def testAssertRaisesRegexpMismatch(self):
2876 def Stub():
2877 raise Exception('Unexpected')
2878
2879 self.assertRaisesRegexp(
2880 self.failureException,
2881 r'"\^Expected\$" does not match "Unexpected"',
2882 self.assertRaisesRegexp, Exception, '^Expected$',
2883 Stub)
2884 self.assertRaisesRegexp(
2885 self.failureException,
2886 r'"\^Expected\$" does not match "Unexpected"',
2887 self.assertRaisesRegexp, Exception, u'^Expected$',
2888 Stub)
2889 self.assertRaisesRegexp(
2890 self.failureException,
2891 r'"\^Expected\$" does not match "Unexpected"',
2892 self.assertRaisesRegexp, Exception,
2893 re.compile('^Expected$'), Stub)
2894
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00002895 def testAssertRaisesExcValue(self):
2896 class ExceptionMock(Exception):
2897 pass
2898
2899 def Stub(foo):
2900 raise ExceptionMock(foo)
2901 v = "particular value"
2902
2903 ctx = self.assertRaises(ExceptionMock)
2904 with ctx:
2905 Stub(v)
Georg Brandldc3694b2010-02-07 17:02:22 +00002906 e = ctx.exception
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002907 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00002908 self.assertEqual(e.args[0], v)
2909
Gregory P. Smith7558d572009-03-31 19:03:28 +00002910 def testSynonymAssertMethodNames(self):
2911 """Test undocumented method name synonyms.
2912
2913 Please do not use these methods names in your own code.
2914
2915 This test confirms their continued existence and functionality
2916 in order to avoid breaking existing code.
2917 """
2918 self.assertNotEquals(3, 5)
2919 self.assertEquals(3, 3)
2920 self.assertAlmostEquals(2.0, 2.0)
2921 self.assertNotAlmostEquals(3.0, 5.0)
2922 self.assert_(True)
2923
2924 def testPendingDeprecationMethodNames(self):
2925 """Test fail* methods pending deprecation, they will warn in 3.2.
2926
2927 Do not use these methods. They will go away in 3.3.
2928 """
2929 self.failIfEqual(3, 5)
2930 self.failUnlessEqual(3, 3)
2931 self.failUnlessAlmostEqual(2.0, 2.0)
2932 self.failIfAlmostEqual(3.0, 5.0)
2933 self.failUnless(True)
2934 self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam')
2935 self.failIf(False)
2936
Michael Foorde2942d02009-04-02 05:51:54 +00002937 def testDeepcopy(self):
2938 # Issue: 5660
2939 class TestableTest(TestCase):
2940 def testNothing(self):
2941 pass
2942
2943 test = TestableTest('testNothing')
2944
2945 # This shouldn't blow up
2946 deepcopy(test)
2947
Benjamin Peterson692428e2009-03-23 21:50:21 +00002948
2949class Test_TestSkipping(TestCase):
2950
2951 def test_skipping(self):
2952 class Foo(unittest.TestCase):
2953 def test_skip_me(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002954 self.skipTest("skip")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002955 events = []
2956 result = LoggingResult(events)
2957 test = Foo("test_skip_me")
2958 test.run(result)
2959 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2960 self.assertEqual(result.skipped, [(test, "skip")])
2961
2962 # Try letting setUp skip the test now.
2963 class Foo(unittest.TestCase):
2964 def setUp(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002965 self.skipTest("testing")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002966 def test_nothing(self): pass
2967 events = []
2968 result = LoggingResult(events)
2969 test = Foo("test_nothing")
2970 test.run(result)
2971 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2972 self.assertEqual(result.skipped, [(test, "testing")])
2973 self.assertEqual(result.testsRun, 1)
2974
2975 def test_skipping_decorators(self):
2976 op_table = ((unittest.skipUnless, False, True),
2977 (unittest.skipIf, True, False))
2978 for deco, do_skip, dont_skip in op_table:
2979 class Foo(unittest.TestCase):
2980 @deco(do_skip, "testing")
2981 def test_skip(self): pass
2982
2983 @deco(dont_skip, "testing")
2984 def test_dont_skip(self): pass
2985 test_do_skip = Foo("test_skip")
2986 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002987 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002988 events = []
2989 result = LoggingResult(events)
2990 suite.run(result)
2991 self.assertEqual(len(result.skipped), 1)
2992 expected = ['startTest', 'addSkip', 'stopTest',
2993 'startTest', 'addSuccess', 'stopTest']
2994 self.assertEqual(events, expected)
2995 self.assertEqual(result.testsRun, 2)
2996 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
2997 self.assertTrue(result.wasSuccessful())
2998
2999 def test_skip_class(self):
3000 @unittest.skip("testing")
3001 class Foo(unittest.TestCase):
3002 def test_1(self):
3003 record.append(1)
3004 record = []
3005 result = unittest.TestResult()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003006 test = Foo("test_1")
3007 suite = unittest.TestSuite([test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003008 suite.run(result)
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003009 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003010 self.assertEqual(record, [])
3011
3012 def test_expected_failure(self):
3013 class Foo(unittest.TestCase):
3014 @unittest.expectedFailure
3015 def test_die(self):
3016 self.fail("help me!")
3017 events = []
3018 result = LoggingResult(events)
3019 test = Foo("test_die")
3020 test.run(result)
3021 self.assertEqual(events,
3022 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003023 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00003024 self.assertTrue(result.wasSuccessful())
3025
3026 def test_unexpected_success(self):
3027 class Foo(unittest.TestCase):
3028 @unittest.expectedFailure
3029 def test_die(self):
3030 pass
3031 events = []
3032 result = LoggingResult(events)
3033 test = Foo("test_die")
3034 test.run(result)
3035 self.assertEqual(events,
3036 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3037 self.assertFalse(result.failures)
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003038 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003039 self.assertTrue(result.wasSuccessful())
3040
3041
3042
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003043class Test_Assertions(TestCase):
3044 def test_AlmostEqual(self):
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003045 self.assertAlmostEqual(1.00000001, 1.0)
3046 self.assertNotAlmostEqual(1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003047 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003048 self.assertAlmostEqual, 1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003049 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003050 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003051
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003052 self.assertAlmostEqual(1.1, 1.0, places=0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003053 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003054 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003055
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003056 self.assertAlmostEqual(0, .1+.1j, places=0)
3057 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003058 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003059 self.assertAlmostEqual, 0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003060 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003061 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003062
Michael Foordc3f79372009-09-13 16:40:02 +00003063 self.assertAlmostEqual(float('inf'), float('inf'))
3064 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3065 float('inf'), float('inf'))
3066
3067
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003068 def test_assertRaises(self):
3069 def _raise(e):
3070 raise e
3071 self.assertRaises(KeyError, _raise, KeyError)
3072 self.assertRaises(KeyError, _raise, KeyError("key"))
3073 try:
3074 self.assertRaises(KeyError, lambda: None)
Gregory P. Smith28399852009-03-31 16:54:10 +00003075 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003076 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003077 else:
3078 self.fail("assertRaises() didn't fail")
3079 try:
3080 self.assertRaises(KeyError, _raise, ValueError)
3081 except ValueError:
3082 pass
3083 else:
3084 self.fail("assertRaises() didn't let exception pass through")
Michael Foord2bd52dc2010-02-07 18:44:12 +00003085 with self.assertRaises(KeyError) as cm:
3086 try:
3087 raise KeyError
3088 except Exception, e:
3089 raise
3090 self.assertIs(cm.exception, e)
3091
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003092 with self.assertRaises(KeyError):
3093 raise KeyError("key")
3094 try:
3095 with self.assertRaises(KeyError):
3096 pass
Gregory P. Smith28399852009-03-31 16:54:10 +00003097 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003098 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003099 else:
3100 self.fail("assertRaises() didn't fail")
3101 try:
3102 with self.assertRaises(KeyError):
3103 raise ValueError
3104 except ValueError:
3105 pass
3106 else:
3107 self.fail("assertRaises() didn't let exception pass through")
3108
3109
Michael Foord345b2fe2009-04-02 03:20:38 +00003110class TestLongMessage(TestCase):
3111 """Test that the individual asserts honour longMessage.
3112 This actually tests all the message behaviour for
3113 asserts that use longMessage."""
3114
3115 def setUp(self):
3116 class TestableTestFalse(TestCase):
3117 longMessage = False
3118 failureException = self.failureException
3119
3120 def testTest(self):
3121 pass
3122
3123 class TestableTestTrue(TestCase):
3124 longMessage = True
3125 failureException = self.failureException
3126
3127 def testTest(self):
3128 pass
3129
3130 self.testableTrue = TestableTestTrue('testTest')
3131 self.testableFalse = TestableTestFalse('testTest')
3132
3133 def testDefault(self):
3134 self.assertFalse(TestCase.longMessage)
3135
3136 def test_formatMsg(self):
3137 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3138 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3139
3140 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3141 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3142
3143 def assertMessages(self, methodName, args, errors):
3144 def getMethod(i):
3145 useTestableFalse = i < 2
3146 if useTestableFalse:
3147 test = self.testableFalse
3148 else:
3149 test = self.testableTrue
3150 return getattr(test, methodName)
3151
3152 for i, expected_regexp in enumerate(errors):
3153 testMethod = getMethod(i)
3154 kwargs = {}
3155 withMsg = i % 2
3156 if withMsg:
3157 kwargs = {"msg": "oops"}
3158
3159 with self.assertRaisesRegexp(self.failureException,
3160 expected_regexp=expected_regexp):
3161 testMethod(*args, **kwargs)
3162
3163 def testAssertTrue(self):
3164 self.assertMessages('assertTrue', (False,),
3165 ["^False is not True$", "^oops$", "^False is not True$",
3166 "^False is not True : oops$"])
3167
3168 def testAssertFalse(self):
3169 self.assertMessages('assertFalse', (True,),
3170 ["^True is not False$", "^oops$", "^True is not False$",
3171 "^True is not False : oops$"])
3172
3173 def testNotEqual(self):
3174 self.assertMessages('assertNotEqual', (1, 1),
3175 ["^1 == 1$", "^oops$", "^1 == 1$",
3176 "^1 == 1 : oops$"])
3177
3178 def testAlmostEqual(self):
3179 self.assertMessages('assertAlmostEqual', (1, 2),
3180 ["^1 != 2 within 7 places$", "^oops$",
3181 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3182
3183 def testNotAlmostEqual(self):
3184 self.assertMessages('assertNotAlmostEqual', (1, 1),
3185 ["^1 == 1 within 7 places$", "^oops$",
3186 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3187
3188 def test_baseAssertEqual(self):
3189 self.assertMessages('_baseAssertEqual', (1, 2),
3190 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3191
3192 def testAssertSequenceEqual(self):
3193 # Error messages are multiline so not testing on full message
3194 # assertTupleEqual and assertListEqual delegate to this method
3195 self.assertMessages('assertSequenceEqual', ([], [None]),
3196 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3197 r"\+ \[None\] : oops$"])
3198
3199 def testAssertSetEqual(self):
3200 self.assertMessages('assertSetEqual', (set(), set([None])),
3201 ["None$", "^oops$", "None$",
3202 "None : oops$"])
3203
3204 def testAssertIn(self):
3205 self.assertMessages('assertIn', (None, []),
3206 ['^None not found in \[\]$', "^oops$",
3207 '^None not found in \[\]$',
3208 '^None not found in \[\] : oops$'])
3209
3210 def testAssertNotIn(self):
3211 self.assertMessages('assertNotIn', (None, [None]),
3212 ['^None unexpectedly found in \[None\]$', "^oops$",
3213 '^None unexpectedly found in \[None\]$',
3214 '^None unexpectedly found in \[None\] : oops$'])
3215
3216 def testAssertDictEqual(self):
3217 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3218 [r"\+ \{'key': 'value'\}$", "^oops$",
3219 "\+ \{'key': 'value'\}$",
3220 "\+ \{'key': 'value'\} : oops$"])
3221
3222 def testAssertDictContainsSubset(self):
3223 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3224 ["^Missing: 'key'$", "^oops$",
3225 "^Missing: 'key'$",
3226 "^Missing: 'key' : oops$"])
3227
3228 def testAssertSameElements(self):
3229 self.assertMessages('assertSameElements', ([], [None]),
3230 [r"\[None\]$", "^oops$",
3231 r"\[None\]$",
3232 r"\[None\] : oops$"])
3233
3234 def testAssertMultiLineEqual(self):
3235 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3236 [r"\+ foo$", "^oops$",
3237 r"\+ foo$",
3238 r"\+ foo : oops$"])
3239
3240 def testAssertLess(self):
3241 self.assertMessages('assertLess', (2, 1),
3242 ["^2 not less than 1$", "^oops$",
3243 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3244
3245 def testAssertLessEqual(self):
3246 self.assertMessages('assertLessEqual', (2, 1),
3247 ["^2 not less than or equal to 1$", "^oops$",
3248 "^2 not less than or equal to 1$",
3249 "^2 not less than or equal to 1 : oops$"])
3250
3251 def testAssertGreater(self):
3252 self.assertMessages('assertGreater', (1, 2),
3253 ["^1 not greater than 2$", "^oops$",
3254 "^1 not greater than 2$",
3255 "^1 not greater than 2 : oops$"])
3256
3257 def testAssertGreaterEqual(self):
3258 self.assertMessages('assertGreaterEqual', (1, 2),
3259 ["^1 not greater than or equal to 2$", "^oops$",
3260 "^1 not greater than or equal to 2$",
3261 "^1 not greater than or equal to 2 : oops$"])
3262
3263 def testAssertIsNone(self):
3264 self.assertMessages('assertIsNone', ('not None',),
3265 ["^'not None' is not None$", "^oops$",
3266 "^'not None' is not None$",
3267 "^'not None' is not None : oops$"])
3268
3269 def testAssertIsNotNone(self):
3270 self.assertMessages('assertIsNotNone', (None,),
3271 ["^unexpectedly None$", "^oops$",
3272 "^unexpectedly None$",
3273 "^unexpectedly None : oops$"])
3274
Michael Foordf2dfef12009-04-05 19:19:28 +00003275 def testAssertIs(self):
3276 self.assertMessages('assertIs', (None, 'foo'),
3277 ["^None is not 'foo'$", "^oops$",
3278 "^None is not 'foo'$",
3279 "^None is not 'foo' : oops$"])
3280
3281 def testAssertIsNot(self):
3282 self.assertMessages('assertIsNot', (None, None),
3283 ["^unexpectedly identical: None$", "^oops$",
3284 "^unexpectedly identical: None$",
3285 "^unexpectedly identical: None : oops$"])
3286
Michael Foord345b2fe2009-04-02 03:20:38 +00003287
Michael Foorde2fb98f2009-05-02 20:15:05 +00003288class TestCleanUp(TestCase):
3289
3290 def testCleanUp(self):
3291 class TestableTest(TestCase):
3292 def testNothing(self):
3293 pass
3294
3295 test = TestableTest('testNothing')
3296 self.assertEqual(test._cleanups, [])
3297
3298 cleanups = []
3299
3300 def cleanup1(*args, **kwargs):
3301 cleanups.append((1, args, kwargs))
3302
3303 def cleanup2(*args, **kwargs):
3304 cleanups.append((2, args, kwargs))
3305
3306 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3307 test.addCleanup(cleanup2)
3308
3309 self.assertEqual(test._cleanups,
3310 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3311 (cleanup2, (), {})])
3312
3313 result = test.doCleanups()
3314 self.assertTrue(result)
3315
3316 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3317
3318 def testCleanUpWithErrors(self):
3319 class TestableTest(TestCase):
3320 def testNothing(self):
3321 pass
3322
3323 class MockResult(object):
3324 errors = []
3325 def addError(self, test, exc_info):
3326 self.errors.append((test, exc_info))
3327
3328 result = MockResult()
3329 test = TestableTest('testNothing')
Michael Foorda50af062009-05-21 22:57:02 +00003330 test._resultForDoCleanups = result
Michael Foorde2fb98f2009-05-02 20:15:05 +00003331
3332 exc1 = Exception('foo')
3333 exc2 = Exception('bar')
3334 def cleanup1():
3335 raise exc1
3336
3337 def cleanup2():
3338 raise exc2
3339
3340 test.addCleanup(cleanup1)
3341 test.addCleanup(cleanup2)
3342
3343 self.assertFalse(test.doCleanups())
3344
3345 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3346 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3347 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3348
3349 def testCleanupInRun(self):
3350 blowUp = False
3351 ordering = []
3352
3353 class TestableTest(TestCase):
3354 def setUp(self):
3355 ordering.append('setUp')
3356 if blowUp:
3357 raise Exception('foo')
3358
3359 def testNothing(self):
3360 ordering.append('test')
3361
3362 def tearDown(self):
3363 ordering.append('tearDown')
3364
3365 test = TestableTest('testNothing')
3366
3367 def cleanup1():
3368 ordering.append('cleanup1')
3369 def cleanup2():
3370 ordering.append('cleanup2')
3371 test.addCleanup(cleanup1)
3372 test.addCleanup(cleanup2)
3373
3374 def success(some_test):
3375 self.assertEqual(some_test, test)
3376 ordering.append('success')
3377
3378 result = unittest.TestResult()
3379 result.addSuccess = success
3380
3381 test.run(result)
3382 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3383 'cleanup2', 'cleanup1', 'success'])
3384
3385 blowUp = True
3386 ordering = []
3387 test = TestableTest('testNothing')
3388 test.addCleanup(cleanup1)
3389 test.run(result)
3390 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3391
3392
Michael Foord829f6b82009-05-02 11:43:06 +00003393class Test_TestProgram(TestCase):
3394
3395 # Horrible white box test
3396 def testNoExit(self):
3397 result = object()
3398 test = object()
3399
3400 class FakeRunner(object):
3401 def run(self, test):
3402 self.test = test
3403 return result
3404
3405 runner = FakeRunner()
3406
Michael Foord5d31e052009-05-11 17:59:43 +00003407 oldParseArgs = TestProgram.parseArgs
3408 def restoreParseArgs():
Michael Foord829f6b82009-05-02 11:43:06 +00003409 TestProgram.parseArgs = oldParseArgs
Michael Foord5d31e052009-05-11 17:59:43 +00003410 TestProgram.parseArgs = lambda *args: None
3411 self.addCleanup(restoreParseArgs)
3412
3413 def removeTest():
Michael Foord829f6b82009-05-02 11:43:06 +00003414 del TestProgram.test
Michael Foord5d31e052009-05-11 17:59:43 +00003415 TestProgram.test = test
3416 self.addCleanup(removeTest)
3417
3418 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3419
3420 self.assertEqual(program.result, result)
3421 self.assertEqual(runner.test, test)
3422 self.assertEqual(program.verbosity, 2)
Michael Foord829f6b82009-05-02 11:43:06 +00003423
Michael Foord829f6b82009-05-02 11:43:06 +00003424 class FooBar(unittest.TestCase):
3425 def testPass(self):
3426 assert True
3427 def testFail(self):
3428 assert False
3429
3430 class FooBarLoader(unittest.TestLoader):
3431 """Test loader that returns a suite containing FooBar."""
3432 def loadTestsFromModule(self, module):
3433 return self.suiteClass(
3434 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3435
3436
3437 def test_NonExit(self):
3438 program = unittest.main(exit=False,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003439 argv=["foobar"],
3440 testRunner=unittest.TextTestRunner(stream=StringIO()),
3441 testLoader=self.FooBarLoader())
Michael Foord829f6b82009-05-02 11:43:06 +00003442 self.assertTrue(hasattr(program, 'result'))
3443
3444
3445 def test_Exit(self):
3446 self.assertRaises(
3447 SystemExit,
3448 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003449 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003450 testRunner=unittest.TextTestRunner(stream=StringIO()),
3451 exit=True,
3452 testLoader=self.FooBarLoader())
3453
3454
3455 def test_ExitAsDefault(self):
3456 self.assertRaises(
3457 SystemExit,
3458 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003459 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003460 testRunner=unittest.TextTestRunner(stream=StringIO()),
3461 testLoader=self.FooBarLoader())
3462
3463
Michael Foord07ef4872009-05-02 22:43:34 +00003464class Test_TextTestRunner(TestCase):
3465 """Tests for TextTestRunner."""
3466
3467 def test_works_with_result_without_startTestRun_stopTestRun(self):
3468 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3469 separator2 = ''
3470 def printErrors(self):
3471 pass
3472
3473 class Runner(unittest.TextTestRunner):
3474 def __init__(self):
3475 super(Runner, self).__init__(StringIO())
3476
3477 def _makeResult(self):
3478 return OldTextResult()
3479
3480 runner = Runner()
3481 runner.run(unittest.TestSuite())
3482
3483 def test_startTestRun_stopTestRun_called(self):
3484 class LoggingTextResult(LoggingResult):
3485 separator2 = ''
3486 def printErrors(self):
3487 pass
3488
3489 class LoggingRunner(unittest.TextTestRunner):
3490 def __init__(self, events):
3491 super(LoggingRunner, self).__init__(StringIO())
3492 self._events = events
3493
3494 def _makeResult(self):
3495 return LoggingTextResult(self._events)
3496
3497 events = []
3498 runner = LoggingRunner(events)
3499 runner.run(unittest.TestSuite())
3500 expected = ['startTestRun', 'stopTestRun']
3501 self.assertEqual(events, expected)
3502
Antoine Pitrou0734c632009-11-10 20:49:30 +00003503 def test_pickle_unpickle(self):
3504 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3505 # required by test_multiprocessing under Windows (in verbose mode).
3506 import StringIO
3507 # cStringIO objects are not pickleable, but StringIO objects are.
3508 stream = StringIO.StringIO("foo")
3509 runner = unittest.TextTestRunner(stream)
3510 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
3511 s = pickle.dumps(runner, protocol=protocol)
3512 obj = pickle.loads(s)
3513 # StringIO objects never compare equal, a cheap test instead.
3514 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3515
Michael Foorddb43b5a2010-02-10 14:25:12 +00003516 def test_resultclass(self):
3517 def MockResultClass(*args):
3518 return args
3519 STREAM = object()
3520 DESCRIPTIONS = object()
3521 VERBOSITY = object()
3522 runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY,
3523 resultclass=MockResultClass)
3524 self.assertEqual(runner.resultclass, MockResultClass)
3525
3526 expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY)
3527 self.assertEqual(runner._makeResult(), expectedresult)
3528
Michael Foord07ef4872009-05-02 22:43:34 +00003529
Michael Foordb4a81c82009-05-29 20:33:46 +00003530class TestDiscovery(TestCase):
3531
3532 # Heavily mocked tests so I can avoid hitting the filesystem
Michael Foorde91ea562009-09-13 19:07:03 +00003533 def test_get_name_from_path(self):
Michael Foordb4a81c82009-05-29 20:33:46 +00003534 loader = unittest.TestLoader()
3535
Michael Foordb4a81c82009-05-29 20:33:46 +00003536 loader._top_level_dir = '/foo'
Michael Foorde91ea562009-09-13 19:07:03 +00003537 name = loader._get_name_from_path('/foo/bar/baz.py')
3538 self.assertEqual(name, 'bar.baz')
Michael Foordb4a81c82009-05-29 20:33:46 +00003539
3540 if not __debug__:
3541 # asserts are off
3542 return
3543
3544 with self.assertRaises(AssertionError):
Michael Foorde91ea562009-09-13 19:07:03 +00003545 loader._get_name_from_path('/bar/baz.py')
Michael Foordb4a81c82009-05-29 20:33:46 +00003546
3547 def test_find_tests(self):
3548 loader = unittest.TestLoader()
3549
3550 original_listdir = os.listdir
3551 def restore_listdir():
3552 os.listdir = original_listdir
3553 original_isfile = os.path.isfile
3554 def restore_isfile():
3555 os.path.isfile = original_isfile
3556 original_isdir = os.path.isdir
3557 def restore_isdir():
3558 os.path.isdir = original_isdir
3559
3560 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Michael Foorde91ea562009-09-13 19:07:03 +00003561 'test.foo', 'test-not-a-module.py', 'another_dir'],
Michael Foordb4a81c82009-05-29 20:33:46 +00003562 ['test3.py', 'test4.py', ]]
3563 os.listdir = lambda path: path_lists.pop(0)
3564 self.addCleanup(restore_listdir)
3565
3566 def isdir(path):
3567 return path.endswith('dir')
3568 os.path.isdir = isdir
3569 self.addCleanup(restore_isdir)
3570
3571 def isfile(path):
3572 # another_dir is not a package and so shouldn't be recursed into
3573 return not path.endswith('dir') and not 'another_dir' in path
3574 os.path.isfile = isfile
3575 self.addCleanup(restore_isfile)
3576
Michael Foorde91ea562009-09-13 19:07:03 +00003577 loader._get_module_from_name = lambda path: path + ' module'
Michael Foordb4a81c82009-05-29 20:33:46 +00003578 loader.loadTestsFromModule = lambda module: module + ' tests'
3579
3580 loader._top_level_dir = '/foo'
3581 suite = list(loader._find_tests('/foo', 'test*.py'))
3582
Michael Foorde91ea562009-09-13 19:07:03 +00003583 expected = [name + ' module tests' for name in
3584 ('test1', 'test2')]
3585 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3586 ('test3', 'test4')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003587 self.assertEqual(suite, expected)
3588
3589 def test_find_tests_with_package(self):
3590 loader = unittest.TestLoader()
3591
3592 original_listdir = os.listdir
3593 def restore_listdir():
3594 os.listdir = original_listdir
3595 original_isfile = os.path.isfile
3596 def restore_isfile():
3597 os.path.isfile = original_isfile
3598 original_isdir = os.path.isdir
3599 def restore_isdir():
3600 os.path.isdir = original_isdir
3601
3602 directories = ['a_directory', 'test_directory', 'test_directory2']
3603 path_lists = [directories, [], [], []]
3604 os.listdir = lambda path: path_lists.pop(0)
3605 self.addCleanup(restore_listdir)
3606
3607 os.path.isdir = lambda path: True
3608 self.addCleanup(restore_isdir)
3609
3610 os.path.isfile = lambda path: os.path.basename(path) not in directories
3611 self.addCleanup(restore_isfile)
3612
3613 class Module(object):
3614 paths = []
3615 load_tests_args = []
3616
3617 def __init__(self, path):
3618 self.path = path
3619 self.paths.append(path)
3620 if os.path.basename(path) == 'test_directory':
3621 def load_tests(loader, tests, pattern):
3622 self.load_tests_args.append((loader, tests, pattern))
3623 return 'load_tests'
3624 self.load_tests = load_tests
3625
3626 def __eq__(self, other):
3627 return self.path == other.path
3628
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003629 # Silence py3k warning
3630 __hash__ = None
3631
Michael Foorde91ea562009-09-13 19:07:03 +00003632 loader._get_module_from_name = lambda name: Module(name)
Michael Foordb4a81c82009-05-29 20:33:46 +00003633 def loadTestsFromModule(module, use_load_tests):
3634 if use_load_tests:
3635 raise self.failureException('use_load_tests should be False for packages')
3636 return module.path + ' module tests'
3637 loader.loadTestsFromModule = loadTestsFromModule
3638
3639 loader._top_level_dir = '/foo'
3640 # this time no '.py' on the pattern so that it can match
3641 # a test package
3642 suite = list(loader._find_tests('/foo', 'test*'))
3643
3644 # We should have loaded tests from the test_directory package by calling load_tests
3645 # and directly from the test_directory2 package
Michael Foordd53d0852009-06-05 14:14:34 +00003646 self.assertEqual(suite,
Michael Foorde91ea562009-09-13 19:07:03 +00003647 ['load_tests', 'test_directory2' + ' module tests'])
3648 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Michael Foordb4a81c82009-05-29 20:33:46 +00003649
3650 # load_tests should have been called once with loader, tests and pattern
3651 self.assertEqual(Module.load_tests_args,
Michael Foorde91ea562009-09-13 19:07:03 +00003652 [(loader, 'test_directory' + ' module tests', 'test*')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003653
3654 def test_discover(self):
3655 loader = unittest.TestLoader()
3656
3657 original_isfile = os.path.isfile
3658 def restore_isfile():
3659 os.path.isfile = original_isfile
3660
3661 os.path.isfile = lambda path: False
3662 self.addCleanup(restore_isfile)
3663
Nick Coghlanb6edf192009-10-17 08:21:21 +00003664 orig_sys_path = sys.path[:]
3665 def restore_path():
3666 sys.path[:] = orig_sys_path
3667 self.addCleanup(restore_path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003668
Nick Coghlanb6edf192009-10-17 08:21:21 +00003669 full_path = os.path.abspath(os.path.normpath('/foo'))
Michael Foordb4a81c82009-05-29 20:33:46 +00003670 with self.assertRaises(ImportError):
3671 loader.discover('/foo/bar', top_level_dir='/foo')
3672
3673 self.assertEqual(loader._top_level_dir, full_path)
3674 self.assertIn(full_path, sys.path)
3675
3676 os.path.isfile = lambda path: True
3677 _find_tests_args = []
3678 def _find_tests(start_dir, pattern):
3679 _find_tests_args.append((start_dir, pattern))
3680 return ['tests']
3681 loader._find_tests = _find_tests
3682 loader.suiteClass = str
3683
3684 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3685
3686 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3687 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3688 self.assertEqual(suite, "['tests']")
3689 self.assertEqual(loader._top_level_dir, top_level_dir)
3690 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlanb6edf192009-10-17 08:21:21 +00003691 self.assertIn(top_level_dir, sys.path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003692
Michael Foorde91ea562009-09-13 19:07:03 +00003693 def test_discover_with_modules_that_fail_to_import(self):
3694 loader = unittest.TestLoader()
3695
3696 listdir = os.listdir
3697 os.listdir = lambda _: ['test_this_does_not_exist.py']
3698 isfile = os.path.isfile
3699 os.path.isfile = lambda _: True
Nick Coghlanb6edf192009-10-17 08:21:21 +00003700 orig_sys_path = sys.path[:]
Michael Foorde91ea562009-09-13 19:07:03 +00003701 def restore():
3702 os.path.isfile = isfile
3703 os.listdir = listdir
Nick Coghlanb6edf192009-10-17 08:21:21 +00003704 sys.path[:] = orig_sys_path
Michael Foorde91ea562009-09-13 19:07:03 +00003705 self.addCleanup(restore)
3706
3707 suite = loader.discover('.')
Nick Coghlanb6edf192009-10-17 08:21:21 +00003708 self.assertIn(os.getcwd(), sys.path)
Michael Foorde91ea562009-09-13 19:07:03 +00003709 self.assertEqual(suite.countTestCases(), 1)
3710 test = list(list(suite)[0])[0] # extract test from suite
3711
3712 with self.assertRaises(ImportError):
3713 test.test_this_does_not_exist()
3714
Michael Foordb4a81c82009-05-29 20:33:46 +00003715 def test_command_line_handling_parseArgs(self):
3716 # Haha - take that uninstantiable class
3717 program = object.__new__(TestProgram)
3718
3719 args = []
3720 def do_discovery(argv):
3721 args.extend(argv)
3722 program._do_discovery = do_discovery
3723 program.parseArgs(['something', 'discover'])
3724 self.assertEqual(args, [])
3725
3726 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3727 self.assertEqual(args, ['foo', 'bar'])
3728
3729 def test_command_line_handling_do_discovery_too_many_arguments(self):
3730 class Stop(Exception):
3731 pass
3732 def usageExit():
3733 raise Stop
3734
3735 program = object.__new__(TestProgram)
3736 program.usageExit = usageExit
3737
3738 with self.assertRaises(Stop):
3739 # too many args
3740 program._do_discovery(['one', 'two', 'three', 'four'])
3741
3742
3743 def test_command_line_handling_do_discovery_calls_loader(self):
3744 program = object.__new__(TestProgram)
3745
3746 class Loader(object):
3747 args = []
3748 def discover(self, start_dir, pattern, top_level_dir):
3749 self.args.append((start_dir, pattern, top_level_dir))
3750 return 'tests'
3751
3752 program._do_discovery(['-v'], Loader=Loader)
3753 self.assertEqual(program.verbosity, 2)
3754 self.assertEqual(program.test, 'tests')
3755 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3756
3757 Loader.args = []
3758 program = object.__new__(TestProgram)
3759 program._do_discovery(['--verbose'], Loader=Loader)
3760 self.assertEqual(program.test, 'tests')
3761 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3762
3763 Loader.args = []
3764 program = object.__new__(TestProgram)
3765 program._do_discovery([], Loader=Loader)
3766 self.assertEqual(program.test, 'tests')
3767 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3768
3769 Loader.args = []
3770 program = object.__new__(TestProgram)
3771 program._do_discovery(['fish'], Loader=Loader)
3772 self.assertEqual(program.test, 'tests')
3773 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3774
3775 Loader.args = []
3776 program = object.__new__(TestProgram)
3777 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3778 self.assertEqual(program.test, 'tests')
3779 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3780
3781 Loader.args = []
3782 program = object.__new__(TestProgram)
3783 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3784 self.assertEqual(program.test, 'tests')
3785 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3786
3787 Loader.args = []
3788 program = object.__new__(TestProgram)
3789 program._do_discovery(['-s', 'fish'], Loader=Loader)
3790 self.assertEqual(program.test, 'tests')
3791 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3792
3793 Loader.args = []
3794 program = object.__new__(TestProgram)
3795 program._do_discovery(['-t', 'fish'], Loader=Loader)
3796 self.assertEqual(program.test, 'tests')
3797 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3798
3799 Loader.args = []
3800 program = object.__new__(TestProgram)
3801 program._do_discovery(['-p', 'fish'], Loader=Loader)
3802 self.assertEqual(program.test, 'tests')
3803 self.assertEqual(Loader.args, [('.', 'fish', None)])
3804
3805 Loader.args = []
3806 program = object.__new__(TestProgram)
3807 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3808 self.assertEqual(program.test, 'tests')
3809 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3810 self.assertEqual(program.verbosity, 2)
3811
3812
Jim Fultonfafd8742004-08-28 15:22:12 +00003813######################################################################
3814## Main
3815######################################################################
3816
3817def test_main():
Georg Brandl15c5ce92007-03-07 09:09:40 +00003818 test_support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003819 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Michael Foord829f6b82009-05-02 11:43:06 +00003820 Test_TestSkipping, Test_Assertions, TestLongMessage,
Antoine Pitrou0734c632009-11-10 20:49:30 +00003821 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner)
Jim Fultonfafd8742004-08-28 15:22:12 +00003822
Georg Brandl15c5ce92007-03-07 09:09:40 +00003823if __name__ == "__main__":
Tim Petersea5962f2007-03-12 18:07:52 +00003824 test_main()