blob: ab043822daf01a4e97151ed606ff699017ee3016 [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
2035### Support code for Test_TestCase
2036################################################################
2037
2038class Foo(unittest.TestCase):
2039 def runTest(self): pass
2040 def test1(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002041
Georg Brandl15c5ce92007-03-07 09:09:40 +00002042class Bar(Foo):
2043 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002044
Michael Foord07ef4872009-05-02 22:43:34 +00002045class LoggingTestCase(unittest.TestCase):
2046 """A test case which logs its calls."""
2047
2048 def __init__(self, events):
2049 super(LoggingTestCase, self).__init__('test')
2050 self.events = events
2051
2052 def setUp(self):
2053 self.events.append('setUp')
2054
2055 def test(self):
2056 self.events.append('test')
2057
2058 def tearDown(self):
2059 self.events.append('tearDown')
2060
2061class ResultWithNoStartTestRunStopTestRun(object):
2062 """An object honouring TestResult before startTestRun/stopTestRun."""
2063
2064 def __init__(self):
2065 self.failures = []
2066 self.errors = []
2067 self.testsRun = 0
2068 self.skipped = []
2069 self.expectedFailures = []
2070 self.unexpectedSuccesses = []
2071 self.shouldStop = False
2072
2073 def startTest(self, test):
2074 pass
2075
2076 def stopTest(self, test):
2077 pass
2078
2079 def addError(self, test):
2080 pass
2081
2082 def addFailure(self, test):
2083 pass
2084
2085 def addSuccess(self, test):
2086 pass
2087
2088 def wasSuccessful(self):
2089 return True
2090
2091
Georg Brandl15c5ce92007-03-07 09:09:40 +00002092################################################################
2093### /Support code for Test_TestCase
2094
2095class Test_TestCase(TestCase, TestEquality, TestHashing):
2096
2097 ### Set up attributes used by inherited tests
2098 ################################################################
2099
2100 # Used by TestHashing.test_hash and TestEquality.test_eq
2101 eq_pairs = [(Foo('test1'), Foo('test1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002102
Georg Brandl15c5ce92007-03-07 09:09:40 +00002103 # Used by TestEquality.test_ne
2104 ne_pairs = [(Foo('test1'), Foo('runTest'))
2105 ,(Foo('test1'), Bar('test1'))
2106 ,(Foo('test1'), Bar('test2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002107
Georg Brandl15c5ce92007-03-07 09:09:40 +00002108 ################################################################
2109 ### /Set up attributes used by inherited tests
Tim Petersea5962f2007-03-12 18:07:52 +00002110
Georg Brandl15c5ce92007-03-07 09:09:40 +00002111
2112 # "class TestCase([methodName])"
2113 # ...
2114 # "Each instance of TestCase will run a single test method: the
2115 # method named methodName."
2116 # ...
2117 # "methodName defaults to "runTest"."
2118 #
2119 # Make sure it really is optional, and that it defaults to the proper
2120 # thing.
2121 def test_init__no_test_name(self):
2122 class Test(unittest.TestCase):
2123 def runTest(self): raise MyException()
2124 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002125
Georg Brandl15c5ce92007-03-07 09:09:40 +00002126 self.assertEqual(Test().id()[-13:], '.Test.runTest')
Tim Petersea5962f2007-03-12 18:07:52 +00002127
Georg Brandl15c5ce92007-03-07 09:09:40 +00002128 # "class TestCase([methodName])"
2129 # ...
2130 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002131 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002132 def test_init__test_name__valid(self):
2133 class Test(unittest.TestCase):
2134 def runTest(self): raise MyException()
2135 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002136
Georg Brandl15c5ce92007-03-07 09:09:40 +00002137 self.assertEqual(Test('test').id()[-10:], '.Test.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002138
Georg Brandl15c5ce92007-03-07 09:09:40 +00002139 # "class TestCase([methodName])"
2140 # ...
2141 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002142 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002143 def test_init__test_name__invalid(self):
2144 class Test(unittest.TestCase):
2145 def runTest(self): raise MyException()
2146 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002147
Georg Brandl15c5ce92007-03-07 09:09:40 +00002148 try:
2149 Test('testfoo')
2150 except ValueError:
2151 pass
2152 else:
2153 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +00002154
Georg Brandl15c5ce92007-03-07 09:09:40 +00002155 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00002156 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00002157 def test_countTestCases(self):
2158 class Foo(unittest.TestCase):
2159 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002160
Georg Brandl15c5ce92007-03-07 09:09:40 +00002161 self.assertEqual(Foo('test').countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00002162
Georg Brandl15c5ce92007-03-07 09:09:40 +00002163 # "Return the default type of test result object to be used to run this
2164 # test. For TestCase instances, this will always be
2165 # unittest.TestResult; subclasses of TestCase should
2166 # override this as necessary."
2167 def test_defaultTestResult(self):
2168 class Foo(unittest.TestCase):
2169 def runTest(self):
2170 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002171
Georg Brandl15c5ce92007-03-07 09:09:40 +00002172 result = Foo().defaultTestResult()
2173 self.assertEqual(type(result), unittest.TestResult)
2174
2175 # "When a setUp() method is defined, the test runner will run that method
2176 # prior to each test. Likewise, if a tearDown() method is defined, the
2177 # test runner will invoke that method after each test. In the example,
2178 # setUp() was used to create a fresh sequence for each test."
2179 #
2180 # Make sure the proper call order is maintained, even if setUp() raises
2181 # an exception.
2182 def test_run_call_order__error_in_setUp(self):
2183 events = []
2184 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002185
Michael Foord07ef4872009-05-02 22:43:34 +00002186 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002187 def setUp(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002188 super(Foo, self).setUp()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002189 raise RuntimeError('raised by Foo.setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002190
Michael Foord07ef4872009-05-02 22:43:34 +00002191 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002192 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2193 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002194
Michael Foord07ef4872009-05-02 22:43:34 +00002195 # "With a temporary result stopTestRun is called when setUp errors.
2196 def test_run_call_order__error_in_setUp_default_result(self):
2197 events = []
2198
2199 class Foo(LoggingTestCase):
2200 def defaultTestResult(self):
2201 return LoggingResult(self.events)
2202
2203 def setUp(self):
2204 super(Foo, self).setUp()
2205 raise RuntimeError('raised by Foo.setUp')
2206
2207 Foo(events).run()
2208 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2209 'stopTest', 'stopTestRun']
2210 self.assertEqual(events, expected)
2211
Georg Brandl15c5ce92007-03-07 09:09:40 +00002212 # "When a setUp() method is defined, the test runner will run that method
2213 # prior to each test. Likewise, if a tearDown() method is defined, the
2214 # test runner will invoke that method after each test. In the example,
2215 # setUp() was used to create a fresh sequence for each test."
2216 #
2217 # Make sure the proper call order is maintained, even if the test raises
2218 # an error (as opposed to a failure).
2219 def test_run_call_order__error_in_test(self):
2220 events = []
2221 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002222
Michael Foord07ef4872009-05-02 22:43:34 +00002223 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002224 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002225 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002226 raise RuntimeError('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002227
Georg Brandl15c5ce92007-03-07 09:09:40 +00002228 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2229 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002230 Foo(events).run(result)
2231 self.assertEqual(events, expected)
2232
2233 # "With a default result, an error in the test still results in stopTestRun
2234 # being called."
2235 def test_run_call_order__error_in_test_default_result(self):
2236 events = []
2237
2238 class Foo(LoggingTestCase):
2239 def defaultTestResult(self):
2240 return LoggingResult(self.events)
2241
2242 def test(self):
2243 super(Foo, self).test()
2244 raise RuntimeError('raised by Foo.test')
2245
2246 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2247 'tearDown', 'stopTest', 'stopTestRun']
2248 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002249 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002250
Georg Brandl15c5ce92007-03-07 09:09:40 +00002251 # "When a setUp() method is defined, the test runner will run that method
2252 # prior to each test. Likewise, if a tearDown() method is defined, the
2253 # test runner will invoke that method after each test. In the example,
2254 # setUp() was used to create a fresh sequence for each test."
2255 #
2256 # Make sure the proper call order is maintained, even if the test signals
2257 # a failure (as opposed to an error).
2258 def test_run_call_order__failure_in_test(self):
2259 events = []
2260 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002261
Michael Foord07ef4872009-05-02 22:43:34 +00002262 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002263 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002264 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002265 self.fail('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002266
Georg Brandl15c5ce92007-03-07 09:09:40 +00002267 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2268 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002269 Foo(events).run(result)
2270 self.assertEqual(events, expected)
2271
2272 # "When a test fails with a default result stopTestRun is still called."
2273 def test_run_call_order__failure_in_test_default_result(self):
2274
2275 class Foo(LoggingTestCase):
2276 def defaultTestResult(self):
2277 return LoggingResult(self.events)
2278 def test(self):
2279 super(Foo, self).test()
2280 self.fail('raised by Foo.test')
2281
2282 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2283 'tearDown', 'stopTest', 'stopTestRun']
2284 events = []
2285 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002286 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002287
Georg Brandl15c5ce92007-03-07 09:09:40 +00002288 # "When a setUp() method is defined, the test runner will run that method
2289 # prior to each test. Likewise, if a tearDown() method is defined, the
2290 # test runner will invoke that method after each test. In the example,
2291 # setUp() was used to create a fresh sequence for each test."
2292 #
2293 # Make sure the proper call order is maintained, even if tearDown() raises
2294 # an exception.
2295 def test_run_call_order__error_in_tearDown(self):
2296 events = []
2297 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002298
Michael Foord07ef4872009-05-02 22:43:34 +00002299 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002300 def tearDown(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002301 super(Foo, self).tearDown()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002302 raise RuntimeError('raised by Foo.tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002303
Michael Foord07ef4872009-05-02 22:43:34 +00002304 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002305 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2306 'stopTest']
2307 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002308
Michael Foord07ef4872009-05-02 22:43:34 +00002309 # "When tearDown errors with a default result stopTestRun is still called."
2310 def test_run_call_order__error_in_tearDown_default_result(self):
2311
2312 class Foo(LoggingTestCase):
2313 def defaultTestResult(self):
2314 return LoggingResult(self.events)
2315 def tearDown(self):
2316 super(Foo, self).tearDown()
2317 raise RuntimeError('raised by Foo.tearDown')
2318
2319 events = []
2320 Foo(events).run()
2321 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2322 'addError', 'stopTest', 'stopTestRun']
2323 self.assertEqual(events, expected)
2324
2325 # "TestCase.run() still works when the defaultTestResult is a TestResult
2326 # that does not support startTestRun and stopTestRun.
2327 def test_run_call_order_default_result(self):
2328
2329 class Foo(unittest.TestCase):
2330 def defaultTestResult(self):
2331 return ResultWithNoStartTestRunStopTestRun()
2332 def test(self):
2333 pass
2334
2335 Foo('test').run()
2336
Georg Brandl15c5ce92007-03-07 09:09:40 +00002337 # "This class attribute gives the exception raised by the test() method.
2338 # If a test framework needs to use a specialized exception, possibly to
2339 # carry additional information, it must subclass this exception in
2340 # order to ``play fair'' with the framework. The initial value of this
2341 # attribute is AssertionError"
2342 def test_failureException__default(self):
2343 class Foo(unittest.TestCase):
2344 def test(self):
2345 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002346
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002347 self.assertTrue(Foo('test').failureException is AssertionError)
Tim Petersea5962f2007-03-12 18:07:52 +00002348
Georg Brandl15c5ce92007-03-07 09:09:40 +00002349 # "This class attribute gives the exception raised by the test() method.
2350 # If a test framework needs to use a specialized exception, possibly to
2351 # carry additional information, it must subclass this exception in
2352 # order to ``play fair'' with the framework."
2353 #
2354 # Make sure TestCase.run() respects the designated failureException
2355 def test_failureException__subclassing__explicit_raise(self):
2356 events = []
2357 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002358
Georg Brandl15c5ce92007-03-07 09:09:40 +00002359 class Foo(unittest.TestCase):
2360 def test(self):
2361 raise RuntimeError()
Tim Petersea5962f2007-03-12 18:07:52 +00002362
Georg Brandl15c5ce92007-03-07 09:09:40 +00002363 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002364
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002365 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002366
2367
Georg Brandl15c5ce92007-03-07 09:09:40 +00002368 Foo('test').run(result)
2369 expected = ['startTest', 'addFailure', 'stopTest']
2370 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002371
Georg Brandl15c5ce92007-03-07 09:09:40 +00002372 # "This class attribute gives the exception raised by the test() method.
2373 # If a test framework needs to use a specialized exception, possibly to
2374 # carry additional information, it must subclass this exception in
2375 # order to ``play fair'' with the framework."
2376 #
2377 # Make sure TestCase.run() respects the designated failureException
2378 def test_failureException__subclassing__implicit_raise(self):
2379 events = []
2380 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002381
Georg Brandl15c5ce92007-03-07 09:09:40 +00002382 class Foo(unittest.TestCase):
2383 def test(self):
2384 self.fail("foo")
Tim Petersea5962f2007-03-12 18:07:52 +00002385
Georg Brandl15c5ce92007-03-07 09:09:40 +00002386 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002387
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002388 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002389
2390
Georg Brandl15c5ce92007-03-07 09:09:40 +00002391 Foo('test').run(result)
2392 expected = ['startTest', 'addFailure', 'stopTest']
2393 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002394
2395 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002396 def test_setUp(self):
2397 class Foo(unittest.TestCase):
2398 def runTest(self):
2399 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002400
Georg Brandl15c5ce92007-03-07 09:09:40 +00002401 # ... and nothing should happen
2402 Foo().setUp()
Tim Petersea5962f2007-03-12 18:07:52 +00002403
2404 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002405 def test_tearDown(self):
2406 class Foo(unittest.TestCase):
2407 def runTest(self):
2408 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002409
Georg Brandl15c5ce92007-03-07 09:09:40 +00002410 # ... and nothing should happen
2411 Foo().tearDown()
Tim Petersea5962f2007-03-12 18:07:52 +00002412
Georg Brandl15c5ce92007-03-07 09:09:40 +00002413 # "Return a string identifying the specific test case."
2414 #
2415 # Because of the vague nature of the docs, I'm not going to lock this
2416 # test down too much. Really all that can be asserted is that the id()
2417 # will be a string (either 8-byte or unicode -- again, because the docs
2418 # just say "string")
2419 def test_id(self):
2420 class Foo(unittest.TestCase):
2421 def runTest(self):
2422 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002423
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002424 self.assertIsInstance(Foo().id(), basestring)
Tim Petersea5962f2007-03-12 18:07:52 +00002425
Georg Brandl15c5ce92007-03-07 09:09:40 +00002426 # "If result is omitted or None, a temporary result object is created
Michael Foord07ef4872009-05-02 22:43:34 +00002427 # and used, but is not made available to the caller. As TestCase owns the
2428 # temporary result startTestRun and stopTestRun are called.
2429
Georg Brandl15c5ce92007-03-07 09:09:40 +00002430 def test_run__uses_defaultTestResult(self):
2431 events = []
Tim Petersea5962f2007-03-12 18:07:52 +00002432
Georg Brandl15c5ce92007-03-07 09:09:40 +00002433 class Foo(unittest.TestCase):
2434 def test(self):
2435 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002436
Georg Brandl15c5ce92007-03-07 09:09:40 +00002437 def defaultTestResult(self):
2438 return LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002439
2440 # Make run() find a result object on its own
Georg Brandl15c5ce92007-03-07 09:09:40 +00002441 Foo('test').run()
Tim Petersea5962f2007-03-12 18:07:52 +00002442
Michael Foord07ef4872009-05-02 22:43:34 +00002443 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2444 'stopTest', 'stopTestRun']
Georg Brandl15c5ce92007-03-07 09:09:40 +00002445 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002446
Gregory P. Smith28399852009-03-31 16:54:10 +00002447 def testShortDescriptionWithoutDocstring(self):
2448 self.assertEqual(
2449 self.shortDescription(),
2450 'testShortDescriptionWithoutDocstring (' + __name__ +
2451 '.Test_TestCase)')
2452
2453 def testShortDescriptionWithOneLineDocstring(self):
2454 """Tests shortDescription() for a method with a docstring."""
2455 self.assertEqual(
2456 self.shortDescription(),
2457 ('testShortDescriptionWithOneLineDocstring '
2458 '(' + __name__ + '.Test_TestCase)\n'
2459 'Tests shortDescription() for a method with a docstring.'))
2460
2461 def testShortDescriptionWithMultiLineDocstring(self):
2462 """Tests shortDescription() for a method with a longer docstring.
2463
2464 This method ensures that only the first line of a docstring is
2465 returned used in the short description, no matter how long the
2466 whole thing is.
2467 """
2468 self.assertEqual(
2469 self.shortDescription(),
2470 ('testShortDescriptionWithMultiLineDocstring '
2471 '(' + __name__ + '.Test_TestCase)\n'
2472 'Tests shortDescription() for a method with a longer '
2473 'docstring.'))
2474
Gregory P. Smith28399852009-03-31 16:54:10 +00002475 def testAddTypeEqualityFunc(self):
2476 class SadSnake(object):
2477 """Dummy class for test_addTypeEqualityFunc."""
2478 s1, s2 = SadSnake(), SadSnake()
2479 self.assertFalse(s1 == s2)
2480 def AllSnakesCreatedEqual(a, b, msg=None):
2481 return type(a) == type(b) == SadSnake
2482 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2483 self.assertEqual(s1, s2)
2484 # No this doesn't clean up and remove the SadSnake equality func
2485 # from this TestCase instance but since its a local nothing else
2486 # will ever notice that.
2487
Michael Foordf2dfef12009-04-05 19:19:28 +00002488 def testAssertIs(self):
2489 thing = object()
2490 self.assertIs(thing, thing)
2491 self.assertRaises(self.failureException, self.assertIs, thing, object())
2492
2493 def testAssertIsNot(self):
2494 thing = object()
2495 self.assertIsNot(thing, object())
2496 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2497
Georg Brandlf895cf52009-10-01 20:59:31 +00002498 def testAssertIsInstance(self):
2499 thing = []
2500 self.assertIsInstance(thing, list)
2501 self.assertRaises(self.failureException, self.assertIsInstance,
2502 thing, dict)
2503
2504 def testAssertNotIsInstance(self):
2505 thing = []
2506 self.assertNotIsInstance(thing, dict)
2507 self.assertRaises(self.failureException, self.assertNotIsInstance,
2508 thing, list)
2509
Gregory P. Smith28399852009-03-31 16:54:10 +00002510 def testAssertIn(self):
2511 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2512
2513 self.assertIn('a', 'abc')
2514 self.assertIn(2, [1, 2, 3])
2515 self.assertIn('monkey', animals)
2516
2517 self.assertNotIn('d', 'abc')
2518 self.assertNotIn(0, [1, 2, 3])
2519 self.assertNotIn('otter', animals)
2520
2521 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2522 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2523 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2524 animals)
2525
2526 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2527 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2528 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2529 animals)
2530
2531 def testAssertDictContainsSubset(self):
2532 self.assertDictContainsSubset({}, {})
2533 self.assertDictContainsSubset({}, {'a': 1})
2534 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2535 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2536 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2537
2538 self.assertRaises(unittest.TestCase.failureException,
2539 self.assertDictContainsSubset, {'a': 2}, {'a': 1},
2540 '.*Mismatched values:.*')
2541
2542 self.assertRaises(unittest.TestCase.failureException,
2543 self.assertDictContainsSubset, {'c': 1}, {'a': 1},
2544 '.*Missing:.*')
2545
2546 self.assertRaises(unittest.TestCase.failureException,
2547 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2548 {'a': 1}, '.*Missing:.*')
2549
2550 self.assertRaises(unittest.TestCase.failureException,
2551 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2552 {'a': 1}, '.*Missing:.*Mismatched values:.*')
2553
2554 def testAssertEqual(self):
2555 equal_pairs = [
2556 ((), ()),
2557 ({}, {}),
2558 ([], []),
2559 (set(), set()),
2560 (frozenset(), frozenset())]
2561 for a, b in equal_pairs:
2562 # This mess of try excepts is to test the assertEqual behavior
2563 # itself.
2564 try:
2565 self.assertEqual(a, b)
2566 except self.failureException:
2567 self.fail('assertEqual(%r, %r) failed' % (a, b))
2568 try:
2569 self.assertEqual(a, b, msg='foo')
2570 except self.failureException:
2571 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2572 try:
2573 self.assertEqual(a, b, 'foo')
2574 except self.failureException:
2575 self.fail('assertEqual(%r, %r) with third parameter failed' %
2576 (a, b))
2577
2578 unequal_pairs = [
2579 ((), []),
2580 ({}, set()),
2581 (set([4,1]), frozenset([4,2])),
2582 (frozenset([4,5]), set([2,3])),
2583 (set([3,4]), set([5,4]))]
2584 for a, b in unequal_pairs:
2585 self.assertRaises(self.failureException, self.assertEqual, a, b)
2586 self.assertRaises(self.failureException, self.assertEqual, a, b,
2587 'foo')
2588 self.assertRaises(self.failureException, self.assertEqual, a, b,
2589 msg='foo')
2590
2591 def testEquality(self):
2592 self.assertListEqual([], [])
2593 self.assertTupleEqual((), ())
2594 self.assertSequenceEqual([], ())
2595
2596 a = [0, 'a', []]
2597 b = []
2598 self.assertRaises(unittest.TestCase.failureException,
2599 self.assertListEqual, a, b)
2600 self.assertRaises(unittest.TestCase.failureException,
2601 self.assertListEqual, tuple(a), tuple(b))
2602 self.assertRaises(unittest.TestCase.failureException,
2603 self.assertSequenceEqual, a, tuple(b))
2604
2605 b.extend(a)
2606 self.assertListEqual(a, b)
2607 self.assertTupleEqual(tuple(a), tuple(b))
2608 self.assertSequenceEqual(a, tuple(b))
2609 self.assertSequenceEqual(tuple(a), b)
2610
2611 self.assertRaises(self.failureException, self.assertListEqual,
2612 a, tuple(b))
2613 self.assertRaises(self.failureException, self.assertTupleEqual,
2614 tuple(a), b)
2615 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2616 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2617 tuple(b))
2618 self.assertRaises(self.failureException, self.assertSequenceEqual,
2619 None, tuple(b))
2620 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2621 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2622 self.assertRaises(self.failureException, self.assertSequenceEqual,
2623 1, 1)
2624
2625 self.assertDictEqual({}, {})
2626
2627 c = { 'x': 1 }
2628 d = {}
2629 self.assertRaises(unittest.TestCase.failureException,
2630 self.assertDictEqual, c, d)
2631
2632 d.update(c)
2633 self.assertDictEqual(c, d)
2634
2635 d['x'] = 0
2636 self.assertRaises(unittest.TestCase.failureException,
2637 self.assertDictEqual, c, d, 'These are unequal')
2638
2639 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2640 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2641 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2642
2643 self.assertSameElements([1, 2, 3], [3, 2, 1])
2644 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2645 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2646 self.assertRaises(self.failureException, self.assertSameElements,
2647 [10], [10, 11])
2648 self.assertRaises(self.failureException, self.assertSameElements,
2649 [10, 11], [10])
2650
2651 # Test that sequences of unhashable objects can be tested for sameness:
2652 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Michael Foordf2dfef12009-04-05 19:19:28 +00002653
Gregory P. Smith28399852009-03-31 16:54:10 +00002654 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2655 self.assertRaises(self.failureException, self.assertSameElements,
2656 [[1]], [[2]])
2657
2658 def testAssertSetEqual(self):
2659 set1 = set()
2660 set2 = set()
2661 self.assertSetEqual(set1, set2)
2662
2663 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2664 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2665 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2666 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2667
2668 set1 = set(['a'])
2669 set2 = set()
2670 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2671
2672 set1 = set(['a'])
2673 set2 = set(['a'])
2674 self.assertSetEqual(set1, set2)
2675
2676 set1 = set(['a'])
2677 set2 = set(['a', 'b'])
2678 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2679
2680 set1 = set(['a'])
2681 set2 = frozenset(['a', 'b'])
2682 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2683
2684 set1 = set(['a', 'b'])
2685 set2 = frozenset(['a', 'b'])
2686 self.assertSetEqual(set1, set2)
2687
2688 set1 = set()
2689 set2 = "foo"
2690 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2691 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2692
2693 # make sure any string formatting is tuple-safe
2694 set1 = set([(0, 1), (2, 3)])
2695 set2 = set([(4, 5)])
2696 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2697
2698 def testInequality(self):
2699 # Try ints
2700 self.assertGreater(2, 1)
2701 self.assertGreaterEqual(2, 1)
2702 self.assertGreaterEqual(1, 1)
2703 self.assertLess(1, 2)
2704 self.assertLessEqual(1, 2)
2705 self.assertLessEqual(1, 1)
2706 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2707 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2708 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2709 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2710 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2711 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2712
2713 # Try Floats
2714 self.assertGreater(1.1, 1.0)
2715 self.assertGreaterEqual(1.1, 1.0)
2716 self.assertGreaterEqual(1.0, 1.0)
2717 self.assertLess(1.0, 1.1)
2718 self.assertLessEqual(1.0, 1.1)
2719 self.assertLessEqual(1.0, 1.0)
2720 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2721 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2722 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2723 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2724 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2725 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2726
2727 # Try Strings
2728 self.assertGreater('bug', 'ant')
2729 self.assertGreaterEqual('bug', 'ant')
2730 self.assertGreaterEqual('ant', 'ant')
2731 self.assertLess('ant', 'bug')
2732 self.assertLessEqual('ant', 'bug')
2733 self.assertLessEqual('ant', 'ant')
2734 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2735 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2736 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2737 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2738 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2739 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2740
2741 # Try Unicode
2742 self.assertGreater(u'bug', u'ant')
2743 self.assertGreaterEqual(u'bug', u'ant')
2744 self.assertGreaterEqual(u'ant', u'ant')
2745 self.assertLess(u'ant', u'bug')
2746 self.assertLessEqual(u'ant', u'bug')
2747 self.assertLessEqual(u'ant', u'ant')
2748 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug')
2749 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant')
2750 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2751 u'bug')
2752 self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant')
2753 self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant')
2754 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant')
2755
2756 # Try Mixed String/Unicode
2757 self.assertGreater('bug', u'ant')
2758 self.assertGreater(u'bug', 'ant')
2759 self.assertGreaterEqual('bug', u'ant')
2760 self.assertGreaterEqual(u'bug', 'ant')
2761 self.assertGreaterEqual('ant', u'ant')
2762 self.assertGreaterEqual(u'ant', 'ant')
2763 self.assertLess('ant', u'bug')
2764 self.assertLess(u'ant', 'bug')
2765 self.assertLessEqual('ant', u'bug')
2766 self.assertLessEqual(u'ant', 'bug')
2767 self.assertLessEqual('ant', u'ant')
2768 self.assertLessEqual(u'ant', 'ant')
2769 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug')
2770 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug')
2771 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant')
2772 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant')
2773 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant',
2774 u'bug')
2775 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2776 'bug')
2777 self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant')
2778 self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant')
2779 self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant')
2780 self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant')
2781 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant')
2782 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant')
2783
2784 def testAssertMultiLineEqual(self):
2785 sample_text = b"""\
2786http://www.python.org/doc/2.3/lib/module-unittest.html
2787test case
2788 A test case is the smallest unit of testing. [...]
2789"""
2790 revised_sample_text = b"""\
2791http://www.python.org/doc/2.4.1/lib/module-unittest.html
2792test case
2793 A test case is the smallest unit of testing. [...] You may provide your
2794 own implementation that does not subclass from TestCase, of course.
2795"""
2796 sample_text_error = b"""
2797- http://www.python.org/doc/2.3/lib/module-unittest.html
2798? ^
2799+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2800? ^^^
2801 test case
2802- A test case is the smallest unit of testing. [...]
2803+ A test case is the smallest unit of testing. [...] You may provide your
2804? +++++++++++++++++++++
2805+ own implementation that does not subclass from TestCase, of course.
2806"""
2807
2808 for type_changer in (lambda x: x, lambda x: x.decode('utf8')):
2809 try:
2810 self.assertMultiLineEqual(type_changer(sample_text),
2811 type_changer(revised_sample_text))
2812 except self.failureException, e:
2813 # no fair testing ourself with ourself, use assertEqual..
2814 self.assertEqual(sample_text_error, str(e).encode('utf8'))
2815
2816 def testAssertIsNone(self):
2817 self.assertIsNone(None)
2818 self.assertRaises(self.failureException, self.assertIsNone, False)
2819 self.assertIsNotNone('DjZoPloGears on Rails')
2820 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2821
2822 def testAssertRegexpMatches(self):
2823 self.assertRegexpMatches('asdfabasdf', r'ab+')
2824 self.assertRaises(self.failureException, self.assertRegexpMatches,
2825 'saaas', r'aaaa')
2826
2827 def testAssertRaisesRegexp(self):
2828 class ExceptionMock(Exception):
2829 pass
2830
2831 def Stub():
2832 raise ExceptionMock('We expect')
2833
2834 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2835 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2836 self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
2837
2838 def testAssertNotRaisesRegexp(self):
2839 self.assertRaisesRegexp(
2840 self.failureException, '^Exception not raised$',
2841 self.assertRaisesRegexp, Exception, re.compile('x'),
2842 lambda: None)
2843 self.assertRaisesRegexp(
2844 self.failureException, '^Exception not raised$',
2845 self.assertRaisesRegexp, Exception, 'x',
2846 lambda: None)
2847 self.assertRaisesRegexp(
2848 self.failureException, '^Exception not raised$',
2849 self.assertRaisesRegexp, Exception, u'x',
2850 lambda: None)
2851
2852 def testAssertRaisesRegexpMismatch(self):
2853 def Stub():
2854 raise Exception('Unexpected')
2855
2856 self.assertRaisesRegexp(
2857 self.failureException,
2858 r'"\^Expected\$" does not match "Unexpected"',
2859 self.assertRaisesRegexp, Exception, '^Expected$',
2860 Stub)
2861 self.assertRaisesRegexp(
2862 self.failureException,
2863 r'"\^Expected\$" does not match "Unexpected"',
2864 self.assertRaisesRegexp, Exception, u'^Expected$',
2865 Stub)
2866 self.assertRaisesRegexp(
2867 self.failureException,
2868 r'"\^Expected\$" does not match "Unexpected"',
2869 self.assertRaisesRegexp, Exception,
2870 re.compile('^Expected$'), Stub)
2871
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00002872 def testAssertRaisesExcValue(self):
2873 class ExceptionMock(Exception):
2874 pass
2875
2876 def Stub(foo):
2877 raise ExceptionMock(foo)
2878 v = "particular value"
2879
2880 ctx = self.assertRaises(ExceptionMock)
2881 with ctx:
2882 Stub(v)
Georg Brandldc3694b2010-02-07 17:02:22 +00002883 e = ctx.exception
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002884 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00002885 self.assertEqual(e.args[0], v)
2886
Gregory P. Smith7558d572009-03-31 19:03:28 +00002887 def testSynonymAssertMethodNames(self):
2888 """Test undocumented method name synonyms.
2889
2890 Please do not use these methods names in your own code.
2891
2892 This test confirms their continued existence and functionality
2893 in order to avoid breaking existing code.
2894 """
2895 self.assertNotEquals(3, 5)
2896 self.assertEquals(3, 3)
2897 self.assertAlmostEquals(2.0, 2.0)
2898 self.assertNotAlmostEquals(3.0, 5.0)
2899 self.assert_(True)
2900
2901 def testPendingDeprecationMethodNames(self):
2902 """Test fail* methods pending deprecation, they will warn in 3.2.
2903
2904 Do not use these methods. They will go away in 3.3.
2905 """
2906 self.failIfEqual(3, 5)
2907 self.failUnlessEqual(3, 3)
2908 self.failUnlessAlmostEqual(2.0, 2.0)
2909 self.failIfAlmostEqual(3.0, 5.0)
2910 self.failUnless(True)
2911 self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam')
2912 self.failIf(False)
2913
Michael Foorde2942d02009-04-02 05:51:54 +00002914 def testDeepcopy(self):
2915 # Issue: 5660
2916 class TestableTest(TestCase):
2917 def testNothing(self):
2918 pass
2919
2920 test = TestableTest('testNothing')
2921
2922 # This shouldn't blow up
2923 deepcopy(test)
2924
Benjamin Peterson692428e2009-03-23 21:50:21 +00002925
2926class Test_TestSkipping(TestCase):
2927
2928 def test_skipping(self):
2929 class Foo(unittest.TestCase):
2930 def test_skip_me(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002931 self.skipTest("skip")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002932 events = []
2933 result = LoggingResult(events)
2934 test = Foo("test_skip_me")
2935 test.run(result)
2936 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2937 self.assertEqual(result.skipped, [(test, "skip")])
2938
2939 # Try letting setUp skip the test now.
2940 class Foo(unittest.TestCase):
2941 def setUp(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002942 self.skipTest("testing")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002943 def test_nothing(self): pass
2944 events = []
2945 result = LoggingResult(events)
2946 test = Foo("test_nothing")
2947 test.run(result)
2948 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2949 self.assertEqual(result.skipped, [(test, "testing")])
2950 self.assertEqual(result.testsRun, 1)
2951
2952 def test_skipping_decorators(self):
2953 op_table = ((unittest.skipUnless, False, True),
2954 (unittest.skipIf, True, False))
2955 for deco, do_skip, dont_skip in op_table:
2956 class Foo(unittest.TestCase):
2957 @deco(do_skip, "testing")
2958 def test_skip(self): pass
2959
2960 @deco(dont_skip, "testing")
2961 def test_dont_skip(self): pass
2962 test_do_skip = Foo("test_skip")
2963 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002964 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002965 events = []
2966 result = LoggingResult(events)
2967 suite.run(result)
2968 self.assertEqual(len(result.skipped), 1)
2969 expected = ['startTest', 'addSkip', 'stopTest',
2970 'startTest', 'addSuccess', 'stopTest']
2971 self.assertEqual(events, expected)
2972 self.assertEqual(result.testsRun, 2)
2973 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
2974 self.assertTrue(result.wasSuccessful())
2975
2976 def test_skip_class(self):
2977 @unittest.skip("testing")
2978 class Foo(unittest.TestCase):
2979 def test_1(self):
2980 record.append(1)
2981 record = []
2982 result = unittest.TestResult()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002983 test = Foo("test_1")
2984 suite = unittest.TestSuite([test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002985 suite.run(result)
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002986 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002987 self.assertEqual(record, [])
2988
2989 def test_expected_failure(self):
2990 class Foo(unittest.TestCase):
2991 @unittest.expectedFailure
2992 def test_die(self):
2993 self.fail("help me!")
2994 events = []
2995 result = LoggingResult(events)
2996 test = Foo("test_die")
2997 test.run(result)
2998 self.assertEqual(events,
2999 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003000 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00003001 self.assertTrue(result.wasSuccessful())
3002
3003 def test_unexpected_success(self):
3004 class Foo(unittest.TestCase):
3005 @unittest.expectedFailure
3006 def test_die(self):
3007 pass
3008 events = []
3009 result = LoggingResult(events)
3010 test = Foo("test_die")
3011 test.run(result)
3012 self.assertEqual(events,
3013 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3014 self.assertFalse(result.failures)
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003015 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003016 self.assertTrue(result.wasSuccessful())
3017
3018
3019
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003020class Test_Assertions(TestCase):
3021 def test_AlmostEqual(self):
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003022 self.assertAlmostEqual(1.00000001, 1.0)
3023 self.assertNotAlmostEqual(1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003024 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003025 self.assertAlmostEqual, 1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003026 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003027 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003028
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003029 self.assertAlmostEqual(1.1, 1.0, places=0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003030 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003031 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003032
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003033 self.assertAlmostEqual(0, .1+.1j, places=0)
3034 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003035 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003036 self.assertAlmostEqual, 0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003037 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003038 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003039
Michael Foordc3f79372009-09-13 16:40:02 +00003040 self.assertAlmostEqual(float('inf'), float('inf'))
3041 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3042 float('inf'), float('inf'))
3043
3044
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003045 def test_assertRaises(self):
3046 def _raise(e):
3047 raise e
3048 self.assertRaises(KeyError, _raise, KeyError)
3049 self.assertRaises(KeyError, _raise, KeyError("key"))
3050 try:
3051 self.assertRaises(KeyError, lambda: None)
Gregory P. Smith28399852009-03-31 16:54:10 +00003052 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003053 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003054 else:
3055 self.fail("assertRaises() didn't fail")
3056 try:
3057 self.assertRaises(KeyError, _raise, ValueError)
3058 except ValueError:
3059 pass
3060 else:
3061 self.fail("assertRaises() didn't let exception pass through")
3062 with self.assertRaises(KeyError):
3063 raise KeyError
3064 with self.assertRaises(KeyError):
3065 raise KeyError("key")
3066 try:
3067 with self.assertRaises(KeyError):
3068 pass
Gregory P. Smith28399852009-03-31 16:54:10 +00003069 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003070 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003071 else:
3072 self.fail("assertRaises() didn't fail")
3073 try:
3074 with self.assertRaises(KeyError):
3075 raise ValueError
3076 except ValueError:
3077 pass
3078 else:
3079 self.fail("assertRaises() didn't let exception pass through")
3080
3081
Michael Foord345b2fe2009-04-02 03:20:38 +00003082class TestLongMessage(TestCase):
3083 """Test that the individual asserts honour longMessage.
3084 This actually tests all the message behaviour for
3085 asserts that use longMessage."""
3086
3087 def setUp(self):
3088 class TestableTestFalse(TestCase):
3089 longMessage = False
3090 failureException = self.failureException
3091
3092 def testTest(self):
3093 pass
3094
3095 class TestableTestTrue(TestCase):
3096 longMessage = True
3097 failureException = self.failureException
3098
3099 def testTest(self):
3100 pass
3101
3102 self.testableTrue = TestableTestTrue('testTest')
3103 self.testableFalse = TestableTestFalse('testTest')
3104
3105 def testDefault(self):
3106 self.assertFalse(TestCase.longMessage)
3107
3108 def test_formatMsg(self):
3109 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3110 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3111
3112 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3113 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3114
3115 def assertMessages(self, methodName, args, errors):
3116 def getMethod(i):
3117 useTestableFalse = i < 2
3118 if useTestableFalse:
3119 test = self.testableFalse
3120 else:
3121 test = self.testableTrue
3122 return getattr(test, methodName)
3123
3124 for i, expected_regexp in enumerate(errors):
3125 testMethod = getMethod(i)
3126 kwargs = {}
3127 withMsg = i % 2
3128 if withMsg:
3129 kwargs = {"msg": "oops"}
3130
3131 with self.assertRaisesRegexp(self.failureException,
3132 expected_regexp=expected_regexp):
3133 testMethod(*args, **kwargs)
3134
3135 def testAssertTrue(self):
3136 self.assertMessages('assertTrue', (False,),
3137 ["^False is not True$", "^oops$", "^False is not True$",
3138 "^False is not True : oops$"])
3139
3140 def testAssertFalse(self):
3141 self.assertMessages('assertFalse', (True,),
3142 ["^True is not False$", "^oops$", "^True is not False$",
3143 "^True is not False : oops$"])
3144
3145 def testNotEqual(self):
3146 self.assertMessages('assertNotEqual', (1, 1),
3147 ["^1 == 1$", "^oops$", "^1 == 1$",
3148 "^1 == 1 : oops$"])
3149
3150 def testAlmostEqual(self):
3151 self.assertMessages('assertAlmostEqual', (1, 2),
3152 ["^1 != 2 within 7 places$", "^oops$",
3153 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3154
3155 def testNotAlmostEqual(self):
3156 self.assertMessages('assertNotAlmostEqual', (1, 1),
3157 ["^1 == 1 within 7 places$", "^oops$",
3158 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3159
3160 def test_baseAssertEqual(self):
3161 self.assertMessages('_baseAssertEqual', (1, 2),
3162 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3163
3164 def testAssertSequenceEqual(self):
3165 # Error messages are multiline so not testing on full message
3166 # assertTupleEqual and assertListEqual delegate to this method
3167 self.assertMessages('assertSequenceEqual', ([], [None]),
3168 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3169 r"\+ \[None\] : oops$"])
3170
3171 def testAssertSetEqual(self):
3172 self.assertMessages('assertSetEqual', (set(), set([None])),
3173 ["None$", "^oops$", "None$",
3174 "None : oops$"])
3175
3176 def testAssertIn(self):
3177 self.assertMessages('assertIn', (None, []),
3178 ['^None not found in \[\]$', "^oops$",
3179 '^None not found in \[\]$',
3180 '^None not found in \[\] : oops$'])
3181
3182 def testAssertNotIn(self):
3183 self.assertMessages('assertNotIn', (None, [None]),
3184 ['^None unexpectedly found in \[None\]$', "^oops$",
3185 '^None unexpectedly found in \[None\]$',
3186 '^None unexpectedly found in \[None\] : oops$'])
3187
3188 def testAssertDictEqual(self):
3189 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3190 [r"\+ \{'key': 'value'\}$", "^oops$",
3191 "\+ \{'key': 'value'\}$",
3192 "\+ \{'key': 'value'\} : oops$"])
3193
3194 def testAssertDictContainsSubset(self):
3195 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3196 ["^Missing: 'key'$", "^oops$",
3197 "^Missing: 'key'$",
3198 "^Missing: 'key' : oops$"])
3199
3200 def testAssertSameElements(self):
3201 self.assertMessages('assertSameElements', ([], [None]),
3202 [r"\[None\]$", "^oops$",
3203 r"\[None\]$",
3204 r"\[None\] : oops$"])
3205
3206 def testAssertMultiLineEqual(self):
3207 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3208 [r"\+ foo$", "^oops$",
3209 r"\+ foo$",
3210 r"\+ foo : oops$"])
3211
3212 def testAssertLess(self):
3213 self.assertMessages('assertLess', (2, 1),
3214 ["^2 not less than 1$", "^oops$",
3215 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3216
3217 def testAssertLessEqual(self):
3218 self.assertMessages('assertLessEqual', (2, 1),
3219 ["^2 not less than or equal to 1$", "^oops$",
3220 "^2 not less than or equal to 1$",
3221 "^2 not less than or equal to 1 : oops$"])
3222
3223 def testAssertGreater(self):
3224 self.assertMessages('assertGreater', (1, 2),
3225 ["^1 not greater than 2$", "^oops$",
3226 "^1 not greater than 2$",
3227 "^1 not greater than 2 : oops$"])
3228
3229 def testAssertGreaterEqual(self):
3230 self.assertMessages('assertGreaterEqual', (1, 2),
3231 ["^1 not greater than or equal to 2$", "^oops$",
3232 "^1 not greater than or equal to 2$",
3233 "^1 not greater than or equal to 2 : oops$"])
3234
3235 def testAssertIsNone(self):
3236 self.assertMessages('assertIsNone', ('not None',),
3237 ["^'not None' is not None$", "^oops$",
3238 "^'not None' is not None$",
3239 "^'not None' is not None : oops$"])
3240
3241 def testAssertIsNotNone(self):
3242 self.assertMessages('assertIsNotNone', (None,),
3243 ["^unexpectedly None$", "^oops$",
3244 "^unexpectedly None$",
3245 "^unexpectedly None : oops$"])
3246
Michael Foordf2dfef12009-04-05 19:19:28 +00003247 def testAssertIs(self):
3248 self.assertMessages('assertIs', (None, 'foo'),
3249 ["^None is not 'foo'$", "^oops$",
3250 "^None is not 'foo'$",
3251 "^None is not 'foo' : oops$"])
3252
3253 def testAssertIsNot(self):
3254 self.assertMessages('assertIsNot', (None, None),
3255 ["^unexpectedly identical: None$", "^oops$",
3256 "^unexpectedly identical: None$",
3257 "^unexpectedly identical: None : oops$"])
3258
Michael Foord345b2fe2009-04-02 03:20:38 +00003259
Michael Foorde2fb98f2009-05-02 20:15:05 +00003260class TestCleanUp(TestCase):
3261
3262 def testCleanUp(self):
3263 class TestableTest(TestCase):
3264 def testNothing(self):
3265 pass
3266
3267 test = TestableTest('testNothing')
3268 self.assertEqual(test._cleanups, [])
3269
3270 cleanups = []
3271
3272 def cleanup1(*args, **kwargs):
3273 cleanups.append((1, args, kwargs))
3274
3275 def cleanup2(*args, **kwargs):
3276 cleanups.append((2, args, kwargs))
3277
3278 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3279 test.addCleanup(cleanup2)
3280
3281 self.assertEqual(test._cleanups,
3282 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3283 (cleanup2, (), {})])
3284
3285 result = test.doCleanups()
3286 self.assertTrue(result)
3287
3288 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3289
3290 def testCleanUpWithErrors(self):
3291 class TestableTest(TestCase):
3292 def testNothing(self):
3293 pass
3294
3295 class MockResult(object):
3296 errors = []
3297 def addError(self, test, exc_info):
3298 self.errors.append((test, exc_info))
3299
3300 result = MockResult()
3301 test = TestableTest('testNothing')
Michael Foorda50af062009-05-21 22:57:02 +00003302 test._resultForDoCleanups = result
Michael Foorde2fb98f2009-05-02 20:15:05 +00003303
3304 exc1 = Exception('foo')
3305 exc2 = Exception('bar')
3306 def cleanup1():
3307 raise exc1
3308
3309 def cleanup2():
3310 raise exc2
3311
3312 test.addCleanup(cleanup1)
3313 test.addCleanup(cleanup2)
3314
3315 self.assertFalse(test.doCleanups())
3316
3317 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3318 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3319 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3320
3321 def testCleanupInRun(self):
3322 blowUp = False
3323 ordering = []
3324
3325 class TestableTest(TestCase):
3326 def setUp(self):
3327 ordering.append('setUp')
3328 if blowUp:
3329 raise Exception('foo')
3330
3331 def testNothing(self):
3332 ordering.append('test')
3333
3334 def tearDown(self):
3335 ordering.append('tearDown')
3336
3337 test = TestableTest('testNothing')
3338
3339 def cleanup1():
3340 ordering.append('cleanup1')
3341 def cleanup2():
3342 ordering.append('cleanup2')
3343 test.addCleanup(cleanup1)
3344 test.addCleanup(cleanup2)
3345
3346 def success(some_test):
3347 self.assertEqual(some_test, test)
3348 ordering.append('success')
3349
3350 result = unittest.TestResult()
3351 result.addSuccess = success
3352
3353 test.run(result)
3354 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3355 'cleanup2', 'cleanup1', 'success'])
3356
3357 blowUp = True
3358 ordering = []
3359 test = TestableTest('testNothing')
3360 test.addCleanup(cleanup1)
3361 test.run(result)
3362 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3363
3364
Michael Foord829f6b82009-05-02 11:43:06 +00003365class Test_TestProgram(TestCase):
3366
3367 # Horrible white box test
3368 def testNoExit(self):
3369 result = object()
3370 test = object()
3371
3372 class FakeRunner(object):
3373 def run(self, test):
3374 self.test = test
3375 return result
3376
3377 runner = FakeRunner()
3378
Michael Foord5d31e052009-05-11 17:59:43 +00003379 oldParseArgs = TestProgram.parseArgs
3380 def restoreParseArgs():
Michael Foord829f6b82009-05-02 11:43:06 +00003381 TestProgram.parseArgs = oldParseArgs
Michael Foord5d31e052009-05-11 17:59:43 +00003382 TestProgram.parseArgs = lambda *args: None
3383 self.addCleanup(restoreParseArgs)
3384
3385 def removeTest():
Michael Foord829f6b82009-05-02 11:43:06 +00003386 del TestProgram.test
Michael Foord5d31e052009-05-11 17:59:43 +00003387 TestProgram.test = test
3388 self.addCleanup(removeTest)
3389
3390 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3391
3392 self.assertEqual(program.result, result)
3393 self.assertEqual(runner.test, test)
3394 self.assertEqual(program.verbosity, 2)
Michael Foord829f6b82009-05-02 11:43:06 +00003395
Michael Foord829f6b82009-05-02 11:43:06 +00003396 class FooBar(unittest.TestCase):
3397 def testPass(self):
3398 assert True
3399 def testFail(self):
3400 assert False
3401
3402 class FooBarLoader(unittest.TestLoader):
3403 """Test loader that returns a suite containing FooBar."""
3404 def loadTestsFromModule(self, module):
3405 return self.suiteClass(
3406 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3407
3408
3409 def test_NonExit(self):
3410 program = unittest.main(exit=False,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003411 argv=["foobar"],
3412 testRunner=unittest.TextTestRunner(stream=StringIO()),
3413 testLoader=self.FooBarLoader())
Michael Foord829f6b82009-05-02 11:43:06 +00003414 self.assertTrue(hasattr(program, 'result'))
3415
3416
3417 def test_Exit(self):
3418 self.assertRaises(
3419 SystemExit,
3420 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003421 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003422 testRunner=unittest.TextTestRunner(stream=StringIO()),
3423 exit=True,
3424 testLoader=self.FooBarLoader())
3425
3426
3427 def test_ExitAsDefault(self):
3428 self.assertRaises(
3429 SystemExit,
3430 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003431 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003432 testRunner=unittest.TextTestRunner(stream=StringIO()),
3433 testLoader=self.FooBarLoader())
3434
3435
Michael Foord07ef4872009-05-02 22:43:34 +00003436class Test_TextTestRunner(TestCase):
3437 """Tests for TextTestRunner."""
3438
3439 def test_works_with_result_without_startTestRun_stopTestRun(self):
3440 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3441 separator2 = ''
3442 def printErrors(self):
3443 pass
3444
3445 class Runner(unittest.TextTestRunner):
3446 def __init__(self):
3447 super(Runner, self).__init__(StringIO())
3448
3449 def _makeResult(self):
3450 return OldTextResult()
3451
3452 runner = Runner()
3453 runner.run(unittest.TestSuite())
3454
3455 def test_startTestRun_stopTestRun_called(self):
3456 class LoggingTextResult(LoggingResult):
3457 separator2 = ''
3458 def printErrors(self):
3459 pass
3460
3461 class LoggingRunner(unittest.TextTestRunner):
3462 def __init__(self, events):
3463 super(LoggingRunner, self).__init__(StringIO())
3464 self._events = events
3465
3466 def _makeResult(self):
3467 return LoggingTextResult(self._events)
3468
3469 events = []
3470 runner = LoggingRunner(events)
3471 runner.run(unittest.TestSuite())
3472 expected = ['startTestRun', 'stopTestRun']
3473 self.assertEqual(events, expected)
3474
Antoine Pitrou0734c632009-11-10 20:49:30 +00003475 def test_pickle_unpickle(self):
3476 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3477 # required by test_multiprocessing under Windows (in verbose mode).
3478 import StringIO
3479 # cStringIO objects are not pickleable, but StringIO objects are.
3480 stream = StringIO.StringIO("foo")
3481 runner = unittest.TextTestRunner(stream)
3482 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
3483 s = pickle.dumps(runner, protocol=protocol)
3484 obj = pickle.loads(s)
3485 # StringIO objects never compare equal, a cheap test instead.
3486 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3487
Michael Foord07ef4872009-05-02 22:43:34 +00003488
Michael Foordb4a81c82009-05-29 20:33:46 +00003489class TestDiscovery(TestCase):
3490
3491 # Heavily mocked tests so I can avoid hitting the filesystem
Michael Foorde91ea562009-09-13 19:07:03 +00003492 def test_get_name_from_path(self):
Michael Foordb4a81c82009-05-29 20:33:46 +00003493 loader = unittest.TestLoader()
3494
Michael Foordb4a81c82009-05-29 20:33:46 +00003495 loader._top_level_dir = '/foo'
Michael Foorde91ea562009-09-13 19:07:03 +00003496 name = loader._get_name_from_path('/foo/bar/baz.py')
3497 self.assertEqual(name, 'bar.baz')
Michael Foordb4a81c82009-05-29 20:33:46 +00003498
3499 if not __debug__:
3500 # asserts are off
3501 return
3502
3503 with self.assertRaises(AssertionError):
Michael Foorde91ea562009-09-13 19:07:03 +00003504 loader._get_name_from_path('/bar/baz.py')
Michael Foordb4a81c82009-05-29 20:33:46 +00003505
3506 def test_find_tests(self):
3507 loader = unittest.TestLoader()
3508
3509 original_listdir = os.listdir
3510 def restore_listdir():
3511 os.listdir = original_listdir
3512 original_isfile = os.path.isfile
3513 def restore_isfile():
3514 os.path.isfile = original_isfile
3515 original_isdir = os.path.isdir
3516 def restore_isdir():
3517 os.path.isdir = original_isdir
3518
3519 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Michael Foorde91ea562009-09-13 19:07:03 +00003520 'test.foo', 'test-not-a-module.py', 'another_dir'],
Michael Foordb4a81c82009-05-29 20:33:46 +00003521 ['test3.py', 'test4.py', ]]
3522 os.listdir = lambda path: path_lists.pop(0)
3523 self.addCleanup(restore_listdir)
3524
3525 def isdir(path):
3526 return path.endswith('dir')
3527 os.path.isdir = isdir
3528 self.addCleanup(restore_isdir)
3529
3530 def isfile(path):
3531 # another_dir is not a package and so shouldn't be recursed into
3532 return not path.endswith('dir') and not 'another_dir' in path
3533 os.path.isfile = isfile
3534 self.addCleanup(restore_isfile)
3535
Michael Foorde91ea562009-09-13 19:07:03 +00003536 loader._get_module_from_name = lambda path: path + ' module'
Michael Foordb4a81c82009-05-29 20:33:46 +00003537 loader.loadTestsFromModule = lambda module: module + ' tests'
3538
3539 loader._top_level_dir = '/foo'
3540 suite = list(loader._find_tests('/foo', 'test*.py'))
3541
Michael Foorde91ea562009-09-13 19:07:03 +00003542 expected = [name + ' module tests' for name in
3543 ('test1', 'test2')]
3544 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3545 ('test3', 'test4')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003546 self.assertEqual(suite, expected)
3547
3548 def test_find_tests_with_package(self):
3549 loader = unittest.TestLoader()
3550
3551 original_listdir = os.listdir
3552 def restore_listdir():
3553 os.listdir = original_listdir
3554 original_isfile = os.path.isfile
3555 def restore_isfile():
3556 os.path.isfile = original_isfile
3557 original_isdir = os.path.isdir
3558 def restore_isdir():
3559 os.path.isdir = original_isdir
3560
3561 directories = ['a_directory', 'test_directory', 'test_directory2']
3562 path_lists = [directories, [], [], []]
3563 os.listdir = lambda path: path_lists.pop(0)
3564 self.addCleanup(restore_listdir)
3565
3566 os.path.isdir = lambda path: True
3567 self.addCleanup(restore_isdir)
3568
3569 os.path.isfile = lambda path: os.path.basename(path) not in directories
3570 self.addCleanup(restore_isfile)
3571
3572 class Module(object):
3573 paths = []
3574 load_tests_args = []
3575
3576 def __init__(self, path):
3577 self.path = path
3578 self.paths.append(path)
3579 if os.path.basename(path) == 'test_directory':
3580 def load_tests(loader, tests, pattern):
3581 self.load_tests_args.append((loader, tests, pattern))
3582 return 'load_tests'
3583 self.load_tests = load_tests
3584
3585 def __eq__(self, other):
3586 return self.path == other.path
3587
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003588 # Silence py3k warning
3589 __hash__ = None
3590
Michael Foorde91ea562009-09-13 19:07:03 +00003591 loader._get_module_from_name = lambda name: Module(name)
Michael Foordb4a81c82009-05-29 20:33:46 +00003592 def loadTestsFromModule(module, use_load_tests):
3593 if use_load_tests:
3594 raise self.failureException('use_load_tests should be False for packages')
3595 return module.path + ' module tests'
3596 loader.loadTestsFromModule = loadTestsFromModule
3597
3598 loader._top_level_dir = '/foo'
3599 # this time no '.py' on the pattern so that it can match
3600 # a test package
3601 suite = list(loader._find_tests('/foo', 'test*'))
3602
3603 # We should have loaded tests from the test_directory package by calling load_tests
3604 # and directly from the test_directory2 package
Michael Foordd53d0852009-06-05 14:14:34 +00003605 self.assertEqual(suite,
Michael Foorde91ea562009-09-13 19:07:03 +00003606 ['load_tests', 'test_directory2' + ' module tests'])
3607 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Michael Foordb4a81c82009-05-29 20:33:46 +00003608
3609 # load_tests should have been called once with loader, tests and pattern
3610 self.assertEqual(Module.load_tests_args,
Michael Foorde91ea562009-09-13 19:07:03 +00003611 [(loader, 'test_directory' + ' module tests', 'test*')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003612
3613 def test_discover(self):
3614 loader = unittest.TestLoader()
3615
3616 original_isfile = os.path.isfile
3617 def restore_isfile():
3618 os.path.isfile = original_isfile
3619
3620 os.path.isfile = lambda path: False
3621 self.addCleanup(restore_isfile)
3622
Nick Coghlanb6edf192009-10-17 08:21:21 +00003623 orig_sys_path = sys.path[:]
3624 def restore_path():
3625 sys.path[:] = orig_sys_path
3626 self.addCleanup(restore_path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003627
Nick Coghlanb6edf192009-10-17 08:21:21 +00003628 full_path = os.path.abspath(os.path.normpath('/foo'))
Michael Foordb4a81c82009-05-29 20:33:46 +00003629 with self.assertRaises(ImportError):
3630 loader.discover('/foo/bar', top_level_dir='/foo')
3631
3632 self.assertEqual(loader._top_level_dir, full_path)
3633 self.assertIn(full_path, sys.path)
3634
3635 os.path.isfile = lambda path: True
3636 _find_tests_args = []
3637 def _find_tests(start_dir, pattern):
3638 _find_tests_args.append((start_dir, pattern))
3639 return ['tests']
3640 loader._find_tests = _find_tests
3641 loader.suiteClass = str
3642
3643 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3644
3645 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3646 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3647 self.assertEqual(suite, "['tests']")
3648 self.assertEqual(loader._top_level_dir, top_level_dir)
3649 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlanb6edf192009-10-17 08:21:21 +00003650 self.assertIn(top_level_dir, sys.path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003651
Michael Foorde91ea562009-09-13 19:07:03 +00003652 def test_discover_with_modules_that_fail_to_import(self):
3653 loader = unittest.TestLoader()
3654
3655 listdir = os.listdir
3656 os.listdir = lambda _: ['test_this_does_not_exist.py']
3657 isfile = os.path.isfile
3658 os.path.isfile = lambda _: True
Nick Coghlanb6edf192009-10-17 08:21:21 +00003659 orig_sys_path = sys.path[:]
Michael Foorde91ea562009-09-13 19:07:03 +00003660 def restore():
3661 os.path.isfile = isfile
3662 os.listdir = listdir
Nick Coghlanb6edf192009-10-17 08:21:21 +00003663 sys.path[:] = orig_sys_path
Michael Foorde91ea562009-09-13 19:07:03 +00003664 self.addCleanup(restore)
3665
3666 suite = loader.discover('.')
Nick Coghlanb6edf192009-10-17 08:21:21 +00003667 self.assertIn(os.getcwd(), sys.path)
Michael Foorde91ea562009-09-13 19:07:03 +00003668 self.assertEqual(suite.countTestCases(), 1)
3669 test = list(list(suite)[0])[0] # extract test from suite
3670
3671 with self.assertRaises(ImportError):
3672 test.test_this_does_not_exist()
3673
Michael Foordb4a81c82009-05-29 20:33:46 +00003674 def test_command_line_handling_parseArgs(self):
3675 # Haha - take that uninstantiable class
3676 program = object.__new__(TestProgram)
3677
3678 args = []
3679 def do_discovery(argv):
3680 args.extend(argv)
3681 program._do_discovery = do_discovery
3682 program.parseArgs(['something', 'discover'])
3683 self.assertEqual(args, [])
3684
3685 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3686 self.assertEqual(args, ['foo', 'bar'])
3687
3688 def test_command_line_handling_do_discovery_too_many_arguments(self):
3689 class Stop(Exception):
3690 pass
3691 def usageExit():
3692 raise Stop
3693
3694 program = object.__new__(TestProgram)
3695 program.usageExit = usageExit
3696
3697 with self.assertRaises(Stop):
3698 # too many args
3699 program._do_discovery(['one', 'two', 'three', 'four'])
3700
3701
3702 def test_command_line_handling_do_discovery_calls_loader(self):
3703 program = object.__new__(TestProgram)
3704
3705 class Loader(object):
3706 args = []
3707 def discover(self, start_dir, pattern, top_level_dir):
3708 self.args.append((start_dir, pattern, top_level_dir))
3709 return 'tests'
3710
3711 program._do_discovery(['-v'], Loader=Loader)
3712 self.assertEqual(program.verbosity, 2)
3713 self.assertEqual(program.test, 'tests')
3714 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3715
3716 Loader.args = []
3717 program = object.__new__(TestProgram)
3718 program._do_discovery(['--verbose'], Loader=Loader)
3719 self.assertEqual(program.test, 'tests')
3720 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3721
3722 Loader.args = []
3723 program = object.__new__(TestProgram)
3724 program._do_discovery([], Loader=Loader)
3725 self.assertEqual(program.test, 'tests')
3726 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3727
3728 Loader.args = []
3729 program = object.__new__(TestProgram)
3730 program._do_discovery(['fish'], Loader=Loader)
3731 self.assertEqual(program.test, 'tests')
3732 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3733
3734 Loader.args = []
3735 program = object.__new__(TestProgram)
3736 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3737 self.assertEqual(program.test, 'tests')
3738 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3739
3740 Loader.args = []
3741 program = object.__new__(TestProgram)
3742 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3743 self.assertEqual(program.test, 'tests')
3744 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3745
3746 Loader.args = []
3747 program = object.__new__(TestProgram)
3748 program._do_discovery(['-s', 'fish'], Loader=Loader)
3749 self.assertEqual(program.test, 'tests')
3750 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3751
3752 Loader.args = []
3753 program = object.__new__(TestProgram)
3754 program._do_discovery(['-t', 'fish'], Loader=Loader)
3755 self.assertEqual(program.test, 'tests')
3756 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3757
3758 Loader.args = []
3759 program = object.__new__(TestProgram)
3760 program._do_discovery(['-p', 'fish'], Loader=Loader)
3761 self.assertEqual(program.test, 'tests')
3762 self.assertEqual(Loader.args, [('.', 'fish', None)])
3763
3764 Loader.args = []
3765 program = object.__new__(TestProgram)
3766 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3767 self.assertEqual(program.test, 'tests')
3768 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3769 self.assertEqual(program.verbosity, 2)
3770
3771
Jim Fultonfafd8742004-08-28 15:22:12 +00003772######################################################################
3773## Main
3774######################################################################
3775
3776def test_main():
Georg Brandl15c5ce92007-03-07 09:09:40 +00003777 test_support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003778 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Michael Foord829f6b82009-05-02 11:43:06 +00003779 Test_TestSkipping, Test_Assertions, TestLongMessage,
Antoine Pitrou0734c632009-11-10 20:49:30 +00003780 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner)
Jim Fultonfafd8742004-08-28 15:22:12 +00003781
Georg Brandl15c5ce92007-03-07 09:09:40 +00003782if __name__ == "__main__":
Tim Petersea5962f2007-03-12 18:07:52 +00003783 test_main()