blob: d009bf9ce87c31626d96f2ffb341070bbc2e421a [file] [log] [blame]
Jim Fultonfafd8742004-08-28 15:22:12 +00001"""Test script for unittest.
2
Georg Brandl15c5ce92007-03-07 09:09:40 +00003By Collin Winter <collinw at gmail.com>
4
5Still need testing:
6 TestCase.{assert,fail}* methods (some are tested implicitly)
Jim Fultonfafd8742004-08-28 15:22:12 +00007"""
8
Michael Foordb4a81c82009-05-29 20:33:46 +00009import os
Gregory P. Smith28399852009-03-31 16:54:10 +000010import re
Michael Foordb4a81c82009-05-29 20:33:46 +000011import sys
Georg Brandl15c5ce92007-03-07 09:09:40 +000012from test import test_support
Jim Fultonfafd8742004-08-28 15:22:12 +000013import unittest
Michael Foord829f6b82009-05-02 11:43:06 +000014from unittest import TestCase, TestProgram
Christian Heimesc756d002007-11-27 21:34:01 +000015import types
Michael Foorde2942d02009-04-02 05:51:54 +000016from copy import deepcopy
Michael Foord829f6b82009-05-02 11:43:06 +000017from cStringIO import StringIO
Antoine Pitrou0734c632009-11-10 20:49:30 +000018import pickle
Michael Foord2f677562010-02-21 14:48:59 +000019import warnings
Jim Fultonfafd8742004-08-28 15:22:12 +000020
Michael Foord225a0992010-02-18 20:30:09 +000021
Georg Brandl15c5ce92007-03-07 09:09:40 +000022### Support code
23################################################################
Jim Fultonfafd8742004-08-28 15:22:12 +000024
Georg Brandl15c5ce92007-03-07 09:09:40 +000025class LoggingResult(unittest.TestResult):
26 def __init__(self, log):
27 self._events = log
28 super(LoggingResult, self).__init__()
29
30 def startTest(self, test):
31 self._events.append('startTest')
32 super(LoggingResult, self).startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +000033
Michael Foord07ef4872009-05-02 22:43:34 +000034 def startTestRun(self):
35 self._events.append('startTestRun')
36 super(LoggingResult, self).startTestRun()
37
Georg Brandl15c5ce92007-03-07 09:09:40 +000038 def stopTest(self, test):
39 self._events.append('stopTest')
40 super(LoggingResult, self).stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +000041
Michael Foord07ef4872009-05-02 22:43:34 +000042 def stopTestRun(self):
43 self._events.append('stopTestRun')
44 super(LoggingResult, self).stopTestRun()
45
Georg Brandl15c5ce92007-03-07 09:09:40 +000046 def addFailure(self, *args):
47 self._events.append('addFailure')
48 super(LoggingResult, self).addFailure(*args)
Tim Petersea5962f2007-03-12 18:07:52 +000049
Benjamin Peterson692428e2009-03-23 21:50:21 +000050 def addSuccess(self, *args):
51 self._events.append('addSuccess')
52 super(LoggingResult, self).addSuccess(*args)
53
Georg Brandl15c5ce92007-03-07 09:09:40 +000054 def addError(self, *args):
55 self._events.append('addError')
56 super(LoggingResult, self).addError(*args)
57
Benjamin Peterson692428e2009-03-23 21:50:21 +000058 def addSkip(self, *args):
59 self._events.append('addSkip')
60 super(LoggingResult, self).addSkip(*args)
61
62 def addExpectedFailure(self, *args):
63 self._events.append('addExpectedFailure')
64 super(LoggingResult, self).addExpectedFailure(*args)
65
66 def addUnexpectedSuccess(self, *args):
67 self._events.append('addUnexpectedSuccess')
68 super(LoggingResult, self).addUnexpectedSuccess(*args)
69
70
Georg Brandl15c5ce92007-03-07 09:09:40 +000071class TestEquality(object):
Michael Foord345b2fe2009-04-02 03:20:38 +000072 """Used as a mixin for TestCase"""
73
Tim Petersea5962f2007-03-12 18:07:52 +000074 # Check for a valid __eq__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000075 def test_eq(self):
76 for obj_1, obj_2 in self.eq_pairs:
77 self.assertEqual(obj_1, obj_2)
78 self.assertEqual(obj_2, obj_1)
Tim Petersea5962f2007-03-12 18:07:52 +000079
80 # Check for a valid __ne__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000081 def test_ne(self):
82 for obj_1, obj_2 in self.ne_pairs:
Benjamin Peterson6b0032f2009-06-30 23:30:12 +000083 self.assertNotEqual(obj_1, obj_2)
84 self.assertNotEqual(obj_2, obj_1)
Tim Petersea5962f2007-03-12 18:07:52 +000085
Georg Brandl15c5ce92007-03-07 09:09:40 +000086class TestHashing(object):
Michael Foord345b2fe2009-04-02 03:20:38 +000087 """Used as a mixin for TestCase"""
88
Tim Petersea5962f2007-03-12 18:07:52 +000089 # Check for a valid __hash__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000090 def test_hash(self):
91 for obj_1, obj_2 in self.eq_pairs:
92 try:
Gregory P. Smith28399852009-03-31 16:54:10 +000093 if not hash(obj_1) == hash(obj_2):
94 self.fail("%r and %r do not hash equal" % (obj_1, obj_2))
Georg Brandl15c5ce92007-03-07 09:09:40 +000095 except KeyboardInterrupt:
96 raise
Georg Brandl15c5ce92007-03-07 09:09:40 +000097 except Exception, e:
Gregory P. Smith28399852009-03-31 16:54:10 +000098 self.fail("Problem hashing %r and %r: %s" % (obj_1, obj_2, e))
Tim Petersea5962f2007-03-12 18:07:52 +000099
Georg Brandl15c5ce92007-03-07 09:09:40 +0000100 for obj_1, obj_2 in self.ne_pairs:
101 try:
Gregory P. Smith28399852009-03-31 16:54:10 +0000102 if hash(obj_1) == hash(obj_2):
103 self.fail("%s and %s hash equal, but shouldn't" %
104 (obj_1, obj_2))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000105 except KeyboardInterrupt:
106 raise
Georg Brandl15c5ce92007-03-07 09:09:40 +0000107 except Exception, e:
108 self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e))
Tim Petersea5962f2007-03-12 18:07:52 +0000109
Georg Brandl15c5ce92007-03-07 09:09:40 +0000110
Benjamin Peterson692428e2009-03-23 21:50:21 +0000111# List subclass we can add attributes to.
112class MyClassSuite(list):
113
Benjamin Peterson176a56c2009-05-25 00:48:58 +0000114 def __init__(self, tests):
Benjamin Peterson692428e2009-03-23 21:50:21 +0000115 super(MyClassSuite, self).__init__(tests)
116
117
Georg Brandl15c5ce92007-03-07 09:09:40 +0000118################################################################
119### /Support code
120
121class Test_TestLoader(TestCase):
122
123 ### Tests for TestLoader.loadTestsFromTestCase
124 ################################################################
125
126 # "Return a suite of all tests cases contained in the TestCase-derived
127 # class testCaseClass"
128 def test_loadTestsFromTestCase(self):
129 class Foo(unittest.TestCase):
130 def test_1(self): pass
131 def test_2(self): pass
132 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000133
Georg Brandl15c5ce92007-03-07 09:09:40 +0000134 tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +0000135
Georg Brandl15c5ce92007-03-07 09:09:40 +0000136 loader = unittest.TestLoader()
137 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +0000138
Georg Brandl15c5ce92007-03-07 09:09:40 +0000139 # "Return a suite of all tests cases contained in the TestCase-derived
140 # class testCaseClass"
141 #
Tim Petersea5962f2007-03-12 18:07:52 +0000142 # Make sure it does the right thing even if no tests were found
Georg Brandl15c5ce92007-03-07 09:09:40 +0000143 def test_loadTestsFromTestCase__no_matches(self):
144 class Foo(unittest.TestCase):
145 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000146
Georg Brandl15c5ce92007-03-07 09:09:40 +0000147 empty_suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +0000148
Georg Brandl15c5ce92007-03-07 09:09:40 +0000149 loader = unittest.TestLoader()
150 self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite)
Tim Petersea5962f2007-03-12 18:07:52 +0000151
Georg Brandl15c5ce92007-03-07 09:09:40 +0000152 # "Return a suite of all tests cases contained in the TestCase-derived
153 # class testCaseClass"
154 #
155 # What happens if loadTestsFromTestCase() is given an object
156 # that isn't a subclass of TestCase? Specifically, what happens
157 # if testCaseClass is a subclass of TestSuite?
158 #
159 # This is checked for specifically in the code, so we better add a
160 # test for it.
161 def test_loadTestsFromTestCase__TestSuite_subclass(self):
162 class NotATestCase(unittest.TestSuite):
163 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000164
Georg Brandl15c5ce92007-03-07 09:09:40 +0000165 loader = unittest.TestLoader()
166 try:
167 loader.loadTestsFromTestCase(NotATestCase)
168 except TypeError:
169 pass
170 else:
171 self.fail('Should raise TypeError')
Tim Petersea5962f2007-03-12 18:07:52 +0000172
Georg Brandl15c5ce92007-03-07 09:09:40 +0000173 # "Return a suite of all tests cases contained in the TestCase-derived
174 # class testCaseClass"
175 #
176 # Make sure loadTestsFromTestCase() picks up the default test method
177 # name (as specified by TestCase), even though the method name does
178 # not match the default TestLoader.testMethodPrefix string
179 def test_loadTestsFromTestCase__default_method_name(self):
180 class Foo(unittest.TestCase):
181 def runTest(self):
182 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000183
Georg Brandl15c5ce92007-03-07 09:09:40 +0000184 loader = unittest.TestLoader()
185 # This has to be false for the test to succeed
Benjamin Peterson6b0032f2009-06-30 23:30:12 +0000186 self.assertFalse('runTest'.startswith(loader.testMethodPrefix))
Tim Petersea5962f2007-03-12 18:07:52 +0000187
Georg Brandl15c5ce92007-03-07 09:09:40 +0000188 suite = loader.loadTestsFromTestCase(Foo)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000189 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000190 self.assertEqual(list(suite), [Foo('runTest')])
191
192 ################################################################
193 ### /Tests for TestLoader.loadTestsFromTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000194
Georg Brandl15c5ce92007-03-07 09:09:40 +0000195 ### Tests for TestLoader.loadTestsFromModule
196 ################################################################
197
198 # "This method searches `module` for classes derived from TestCase"
199 def test_loadTestsFromModule__TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000200 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000201 class MyTestCase(unittest.TestCase):
202 def test(self):
203 pass
204 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000205
Georg Brandl15c5ce92007-03-07 09:09:40 +0000206 loader = unittest.TestLoader()
207 suite = loader.loadTestsFromModule(m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000208 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000209
Georg Brandl15c5ce92007-03-07 09:09:40 +0000210 expected = [loader.suiteClass([MyTestCase('test')])]
211 self.assertEqual(list(suite), expected)
Tim Petersea5962f2007-03-12 18:07:52 +0000212
Georg Brandl15c5ce92007-03-07 09:09:40 +0000213 # "This method searches `module` for classes derived from TestCase"
Tim Petersea5962f2007-03-12 18:07:52 +0000214 #
Georg Brandl15c5ce92007-03-07 09:09:40 +0000215 # What happens if no tests are found (no TestCase instances)?
216 def test_loadTestsFromModule__no_TestCase_instances(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000217 m = types.ModuleType('m')
Tim Petersea5962f2007-03-12 18:07:52 +0000218
Georg Brandl15c5ce92007-03-07 09:09:40 +0000219 loader = unittest.TestLoader()
220 suite = loader.loadTestsFromModule(m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000221 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000222 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000223
Georg Brandl15c5ce92007-03-07 09:09:40 +0000224 # "This method searches `module` for classes derived from TestCase"
225 #
Tim Petersea5962f2007-03-12 18:07:52 +0000226 # What happens if no tests are found (TestCases instances, but no tests)?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000227 def test_loadTestsFromModule__no_TestCase_tests(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000228 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000229 class MyTestCase(unittest.TestCase):
230 pass
231 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000232
Georg Brandl15c5ce92007-03-07 09:09:40 +0000233 loader = unittest.TestLoader()
234 suite = loader.loadTestsFromModule(m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000235 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000236
Georg Brandl15c5ce92007-03-07 09:09:40 +0000237 self.assertEqual(list(suite), [loader.suiteClass()])
Tim Petersea5962f2007-03-12 18:07:52 +0000238
Georg Brandl15c5ce92007-03-07 09:09:40 +0000239 # "This method searches `module` for classes derived from TestCase"s
240 #
241 # What happens if loadTestsFromModule() is given something other
242 # than a module?
243 #
244 # XXX Currently, it succeeds anyway. This flexibility
245 # should either be documented or loadTestsFromModule() should
246 # raise a TypeError
247 #
248 # XXX Certain people are using this behaviour. We'll add a test for it
249 def test_loadTestsFromModule__not_a_module(self):
250 class MyTestCase(unittest.TestCase):
251 def test(self):
252 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000253
Georg Brandl15c5ce92007-03-07 09:09:40 +0000254 class NotAModule(object):
255 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000256
Georg Brandl15c5ce92007-03-07 09:09:40 +0000257 loader = unittest.TestLoader()
258 suite = loader.loadTestsFromModule(NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000259
Georg Brandl15c5ce92007-03-07 09:09:40 +0000260 reference = [unittest.TestSuite([MyTestCase('test')])]
261 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000262
Michael Foordb4a81c82009-05-29 20:33:46 +0000263
264 # Check that loadTestsFromModule honors (or not) a module
265 # with a load_tests function.
266 def test_loadTestsFromModule__load_tests(self):
267 m = types.ModuleType('m')
268 class MyTestCase(unittest.TestCase):
269 def test(self):
270 pass
271 m.testcase_1 = MyTestCase
272
273 load_tests_args = []
274 def load_tests(loader, tests, pattern):
Michael Foord08770602010-02-06 00:22:26 +0000275 self.assertIsInstance(tests, unittest.TestSuite)
Michael Foordb4a81c82009-05-29 20:33:46 +0000276 load_tests_args.extend((loader, tests, pattern))
277 return tests
278 m.load_tests = load_tests
279
280 loader = unittest.TestLoader()
281 suite = loader.loadTestsFromModule(m)
Michael Foord08770602010-02-06 00:22:26 +0000282 self.assertIsInstance(suite, unittest.TestSuite)
Michael Foordb4a81c82009-05-29 20:33:46 +0000283 self.assertEquals(load_tests_args, [loader, suite, None])
284
285 load_tests_args = []
286 suite = loader.loadTestsFromModule(m, use_load_tests=False)
287 self.assertEquals(load_tests_args, [])
288
Georg Brandl15c5ce92007-03-07 09:09:40 +0000289 ################################################################
290 ### /Tests for TestLoader.loadTestsFromModule()
Tim Petersea5962f2007-03-12 18:07:52 +0000291
Georg Brandl15c5ce92007-03-07 09:09:40 +0000292 ### Tests for TestLoader.loadTestsFromName()
293 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000294
Georg Brandl15c5ce92007-03-07 09:09:40 +0000295 # "The specifier name is a ``dotted name'' that may resolve either to
296 # a module, a test case class, a TestSuite instance, a test method
297 # within a test case class, or a callable object which returns a
298 # TestCase or TestSuite instance."
299 #
300 # Is ValueError raised in response to an empty name?
301 def test_loadTestsFromName__empty_name(self):
302 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000303
Georg Brandl15c5ce92007-03-07 09:09:40 +0000304 try:
305 loader.loadTestsFromName('')
306 except ValueError, e:
307 self.assertEqual(str(e), "Empty module name")
308 else:
309 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000310
Georg Brandl15c5ce92007-03-07 09:09:40 +0000311 # "The specifier name is a ``dotted name'' that may resolve either to
312 # a module, a test case class, a TestSuite instance, a test method
313 # within a test case class, or a callable object which returns a
314 # TestCase or TestSuite instance."
315 #
Tim Petersea5962f2007-03-12 18:07:52 +0000316 # What happens when the name contains invalid characters?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000317 def test_loadTestsFromName__malformed_name(self):
318 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000319
Georg Brandl15c5ce92007-03-07 09:09:40 +0000320 # XXX Should this raise ValueError or ImportError?
321 try:
322 loader.loadTestsFromName('abc () //')
323 except ValueError:
324 pass
325 except ImportError:
326 pass
327 else:
328 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000329
Georg Brandl15c5ce92007-03-07 09:09:40 +0000330 # "The specifier name is a ``dotted name'' that may resolve ... to a
331 # module"
332 #
Tim Petersea5962f2007-03-12 18:07:52 +0000333 # What happens when a module by that name can't be found?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000334 def test_loadTestsFromName__unknown_module_name(self):
335 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000336
Georg Brandl15c5ce92007-03-07 09:09:40 +0000337 try:
338 loader.loadTestsFromName('sdasfasfasdf')
339 except ImportError, e:
340 self.assertEqual(str(e), "No module named sdasfasfasdf")
341 else:
342 self.fail("TestLoader.loadTestsFromName failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000343
Georg Brandl15c5ce92007-03-07 09:09:40 +0000344 # "The specifier name is a ``dotted name'' that may resolve either to
345 # a module, a test case class, a TestSuite instance, a test method
346 # within a test case class, or a callable object which returns a
347 # TestCase or TestSuite instance."
348 #
Tim Petersea5962f2007-03-12 18:07:52 +0000349 # What happens when the module is found, but the attribute can't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000350 def test_loadTestsFromName__unknown_attr_name(self):
351 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000352
Georg Brandl15c5ce92007-03-07 09:09:40 +0000353 try:
354 loader.loadTestsFromName('unittest.sdasfasfasdf')
355 except AttributeError, e:
356 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
357 else:
358 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000359
Georg Brandl15c5ce92007-03-07 09:09:40 +0000360 # "The specifier name is a ``dotted name'' that may resolve either to
361 # a module, a test case class, a TestSuite instance, a test method
362 # within a test case class, or a callable object which returns a
363 # TestCase or TestSuite instance."
364 #
365 # What happens when we provide the module, but the attribute can't be
366 # found?
367 def test_loadTestsFromName__relative_unknown_name(self):
368 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000369
Georg Brandl15c5ce92007-03-07 09:09:40 +0000370 try:
371 loader.loadTestsFromName('sdasfasfasdf', unittest)
372 except AttributeError, e:
373 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
374 else:
375 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000376
Georg Brandl15c5ce92007-03-07 09:09:40 +0000377 # "The specifier name is a ``dotted name'' that may resolve either to
378 # a module, a test case class, a TestSuite instance, a test method
379 # within a test case class, or a callable object which returns a
380 # TestCase or TestSuite instance."
381 # ...
382 # "The method optionally resolves name relative to the given module"
383 #
384 # Does loadTestsFromName raise ValueError when passed an empty
385 # name relative to a provided module?
386 #
387 # XXX Should probably raise a ValueError instead of an AttributeError
388 def test_loadTestsFromName__relative_empty_name(self):
389 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000390
Georg Brandl15c5ce92007-03-07 09:09:40 +0000391 try:
392 loader.loadTestsFromName('', unittest)
393 except AttributeError, e:
394 pass
395 else:
396 self.fail("Failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000397
Georg Brandl15c5ce92007-03-07 09:09:40 +0000398 # "The specifier name is a ``dotted name'' that may resolve either to
399 # a module, a test case class, a TestSuite instance, a test method
400 # within a test case class, or a callable object which returns a
401 # TestCase or TestSuite instance."
402 # ...
403 # "The method optionally resolves name relative to the given module"
404 #
405 # What happens when an impossible name is given, relative to the provided
406 # `module`?
407 def test_loadTestsFromName__relative_malformed_name(self):
408 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000409
Georg Brandl15c5ce92007-03-07 09:09:40 +0000410 # XXX Should this raise AttributeError or ValueError?
411 try:
412 loader.loadTestsFromName('abc () //', unittest)
413 except ValueError:
414 pass
415 except AttributeError:
416 pass
417 else:
418 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
419
420 # "The method optionally resolves name relative to the given module"
421 #
422 # Does loadTestsFromName raise TypeError when the `module` argument
423 # isn't a module object?
424 #
425 # XXX Accepts the not-a-module object, ignorning the object's type
426 # This should raise an exception or the method name should be changed
427 #
428 # XXX Some people are relying on this, so keep it for now
429 def test_loadTestsFromName__relative_not_a_module(self):
430 class MyTestCase(unittest.TestCase):
431 def test(self):
432 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000433
Georg Brandl15c5ce92007-03-07 09:09:40 +0000434 class NotAModule(object):
435 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000436
Georg Brandl15c5ce92007-03-07 09:09:40 +0000437 loader = unittest.TestLoader()
438 suite = loader.loadTestsFromName('test_2', NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000439
Georg Brandl15c5ce92007-03-07 09:09:40 +0000440 reference = [MyTestCase('test')]
441 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000442
Georg Brandl15c5ce92007-03-07 09:09:40 +0000443 # "The specifier name is a ``dotted name'' that may resolve either to
444 # a module, a test case class, a TestSuite instance, a test method
445 # within a test case class, or a callable object which returns a
446 # TestCase or TestSuite instance."
447 #
448 # Does it raise an exception if the name resolves to an invalid
449 # object?
450 def test_loadTestsFromName__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000451 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000452 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000453
Georg Brandl15c5ce92007-03-07 09:09:40 +0000454 loader = unittest.TestLoader()
455 try:
456 loader.loadTestsFromName('testcase_1', m)
457 except TypeError:
458 pass
459 else:
460 self.fail("Should have raised TypeError")
461
462 # "The specifier name is a ``dotted name'' that may
463 # resolve either to ... a test case class"
464 def test_loadTestsFromName__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000465 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000466 class MyTestCase(unittest.TestCase):
467 def test(self):
468 pass
469 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000470
Georg Brandl15c5ce92007-03-07 09:09:40 +0000471 loader = unittest.TestLoader()
472 suite = loader.loadTestsFromName('testcase_1', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000473 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000474 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000475
Georg Brandl15c5ce92007-03-07 09:09:40 +0000476 # "The specifier name is a ``dotted name'' that may resolve either to
477 # a module, a test case class, a TestSuite instance, a test method
478 # within a test case class, or a callable object which returns a
479 # TestCase or TestSuite instance."
480 def test_loadTestsFromName__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000481 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000482 class MyTestCase(unittest.TestCase):
483 def test(self):
484 pass
485 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000486
Georg Brandl15c5ce92007-03-07 09:09:40 +0000487 loader = unittest.TestLoader()
488 suite = loader.loadTestsFromName('testsuite', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000489 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000490
Georg Brandl15c5ce92007-03-07 09:09:40 +0000491 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000492
Georg Brandl15c5ce92007-03-07 09:09:40 +0000493 # "The specifier name is a ``dotted name'' that may resolve ... to
494 # ... a test method within a test case class"
495 def test_loadTestsFromName__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000496 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000497 class MyTestCase(unittest.TestCase):
498 def test(self):
499 pass
500 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000501
Georg Brandl15c5ce92007-03-07 09:09:40 +0000502 loader = unittest.TestLoader()
503 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000504 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000505
Georg Brandl15c5ce92007-03-07 09:09:40 +0000506 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000507
Georg Brandl15c5ce92007-03-07 09:09:40 +0000508 # "The specifier name is a ``dotted name'' that may resolve either to
509 # a module, a test case class, a TestSuite instance, a test method
510 # within a test case class, or a callable object which returns a
511 # TestCase or TestSuite instance."
512 #
513 # Does loadTestsFromName() raise the proper exception when trying to
514 # resolve "a test method within a test case class" that doesn't exist
515 # for the given name (relative to a provided module)?
516 def test_loadTestsFromName__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000517 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000518 class MyTestCase(unittest.TestCase):
519 def test(self):
520 pass
521 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000522
Georg Brandl15c5ce92007-03-07 09:09:40 +0000523 loader = unittest.TestLoader()
524 try:
525 loader.loadTestsFromName('testcase_1.testfoo', m)
526 except AttributeError, e:
527 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
528 else:
529 self.fail("Failed to raise AttributeError")
530
531 # "The specifier name is a ``dotted name'' that may resolve ... to
532 # ... a callable object which returns a ... TestSuite instance"
533 def test_loadTestsFromName__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000534 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000535 testcase_1 = unittest.FunctionTestCase(lambda: None)
536 testcase_2 = unittest.FunctionTestCase(lambda: None)
537 def return_TestSuite():
538 return unittest.TestSuite([testcase_1, testcase_2])
539 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000540
Georg Brandl15c5ce92007-03-07 09:09:40 +0000541 loader = unittest.TestLoader()
542 suite = loader.loadTestsFromName('return_TestSuite', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000543 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000544 self.assertEqual(list(suite), [testcase_1, testcase_2])
Tim Petersea5962f2007-03-12 18:07:52 +0000545
Georg Brandl15c5ce92007-03-07 09:09:40 +0000546 # "The specifier name is a ``dotted name'' that may resolve ... to
547 # ... a callable object which returns a TestCase ... instance"
548 def test_loadTestsFromName__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000549 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000550 testcase_1 = unittest.FunctionTestCase(lambda: None)
551 def return_TestCase():
552 return testcase_1
553 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000554
Georg Brandl15c5ce92007-03-07 09:09:40 +0000555 loader = unittest.TestLoader()
556 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000557 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000558 self.assertEqual(list(suite), [testcase_1])
Tim Petersea5962f2007-03-12 18:07:52 +0000559
Georg Brandl15c5ce92007-03-07 09:09:40 +0000560 # "The specifier name is a ``dotted name'' that may resolve ... to
Michael Foord5a9719d2009-09-13 17:28:35 +0000561 # ... a callable object which returns a TestCase ... instance"
562 #*****************************************************************
563 #Override the suiteClass attribute to ensure that the suiteClass
564 #attribute is used
565 def test_loadTestsFromName__callable__TestCase_instance_ProperSuiteClass(self):
566 class SubTestSuite(unittest.TestSuite):
567 pass
568 m = types.ModuleType('m')
569 testcase_1 = unittest.FunctionTestCase(lambda: None)
570 def return_TestCase():
571 return testcase_1
572 m.return_TestCase = return_TestCase
573
574 loader = unittest.TestLoader()
575 loader.suiteClass = SubTestSuite
576 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000577 self.assertIsInstance(suite, loader.suiteClass)
Michael Foord5a9719d2009-09-13 17:28:35 +0000578 self.assertEqual(list(suite), [testcase_1])
579
580 # "The specifier name is a ``dotted name'' that may resolve ... to
581 # ... a test method within a test case class"
582 #*****************************************************************
583 #Override the suiteClass attribute to ensure that the suiteClass
584 #attribute is used
585 def test_loadTestsFromName__relative_testmethod_ProperSuiteClass(self):
586 class SubTestSuite(unittest.TestSuite):
587 pass
588 m = types.ModuleType('m')
589 class MyTestCase(unittest.TestCase):
590 def test(self):
591 pass
592 m.testcase_1 = MyTestCase
593
594 loader = unittest.TestLoader()
595 loader.suiteClass=SubTestSuite
596 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000597 self.assertIsInstance(suite, loader.suiteClass)
Michael Foord5a9719d2009-09-13 17:28:35 +0000598
599 self.assertEqual(list(suite), [MyTestCase('test')])
600
601 # "The specifier name is a ``dotted name'' that may resolve ... to
Georg Brandl15c5ce92007-03-07 09:09:40 +0000602 # ... a callable object which returns a TestCase or TestSuite instance"
603 #
604 # What happens if the callable returns something else?
605 def test_loadTestsFromName__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000606 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000607 def return_wrong():
608 return 6
609 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000610
Georg Brandl15c5ce92007-03-07 09:09:40 +0000611 loader = unittest.TestLoader()
612 try:
613 suite = loader.loadTestsFromName('return_wrong', m)
614 except TypeError:
615 pass
616 else:
617 self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000618
Georg Brandl15c5ce92007-03-07 09:09:40 +0000619 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +0000620 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +0000621 def test_loadTestsFromName__module_not_loaded(self):
622 # We're going to try to load this module as a side-effect, so it
623 # better not be loaded before we try.
624 #
625 # Why pick audioop? Google shows it isn't used very often, so there's
626 # a good chance that it won't be imported when this test is run
627 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +0000628
Georg Brandl15c5ce92007-03-07 09:09:40 +0000629 if module_name in sys.modules:
630 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000631
Georg Brandl15c5ce92007-03-07 09:09:40 +0000632 loader = unittest.TestLoader()
633 try:
634 suite = loader.loadTestsFromName(module_name)
635
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000636 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000637 self.assertEqual(list(suite), [])
638
639 # audioop should now be loaded, thanks to loadTestsFromName()
Ezio Melottiaa980582010-01-23 23:04:36 +0000640 self.assertIn(module_name, sys.modules)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000641 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000642 if module_name in sys.modules:
643 del sys.modules[module_name]
Georg Brandl15c5ce92007-03-07 09:09:40 +0000644
645 ################################################################
646 ### Tests for TestLoader.loadTestsFromName()
647
648 ### Tests for TestLoader.loadTestsFromNames()
649 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000650
Georg Brandl15c5ce92007-03-07 09:09:40 +0000651 # "Similar to loadTestsFromName(), but takes a sequence of names rather
652 # than a single name."
653 #
654 # What happens if that sequence of names is empty?
655 def test_loadTestsFromNames__empty_name_list(self):
656 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000657
Georg Brandl15c5ce92007-03-07 09:09:40 +0000658 suite = loader.loadTestsFromNames([])
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000659 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000660 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000661
Georg Brandl15c5ce92007-03-07 09:09:40 +0000662 # "Similar to loadTestsFromName(), but takes a sequence of names rather
663 # than a single name."
664 # ...
665 # "The method optionally resolves name relative to the given module"
666 #
667 # What happens if that sequence of names is empty?
668 #
669 # XXX Should this raise a ValueError or just return an empty TestSuite?
670 def test_loadTestsFromNames__relative_empty_name_list(self):
671 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000672
Georg Brandl15c5ce92007-03-07 09:09:40 +0000673 suite = loader.loadTestsFromNames([], unittest)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000674 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000675 self.assertEqual(list(suite), [])
676
677 # "The specifier name is a ``dotted name'' that may resolve either to
678 # a module, a test case class, a TestSuite instance, a test method
679 # within a test case class, or a callable object which returns a
680 # TestCase or TestSuite instance."
681 #
682 # Is ValueError raised in response to an empty name?
683 def test_loadTestsFromNames__empty_name(self):
684 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000685
Georg Brandl15c5ce92007-03-07 09:09:40 +0000686 try:
687 loader.loadTestsFromNames([''])
688 except ValueError, e:
689 self.assertEqual(str(e), "Empty module name")
690 else:
691 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000692
Georg Brandl15c5ce92007-03-07 09:09:40 +0000693 # "The specifier name is a ``dotted name'' that may resolve either to
694 # a module, a test case class, a TestSuite instance, a test method
695 # within a test case class, or a callable object which returns a
696 # TestCase or TestSuite instance."
697 #
Tim Petersea5962f2007-03-12 18:07:52 +0000698 # What happens when presented with an impossible module name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000699 def test_loadTestsFromNames__malformed_name(self):
700 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000701
Georg Brandl15c5ce92007-03-07 09:09:40 +0000702 # XXX Should this raise ValueError or ImportError?
703 try:
704 loader.loadTestsFromNames(['abc () //'])
705 except ValueError:
706 pass
707 except ImportError:
708 pass
709 else:
710 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000711
Georg Brandl15c5ce92007-03-07 09:09:40 +0000712 # "The specifier name is a ``dotted name'' that may resolve either to
713 # a module, a test case class, a TestSuite instance, a test method
714 # within a test case class, or a callable object which returns a
715 # TestCase or TestSuite instance."
716 #
Tim Petersea5962f2007-03-12 18:07:52 +0000717 # What happens when no module can be found for the given name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000718 def test_loadTestsFromNames__unknown_module_name(self):
719 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000720
Georg Brandl15c5ce92007-03-07 09:09:40 +0000721 try:
722 loader.loadTestsFromNames(['sdasfasfasdf'])
723 except ImportError, e:
724 self.assertEqual(str(e), "No module named sdasfasfasdf")
725 else:
726 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000727
Georg Brandl15c5ce92007-03-07 09:09:40 +0000728 # "The specifier name is a ``dotted name'' that may resolve either to
729 # a module, a test case class, a TestSuite instance, a test method
730 # within a test case class, or a callable object which returns a
731 # TestCase or TestSuite instance."
732 #
Tim Petersea5962f2007-03-12 18:07:52 +0000733 # What happens when the module can be found, but not the attribute?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000734 def test_loadTestsFromNames__unknown_attr_name(self):
735 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000736
Georg Brandl15c5ce92007-03-07 09:09:40 +0000737 try:
738 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
739 except AttributeError, e:
740 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
741 else:
742 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000743
Georg Brandl15c5ce92007-03-07 09:09:40 +0000744 # "The specifier name is a ``dotted name'' that may resolve either to
745 # a module, a test case class, a TestSuite instance, a test method
746 # within a test case class, or a callable object which returns a
747 # TestCase or TestSuite instance."
748 # ...
749 # "The method optionally resolves name relative to the given module"
750 #
751 # What happens when given an unknown attribute on a specified `module`
752 # argument?
753 def test_loadTestsFromNames__unknown_name_relative_1(self):
754 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000755
Georg Brandl15c5ce92007-03-07 09:09:40 +0000756 try:
757 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
758 except AttributeError, e:
759 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
760 else:
761 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000762
Georg Brandl15c5ce92007-03-07 09:09:40 +0000763 # "The specifier name is a ``dotted name'' that may resolve either to
764 # a module, a test case class, a TestSuite instance, a test method
765 # within a test case class, or a callable object which returns a
766 # TestCase or TestSuite instance."
767 # ...
768 # "The method optionally resolves name relative to the given module"
769 #
770 # Do unknown attributes (relative to a provided module) still raise an
Tim Petersea5962f2007-03-12 18:07:52 +0000771 # exception even in the presence of valid attribute names?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000772 def test_loadTestsFromNames__unknown_name_relative_2(self):
773 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000774
Georg Brandl15c5ce92007-03-07 09:09:40 +0000775 try:
776 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
777 except AttributeError, e:
778 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
779 else:
780 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
781
782 # "The specifier name is a ``dotted name'' that may resolve either to
783 # a module, a test case class, a TestSuite instance, a test method
784 # within a test case class, or a callable object which returns a
785 # TestCase or TestSuite instance."
786 # ...
787 # "The method optionally resolves name relative to the given module"
788 #
789 # What happens when faced with the empty string?
790 #
791 # XXX This currently raises AttributeError, though ValueError is probably
792 # more appropriate
793 def test_loadTestsFromNames__relative_empty_name(self):
794 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000795
Georg Brandl15c5ce92007-03-07 09:09:40 +0000796 try:
797 loader.loadTestsFromNames([''], unittest)
798 except AttributeError:
799 pass
800 else:
801 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000802
Georg Brandl15c5ce92007-03-07 09:09:40 +0000803 # "The specifier name is a ``dotted name'' that may resolve either to
804 # a module, a test case class, a TestSuite instance, a test method
805 # within a test case class, or a callable object which returns a
806 # TestCase or TestSuite instance."
807 # ...
808 # "The method optionally resolves name relative to the given module"
809 #
Tim Petersea5962f2007-03-12 18:07:52 +0000810 # What happens when presented with an impossible attribute name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000811 def test_loadTestsFromNames__relative_malformed_name(self):
812 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000813
Georg Brandl15c5ce92007-03-07 09:09:40 +0000814 # XXX Should this raise AttributeError or ValueError?
815 try:
816 loader.loadTestsFromNames(['abc () //'], unittest)
817 except AttributeError:
818 pass
819 except ValueError:
820 pass
821 else:
822 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
823
824 # "The method optionally resolves name relative to the given module"
825 #
826 # Does loadTestsFromNames() make sure the provided `module` is in fact
827 # a module?
828 #
829 # XXX This validation is currently not done. This flexibility should
830 # either be documented or a TypeError should be raised.
831 def test_loadTestsFromNames__relative_not_a_module(self):
832 class MyTestCase(unittest.TestCase):
833 def test(self):
834 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000835
Georg Brandl15c5ce92007-03-07 09:09:40 +0000836 class NotAModule(object):
837 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000838
Georg Brandl15c5ce92007-03-07 09:09:40 +0000839 loader = unittest.TestLoader()
840 suite = loader.loadTestsFromNames(['test_2'], NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000841
Georg Brandl15c5ce92007-03-07 09:09:40 +0000842 reference = [unittest.TestSuite([MyTestCase('test')])]
843 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000844
Georg Brandl15c5ce92007-03-07 09:09:40 +0000845 # "The specifier name is a ``dotted name'' that may resolve either to
846 # a module, a test case class, a TestSuite instance, a test method
847 # within a test case class, or a callable object which returns a
848 # TestCase or TestSuite instance."
849 #
850 # Does it raise an exception if the name resolves to an invalid
851 # object?
852 def test_loadTestsFromNames__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000853 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000854 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000855
Georg Brandl15c5ce92007-03-07 09:09:40 +0000856 loader = unittest.TestLoader()
857 try:
858 loader.loadTestsFromNames(['testcase_1'], m)
859 except TypeError:
860 pass
861 else:
862 self.fail("Should have raised TypeError")
863
864 # "The specifier name is a ``dotted name'' that may resolve ... to
865 # ... a test case class"
866 def test_loadTestsFromNames__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000867 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000868 class MyTestCase(unittest.TestCase):
869 def test(self):
870 pass
871 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000872
Georg Brandl15c5ce92007-03-07 09:09:40 +0000873 loader = unittest.TestLoader()
874 suite = loader.loadTestsFromNames(['testcase_1'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000875 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000876
Georg Brandl15c5ce92007-03-07 09:09:40 +0000877 expected = loader.suiteClass([MyTestCase('test')])
878 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000879
Georg Brandl15c5ce92007-03-07 09:09:40 +0000880 # "The specifier name is a ``dotted name'' that may resolve ... to
881 # ... a TestSuite instance"
882 def test_loadTestsFromNames__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000883 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000884 class MyTestCase(unittest.TestCase):
885 def test(self):
886 pass
887 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000888
Georg Brandl15c5ce92007-03-07 09:09:40 +0000889 loader = unittest.TestLoader()
890 suite = loader.loadTestsFromNames(['testsuite'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000891 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000892
Georg Brandl15c5ce92007-03-07 09:09:40 +0000893 self.assertEqual(list(suite), [m.testsuite])
Tim Petersea5962f2007-03-12 18:07:52 +0000894
Georg Brandl15c5ce92007-03-07 09:09:40 +0000895 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
896 # test method within a test case class"
897 def test_loadTestsFromNames__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000898 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000899 class MyTestCase(unittest.TestCase):
900 def test(self):
901 pass
902 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000903
Georg Brandl15c5ce92007-03-07 09:09:40 +0000904 loader = unittest.TestLoader()
905 suite = loader.loadTestsFromNames(['testcase_1.test'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000906 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000907
Georg Brandl15c5ce92007-03-07 09:09:40 +0000908 ref_suite = unittest.TestSuite([MyTestCase('test')])
909 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000910
Georg Brandl15c5ce92007-03-07 09:09:40 +0000911 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
912 # test method within a test case class"
913 #
914 # Does the method gracefully handle names that initially look like they
Tim Petersea5962f2007-03-12 18:07:52 +0000915 # resolve to "a test method within a test case class" but don't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000916 def test_loadTestsFromNames__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000917 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000918 class MyTestCase(unittest.TestCase):
919 def test(self):
920 pass
921 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000922
Georg Brandl15c5ce92007-03-07 09:09:40 +0000923 loader = unittest.TestLoader()
924 try:
925 loader.loadTestsFromNames(['testcase_1.testfoo'], m)
926 except AttributeError, e:
927 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
928 else:
929 self.fail("Failed to raise AttributeError")
930
931 # "The specifier name is a ``dotted name'' that may resolve ... to
932 # ... a callable object which returns a ... TestSuite instance"
933 def test_loadTestsFromNames__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000934 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000935 testcase_1 = unittest.FunctionTestCase(lambda: None)
936 testcase_2 = unittest.FunctionTestCase(lambda: None)
937 def return_TestSuite():
938 return unittest.TestSuite([testcase_1, testcase_2])
939 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000940
Georg Brandl15c5ce92007-03-07 09:09:40 +0000941 loader = unittest.TestLoader()
942 suite = loader.loadTestsFromNames(['return_TestSuite'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000943 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000944
Georg Brandl15c5ce92007-03-07 09:09:40 +0000945 expected = unittest.TestSuite([testcase_1, testcase_2])
946 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000947
Georg Brandl15c5ce92007-03-07 09:09:40 +0000948 # "The specifier name is a ``dotted name'' that may resolve ... to
949 # ... a callable object which returns a TestCase ... instance"
950 def test_loadTestsFromNames__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000951 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000952 testcase_1 = unittest.FunctionTestCase(lambda: None)
953 def return_TestCase():
954 return testcase_1
955 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000956
Georg Brandl15c5ce92007-03-07 09:09:40 +0000957 loader = unittest.TestLoader()
958 suite = loader.loadTestsFromNames(['return_TestCase'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000959 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000960
Georg Brandl15c5ce92007-03-07 09:09:40 +0000961 ref_suite = unittest.TestSuite([testcase_1])
962 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000963
Georg Brandl15c5ce92007-03-07 09:09:40 +0000964 # "The specifier name is a ``dotted name'' that may resolve ... to
965 # ... a callable object which returns a TestCase or TestSuite instance"
966 #
Tim Petersea5962f2007-03-12 18:07:52 +0000967 # Are staticmethods handled correctly?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000968 def test_loadTestsFromNames__callable__call_staticmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000969 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000970 class Test1(unittest.TestCase):
971 def test(self):
972 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000973
Georg Brandl15c5ce92007-03-07 09:09:40 +0000974 testcase_1 = Test1('test')
975 class Foo(unittest.TestCase):
976 @staticmethod
977 def foo():
978 return testcase_1
979 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +0000980
Georg Brandl15c5ce92007-03-07 09:09:40 +0000981 loader = unittest.TestLoader()
982 suite = loader.loadTestsFromNames(['Foo.foo'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000983 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000984
Georg Brandl15c5ce92007-03-07 09:09:40 +0000985 ref_suite = unittest.TestSuite([testcase_1])
986 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000987
Georg Brandl15c5ce92007-03-07 09:09:40 +0000988 # "The specifier name is a ``dotted name'' that may resolve ... to
989 # ... a callable object which returns a TestCase or TestSuite instance"
990 #
991 # What happens when the callable returns something else?
992 def test_loadTestsFromNames__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000993 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000994 def return_wrong():
995 return 6
996 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000997
Georg Brandl15c5ce92007-03-07 09:09:40 +0000998 loader = unittest.TestLoader()
999 try:
1000 suite = loader.loadTestsFromNames(['return_wrong'], m)
1001 except TypeError:
1002 pass
1003 else:
1004 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +00001005
Georg Brandl15c5ce92007-03-07 09:09:40 +00001006 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +00001007 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001008 def test_loadTestsFromNames__module_not_loaded(self):
1009 # We're going to try to load this module as a side-effect, so it
1010 # better not be loaded before we try.
1011 #
1012 # Why pick audioop? Google shows it isn't used very often, so there's
1013 # a good chance that it won't be imported when this test is run
1014 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +00001015
Georg Brandl15c5ce92007-03-07 09:09:40 +00001016 if module_name in sys.modules:
1017 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +00001018
Georg Brandl15c5ce92007-03-07 09:09:40 +00001019 loader = unittest.TestLoader()
1020 try:
1021 suite = loader.loadTestsFromNames([module_name])
1022
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001023 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +00001024 self.assertEqual(list(suite), [unittest.TestSuite()])
1025
1026 # audioop should now be loaded, thanks to loadTestsFromName()
Ezio Melottiaa980582010-01-23 23:04:36 +00001027 self.assertIn(module_name, sys.modules)
Georg Brandl15c5ce92007-03-07 09:09:40 +00001028 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +00001029 if module_name in sys.modules:
1030 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +00001031
Georg Brandl15c5ce92007-03-07 09:09:40 +00001032 ################################################################
1033 ### /Tests for TestLoader.loadTestsFromNames()
1034
1035 ### Tests for TestLoader.getTestCaseNames()
1036 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001037
Georg Brandl15c5ce92007-03-07 09:09:40 +00001038 # "Return a sorted sequence of method names found within testCaseClass"
1039 #
1040 # Test.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +00001041 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +00001042 def test_getTestCaseNames(self):
1043 class Test(unittest.TestCase):
1044 def test_1(self): pass
1045 def test_2(self): pass
1046 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001047
Georg Brandl15c5ce92007-03-07 09:09:40 +00001048 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001049
Georg Brandl15c5ce92007-03-07 09:09:40 +00001050 self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])
Tim Petersea5962f2007-03-12 18:07:52 +00001051
Georg Brandl15c5ce92007-03-07 09:09:40 +00001052 # "Return a sorted sequence of method names found within testCaseClass"
1053 #
Tim Petersea5962f2007-03-12 18:07:52 +00001054 # Does getTestCaseNames() behave appropriately if no tests are found?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001055 def test_getTestCaseNames__no_tests(self):
1056 class Test(unittest.TestCase):
1057 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001058
Georg Brandl15c5ce92007-03-07 09:09:40 +00001059 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001060
Georg Brandl15c5ce92007-03-07 09:09:40 +00001061 self.assertEqual(loader.getTestCaseNames(Test), [])
Tim Petersea5962f2007-03-12 18:07:52 +00001062
Georg Brandl15c5ce92007-03-07 09:09:40 +00001063 # "Return a sorted sequence of method names found within testCaseClass"
1064 #
1065 # Are not-TestCases handled gracefully?
1066 #
1067 # XXX This should raise a TypeError, not return a list
1068 #
1069 # XXX It's too late in the 2.5 release cycle to fix this, but it should
1070 # probably be revisited for 2.6
1071 def test_getTestCaseNames__not_a_TestCase(self):
1072 class BadCase(int):
1073 def test_foo(self):
1074 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001075
Georg Brandl15c5ce92007-03-07 09:09:40 +00001076 loader = unittest.TestLoader()
1077 names = loader.getTestCaseNames(BadCase)
Tim Petersea5962f2007-03-12 18:07:52 +00001078
Georg Brandl15c5ce92007-03-07 09:09:40 +00001079 self.assertEqual(names, ['test_foo'])
Tim Petersea5962f2007-03-12 18:07:52 +00001080
Georg Brandl15c5ce92007-03-07 09:09:40 +00001081 # "Return a sorted sequence of method names found within testCaseClass"
1082 #
1083 # Make sure inherited names are handled.
1084 #
1085 # TestP.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +00001086 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +00001087 def test_getTestCaseNames__inheritance(self):
1088 class TestP(unittest.TestCase):
1089 def test_1(self): pass
1090 def test_2(self): pass
1091 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001092
Georg Brandl15c5ce92007-03-07 09:09:40 +00001093 class TestC(TestP):
1094 def test_1(self): pass
1095 def test_3(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001096
Georg Brandl15c5ce92007-03-07 09:09:40 +00001097 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001098
Georg Brandl15c5ce92007-03-07 09:09:40 +00001099 names = ['test_1', 'test_2', 'test_3']
1100 self.assertEqual(loader.getTestCaseNames(TestC), names)
Tim Petersea5962f2007-03-12 18:07:52 +00001101
1102 ################################################################
Georg Brandl15c5ce92007-03-07 09:09:40 +00001103 ### /Tests for TestLoader.getTestCaseNames()
1104
1105 ### Tests for TestLoader.testMethodPrefix
1106 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001107
Georg Brandl15c5ce92007-03-07 09:09:40 +00001108 # "String giving the prefix of method names which will be interpreted as
1109 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001110 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001111 # Implicit in the documentation is that testMethodPrefix is respected by
1112 # all loadTestsFrom* methods.
1113 def test_testMethodPrefix__loadTestsFromTestCase(self):
1114 class Foo(unittest.TestCase):
1115 def test_1(self): pass
1116 def test_2(self): pass
1117 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001118
Georg Brandl15c5ce92007-03-07 09:09:40 +00001119 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1120 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001121
Georg Brandl15c5ce92007-03-07 09:09:40 +00001122 loader = unittest.TestLoader()
1123 loader.testMethodPrefix = 'foo'
1124 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
1125
1126 loader.testMethodPrefix = 'test'
1127 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001128
Georg Brandl15c5ce92007-03-07 09:09:40 +00001129 # "String giving the prefix of method names which will be interpreted as
1130 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001131 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001132 # Implicit in the documentation is that testMethodPrefix is respected by
1133 # all loadTestsFrom* methods.
1134 def test_testMethodPrefix__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001135 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001136 class Foo(unittest.TestCase):
1137 def test_1(self): pass
1138 def test_2(self): pass
1139 def foo_bar(self): pass
1140 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001141
Georg Brandl15c5ce92007-03-07 09:09:40 +00001142 tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
1143 tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]
Tim Petersea5962f2007-03-12 18:07:52 +00001144
Georg Brandl15c5ce92007-03-07 09:09:40 +00001145 loader = unittest.TestLoader()
1146 loader.testMethodPrefix = 'foo'
1147 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
1148
1149 loader.testMethodPrefix = 'test'
1150 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001151
Georg Brandl15c5ce92007-03-07 09:09:40 +00001152 # "String giving the prefix of method names which will be interpreted as
1153 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001154 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001155 # Implicit in the documentation is that testMethodPrefix is respected by
1156 # all loadTestsFrom* methods.
1157 def test_testMethodPrefix__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001158 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001159 class Foo(unittest.TestCase):
1160 def test_1(self): pass
1161 def test_2(self): pass
1162 def foo_bar(self): pass
1163 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001164
Georg Brandl15c5ce92007-03-07 09:09:40 +00001165 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1166 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001167
Georg Brandl15c5ce92007-03-07 09:09:40 +00001168 loader = unittest.TestLoader()
1169 loader.testMethodPrefix = 'foo'
1170 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
1171
1172 loader.testMethodPrefix = 'test'
1173 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001174
Georg Brandl15c5ce92007-03-07 09:09:40 +00001175 # "String giving the prefix of method names which will be interpreted as
1176 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001177 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001178 # Implicit in the documentation is that testMethodPrefix is respected by
1179 # all loadTestsFrom* methods.
1180 def test_testMethodPrefix__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001181 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001182 class Foo(unittest.TestCase):
1183 def test_1(self): pass
1184 def test_2(self): pass
1185 def foo_bar(self): pass
1186 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001187
Georg Brandl15c5ce92007-03-07 09:09:40 +00001188 tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
1189 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1190 tests_2 = unittest.TestSuite([tests_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001191
Georg Brandl15c5ce92007-03-07 09:09:40 +00001192 loader = unittest.TestLoader()
1193 loader.testMethodPrefix = 'foo'
1194 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)
1195
1196 loader.testMethodPrefix = 'test'
1197 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001198
Georg Brandl15c5ce92007-03-07 09:09:40 +00001199 # "The default value is 'test'"
1200 def test_testMethodPrefix__default_value(self):
1201 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001202 self.assertTrue(loader.testMethodPrefix == 'test')
Tim Petersea5962f2007-03-12 18:07:52 +00001203
Georg Brandl15c5ce92007-03-07 09:09:40 +00001204 ################################################################
1205 ### /Tests for TestLoader.testMethodPrefix
1206
Tim Petersea5962f2007-03-12 18:07:52 +00001207 ### Tests for TestLoader.sortTestMethodsUsing
Georg Brandl15c5ce92007-03-07 09:09:40 +00001208 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001209
Georg Brandl15c5ce92007-03-07 09:09:40 +00001210 # "Function to be used to compare method names when sorting them in
1211 # getTestCaseNames() and all the loadTestsFromX() methods"
1212 def test_sortTestMethodsUsing__loadTestsFromTestCase(self):
1213 def reversed_cmp(x, y):
1214 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001215
Georg Brandl15c5ce92007-03-07 09:09:40 +00001216 class Foo(unittest.TestCase):
1217 def test_1(self): pass
1218 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001219
Georg Brandl15c5ce92007-03-07 09:09:40 +00001220 loader = unittest.TestLoader()
1221 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001222
Georg Brandl15c5ce92007-03-07 09:09:40 +00001223 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1224 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001225
Georg Brandl15c5ce92007-03-07 09:09:40 +00001226 # "Function to be used to compare method names when sorting them in
1227 # getTestCaseNames() and all the loadTestsFromX() methods"
1228 def test_sortTestMethodsUsing__loadTestsFromModule(self):
1229 def reversed_cmp(x, y):
1230 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001231
Christian Heimesc756d002007-11-27 21:34:01 +00001232 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001233 class Foo(unittest.TestCase):
1234 def test_1(self): pass
1235 def test_2(self): pass
1236 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001237
Georg Brandl15c5ce92007-03-07 09:09:40 +00001238 loader = unittest.TestLoader()
1239 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001240
Georg Brandl15c5ce92007-03-07 09:09:40 +00001241 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1242 self.assertEqual(list(loader.loadTestsFromModule(m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001243
Georg Brandl15c5ce92007-03-07 09:09:40 +00001244 # "Function to be used to compare method names when sorting them in
1245 # getTestCaseNames() and all the loadTestsFromX() methods"
1246 def test_sortTestMethodsUsing__loadTestsFromName(self):
1247 def reversed_cmp(x, y):
1248 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001249
Christian Heimesc756d002007-11-27 21:34:01 +00001250 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001251 class Foo(unittest.TestCase):
1252 def test_1(self): pass
1253 def test_2(self): pass
1254 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001255
Georg Brandl15c5ce92007-03-07 09:09:40 +00001256 loader = unittest.TestLoader()
1257 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001258
Georg Brandl15c5ce92007-03-07 09:09:40 +00001259 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1260 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001261
Georg Brandl15c5ce92007-03-07 09:09:40 +00001262 # "Function to be used to compare method names when sorting them in
1263 # getTestCaseNames() and all the loadTestsFromX() methods"
1264 def test_sortTestMethodsUsing__loadTestsFromNames(self):
1265 def reversed_cmp(x, y):
1266 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001267
Christian Heimesc756d002007-11-27 21:34:01 +00001268 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001269 class Foo(unittest.TestCase):
1270 def test_1(self): pass
1271 def test_2(self): pass
1272 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001273
Georg Brandl15c5ce92007-03-07 09:09:40 +00001274 loader = unittest.TestLoader()
1275 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001276
Georg Brandl15c5ce92007-03-07 09:09:40 +00001277 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1278 self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001279
Georg Brandl15c5ce92007-03-07 09:09:40 +00001280 # "Function to be used to compare method names when sorting them in
1281 # getTestCaseNames()"
1282 #
1283 # Does it actually affect getTestCaseNames()?
1284 def test_sortTestMethodsUsing__getTestCaseNames(self):
1285 def reversed_cmp(x, y):
1286 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001287
Georg Brandl15c5ce92007-03-07 09:09:40 +00001288 class Foo(unittest.TestCase):
1289 def test_1(self): pass
1290 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001291
Georg Brandl15c5ce92007-03-07 09:09:40 +00001292 loader = unittest.TestLoader()
1293 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001294
Georg Brandl15c5ce92007-03-07 09:09:40 +00001295 test_names = ['test_2', 'test_1']
1296 self.assertEqual(loader.getTestCaseNames(Foo), test_names)
Tim Petersea5962f2007-03-12 18:07:52 +00001297
Georg Brandl15c5ce92007-03-07 09:09:40 +00001298 # "The default value is the built-in cmp() function"
1299 def test_sortTestMethodsUsing__default_value(self):
1300 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001301 self.assertTrue(loader.sortTestMethodsUsing is cmp)
Tim Petersea5962f2007-03-12 18:07:52 +00001302
Georg Brandl15c5ce92007-03-07 09:09:40 +00001303 # "it can be set to None to disable the sort."
1304 #
1305 # XXX How is this different from reassigning cmp? Are the tests returned
1306 # in a random order or something? This behaviour should die
1307 def test_sortTestMethodsUsing__None(self):
1308 class Foo(unittest.TestCase):
1309 def test_1(self): pass
1310 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001311
Georg Brandl15c5ce92007-03-07 09:09:40 +00001312 loader = unittest.TestLoader()
1313 loader.sortTestMethodsUsing = None
Tim Petersea5962f2007-03-12 18:07:52 +00001314
Georg Brandl15c5ce92007-03-07 09:09:40 +00001315 test_names = ['test_2', 'test_1']
1316 self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))
Tim Petersea5962f2007-03-12 18:07:52 +00001317
Georg Brandl15c5ce92007-03-07 09:09:40 +00001318 ################################################################
1319 ### /Tests for TestLoader.sortTestMethodsUsing
Tim Petersea5962f2007-03-12 18:07:52 +00001320
Georg Brandl15c5ce92007-03-07 09:09:40 +00001321 ### Tests for TestLoader.suiteClass
1322 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001323
Georg Brandl15c5ce92007-03-07 09:09:40 +00001324 # "Callable object that constructs a test suite from a list of tests."
1325 def test_suiteClass__loadTestsFromTestCase(self):
1326 class Foo(unittest.TestCase):
1327 def test_1(self): pass
1328 def test_2(self): pass
1329 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001330
Georg Brandl15c5ce92007-03-07 09:09:40 +00001331 tests = [Foo('test_1'), Foo('test_2')]
1332
1333 loader = unittest.TestLoader()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001334 loader.suiteClass = list
Georg Brandl15c5ce92007-03-07 09:09:40 +00001335 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001336
Georg Brandl15c5ce92007-03-07 09:09:40 +00001337 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001338 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001339 def test_suiteClass__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001340 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001341 class Foo(unittest.TestCase):
1342 def test_1(self): pass
1343 def test_2(self): pass
1344 def foo_bar(self): pass
1345 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001346
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001347 tests = [[Foo('test_1'), Foo('test_2')]]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001348
1349 loader = unittest.TestLoader()
1350 loader.suiteClass = list
1351 self.assertEqual(loader.loadTestsFromModule(m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001352
Georg Brandl15c5ce92007-03-07 09:09:40 +00001353 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001354 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001355 def test_suiteClass__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001356 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001357 class Foo(unittest.TestCase):
1358 def test_1(self): pass
1359 def test_2(self): pass
1360 def foo_bar(self): pass
1361 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001362
Georg Brandl15c5ce92007-03-07 09:09:40 +00001363 tests = [Foo('test_1'), Foo('test_2')]
1364
1365 loader = unittest.TestLoader()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001366 loader.suiteClass = list
Georg Brandl15c5ce92007-03-07 09:09:40 +00001367 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001368
Georg Brandl15c5ce92007-03-07 09:09:40 +00001369 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001370 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001371 def test_suiteClass__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001372 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001373 class Foo(unittest.TestCase):
1374 def test_1(self): pass
1375 def test_2(self): pass
1376 def foo_bar(self): pass
1377 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001378
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001379 tests = [[Foo('test_1'), Foo('test_2')]]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001380
1381 loader = unittest.TestLoader()
1382 loader.suiteClass = list
1383 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001384
Georg Brandl15c5ce92007-03-07 09:09:40 +00001385 # "The default value is the TestSuite class"
1386 def test_suiteClass__default_value(self):
1387 loader = unittest.TestLoader()
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001388 self.assertTrue(loader.suiteClass is unittest.TestSuite)
Tim Petersea5962f2007-03-12 18:07:52 +00001389
Georg Brandl15c5ce92007-03-07 09:09:40 +00001390 ################################################################
1391 ### /Tests for TestLoader.suiteClass
1392
1393### Support code for Test_TestSuite
1394################################################################
1395
1396class Foo(unittest.TestCase):
1397 def test_1(self): pass
1398 def test_2(self): pass
1399 def test_3(self): pass
1400 def runTest(self): pass
1401
1402def _mk_TestSuite(*names):
1403 return unittest.TestSuite(Foo(n) for n in names)
Tim Petersea5962f2007-03-12 18:07:52 +00001404
Georg Brandl15c5ce92007-03-07 09:09:40 +00001405################################################################
1406### /Support code for Test_TestSuite
1407
1408class Test_TestSuite(TestCase, TestEquality):
1409
1410 ### Set up attributes needed by inherited tests
1411 ################################################################
1412
1413 # Used by TestEquality.test_eq
1414 eq_pairs = [(unittest.TestSuite(), unittest.TestSuite())
1415 ,(unittest.TestSuite(), unittest.TestSuite([]))
1416 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001417
1418 # Used by TestEquality.test_ne
Georg Brandl15c5ce92007-03-07 09:09:40 +00001419 ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1'))
1420 ,(unittest.TestSuite([]), _mk_TestSuite('test_1'))
1421 ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3'))
1422 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001423
Georg Brandl15c5ce92007-03-07 09:09:40 +00001424 ################################################################
1425 ### /Set up attributes needed by inherited tests
1426
1427 ### Tests for TestSuite.__init__
1428 ################################################################
1429
1430 # "class TestSuite([tests])"
1431 #
1432 # The tests iterable should be optional
1433 def test_init__tests_optional(self):
1434 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001435
Georg Brandl15c5ce92007-03-07 09:09:40 +00001436 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001437
Georg Brandl15c5ce92007-03-07 09:09:40 +00001438 # "class TestSuite([tests])"
1439 # ...
1440 # "If tests is given, it must be an iterable of individual test cases
1441 # or other test suites that will be used to build the suite initially"
1442 #
1443 # TestSuite should deal with empty tests iterables by allowing the
Tim Petersea5962f2007-03-12 18:07:52 +00001444 # creation of an empty suite
Georg Brandl15c5ce92007-03-07 09:09:40 +00001445 def test_init__empty_tests(self):
1446 suite = unittest.TestSuite([])
Tim Petersea5962f2007-03-12 18:07:52 +00001447
Georg Brandl15c5ce92007-03-07 09:09:40 +00001448 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001449
Georg Brandl15c5ce92007-03-07 09:09:40 +00001450 # "class TestSuite([tests])"
1451 # ...
1452 # "If tests is given, it must be an iterable of individual test cases
1453 # or other test suites that will be used to build the suite initially"
1454 #
Tim Petersea5962f2007-03-12 18:07:52 +00001455 # TestSuite should allow any iterable to provide tests
Georg Brandl15c5ce92007-03-07 09:09:40 +00001456 def test_init__tests_from_any_iterable(self):
1457 def tests():
1458 yield unittest.FunctionTestCase(lambda: None)
1459 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001460
Georg Brandl15c5ce92007-03-07 09:09:40 +00001461 suite_1 = unittest.TestSuite(tests())
1462 self.assertEqual(suite_1.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001463
Georg Brandl15c5ce92007-03-07 09:09:40 +00001464 suite_2 = unittest.TestSuite(suite_1)
1465 self.assertEqual(suite_2.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001466
Georg Brandl15c5ce92007-03-07 09:09:40 +00001467 suite_3 = unittest.TestSuite(set(suite_1))
1468 self.assertEqual(suite_3.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001469
Georg Brandl15c5ce92007-03-07 09:09:40 +00001470 # "class TestSuite([tests])"
1471 # ...
1472 # "If tests is given, it must be an iterable of individual test cases
1473 # or other test suites that will be used to build the suite initially"
1474 #
1475 # Does TestSuite() also allow other TestSuite() instances to be present
1476 # in the tests iterable?
1477 def test_init__TestSuite_instances_in_tests(self):
1478 def tests():
1479 ftc = unittest.FunctionTestCase(lambda: None)
1480 yield unittest.TestSuite([ftc])
1481 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001482
Georg Brandl15c5ce92007-03-07 09:09:40 +00001483 suite = unittest.TestSuite(tests())
1484 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001485
Georg Brandl15c5ce92007-03-07 09:09:40 +00001486 ################################################################
1487 ### /Tests for TestSuite.__init__
1488
1489 # Container types should support the iter protocol
1490 def test_iter(self):
1491 test1 = unittest.FunctionTestCase(lambda: None)
1492 test2 = unittest.FunctionTestCase(lambda: None)
1493 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001494
Georg Brandl15c5ce92007-03-07 09:09:40 +00001495 self.assertEqual(list(suite), [test1, test2])
Tim Petersea5962f2007-03-12 18:07:52 +00001496
Georg Brandl15c5ce92007-03-07 09:09:40 +00001497 # "Return the number of tests represented by the this test object.
1498 # ...this method is also implemented by the TestSuite class, which can
1499 # return larger [greater than 1] values"
1500 #
Tim Petersea5962f2007-03-12 18:07:52 +00001501 # Presumably an empty TestSuite returns 0?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001502 def test_countTestCases_zero_simple(self):
1503 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001504
Georg Brandl15c5ce92007-03-07 09:09:40 +00001505 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001506
Georg Brandl15c5ce92007-03-07 09:09:40 +00001507 # "Return the number of tests represented by the this test object.
1508 # ...this method is also implemented by the TestSuite class, which can
1509 # return larger [greater than 1] values"
1510 #
1511 # Presumably an empty TestSuite (even if it contains other empty
1512 # TestSuite instances) returns 0?
1513 def test_countTestCases_zero_nested(self):
1514 class Test1(unittest.TestCase):
1515 def test(self):
1516 pass
1517
1518 suite = unittest.TestSuite([unittest.TestSuite()])
Tim Petersea5962f2007-03-12 18:07:52 +00001519
Georg Brandl15c5ce92007-03-07 09:09:40 +00001520 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001521
Georg Brandl15c5ce92007-03-07 09:09:40 +00001522 # "Return the number of tests represented by the this test object.
1523 # ...this method is also implemented by the TestSuite class, which can
1524 # return larger [greater than 1] values"
1525 def test_countTestCases_simple(self):
1526 test1 = unittest.FunctionTestCase(lambda: None)
1527 test2 = unittest.FunctionTestCase(lambda: None)
1528 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001529
Georg Brandl15c5ce92007-03-07 09:09:40 +00001530 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001531
Georg Brandl15c5ce92007-03-07 09:09:40 +00001532 # "Return the number of tests represented by the this test object.
1533 # ...this method is also implemented by the TestSuite class, which can
1534 # return larger [greater than 1] values"
1535 #
1536 # Make sure this holds for nested TestSuite instances, too
1537 def test_countTestCases_nested(self):
1538 class Test1(unittest.TestCase):
1539 def test1(self): pass
1540 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001541
Georg Brandl15c5ce92007-03-07 09:09:40 +00001542 test2 = unittest.FunctionTestCase(lambda: None)
1543 test3 = unittest.FunctionTestCase(lambda: None)
1544 child = unittest.TestSuite((Test1('test2'), test2))
1545 parent = unittest.TestSuite((test3, child, Test1('test1')))
Tim Petersea5962f2007-03-12 18:07:52 +00001546
Georg Brandl15c5ce92007-03-07 09:09:40 +00001547 self.assertEqual(parent.countTestCases(), 4)
Tim Petersea5962f2007-03-12 18:07:52 +00001548
Georg Brandl15c5ce92007-03-07 09:09:40 +00001549 # "Run the tests associated with this suite, collecting the result into
1550 # the test result object passed as result."
1551 #
1552 # And if there are no tests? What then?
1553 def test_run__empty_suite(self):
1554 events = []
1555 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001556
Georg Brandl15c5ce92007-03-07 09:09:40 +00001557 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001558
Georg Brandl15c5ce92007-03-07 09:09:40 +00001559 suite.run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001560
Georg Brandl15c5ce92007-03-07 09:09:40 +00001561 self.assertEqual(events, [])
Tim Petersea5962f2007-03-12 18:07:52 +00001562
Georg Brandl15c5ce92007-03-07 09:09:40 +00001563 # "Note that unlike TestCase.run(), TestSuite.run() requires the
1564 # "result object to be passed in."
1565 def test_run__requires_result(self):
1566 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001567
Georg Brandl15c5ce92007-03-07 09:09:40 +00001568 try:
1569 suite.run()
1570 except TypeError:
1571 pass
1572 else:
1573 self.fail("Failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +00001574
Georg Brandl15c5ce92007-03-07 09:09:40 +00001575 # "Run the tests associated with this suite, collecting the result into
Tim Petersea5962f2007-03-12 18:07:52 +00001576 # the test result object passed as result."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001577 def test_run(self):
1578 events = []
1579 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001580
Georg Brandl15c5ce92007-03-07 09:09:40 +00001581 class LoggingCase(unittest.TestCase):
1582 def run(self, result):
1583 events.append('run %s' % self._testMethodName)
Tim Petersea5962f2007-03-12 18:07:52 +00001584
Georg Brandl15c5ce92007-03-07 09:09:40 +00001585 def test1(self): pass
1586 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001587
1588 tests = [LoggingCase('test1'), LoggingCase('test2')]
1589
Georg Brandl15c5ce92007-03-07 09:09:40 +00001590 unittest.TestSuite(tests).run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001591
Georg Brandl15c5ce92007-03-07 09:09:40 +00001592 self.assertEqual(events, ['run test1', 'run test2'])
Tim Petersea5962f2007-03-12 18:07:52 +00001593
1594 # "Add a TestCase ... to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001595 def test_addTest__TestCase(self):
1596 class Foo(unittest.TestCase):
1597 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001598
Georg Brandl15c5ce92007-03-07 09:09:40 +00001599 test = Foo('test')
1600 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001601
Georg Brandl15c5ce92007-03-07 09:09:40 +00001602 suite.addTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001603
Georg Brandl15c5ce92007-03-07 09:09:40 +00001604 self.assertEqual(suite.countTestCases(), 1)
1605 self.assertEqual(list(suite), [test])
Tim Petersea5962f2007-03-12 18:07:52 +00001606
1607 # "Add a ... TestSuite to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001608 def test_addTest__TestSuite(self):
1609 class Foo(unittest.TestCase):
1610 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001611
Georg Brandl15c5ce92007-03-07 09:09:40 +00001612 suite_2 = unittest.TestSuite([Foo('test')])
Tim Petersea5962f2007-03-12 18:07:52 +00001613
Georg Brandl15c5ce92007-03-07 09:09:40 +00001614 suite = unittest.TestSuite()
1615 suite.addTest(suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001616
Georg Brandl15c5ce92007-03-07 09:09:40 +00001617 self.assertEqual(suite.countTestCases(), 1)
1618 self.assertEqual(list(suite), [suite_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001619
Georg Brandl15c5ce92007-03-07 09:09:40 +00001620 # "Add all the tests from an iterable of TestCase and TestSuite
1621 # instances to this test suite."
Tim Petersea5962f2007-03-12 18:07:52 +00001622 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001623 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001624 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001625 def test_addTests(self):
1626 class Foo(unittest.TestCase):
1627 def test_1(self): pass
1628 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001629
Georg Brandl15c5ce92007-03-07 09:09:40 +00001630 test_1 = Foo('test_1')
1631 test_2 = Foo('test_2')
1632 inner_suite = unittest.TestSuite([test_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001633
Georg Brandl15c5ce92007-03-07 09:09:40 +00001634 def gen():
1635 yield test_1
1636 yield test_2
1637 yield inner_suite
Tim Petersea5962f2007-03-12 18:07:52 +00001638
Georg Brandl15c5ce92007-03-07 09:09:40 +00001639 suite_1 = unittest.TestSuite()
1640 suite_1.addTests(gen())
Tim Petersea5962f2007-03-12 18:07:52 +00001641
Georg Brandl15c5ce92007-03-07 09:09:40 +00001642 self.assertEqual(list(suite_1), list(gen()))
Tim Petersea5962f2007-03-12 18:07:52 +00001643
Georg Brandl15c5ce92007-03-07 09:09:40 +00001644 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001645 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001646 suite_2 = unittest.TestSuite()
1647 for t in gen():
1648 suite_2.addTest(t)
Tim Petersea5962f2007-03-12 18:07:52 +00001649
Georg Brandl15c5ce92007-03-07 09:09:40 +00001650 self.assertEqual(suite_1, suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001651
Georg Brandl15c5ce92007-03-07 09:09:40 +00001652 # "Add all the tests from an iterable of TestCase and TestSuite
1653 # instances to this test suite."
1654 #
Tim Petersea5962f2007-03-12 18:07:52 +00001655 # What happens if it doesn't get an iterable?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001656 def test_addTest__noniterable(self):
1657 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001658
Georg Brandl15c5ce92007-03-07 09:09:40 +00001659 try:
1660 suite.addTests(5)
1661 except TypeError:
1662 pass
1663 else:
1664 self.fail("Failed to raise TypeError")
Georg Brandld9e50262007-03-07 11:54:49 +00001665
1666 def test_addTest__noncallable(self):
1667 suite = unittest.TestSuite()
1668 self.assertRaises(TypeError, suite.addTest, 5)
1669
1670 def test_addTest__casesuiteclass(self):
1671 suite = unittest.TestSuite()
1672 self.assertRaises(TypeError, suite.addTest, Test_TestSuite)
1673 self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)
1674
1675 def test_addTests__string(self):
1676 suite = unittest.TestSuite()
1677 self.assertRaises(TypeError, suite.addTests, "foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001678
1679
Georg Brandl15c5ce92007-03-07 09:09:40 +00001680class Test_FunctionTestCase(TestCase):
Tim Petersea5962f2007-03-12 18:07:52 +00001681
Georg Brandl15c5ce92007-03-07 09:09:40 +00001682 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00001683 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001684 def test_countTestCases(self):
1685 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001686
Georg Brandl15c5ce92007-03-07 09:09:40 +00001687 self.assertEqual(test.countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00001688
Georg Brandl15c5ce92007-03-07 09:09:40 +00001689 # "When a setUp() method is defined, the test runner will run that method
1690 # prior to each test. Likewise, if a tearDown() method is defined, the
1691 # test runner will invoke that method after each test. In the example,
1692 # setUp() was used to create a fresh sequence for each test."
1693 #
1694 # Make sure the proper call order is maintained, even if setUp() raises
1695 # an exception.
1696 def test_run_call_order__error_in_setUp(self):
1697 events = []
1698 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001699
Georg Brandl15c5ce92007-03-07 09:09:40 +00001700 def setUp():
1701 events.append('setUp')
1702 raise RuntimeError('raised by setUp')
1703
1704 def test():
1705 events.append('test')
1706
1707 def tearDown():
1708 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001709
1710 expected = ['startTest', 'setUp', 'addError', 'stopTest']
Georg Brandl15c5ce92007-03-07 09:09:40 +00001711 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1712 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001713
Georg Brandl15c5ce92007-03-07 09:09:40 +00001714 # "When a setUp() method is defined, the test runner will run that method
1715 # prior to each test. Likewise, if a tearDown() method is defined, the
1716 # test runner will invoke that method after each test. In the example,
1717 # setUp() was used to create a fresh sequence for each test."
1718 #
1719 # Make sure the proper call order is maintained, even if the test raises
1720 # an error (as opposed to a failure).
1721 def test_run_call_order__error_in_test(self):
1722 events = []
1723 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001724
Georg Brandl15c5ce92007-03-07 09:09:40 +00001725 def setUp():
1726 events.append('setUp')
1727
1728 def test():
1729 events.append('test')
1730 raise RuntimeError('raised by test')
1731
1732 def tearDown():
1733 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001734
Georg Brandl15c5ce92007-03-07 09:09:40 +00001735 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
1736 'stopTest']
1737 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1738 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001739
Georg Brandl15c5ce92007-03-07 09:09:40 +00001740 # "When a setUp() method is defined, the test runner will run that method
1741 # prior to each test. Likewise, if a tearDown() method is defined, the
1742 # test runner will invoke that method after each test. In the example,
1743 # setUp() was used to create a fresh sequence for each test."
1744 #
1745 # Make sure the proper call order is maintained, even if the test signals
1746 # a failure (as opposed to an error).
1747 def test_run_call_order__failure_in_test(self):
1748 events = []
1749 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001750
Georg Brandl15c5ce92007-03-07 09:09:40 +00001751 def setUp():
1752 events.append('setUp')
1753
1754 def test():
1755 events.append('test')
1756 self.fail('raised by test')
1757
1758 def tearDown():
1759 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001760
Georg Brandl15c5ce92007-03-07 09:09:40 +00001761 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
1762 'stopTest']
1763 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1764 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001765
Georg Brandl15c5ce92007-03-07 09:09:40 +00001766 # "When a setUp() method is defined, the test runner will run that method
1767 # prior to each test. Likewise, if a tearDown() method is defined, the
1768 # test runner will invoke that method after each test. In the example,
1769 # setUp() was used to create a fresh sequence for each test."
1770 #
1771 # Make sure the proper call order is maintained, even if tearDown() raises
1772 # an exception.
1773 def test_run_call_order__error_in_tearDown(self):
1774 events = []
1775 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001776
Georg Brandl15c5ce92007-03-07 09:09:40 +00001777 def setUp():
1778 events.append('setUp')
1779
1780 def test():
1781 events.append('test')
1782
1783 def tearDown():
1784 events.append('tearDown')
1785 raise RuntimeError('raised by tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001786
Georg Brandl15c5ce92007-03-07 09:09:40 +00001787 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
1788 'stopTest']
1789 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1790 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001791
Georg Brandl15c5ce92007-03-07 09:09:40 +00001792 # "Return a string identifying the specific test case."
1793 #
1794 # Because of the vague nature of the docs, I'm not going to lock this
1795 # test down too much. Really all that can be asserted is that the id()
1796 # will be a string (either 8-byte or unicode -- again, because the docs
1797 # just say "string")
1798 def test_id(self):
1799 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001800
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001801 self.assertIsInstance(test.id(), basestring)
Tim Petersea5962f2007-03-12 18:07:52 +00001802
Georg Brandl15c5ce92007-03-07 09:09:40 +00001803 # "Returns a one-line description of the test, or None if no description
1804 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001805 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001806 def test_shortDescription__no_docstring(self):
1807 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001808
Georg Brandl15c5ce92007-03-07 09:09:40 +00001809 self.assertEqual(test.shortDescription(), None)
Tim Petersea5962f2007-03-12 18:07:52 +00001810
Georg Brandl15c5ce92007-03-07 09:09:40 +00001811 # "Returns a one-line description of the test, or None if no description
1812 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001813 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001814 def test_shortDescription__singleline_docstring(self):
1815 desc = "this tests foo"
1816 test = unittest.FunctionTestCase(lambda: None, description=desc)
Tim Petersea5962f2007-03-12 18:07:52 +00001817
Georg Brandl15c5ce92007-03-07 09:09:40 +00001818 self.assertEqual(test.shortDescription(), "this tests foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001819
Georg Brandl15c5ce92007-03-07 09:09:40 +00001820class Test_TestResult(TestCase):
1821 # Note: there are not separate tests for TestResult.wasSuccessful(),
1822 # TestResult.errors, TestResult.failures, TestResult.testsRun or
1823 # TestResult.shouldStop because these only have meaning in terms of
1824 # other TestResult methods.
1825 #
1826 # Accordingly, tests for the aforenamed attributes are incorporated
1827 # in with the tests for the defining methods.
1828 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001829
Georg Brandl15c5ce92007-03-07 09:09:40 +00001830 def test_init(self):
1831 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001832
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001833 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001834 self.assertEqual(len(result.errors), 0)
1835 self.assertEqual(len(result.failures), 0)
1836 self.assertEqual(result.testsRun, 0)
1837 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001838
Georg Brandl15c5ce92007-03-07 09:09:40 +00001839 # "This method can be called to signal that the set of tests being
1840 # run should be aborted by setting the TestResult's shouldStop
Tim Petersea5962f2007-03-12 18:07:52 +00001841 # attribute to True."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001842 def test_stop(self):
1843 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001844
Georg Brandl15c5ce92007-03-07 09:09:40 +00001845 result.stop()
Tim Petersea5962f2007-03-12 18:07:52 +00001846
Georg Brandl15c5ce92007-03-07 09:09:40 +00001847 self.assertEqual(result.shouldStop, True)
Tim Petersea5962f2007-03-12 18:07:52 +00001848
Georg Brandl15c5ce92007-03-07 09:09:40 +00001849 # "Called when the test case test is about to be run. The default
1850 # implementation simply increments the instance's testsRun counter."
1851 def test_startTest(self):
1852 class Foo(unittest.TestCase):
1853 def test_1(self):
1854 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001855
Georg Brandl15c5ce92007-03-07 09:09:40 +00001856 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001857
Georg Brandl15c5ce92007-03-07 09:09:40 +00001858 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001859
Georg Brandl15c5ce92007-03-07 09:09:40 +00001860 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001861
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001862 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001863 self.assertEqual(len(result.errors), 0)
1864 self.assertEqual(len(result.failures), 0)
1865 self.assertEqual(result.testsRun, 1)
1866 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001867
Georg Brandl15c5ce92007-03-07 09:09:40 +00001868 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001869
Georg Brandl15c5ce92007-03-07 09:09:40 +00001870 # "Called after the test case test has been executed, regardless of
1871 # the outcome. The default implementation does nothing."
1872 def test_stopTest(self):
1873 class Foo(unittest.TestCase):
1874 def test_1(self):
1875 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001876
Georg Brandl15c5ce92007-03-07 09:09:40 +00001877 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001878
Georg Brandl15c5ce92007-03-07 09:09:40 +00001879 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001880
Georg Brandl15c5ce92007-03-07 09:09:40 +00001881 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001882
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001883 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001884 self.assertEqual(len(result.errors), 0)
1885 self.assertEqual(len(result.failures), 0)
1886 self.assertEqual(result.testsRun, 1)
1887 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001888
Georg Brandl15c5ce92007-03-07 09:09:40 +00001889 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001890
Georg Brandl15c5ce92007-03-07 09:09:40 +00001891 # Same tests as above; make sure nothing has changed
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001892 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001893 self.assertEqual(len(result.errors), 0)
1894 self.assertEqual(len(result.failures), 0)
1895 self.assertEqual(result.testsRun, 1)
1896 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001897
Michael Foord07ef4872009-05-02 22:43:34 +00001898 # "Called before and after tests are run. The default implementation does nothing."
1899 def test_startTestRun_stopTestRun(self):
1900 result = unittest.TestResult()
1901 result.startTestRun()
1902 result.stopTestRun()
1903
Georg Brandl15c5ce92007-03-07 09:09:40 +00001904 # "addSuccess(test)"
1905 # ...
1906 # "Called when the test case test succeeds"
1907 # ...
1908 # "wasSuccessful() - Returns True if all tests run so far have passed,
1909 # otherwise returns False"
1910 # ...
1911 # "testsRun - The total number of tests run so far."
1912 # ...
1913 # "errors - A list containing 2-tuples of TestCase instances and
1914 # formatted tracebacks. Each tuple represents a test which raised an
1915 # unexpected exception. Contains formatted
1916 # tracebacks instead of sys.exc_info() results."
1917 # ...
1918 # "failures - A list containing 2-tuples of TestCase instances and
1919 # formatted tracebacks. Each tuple represents a test where a failure was
1920 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1921 # methods. Contains formatted tracebacks instead
1922 # of sys.exc_info() results."
1923 def test_addSuccess(self):
1924 class Foo(unittest.TestCase):
1925 def test_1(self):
1926 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001927
Georg Brandl15c5ce92007-03-07 09:09:40 +00001928 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001929
Georg Brandl15c5ce92007-03-07 09:09:40 +00001930 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001931
Georg Brandl15c5ce92007-03-07 09:09:40 +00001932 result.startTest(test)
1933 result.addSuccess(test)
1934 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001935
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001936 self.assertTrue(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001937 self.assertEqual(len(result.errors), 0)
1938 self.assertEqual(len(result.failures), 0)
1939 self.assertEqual(result.testsRun, 1)
1940 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001941
Georg Brandl15c5ce92007-03-07 09:09:40 +00001942 # "addFailure(test, err)"
1943 # ...
1944 # "Called when the test case test signals a failure. err is a tuple of
1945 # the form returned by sys.exc_info(): (type, value, traceback)"
1946 # ...
1947 # "wasSuccessful() - Returns True if all tests run so far have passed,
1948 # otherwise returns False"
1949 # ...
1950 # "testsRun - The total number of tests run so far."
1951 # ...
1952 # "errors - A list containing 2-tuples of TestCase instances and
1953 # formatted tracebacks. Each tuple represents a test which raised an
1954 # unexpected exception. Contains formatted
1955 # tracebacks instead of sys.exc_info() results."
1956 # ...
1957 # "failures - A list containing 2-tuples of TestCase instances and
1958 # formatted tracebacks. Each tuple represents a test where a failure was
1959 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1960 # methods. Contains formatted tracebacks instead
1961 # of sys.exc_info() results."
1962 def test_addFailure(self):
Georg Brandl15c5ce92007-03-07 09:09:40 +00001963 class Foo(unittest.TestCase):
1964 def test_1(self):
1965 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001966
Georg Brandl15c5ce92007-03-07 09:09:40 +00001967 test = Foo('test_1')
1968 try:
1969 test.fail("foo")
1970 except:
1971 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00001972
Georg Brandl15c5ce92007-03-07 09:09:40 +00001973 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001974
Georg Brandl15c5ce92007-03-07 09:09:40 +00001975 result.startTest(test)
1976 result.addFailure(test, exc_info_tuple)
1977 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001978
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001979 self.assertFalse(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001980 self.assertEqual(len(result.errors), 0)
1981 self.assertEqual(len(result.failures), 1)
1982 self.assertEqual(result.testsRun, 1)
1983 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001984
Georg Brandl15c5ce92007-03-07 09:09:40 +00001985 test_case, formatted_exc = result.failures[0]
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001986 self.assertTrue(test_case is test)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001987 self.assertIsInstance(formatted_exc, str)
Tim Petersea5962f2007-03-12 18:07:52 +00001988
Georg Brandl15c5ce92007-03-07 09:09:40 +00001989 # "addError(test, err)"
1990 # ...
1991 # "Called when the test case test raises an unexpected exception err
1992 # is a tuple of the form returned by sys.exc_info():
1993 # (type, value, traceback)"
1994 # ...
1995 # "wasSuccessful() - Returns True if all tests run so far have passed,
1996 # otherwise returns False"
1997 # ...
1998 # "testsRun - The total number of tests run so far."
1999 # ...
2000 # "errors - A list containing 2-tuples of TestCase instances and
2001 # formatted tracebacks. Each tuple represents a test which raised an
2002 # unexpected exception. Contains formatted
2003 # tracebacks instead of sys.exc_info() results."
2004 # ...
2005 # "failures - A list containing 2-tuples of TestCase instances and
2006 # formatted tracebacks. Each tuple represents a test where a failure was
2007 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
2008 # methods. Contains formatted tracebacks instead
2009 # of sys.exc_info() results."
2010 def test_addError(self):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002011 class Foo(unittest.TestCase):
2012 def test_1(self):
2013 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002014
Georg Brandl15c5ce92007-03-07 09:09:40 +00002015 test = Foo('test_1')
2016 try:
2017 raise TypeError()
2018 except:
2019 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00002020
Georg Brandl15c5ce92007-03-07 09:09:40 +00002021 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00002022
Georg Brandl15c5ce92007-03-07 09:09:40 +00002023 result.startTest(test)
2024 result.addError(test, exc_info_tuple)
2025 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00002026
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002027 self.assertFalse(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00002028 self.assertEqual(len(result.errors), 1)
2029 self.assertEqual(len(result.failures), 0)
2030 self.assertEqual(result.testsRun, 1)
2031 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00002032
Georg Brandl15c5ce92007-03-07 09:09:40 +00002033 test_case, formatted_exc = result.errors[0]
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002034 self.assertTrue(test_case is test)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002035 self.assertIsInstance(formatted_exc, str)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002036
Michael Foorddb43b5a2010-02-10 14:25:12 +00002037 def testGetDescriptionWithoutDocstring(self):
Michael Foord1c3abf42010-02-10 15:50:58 +00002038 result = unittest.TextTestResult(None, True, 1)
Michael Foorddb43b5a2010-02-10 14:25:12 +00002039 self.assertEqual(
2040 result.getDescription(self),
2041 'testGetDescriptionWithoutDocstring (' + __name__ +
2042 '.Test_TestResult)')
2043
R. David Murrayf28fd242010-02-23 00:24:49 +00002044 @unittest.skipIf(sys.flags.optimize >= 2,
2045 "Docstrings are omitted with -O2 and above")
Michael Foorddb43b5a2010-02-10 14:25:12 +00002046 def testGetDescriptionWithOneLineDocstring(self):
2047 """Tests getDescription() for a method with a docstring."""
Michael Foord1c3abf42010-02-10 15:50:58 +00002048 result = unittest.TextTestResult(None, True, 1)
Michael Foorddb43b5a2010-02-10 14:25:12 +00002049 self.assertEqual(
2050 result.getDescription(self),
2051 ('testGetDescriptionWithOneLineDocstring '
2052 '(' + __name__ + '.Test_TestResult)\n'
2053 'Tests getDescription() for a method with a docstring.'))
2054
R. David Murrayf28fd242010-02-23 00:24:49 +00002055 @unittest.skipIf(sys.flags.optimize >= 2,
2056 "Docstrings are omitted with -O2 and above")
Michael Foorddb43b5a2010-02-10 14:25:12 +00002057 def testGetDescriptionWithMultiLineDocstring(self):
2058 """Tests getDescription() for a method with a longer docstring.
2059 The second line of the docstring.
2060 """
Michael Foord1c3abf42010-02-10 15:50:58 +00002061 result = unittest.TextTestResult(None, True, 1)
Michael Foorddb43b5a2010-02-10 14:25:12 +00002062 self.assertEqual(
2063 result.getDescription(self),
2064 ('testGetDescriptionWithMultiLineDocstring '
2065 '(' + __name__ + '.Test_TestResult)\n'
2066 'Tests getDescription() for a method with a longer '
2067 'docstring.'))
2068
Michael Foordae3db0a2010-02-22 23:28:32 +00002069classDict = dict(unittest.TestResult.__dict__)
2070for m in 'addSkip', 'addExpectedFailure', 'addUnexpectedSuccess':
2071 del classDict[m]
2072OldResult = type('OldResult', (object,), classDict)
2073
2074class Test_OldTestResult(unittest.TestCase):
2075
2076 def assertOldResultWarning(self, test, failures):
2077 with warnings.catch_warnings(record=True) as log:
2078 result = OldResult()
2079 test.run(result)
2080 self.assertEqual(len(result.failures), failures)
2081 warning, = log
2082 self.assertIs(warning.category, RuntimeWarning)
2083
2084 def testOldTestResult(self):
2085 class Test(unittest.TestCase):
2086 def testSkip(self):
2087 self.skipTest('foobar')
2088 @unittest.expectedFailure
2089 def testExpectedFail(self):
2090 raise TypeError
2091 @unittest.expectedFailure
2092 def testUnexpectedSuccess(self):
2093 pass
2094
2095 for test_name, should_pass in (('testSkip', True),
2096 ('testExpectedFail', True),
2097 ('testUnexpectedSuccess', False)):
2098 test = Test(test_name)
2099 self.assertOldResultWarning(test, int(not should_pass))
2100
2101 def testOldTestTesultSetup(self):
2102 class Test(unittest.TestCase):
2103 def setUp(self):
2104 self.skipTest('no reason')
2105 def testFoo(self):
2106 pass
2107 self.assertOldResultWarning(Test('testFoo'), 0)
2108
2109 def testOldTestResultClass(self):
2110 @unittest.skip('no reason')
2111 class Test(unittest.TestCase):
2112 def testFoo(self):
2113 pass
2114 self.assertOldResultWarning(Test('testFoo'), 0)
2115
Michael Foorddb43b5a2010-02-10 14:25:12 +00002116
Georg Brandl15c5ce92007-03-07 09:09:40 +00002117### Support code for Test_TestCase
2118################################################################
2119
2120class Foo(unittest.TestCase):
2121 def runTest(self): pass
2122 def test1(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002123
Georg Brandl15c5ce92007-03-07 09:09:40 +00002124class Bar(Foo):
2125 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002126
Michael Foord07ef4872009-05-02 22:43:34 +00002127class LoggingTestCase(unittest.TestCase):
2128 """A test case which logs its calls."""
2129
2130 def __init__(self, events):
2131 super(LoggingTestCase, self).__init__('test')
2132 self.events = events
2133
2134 def setUp(self):
2135 self.events.append('setUp')
2136
2137 def test(self):
2138 self.events.append('test')
2139
2140 def tearDown(self):
2141 self.events.append('tearDown')
2142
2143class ResultWithNoStartTestRunStopTestRun(object):
2144 """An object honouring TestResult before startTestRun/stopTestRun."""
2145
2146 def __init__(self):
2147 self.failures = []
2148 self.errors = []
2149 self.testsRun = 0
2150 self.skipped = []
2151 self.expectedFailures = []
2152 self.unexpectedSuccesses = []
2153 self.shouldStop = False
2154
2155 def startTest(self, test):
2156 pass
2157
2158 def stopTest(self, test):
2159 pass
2160
2161 def addError(self, test):
2162 pass
2163
2164 def addFailure(self, test):
2165 pass
2166
2167 def addSuccess(self, test):
2168 pass
2169
2170 def wasSuccessful(self):
2171 return True
2172
2173
Georg Brandl15c5ce92007-03-07 09:09:40 +00002174################################################################
2175### /Support code for Test_TestCase
2176
2177class Test_TestCase(TestCase, TestEquality, TestHashing):
2178
2179 ### Set up attributes used by inherited tests
2180 ################################################################
2181
2182 # Used by TestHashing.test_hash and TestEquality.test_eq
2183 eq_pairs = [(Foo('test1'), Foo('test1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002184
Georg Brandl15c5ce92007-03-07 09:09:40 +00002185 # Used by TestEquality.test_ne
2186 ne_pairs = [(Foo('test1'), Foo('runTest'))
2187 ,(Foo('test1'), Bar('test1'))
2188 ,(Foo('test1'), Bar('test2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002189
Georg Brandl15c5ce92007-03-07 09:09:40 +00002190 ################################################################
2191 ### /Set up attributes used by inherited tests
Tim Petersea5962f2007-03-12 18:07:52 +00002192
Georg Brandl15c5ce92007-03-07 09:09:40 +00002193
2194 # "class TestCase([methodName])"
2195 # ...
2196 # "Each instance of TestCase will run a single test method: the
2197 # method named methodName."
2198 # ...
2199 # "methodName defaults to "runTest"."
2200 #
2201 # Make sure it really is optional, and that it defaults to the proper
2202 # thing.
2203 def test_init__no_test_name(self):
2204 class Test(unittest.TestCase):
2205 def runTest(self): raise MyException()
2206 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002207
Georg Brandl15c5ce92007-03-07 09:09:40 +00002208 self.assertEqual(Test().id()[-13:], '.Test.runTest')
Tim Petersea5962f2007-03-12 18:07:52 +00002209
Georg Brandl15c5ce92007-03-07 09:09:40 +00002210 # "class TestCase([methodName])"
2211 # ...
2212 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002213 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002214 def test_init__test_name__valid(self):
2215 class Test(unittest.TestCase):
2216 def runTest(self): raise MyException()
2217 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002218
Georg Brandl15c5ce92007-03-07 09:09:40 +00002219 self.assertEqual(Test('test').id()[-10:], '.Test.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002220
Georg Brandl15c5ce92007-03-07 09:09:40 +00002221 # "class TestCase([methodName])"
2222 # ...
2223 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002224 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002225 def test_init__test_name__invalid(self):
2226 class Test(unittest.TestCase):
2227 def runTest(self): raise MyException()
2228 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002229
Georg Brandl15c5ce92007-03-07 09:09:40 +00002230 try:
2231 Test('testfoo')
2232 except ValueError:
2233 pass
2234 else:
2235 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +00002236
Georg Brandl15c5ce92007-03-07 09:09:40 +00002237 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00002238 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00002239 def test_countTestCases(self):
2240 class Foo(unittest.TestCase):
2241 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002242
Georg Brandl15c5ce92007-03-07 09:09:40 +00002243 self.assertEqual(Foo('test').countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00002244
Georg Brandl15c5ce92007-03-07 09:09:40 +00002245 # "Return the default type of test result object to be used to run this
2246 # test. For TestCase instances, this will always be
2247 # unittest.TestResult; subclasses of TestCase should
2248 # override this as necessary."
2249 def test_defaultTestResult(self):
2250 class Foo(unittest.TestCase):
2251 def runTest(self):
2252 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002253
Georg Brandl15c5ce92007-03-07 09:09:40 +00002254 result = Foo().defaultTestResult()
2255 self.assertEqual(type(result), unittest.TestResult)
2256
2257 # "When a setUp() method is defined, the test runner will run that method
2258 # prior to each test. Likewise, if a tearDown() method is defined, the
2259 # test runner will invoke that method after each test. In the example,
2260 # setUp() was used to create a fresh sequence for each test."
2261 #
2262 # Make sure the proper call order is maintained, even if setUp() raises
2263 # an exception.
2264 def test_run_call_order__error_in_setUp(self):
2265 events = []
2266 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002267
Michael Foord07ef4872009-05-02 22:43:34 +00002268 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002269 def setUp(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002270 super(Foo, self).setUp()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002271 raise RuntimeError('raised by Foo.setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002272
Michael Foord07ef4872009-05-02 22:43:34 +00002273 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002274 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2275 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002276
Michael Foord07ef4872009-05-02 22:43:34 +00002277 # "With a temporary result stopTestRun is called when setUp errors.
2278 def test_run_call_order__error_in_setUp_default_result(self):
2279 events = []
2280
2281 class Foo(LoggingTestCase):
2282 def defaultTestResult(self):
2283 return LoggingResult(self.events)
2284
2285 def setUp(self):
2286 super(Foo, self).setUp()
2287 raise RuntimeError('raised by Foo.setUp')
2288
2289 Foo(events).run()
2290 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2291 'stopTest', 'stopTestRun']
2292 self.assertEqual(events, expected)
2293
Georg Brandl15c5ce92007-03-07 09:09:40 +00002294 # "When a setUp() method is defined, the test runner will run that method
2295 # prior to each test. Likewise, if a tearDown() method is defined, the
2296 # test runner will invoke that method after each test. In the example,
2297 # setUp() was used to create a fresh sequence for each test."
2298 #
2299 # Make sure the proper call order is maintained, even if the test raises
2300 # an error (as opposed to a failure).
2301 def test_run_call_order__error_in_test(self):
2302 events = []
2303 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002304
Michael Foord07ef4872009-05-02 22:43:34 +00002305 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002306 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002307 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002308 raise RuntimeError('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002309
Georg Brandl15c5ce92007-03-07 09:09:40 +00002310 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2311 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002312 Foo(events).run(result)
2313 self.assertEqual(events, expected)
2314
2315 # "With a default result, an error in the test still results in stopTestRun
2316 # being called."
2317 def test_run_call_order__error_in_test_default_result(self):
2318 events = []
2319
2320 class Foo(LoggingTestCase):
2321 def defaultTestResult(self):
2322 return LoggingResult(self.events)
2323
2324 def test(self):
2325 super(Foo, self).test()
2326 raise RuntimeError('raised by Foo.test')
2327
2328 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2329 'tearDown', 'stopTest', 'stopTestRun']
2330 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002331 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002332
Georg Brandl15c5ce92007-03-07 09:09:40 +00002333 # "When a setUp() method is defined, the test runner will run that method
2334 # prior to each test. Likewise, if a tearDown() method is defined, the
2335 # test runner will invoke that method after each test. In the example,
2336 # setUp() was used to create a fresh sequence for each test."
2337 #
2338 # Make sure the proper call order is maintained, even if the test signals
2339 # a failure (as opposed to an error).
2340 def test_run_call_order__failure_in_test(self):
2341 events = []
2342 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002343
Michael Foord07ef4872009-05-02 22:43:34 +00002344 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002345 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002346 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002347 self.fail('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002348
Georg Brandl15c5ce92007-03-07 09:09:40 +00002349 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2350 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002351 Foo(events).run(result)
2352 self.assertEqual(events, expected)
2353
2354 # "When a test fails with a default result stopTestRun is still called."
2355 def test_run_call_order__failure_in_test_default_result(self):
2356
2357 class Foo(LoggingTestCase):
2358 def defaultTestResult(self):
2359 return LoggingResult(self.events)
2360 def test(self):
2361 super(Foo, self).test()
2362 self.fail('raised by Foo.test')
2363
2364 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2365 'tearDown', 'stopTest', 'stopTestRun']
2366 events = []
2367 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002368 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002369
Georg Brandl15c5ce92007-03-07 09:09:40 +00002370 # "When a setUp() method is defined, the test runner will run that method
2371 # prior to each test. Likewise, if a tearDown() method is defined, the
2372 # test runner will invoke that method after each test. In the example,
2373 # setUp() was used to create a fresh sequence for each test."
2374 #
2375 # Make sure the proper call order is maintained, even if tearDown() raises
2376 # an exception.
2377 def test_run_call_order__error_in_tearDown(self):
2378 events = []
2379 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002380
Michael Foord07ef4872009-05-02 22:43:34 +00002381 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002382 def tearDown(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002383 super(Foo, self).tearDown()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002384 raise RuntimeError('raised by Foo.tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002385
Michael Foord07ef4872009-05-02 22:43:34 +00002386 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002387 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2388 'stopTest']
2389 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002390
Michael Foord07ef4872009-05-02 22:43:34 +00002391 # "When tearDown errors with a default result stopTestRun is still called."
2392 def test_run_call_order__error_in_tearDown_default_result(self):
2393
2394 class Foo(LoggingTestCase):
2395 def defaultTestResult(self):
2396 return LoggingResult(self.events)
2397 def tearDown(self):
2398 super(Foo, self).tearDown()
2399 raise RuntimeError('raised by Foo.tearDown')
2400
2401 events = []
2402 Foo(events).run()
2403 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2404 'addError', 'stopTest', 'stopTestRun']
2405 self.assertEqual(events, expected)
2406
2407 # "TestCase.run() still works when the defaultTestResult is a TestResult
2408 # that does not support startTestRun and stopTestRun.
2409 def test_run_call_order_default_result(self):
2410
2411 class Foo(unittest.TestCase):
2412 def defaultTestResult(self):
2413 return ResultWithNoStartTestRunStopTestRun()
2414 def test(self):
2415 pass
2416
2417 Foo('test').run()
2418
Georg Brandl15c5ce92007-03-07 09:09:40 +00002419 # "This class attribute gives the exception raised by the test() method.
2420 # If a test framework needs to use a specialized exception, possibly to
2421 # carry additional information, it must subclass this exception in
2422 # order to ``play fair'' with the framework. The initial value of this
2423 # attribute is AssertionError"
2424 def test_failureException__default(self):
2425 class Foo(unittest.TestCase):
2426 def test(self):
2427 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002428
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002429 self.assertTrue(Foo('test').failureException is AssertionError)
Tim Petersea5962f2007-03-12 18:07:52 +00002430
Georg Brandl15c5ce92007-03-07 09:09:40 +00002431 # "This class attribute gives the exception raised by the test() method.
2432 # If a test framework needs to use a specialized exception, possibly to
2433 # carry additional information, it must subclass this exception in
2434 # order to ``play fair'' with the framework."
2435 #
2436 # Make sure TestCase.run() respects the designated failureException
2437 def test_failureException__subclassing__explicit_raise(self):
2438 events = []
2439 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002440
Georg Brandl15c5ce92007-03-07 09:09:40 +00002441 class Foo(unittest.TestCase):
2442 def test(self):
2443 raise RuntimeError()
Tim Petersea5962f2007-03-12 18:07:52 +00002444
Georg Brandl15c5ce92007-03-07 09:09:40 +00002445 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002446
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002447 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002448
2449
Georg Brandl15c5ce92007-03-07 09:09:40 +00002450 Foo('test').run(result)
2451 expected = ['startTest', 'addFailure', 'stopTest']
2452 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002453
Georg Brandl15c5ce92007-03-07 09:09:40 +00002454 # "This class attribute gives the exception raised by the test() method.
2455 # If a test framework needs to use a specialized exception, possibly to
2456 # carry additional information, it must subclass this exception in
2457 # order to ``play fair'' with the framework."
2458 #
2459 # Make sure TestCase.run() respects the designated failureException
2460 def test_failureException__subclassing__implicit_raise(self):
2461 events = []
2462 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002463
Georg Brandl15c5ce92007-03-07 09:09:40 +00002464 class Foo(unittest.TestCase):
2465 def test(self):
2466 self.fail("foo")
Tim Petersea5962f2007-03-12 18:07:52 +00002467
Georg Brandl15c5ce92007-03-07 09:09:40 +00002468 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002469
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002470 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002471
2472
Georg Brandl15c5ce92007-03-07 09:09:40 +00002473 Foo('test').run(result)
2474 expected = ['startTest', 'addFailure', 'stopTest']
2475 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002476
2477 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002478 def test_setUp(self):
2479 class Foo(unittest.TestCase):
2480 def runTest(self):
2481 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002482
Georg Brandl15c5ce92007-03-07 09:09:40 +00002483 # ... and nothing should happen
2484 Foo().setUp()
Tim Petersea5962f2007-03-12 18:07:52 +00002485
2486 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002487 def test_tearDown(self):
2488 class Foo(unittest.TestCase):
2489 def runTest(self):
2490 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002491
Georg Brandl15c5ce92007-03-07 09:09:40 +00002492 # ... and nothing should happen
2493 Foo().tearDown()
Tim Petersea5962f2007-03-12 18:07:52 +00002494
Georg Brandl15c5ce92007-03-07 09:09:40 +00002495 # "Return a string identifying the specific test case."
2496 #
2497 # Because of the vague nature of the docs, I'm not going to lock this
2498 # test down too much. Really all that can be asserted is that the id()
2499 # will be a string (either 8-byte or unicode -- again, because the docs
2500 # just say "string")
2501 def test_id(self):
2502 class Foo(unittest.TestCase):
2503 def runTest(self):
2504 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002505
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002506 self.assertIsInstance(Foo().id(), basestring)
Tim Petersea5962f2007-03-12 18:07:52 +00002507
Georg Brandl15c5ce92007-03-07 09:09:40 +00002508 # "If result is omitted or None, a temporary result object is created
Michael Foord07ef4872009-05-02 22:43:34 +00002509 # and used, but is not made available to the caller. As TestCase owns the
2510 # temporary result startTestRun and stopTestRun are called.
2511
Georg Brandl15c5ce92007-03-07 09:09:40 +00002512 def test_run__uses_defaultTestResult(self):
2513 events = []
Tim Petersea5962f2007-03-12 18:07:52 +00002514
Georg Brandl15c5ce92007-03-07 09:09:40 +00002515 class Foo(unittest.TestCase):
2516 def test(self):
2517 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002518
Georg Brandl15c5ce92007-03-07 09:09:40 +00002519 def defaultTestResult(self):
2520 return LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002521
2522 # Make run() find a result object on its own
Georg Brandl15c5ce92007-03-07 09:09:40 +00002523 Foo('test').run()
Tim Petersea5962f2007-03-12 18:07:52 +00002524
Michael Foord07ef4872009-05-02 22:43:34 +00002525 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2526 'stopTest', 'stopTestRun']
Georg Brandl15c5ce92007-03-07 09:09:40 +00002527 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002528
Gregory P. Smith28399852009-03-31 16:54:10 +00002529 def testShortDescriptionWithoutDocstring(self):
Michael Foorddb43b5a2010-02-10 14:25:12 +00002530 self.assertIsNone(self.shortDescription())
Gregory P. Smith28399852009-03-31 16:54:10 +00002531
R. David Murrayf28fd242010-02-23 00:24:49 +00002532 @unittest.skipIf(sys.flags.optimize >= 2,
2533 "Docstrings are omitted with -O2 and above")
Gregory P. Smith28399852009-03-31 16:54:10 +00002534 def testShortDescriptionWithOneLineDocstring(self):
2535 """Tests shortDescription() for a method with a docstring."""
2536 self.assertEqual(
2537 self.shortDescription(),
Michael Foorddb43b5a2010-02-10 14:25:12 +00002538 'Tests shortDescription() for a method with a docstring.')
Gregory P. Smith28399852009-03-31 16:54:10 +00002539
R. David Murrayf28fd242010-02-23 00:24:49 +00002540 @unittest.skipIf(sys.flags.optimize >= 2,
2541 "Docstrings are omitted with -O2 and above")
Gregory P. Smith28399852009-03-31 16:54:10 +00002542 def testShortDescriptionWithMultiLineDocstring(self):
2543 """Tests shortDescription() for a method with a longer docstring.
2544
2545 This method ensures that only the first line of a docstring is
2546 returned used in the short description, no matter how long the
2547 whole thing is.
2548 """
2549 self.assertEqual(
2550 self.shortDescription(),
Gregory P. Smith28399852009-03-31 16:54:10 +00002551 'Tests shortDescription() for a method with a longer '
Michael Foorddb43b5a2010-02-10 14:25:12 +00002552 'docstring.')
Gregory P. Smith28399852009-03-31 16:54:10 +00002553
Gregory P. Smith28399852009-03-31 16:54:10 +00002554 def testAddTypeEqualityFunc(self):
2555 class SadSnake(object):
2556 """Dummy class for test_addTypeEqualityFunc."""
2557 s1, s2 = SadSnake(), SadSnake()
2558 self.assertFalse(s1 == s2)
2559 def AllSnakesCreatedEqual(a, b, msg=None):
2560 return type(a) == type(b) == SadSnake
2561 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2562 self.assertEqual(s1, s2)
2563 # No this doesn't clean up and remove the SadSnake equality func
2564 # from this TestCase instance but since its a local nothing else
2565 # will ever notice that.
2566
Michael Foordf2dfef12009-04-05 19:19:28 +00002567 def testAssertIs(self):
2568 thing = object()
2569 self.assertIs(thing, thing)
2570 self.assertRaises(self.failureException, self.assertIs, thing, object())
2571
2572 def testAssertIsNot(self):
2573 thing = object()
2574 self.assertIsNot(thing, object())
2575 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2576
Georg Brandlf895cf52009-10-01 20:59:31 +00002577 def testAssertIsInstance(self):
2578 thing = []
2579 self.assertIsInstance(thing, list)
2580 self.assertRaises(self.failureException, self.assertIsInstance,
2581 thing, dict)
2582
2583 def testAssertNotIsInstance(self):
2584 thing = []
2585 self.assertNotIsInstance(thing, dict)
2586 self.assertRaises(self.failureException, self.assertNotIsInstance,
2587 thing, list)
2588
Gregory P. Smith28399852009-03-31 16:54:10 +00002589 def testAssertIn(self):
2590 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2591
2592 self.assertIn('a', 'abc')
2593 self.assertIn(2, [1, 2, 3])
2594 self.assertIn('monkey', animals)
2595
2596 self.assertNotIn('d', 'abc')
2597 self.assertNotIn(0, [1, 2, 3])
2598 self.assertNotIn('otter', animals)
2599
2600 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2601 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2602 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2603 animals)
2604
2605 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2606 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2607 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2608 animals)
2609
2610 def testAssertDictContainsSubset(self):
2611 self.assertDictContainsSubset({}, {})
2612 self.assertDictContainsSubset({}, {'a': 1})
2613 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2614 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2615 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2616
Michael Foord225a0992010-02-18 20:30:09 +00002617 with self.assertRaises(self.failureException):
2618 self.assertDictContainsSubset({1: "one"}, {})
Gregory P. Smith28399852009-03-31 16:54:10 +00002619
Michael Foord225a0992010-02-18 20:30:09 +00002620 with self.assertRaises(self.failureException):
2621 self.assertDictContainsSubset({'a': 2}, {'a': 1})
Gregory P. Smith28399852009-03-31 16:54:10 +00002622
Michael Foord225a0992010-02-18 20:30:09 +00002623 with self.assertRaises(self.failureException):
2624 self.assertDictContainsSubset({'c': 1}, {'a': 1})
Gregory P. Smith28399852009-03-31 16:54:10 +00002625
Michael Foord225a0992010-02-18 20:30:09 +00002626 with self.assertRaises(self.failureException):
2627 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2628
2629 with self.assertRaises(self.failureException):
2630 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
2631
Michael Foord2f677562010-02-21 14:48:59 +00002632 with warnings.catch_warnings(record=True):
2633 # silence the UnicodeWarning
2634 one = ''.join(chr(i) for i in range(255))
2635 # this used to cause a UnicodeDecodeError constructing the failure msg
2636 with self.assertRaises(self.failureException):
2637 self.assertDictContainsSubset({'foo': one}, {'foo': u'\uFFFD'})
Gregory P. Smith28399852009-03-31 16:54:10 +00002638
2639 def testAssertEqual(self):
2640 equal_pairs = [
2641 ((), ()),
2642 ({}, {}),
2643 ([], []),
2644 (set(), set()),
2645 (frozenset(), frozenset())]
2646 for a, b in equal_pairs:
2647 # This mess of try excepts is to test the assertEqual behavior
2648 # itself.
2649 try:
2650 self.assertEqual(a, b)
2651 except self.failureException:
2652 self.fail('assertEqual(%r, %r) failed' % (a, b))
2653 try:
2654 self.assertEqual(a, b, msg='foo')
2655 except self.failureException:
2656 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2657 try:
2658 self.assertEqual(a, b, 'foo')
2659 except self.failureException:
2660 self.fail('assertEqual(%r, %r) with third parameter failed' %
2661 (a, b))
2662
2663 unequal_pairs = [
2664 ((), []),
2665 ({}, set()),
2666 (set([4,1]), frozenset([4,2])),
2667 (frozenset([4,5]), set([2,3])),
2668 (set([3,4]), set([5,4]))]
2669 for a, b in unequal_pairs:
2670 self.assertRaises(self.failureException, self.assertEqual, a, b)
2671 self.assertRaises(self.failureException, self.assertEqual, a, b,
2672 'foo')
2673 self.assertRaises(self.failureException, self.assertEqual, a, b,
2674 msg='foo')
2675
2676 def testEquality(self):
2677 self.assertListEqual([], [])
2678 self.assertTupleEqual((), ())
2679 self.assertSequenceEqual([], ())
2680
2681 a = [0, 'a', []]
2682 b = []
2683 self.assertRaises(unittest.TestCase.failureException,
2684 self.assertListEqual, a, b)
2685 self.assertRaises(unittest.TestCase.failureException,
2686 self.assertListEqual, tuple(a), tuple(b))
2687 self.assertRaises(unittest.TestCase.failureException,
2688 self.assertSequenceEqual, a, tuple(b))
2689
2690 b.extend(a)
2691 self.assertListEqual(a, b)
2692 self.assertTupleEqual(tuple(a), tuple(b))
2693 self.assertSequenceEqual(a, tuple(b))
2694 self.assertSequenceEqual(tuple(a), b)
2695
2696 self.assertRaises(self.failureException, self.assertListEqual,
2697 a, tuple(b))
2698 self.assertRaises(self.failureException, self.assertTupleEqual,
2699 tuple(a), b)
2700 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2701 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2702 tuple(b))
2703 self.assertRaises(self.failureException, self.assertSequenceEqual,
2704 None, tuple(b))
2705 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2706 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2707 self.assertRaises(self.failureException, self.assertSequenceEqual,
2708 1, 1)
2709
2710 self.assertDictEqual({}, {})
2711
2712 c = { 'x': 1 }
2713 d = {}
2714 self.assertRaises(unittest.TestCase.failureException,
2715 self.assertDictEqual, c, d)
2716
2717 d.update(c)
2718 self.assertDictEqual(c, d)
2719
2720 d['x'] = 0
2721 self.assertRaises(unittest.TestCase.failureException,
2722 self.assertDictEqual, c, d, 'These are unequal')
2723
2724 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2725 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2726 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2727
2728 self.assertSameElements([1, 2, 3], [3, 2, 1])
2729 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2730 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2731 self.assertRaises(self.failureException, self.assertSameElements,
2732 [10], [10, 11])
2733 self.assertRaises(self.failureException, self.assertSameElements,
2734 [10, 11], [10])
2735
2736 # Test that sequences of unhashable objects can be tested for sameness:
2737 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Michael Foordf2dfef12009-04-05 19:19:28 +00002738
Gregory P. Smith28399852009-03-31 16:54:10 +00002739 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2740 self.assertRaises(self.failureException, self.assertSameElements,
2741 [[1]], [[2]])
2742
2743 def testAssertSetEqual(self):
2744 set1 = set()
2745 set2 = set()
2746 self.assertSetEqual(set1, set2)
2747
2748 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2749 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2750 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2751 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2752
2753 set1 = set(['a'])
2754 set2 = set()
2755 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2756
2757 set1 = set(['a'])
2758 set2 = set(['a'])
2759 self.assertSetEqual(set1, set2)
2760
2761 set1 = set(['a'])
2762 set2 = set(['a', 'b'])
2763 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2764
2765 set1 = set(['a'])
2766 set2 = frozenset(['a', 'b'])
2767 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2768
2769 set1 = set(['a', 'b'])
2770 set2 = frozenset(['a', 'b'])
2771 self.assertSetEqual(set1, set2)
2772
2773 set1 = set()
2774 set2 = "foo"
2775 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2776 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2777
2778 # make sure any string formatting is tuple-safe
2779 set1 = set([(0, 1), (2, 3)])
2780 set2 = set([(4, 5)])
2781 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2782
2783 def testInequality(self):
2784 # Try ints
2785 self.assertGreater(2, 1)
2786 self.assertGreaterEqual(2, 1)
2787 self.assertGreaterEqual(1, 1)
2788 self.assertLess(1, 2)
2789 self.assertLessEqual(1, 2)
2790 self.assertLessEqual(1, 1)
2791 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2792 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2793 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2794 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2795 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2796 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2797
2798 # Try Floats
2799 self.assertGreater(1.1, 1.0)
2800 self.assertGreaterEqual(1.1, 1.0)
2801 self.assertGreaterEqual(1.0, 1.0)
2802 self.assertLess(1.0, 1.1)
2803 self.assertLessEqual(1.0, 1.1)
2804 self.assertLessEqual(1.0, 1.0)
2805 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2806 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2807 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2808 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2809 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2810 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2811
2812 # Try Strings
2813 self.assertGreater('bug', 'ant')
2814 self.assertGreaterEqual('bug', 'ant')
2815 self.assertGreaterEqual('ant', 'ant')
2816 self.assertLess('ant', 'bug')
2817 self.assertLessEqual('ant', 'bug')
2818 self.assertLessEqual('ant', 'ant')
2819 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2820 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2821 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2822 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2823 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2824 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2825
2826 # Try Unicode
2827 self.assertGreater(u'bug', u'ant')
2828 self.assertGreaterEqual(u'bug', u'ant')
2829 self.assertGreaterEqual(u'ant', u'ant')
2830 self.assertLess(u'ant', u'bug')
2831 self.assertLessEqual(u'ant', u'bug')
2832 self.assertLessEqual(u'ant', u'ant')
2833 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug')
2834 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant')
2835 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2836 u'bug')
2837 self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant')
2838 self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant')
2839 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant')
2840
2841 # Try Mixed String/Unicode
2842 self.assertGreater('bug', u'ant')
2843 self.assertGreater(u'bug', 'ant')
2844 self.assertGreaterEqual('bug', u'ant')
2845 self.assertGreaterEqual(u'bug', 'ant')
2846 self.assertGreaterEqual('ant', u'ant')
2847 self.assertGreaterEqual(u'ant', 'ant')
2848 self.assertLess('ant', u'bug')
2849 self.assertLess(u'ant', 'bug')
2850 self.assertLessEqual('ant', u'bug')
2851 self.assertLessEqual(u'ant', 'bug')
2852 self.assertLessEqual('ant', u'ant')
2853 self.assertLessEqual(u'ant', 'ant')
2854 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug')
2855 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug')
2856 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant')
2857 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant')
2858 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant',
2859 u'bug')
2860 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2861 'bug')
2862 self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant')
2863 self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant')
2864 self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant')
2865 self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant')
2866 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant')
2867 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant')
2868
2869 def testAssertMultiLineEqual(self):
2870 sample_text = b"""\
2871http://www.python.org/doc/2.3/lib/module-unittest.html
2872test case
2873 A test case is the smallest unit of testing. [...]
2874"""
2875 revised_sample_text = b"""\
2876http://www.python.org/doc/2.4.1/lib/module-unittest.html
2877test case
2878 A test case is the smallest unit of testing. [...] You may provide your
2879 own implementation that does not subclass from TestCase, of course.
2880"""
2881 sample_text_error = b"""
2882- http://www.python.org/doc/2.3/lib/module-unittest.html
2883? ^
2884+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2885? ^^^
2886 test case
2887- A test case is the smallest unit of testing. [...]
2888+ A test case is the smallest unit of testing. [...] You may provide your
2889? +++++++++++++++++++++
2890+ own implementation that does not subclass from TestCase, of course.
2891"""
2892
2893 for type_changer in (lambda x: x, lambda x: x.decode('utf8')):
2894 try:
2895 self.assertMultiLineEqual(type_changer(sample_text),
2896 type_changer(revised_sample_text))
2897 except self.failureException, e:
Michael Foordfe6349c2010-02-08 22:41:16 +00002898 # assertMultiLineEqual is hooked up as the default for
2899 # unicode strings - so we can't use it for this check
2900 self.assertTrue(sample_text_error == str(e).encode('utf8'))
Gregory P. Smith28399852009-03-31 16:54:10 +00002901
2902 def testAssertIsNone(self):
2903 self.assertIsNone(None)
2904 self.assertRaises(self.failureException, self.assertIsNone, False)
2905 self.assertIsNotNone('DjZoPloGears on Rails')
2906 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2907
2908 def testAssertRegexpMatches(self):
2909 self.assertRegexpMatches('asdfabasdf', r'ab+')
2910 self.assertRaises(self.failureException, self.assertRegexpMatches,
2911 'saaas', r'aaaa')
2912
2913 def testAssertRaisesRegexp(self):
2914 class ExceptionMock(Exception):
2915 pass
2916
2917 def Stub():
2918 raise ExceptionMock('We expect')
2919
2920 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2921 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2922 self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
2923
2924 def testAssertNotRaisesRegexp(self):
2925 self.assertRaisesRegexp(
2926 self.failureException, '^Exception not raised$',
2927 self.assertRaisesRegexp, Exception, re.compile('x'),
2928 lambda: None)
2929 self.assertRaisesRegexp(
2930 self.failureException, '^Exception not raised$',
2931 self.assertRaisesRegexp, Exception, 'x',
2932 lambda: None)
2933 self.assertRaisesRegexp(
2934 self.failureException, '^Exception not raised$',
2935 self.assertRaisesRegexp, Exception, u'x',
2936 lambda: None)
2937
2938 def testAssertRaisesRegexpMismatch(self):
2939 def Stub():
2940 raise Exception('Unexpected')
2941
2942 self.assertRaisesRegexp(
2943 self.failureException,
2944 r'"\^Expected\$" does not match "Unexpected"',
2945 self.assertRaisesRegexp, Exception, '^Expected$',
2946 Stub)
2947 self.assertRaisesRegexp(
2948 self.failureException,
2949 r'"\^Expected\$" does not match "Unexpected"',
2950 self.assertRaisesRegexp, Exception, u'^Expected$',
2951 Stub)
2952 self.assertRaisesRegexp(
2953 self.failureException,
2954 r'"\^Expected\$" does not match "Unexpected"',
2955 self.assertRaisesRegexp, Exception,
2956 re.compile('^Expected$'), Stub)
2957
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00002958 def testAssertRaisesExcValue(self):
2959 class ExceptionMock(Exception):
2960 pass
2961
2962 def Stub(foo):
2963 raise ExceptionMock(foo)
2964 v = "particular value"
2965
2966 ctx = self.assertRaises(ExceptionMock)
2967 with ctx:
2968 Stub(v)
Georg Brandldc3694b2010-02-07 17:02:22 +00002969 e = ctx.exception
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002970 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00002971 self.assertEqual(e.args[0], v)
2972
Gregory P. Smith7558d572009-03-31 19:03:28 +00002973 def testSynonymAssertMethodNames(self):
2974 """Test undocumented method name synonyms.
2975
2976 Please do not use these methods names in your own code.
2977
2978 This test confirms their continued existence and functionality
2979 in order to avoid breaking existing code.
2980 """
2981 self.assertNotEquals(3, 5)
2982 self.assertEquals(3, 3)
2983 self.assertAlmostEquals(2.0, 2.0)
2984 self.assertNotAlmostEquals(3.0, 5.0)
2985 self.assert_(True)
2986
2987 def testPendingDeprecationMethodNames(self):
2988 """Test fail* methods pending deprecation, they will warn in 3.2.
2989
2990 Do not use these methods. They will go away in 3.3.
2991 """
2992 self.failIfEqual(3, 5)
2993 self.failUnlessEqual(3, 3)
2994 self.failUnlessAlmostEqual(2.0, 2.0)
2995 self.failIfAlmostEqual(3.0, 5.0)
2996 self.failUnless(True)
2997 self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam')
2998 self.failIf(False)
2999
Michael Foorde2942d02009-04-02 05:51:54 +00003000 def testDeepcopy(self):
3001 # Issue: 5660
3002 class TestableTest(TestCase):
3003 def testNothing(self):
3004 pass
3005
3006 test = TestableTest('testNothing')
3007
3008 # This shouldn't blow up
3009 deepcopy(test)
3010
Benjamin Peterson692428e2009-03-23 21:50:21 +00003011
3012class Test_TestSkipping(TestCase):
3013
3014 def test_skipping(self):
3015 class Foo(unittest.TestCase):
3016 def test_skip_me(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00003017 self.skipTest("skip")
Benjamin Peterson692428e2009-03-23 21:50:21 +00003018 events = []
3019 result = LoggingResult(events)
3020 test = Foo("test_skip_me")
3021 test.run(result)
3022 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3023 self.assertEqual(result.skipped, [(test, "skip")])
3024
3025 # Try letting setUp skip the test now.
3026 class Foo(unittest.TestCase):
3027 def setUp(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00003028 self.skipTest("testing")
Benjamin Peterson692428e2009-03-23 21:50:21 +00003029 def test_nothing(self): pass
3030 events = []
3031 result = LoggingResult(events)
3032 test = Foo("test_nothing")
3033 test.run(result)
3034 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
3035 self.assertEqual(result.skipped, [(test, "testing")])
3036 self.assertEqual(result.testsRun, 1)
3037
3038 def test_skipping_decorators(self):
3039 op_table = ((unittest.skipUnless, False, True),
3040 (unittest.skipIf, True, False))
3041 for deco, do_skip, dont_skip in op_table:
3042 class Foo(unittest.TestCase):
3043 @deco(do_skip, "testing")
3044 def test_skip(self): pass
3045
3046 @deco(dont_skip, "testing")
3047 def test_dont_skip(self): pass
3048 test_do_skip = Foo("test_skip")
3049 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003050 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003051 events = []
3052 result = LoggingResult(events)
3053 suite.run(result)
3054 self.assertEqual(len(result.skipped), 1)
3055 expected = ['startTest', 'addSkip', 'stopTest',
3056 'startTest', 'addSuccess', 'stopTest']
3057 self.assertEqual(events, expected)
3058 self.assertEqual(result.testsRun, 2)
3059 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
3060 self.assertTrue(result.wasSuccessful())
3061
3062 def test_skip_class(self):
3063 @unittest.skip("testing")
3064 class Foo(unittest.TestCase):
3065 def test_1(self):
3066 record.append(1)
3067 record = []
3068 result = unittest.TestResult()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003069 test = Foo("test_1")
3070 suite = unittest.TestSuite([test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003071 suite.run(result)
Benjamin Peterson176a56c2009-05-25 00:48:58 +00003072 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003073 self.assertEqual(record, [])
3074
3075 def test_expected_failure(self):
3076 class Foo(unittest.TestCase):
3077 @unittest.expectedFailure
3078 def test_die(self):
3079 self.fail("help me!")
3080 events = []
3081 result = LoggingResult(events)
3082 test = Foo("test_die")
3083 test.run(result)
3084 self.assertEqual(events,
3085 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003086 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00003087 self.assertTrue(result.wasSuccessful())
3088
3089 def test_unexpected_success(self):
3090 class Foo(unittest.TestCase):
3091 @unittest.expectedFailure
3092 def test_die(self):
3093 pass
3094 events = []
3095 result = LoggingResult(events)
3096 test = Foo("test_die")
3097 test.run(result)
3098 self.assertEqual(events,
3099 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3100 self.assertFalse(result.failures)
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003101 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003102 self.assertTrue(result.wasSuccessful())
3103
3104
3105
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003106class Test_Assertions(TestCase):
3107 def test_AlmostEqual(self):
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003108 self.assertAlmostEqual(1.00000001, 1.0)
3109 self.assertNotAlmostEqual(1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003110 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003111 self.assertAlmostEqual, 1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003112 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003113 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003114
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003115 self.assertAlmostEqual(1.1, 1.0, places=0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003116 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003117 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003118
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003119 self.assertAlmostEqual(0, .1+.1j, places=0)
3120 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003121 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003122 self.assertAlmostEqual, 0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003123 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003124 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003125
Michael Foordc3f79372009-09-13 16:40:02 +00003126 self.assertAlmostEqual(float('inf'), float('inf'))
3127 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3128 float('inf'), float('inf'))
3129
3130
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003131 def test_assertRaises(self):
3132 def _raise(e):
3133 raise e
3134 self.assertRaises(KeyError, _raise, KeyError)
3135 self.assertRaises(KeyError, _raise, KeyError("key"))
3136 try:
3137 self.assertRaises(KeyError, lambda: None)
Gregory P. Smith28399852009-03-31 16:54:10 +00003138 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003139 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003140 else:
3141 self.fail("assertRaises() didn't fail")
3142 try:
3143 self.assertRaises(KeyError, _raise, ValueError)
3144 except ValueError:
3145 pass
3146 else:
3147 self.fail("assertRaises() didn't let exception pass through")
Michael Foord2bd52dc2010-02-07 18:44:12 +00003148 with self.assertRaises(KeyError) as cm:
3149 try:
3150 raise KeyError
3151 except Exception, e:
3152 raise
3153 self.assertIs(cm.exception, e)
3154
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003155 with self.assertRaises(KeyError):
3156 raise KeyError("key")
3157 try:
3158 with self.assertRaises(KeyError):
3159 pass
Gregory P. Smith28399852009-03-31 16:54:10 +00003160 except self.failureException as e:
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003161 self.assertIn("KeyError not raised", e.args)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003162 else:
3163 self.fail("assertRaises() didn't fail")
3164 try:
3165 with self.assertRaises(KeyError):
3166 raise ValueError
3167 except ValueError:
3168 pass
3169 else:
3170 self.fail("assertRaises() didn't let exception pass through")
3171
3172
Michael Foord345b2fe2009-04-02 03:20:38 +00003173class TestLongMessage(TestCase):
3174 """Test that the individual asserts honour longMessage.
3175 This actually tests all the message behaviour for
3176 asserts that use longMessage."""
3177
3178 def setUp(self):
3179 class TestableTestFalse(TestCase):
3180 longMessage = False
3181 failureException = self.failureException
3182
3183 def testTest(self):
3184 pass
3185
3186 class TestableTestTrue(TestCase):
3187 longMessage = True
3188 failureException = self.failureException
3189
3190 def testTest(self):
3191 pass
3192
3193 self.testableTrue = TestableTestTrue('testTest')
3194 self.testableFalse = TestableTestFalse('testTest')
3195
3196 def testDefault(self):
3197 self.assertFalse(TestCase.longMessage)
3198
3199 def test_formatMsg(self):
3200 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3201 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3202
3203 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3204 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3205
3206 def assertMessages(self, methodName, args, errors):
3207 def getMethod(i):
3208 useTestableFalse = i < 2
3209 if useTestableFalse:
3210 test = self.testableFalse
3211 else:
3212 test = self.testableTrue
3213 return getattr(test, methodName)
3214
3215 for i, expected_regexp in enumerate(errors):
3216 testMethod = getMethod(i)
3217 kwargs = {}
3218 withMsg = i % 2
3219 if withMsg:
3220 kwargs = {"msg": "oops"}
3221
3222 with self.assertRaisesRegexp(self.failureException,
3223 expected_regexp=expected_regexp):
3224 testMethod(*args, **kwargs)
3225
3226 def testAssertTrue(self):
3227 self.assertMessages('assertTrue', (False,),
3228 ["^False is not True$", "^oops$", "^False is not True$",
3229 "^False is not True : oops$"])
3230
3231 def testAssertFalse(self):
3232 self.assertMessages('assertFalse', (True,),
3233 ["^True is not False$", "^oops$", "^True is not False$",
3234 "^True is not False : oops$"])
3235
3236 def testNotEqual(self):
3237 self.assertMessages('assertNotEqual', (1, 1),
3238 ["^1 == 1$", "^oops$", "^1 == 1$",
3239 "^1 == 1 : oops$"])
3240
3241 def testAlmostEqual(self):
3242 self.assertMessages('assertAlmostEqual', (1, 2),
3243 ["^1 != 2 within 7 places$", "^oops$",
3244 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3245
3246 def testNotAlmostEqual(self):
3247 self.assertMessages('assertNotAlmostEqual', (1, 1),
3248 ["^1 == 1 within 7 places$", "^oops$",
3249 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3250
3251 def test_baseAssertEqual(self):
3252 self.assertMessages('_baseAssertEqual', (1, 2),
3253 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3254
3255 def testAssertSequenceEqual(self):
3256 # Error messages are multiline so not testing on full message
3257 # assertTupleEqual and assertListEqual delegate to this method
3258 self.assertMessages('assertSequenceEqual', ([], [None]),
3259 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3260 r"\+ \[None\] : oops$"])
3261
3262 def testAssertSetEqual(self):
3263 self.assertMessages('assertSetEqual', (set(), set([None])),
3264 ["None$", "^oops$", "None$",
3265 "None : oops$"])
3266
3267 def testAssertIn(self):
3268 self.assertMessages('assertIn', (None, []),
3269 ['^None not found in \[\]$', "^oops$",
3270 '^None not found in \[\]$',
3271 '^None not found in \[\] : oops$'])
3272
3273 def testAssertNotIn(self):
3274 self.assertMessages('assertNotIn', (None, [None]),
3275 ['^None unexpectedly found in \[None\]$', "^oops$",
3276 '^None unexpectedly found in \[None\]$',
3277 '^None unexpectedly found in \[None\] : oops$'])
3278
3279 def testAssertDictEqual(self):
3280 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3281 [r"\+ \{'key': 'value'\}$", "^oops$",
3282 "\+ \{'key': 'value'\}$",
3283 "\+ \{'key': 'value'\} : oops$"])
3284
3285 def testAssertDictContainsSubset(self):
3286 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3287 ["^Missing: 'key'$", "^oops$",
3288 "^Missing: 'key'$",
3289 "^Missing: 'key' : oops$"])
3290
3291 def testAssertSameElements(self):
3292 self.assertMessages('assertSameElements', ([], [None]),
3293 [r"\[None\]$", "^oops$",
3294 r"\[None\]$",
3295 r"\[None\] : oops$"])
3296
3297 def testAssertMultiLineEqual(self):
3298 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3299 [r"\+ foo$", "^oops$",
3300 r"\+ foo$",
3301 r"\+ foo : oops$"])
3302
3303 def testAssertLess(self):
3304 self.assertMessages('assertLess', (2, 1),
3305 ["^2 not less than 1$", "^oops$",
3306 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3307
3308 def testAssertLessEqual(self):
3309 self.assertMessages('assertLessEqual', (2, 1),
3310 ["^2 not less than or equal to 1$", "^oops$",
3311 "^2 not less than or equal to 1$",
3312 "^2 not less than or equal to 1 : oops$"])
3313
3314 def testAssertGreater(self):
3315 self.assertMessages('assertGreater', (1, 2),
3316 ["^1 not greater than 2$", "^oops$",
3317 "^1 not greater than 2$",
3318 "^1 not greater than 2 : oops$"])
3319
3320 def testAssertGreaterEqual(self):
3321 self.assertMessages('assertGreaterEqual', (1, 2),
3322 ["^1 not greater than or equal to 2$", "^oops$",
3323 "^1 not greater than or equal to 2$",
3324 "^1 not greater than or equal to 2 : oops$"])
3325
3326 def testAssertIsNone(self):
3327 self.assertMessages('assertIsNone', ('not None',),
3328 ["^'not None' is not None$", "^oops$",
3329 "^'not None' is not None$",
3330 "^'not None' is not None : oops$"])
3331
3332 def testAssertIsNotNone(self):
3333 self.assertMessages('assertIsNotNone', (None,),
3334 ["^unexpectedly None$", "^oops$",
3335 "^unexpectedly None$",
3336 "^unexpectedly None : oops$"])
3337
Michael Foordf2dfef12009-04-05 19:19:28 +00003338 def testAssertIs(self):
3339 self.assertMessages('assertIs', (None, 'foo'),
3340 ["^None is not 'foo'$", "^oops$",
3341 "^None is not 'foo'$",
3342 "^None is not 'foo' : oops$"])
3343
3344 def testAssertIsNot(self):
3345 self.assertMessages('assertIsNot', (None, None),
3346 ["^unexpectedly identical: None$", "^oops$",
3347 "^unexpectedly identical: None$",
3348 "^unexpectedly identical: None : oops$"])
3349
Michael Foord345b2fe2009-04-02 03:20:38 +00003350
Michael Foorde2fb98f2009-05-02 20:15:05 +00003351class TestCleanUp(TestCase):
3352
3353 def testCleanUp(self):
3354 class TestableTest(TestCase):
3355 def testNothing(self):
3356 pass
3357
3358 test = TestableTest('testNothing')
3359 self.assertEqual(test._cleanups, [])
3360
3361 cleanups = []
3362
3363 def cleanup1(*args, **kwargs):
3364 cleanups.append((1, args, kwargs))
3365
3366 def cleanup2(*args, **kwargs):
3367 cleanups.append((2, args, kwargs))
3368
3369 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3370 test.addCleanup(cleanup2)
3371
3372 self.assertEqual(test._cleanups,
3373 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3374 (cleanup2, (), {})])
3375
3376 result = test.doCleanups()
3377 self.assertTrue(result)
3378
3379 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3380
3381 def testCleanUpWithErrors(self):
3382 class TestableTest(TestCase):
3383 def testNothing(self):
3384 pass
3385
3386 class MockResult(object):
3387 errors = []
3388 def addError(self, test, exc_info):
3389 self.errors.append((test, exc_info))
3390
3391 result = MockResult()
3392 test = TestableTest('testNothing')
Michael Foorda50af062009-05-21 22:57:02 +00003393 test._resultForDoCleanups = result
Michael Foorde2fb98f2009-05-02 20:15:05 +00003394
3395 exc1 = Exception('foo')
3396 exc2 = Exception('bar')
3397 def cleanup1():
3398 raise exc1
3399
3400 def cleanup2():
3401 raise exc2
3402
3403 test.addCleanup(cleanup1)
3404 test.addCleanup(cleanup2)
3405
3406 self.assertFalse(test.doCleanups())
3407
3408 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3409 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3410 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3411
3412 def testCleanupInRun(self):
3413 blowUp = False
3414 ordering = []
3415
3416 class TestableTest(TestCase):
3417 def setUp(self):
3418 ordering.append('setUp')
3419 if blowUp:
3420 raise Exception('foo')
3421
3422 def testNothing(self):
3423 ordering.append('test')
3424
3425 def tearDown(self):
3426 ordering.append('tearDown')
3427
3428 test = TestableTest('testNothing')
3429
3430 def cleanup1():
3431 ordering.append('cleanup1')
3432 def cleanup2():
3433 ordering.append('cleanup2')
3434 test.addCleanup(cleanup1)
3435 test.addCleanup(cleanup2)
3436
3437 def success(some_test):
3438 self.assertEqual(some_test, test)
3439 ordering.append('success')
3440
3441 result = unittest.TestResult()
3442 result.addSuccess = success
3443
3444 test.run(result)
3445 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3446 'cleanup2', 'cleanup1', 'success'])
3447
3448 blowUp = True
3449 ordering = []
3450 test = TestableTest('testNothing')
3451 test.addCleanup(cleanup1)
3452 test.run(result)
3453 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3454
3455
Michael Foord829f6b82009-05-02 11:43:06 +00003456class Test_TestProgram(TestCase):
3457
3458 # Horrible white box test
3459 def testNoExit(self):
3460 result = object()
3461 test = object()
3462
3463 class FakeRunner(object):
3464 def run(self, test):
3465 self.test = test
3466 return result
3467
3468 runner = FakeRunner()
3469
Michael Foord5d31e052009-05-11 17:59:43 +00003470 oldParseArgs = TestProgram.parseArgs
3471 def restoreParseArgs():
Michael Foord829f6b82009-05-02 11:43:06 +00003472 TestProgram.parseArgs = oldParseArgs
Michael Foord5d31e052009-05-11 17:59:43 +00003473 TestProgram.parseArgs = lambda *args: None
3474 self.addCleanup(restoreParseArgs)
3475
3476 def removeTest():
Michael Foord829f6b82009-05-02 11:43:06 +00003477 del TestProgram.test
Michael Foord5d31e052009-05-11 17:59:43 +00003478 TestProgram.test = test
3479 self.addCleanup(removeTest)
3480
3481 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3482
3483 self.assertEqual(program.result, result)
3484 self.assertEqual(runner.test, test)
3485 self.assertEqual(program.verbosity, 2)
Michael Foord829f6b82009-05-02 11:43:06 +00003486
Michael Foord829f6b82009-05-02 11:43:06 +00003487 class FooBar(unittest.TestCase):
3488 def testPass(self):
3489 assert True
3490 def testFail(self):
3491 assert False
3492
3493 class FooBarLoader(unittest.TestLoader):
3494 """Test loader that returns a suite containing FooBar."""
3495 def loadTestsFromModule(self, module):
3496 return self.suiteClass(
3497 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3498
3499
3500 def test_NonExit(self):
3501 program = unittest.main(exit=False,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003502 argv=["foobar"],
3503 testRunner=unittest.TextTestRunner(stream=StringIO()),
3504 testLoader=self.FooBarLoader())
Michael Foord829f6b82009-05-02 11:43:06 +00003505 self.assertTrue(hasattr(program, 'result'))
3506
3507
3508 def test_Exit(self):
3509 self.assertRaises(
3510 SystemExit,
3511 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003512 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003513 testRunner=unittest.TextTestRunner(stream=StringIO()),
3514 exit=True,
3515 testLoader=self.FooBarLoader())
3516
3517
3518 def test_ExitAsDefault(self):
3519 self.assertRaises(
3520 SystemExit,
3521 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003522 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003523 testRunner=unittest.TextTestRunner(stream=StringIO()),
3524 testLoader=self.FooBarLoader())
3525
3526
Michael Foord07ef4872009-05-02 22:43:34 +00003527class Test_TextTestRunner(TestCase):
3528 """Tests for TextTestRunner."""
3529
3530 def test_works_with_result_without_startTestRun_stopTestRun(self):
3531 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3532 separator2 = ''
3533 def printErrors(self):
3534 pass
3535
3536 class Runner(unittest.TextTestRunner):
3537 def __init__(self):
3538 super(Runner, self).__init__(StringIO())
3539
3540 def _makeResult(self):
3541 return OldTextResult()
3542
3543 runner = Runner()
3544 runner.run(unittest.TestSuite())
3545
3546 def test_startTestRun_stopTestRun_called(self):
3547 class LoggingTextResult(LoggingResult):
3548 separator2 = ''
3549 def printErrors(self):
3550 pass
3551
3552 class LoggingRunner(unittest.TextTestRunner):
3553 def __init__(self, events):
3554 super(LoggingRunner, self).__init__(StringIO())
3555 self._events = events
3556
3557 def _makeResult(self):
3558 return LoggingTextResult(self._events)
3559
3560 events = []
3561 runner = LoggingRunner(events)
3562 runner.run(unittest.TestSuite())
3563 expected = ['startTestRun', 'stopTestRun']
3564 self.assertEqual(events, expected)
3565
Antoine Pitrou0734c632009-11-10 20:49:30 +00003566 def test_pickle_unpickle(self):
3567 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3568 # required by test_multiprocessing under Windows (in verbose mode).
3569 import StringIO
3570 # cStringIO objects are not pickleable, but StringIO objects are.
3571 stream = StringIO.StringIO("foo")
3572 runner = unittest.TextTestRunner(stream)
3573 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
3574 s = pickle.dumps(runner, protocol=protocol)
3575 obj = pickle.loads(s)
3576 # StringIO objects never compare equal, a cheap test instead.
3577 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3578
Michael Foorddb43b5a2010-02-10 14:25:12 +00003579 def test_resultclass(self):
3580 def MockResultClass(*args):
3581 return args
3582 STREAM = object()
3583 DESCRIPTIONS = object()
3584 VERBOSITY = object()
3585 runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY,
3586 resultclass=MockResultClass)
3587 self.assertEqual(runner.resultclass, MockResultClass)
3588
3589 expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY)
3590 self.assertEqual(runner._makeResult(), expectedresult)
3591
Michael Foord07ef4872009-05-02 22:43:34 +00003592
Michael Foordb4a81c82009-05-29 20:33:46 +00003593class TestDiscovery(TestCase):
3594
3595 # Heavily mocked tests so I can avoid hitting the filesystem
Michael Foorde91ea562009-09-13 19:07:03 +00003596 def test_get_name_from_path(self):
Michael Foordb4a81c82009-05-29 20:33:46 +00003597 loader = unittest.TestLoader()
3598
Michael Foordb4a81c82009-05-29 20:33:46 +00003599 loader._top_level_dir = '/foo'
Michael Foorde91ea562009-09-13 19:07:03 +00003600 name = loader._get_name_from_path('/foo/bar/baz.py')
3601 self.assertEqual(name, 'bar.baz')
Michael Foordb4a81c82009-05-29 20:33:46 +00003602
3603 if not __debug__:
3604 # asserts are off
3605 return
3606
3607 with self.assertRaises(AssertionError):
Michael Foorde91ea562009-09-13 19:07:03 +00003608 loader._get_name_from_path('/bar/baz.py')
Michael Foordb4a81c82009-05-29 20:33:46 +00003609
3610 def test_find_tests(self):
3611 loader = unittest.TestLoader()
3612
3613 original_listdir = os.listdir
3614 def restore_listdir():
3615 os.listdir = original_listdir
3616 original_isfile = os.path.isfile
3617 def restore_isfile():
3618 os.path.isfile = original_isfile
3619 original_isdir = os.path.isdir
3620 def restore_isdir():
3621 os.path.isdir = original_isdir
3622
3623 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Michael Foorde91ea562009-09-13 19:07:03 +00003624 'test.foo', 'test-not-a-module.py', 'another_dir'],
Michael Foordb4a81c82009-05-29 20:33:46 +00003625 ['test3.py', 'test4.py', ]]
3626 os.listdir = lambda path: path_lists.pop(0)
3627 self.addCleanup(restore_listdir)
3628
3629 def isdir(path):
3630 return path.endswith('dir')
3631 os.path.isdir = isdir
3632 self.addCleanup(restore_isdir)
3633
3634 def isfile(path):
3635 # another_dir is not a package and so shouldn't be recursed into
3636 return not path.endswith('dir') and not 'another_dir' in path
3637 os.path.isfile = isfile
3638 self.addCleanup(restore_isfile)
3639
Michael Foorde91ea562009-09-13 19:07:03 +00003640 loader._get_module_from_name = lambda path: path + ' module'
Michael Foordb4a81c82009-05-29 20:33:46 +00003641 loader.loadTestsFromModule = lambda module: module + ' tests'
3642
3643 loader._top_level_dir = '/foo'
3644 suite = list(loader._find_tests('/foo', 'test*.py'))
3645
Michael Foorde91ea562009-09-13 19:07:03 +00003646 expected = [name + ' module tests' for name in
3647 ('test1', 'test2')]
3648 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3649 ('test3', 'test4')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003650 self.assertEqual(suite, expected)
3651
3652 def test_find_tests_with_package(self):
3653 loader = unittest.TestLoader()
3654
3655 original_listdir = os.listdir
3656 def restore_listdir():
3657 os.listdir = original_listdir
3658 original_isfile = os.path.isfile
3659 def restore_isfile():
3660 os.path.isfile = original_isfile
3661 original_isdir = os.path.isdir
3662 def restore_isdir():
3663 os.path.isdir = original_isdir
3664
3665 directories = ['a_directory', 'test_directory', 'test_directory2']
3666 path_lists = [directories, [], [], []]
3667 os.listdir = lambda path: path_lists.pop(0)
3668 self.addCleanup(restore_listdir)
3669
3670 os.path.isdir = lambda path: True
3671 self.addCleanup(restore_isdir)
3672
3673 os.path.isfile = lambda path: os.path.basename(path) not in directories
3674 self.addCleanup(restore_isfile)
3675
3676 class Module(object):
3677 paths = []
3678 load_tests_args = []
3679
3680 def __init__(self, path):
3681 self.path = path
3682 self.paths.append(path)
3683 if os.path.basename(path) == 'test_directory':
3684 def load_tests(loader, tests, pattern):
3685 self.load_tests_args.append((loader, tests, pattern))
3686 return 'load_tests'
3687 self.load_tests = load_tests
3688
3689 def __eq__(self, other):
3690 return self.path == other.path
3691
Ezio Melotti0ac4d4c2010-02-02 15:12:42 +00003692 # Silence py3k warning
3693 __hash__ = None
3694
Michael Foorde91ea562009-09-13 19:07:03 +00003695 loader._get_module_from_name = lambda name: Module(name)
Michael Foordb4a81c82009-05-29 20:33:46 +00003696 def loadTestsFromModule(module, use_load_tests):
3697 if use_load_tests:
3698 raise self.failureException('use_load_tests should be False for packages')
3699 return module.path + ' module tests'
3700 loader.loadTestsFromModule = loadTestsFromModule
3701
3702 loader._top_level_dir = '/foo'
3703 # this time no '.py' on the pattern so that it can match
3704 # a test package
3705 suite = list(loader._find_tests('/foo', 'test*'))
3706
3707 # We should have loaded tests from the test_directory package by calling load_tests
3708 # and directly from the test_directory2 package
Michael Foordd53d0852009-06-05 14:14:34 +00003709 self.assertEqual(suite,
Michael Foorde91ea562009-09-13 19:07:03 +00003710 ['load_tests', 'test_directory2' + ' module tests'])
3711 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Michael Foordb4a81c82009-05-29 20:33:46 +00003712
3713 # load_tests should have been called once with loader, tests and pattern
3714 self.assertEqual(Module.load_tests_args,
Michael Foorde91ea562009-09-13 19:07:03 +00003715 [(loader, 'test_directory' + ' module tests', 'test*')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003716
3717 def test_discover(self):
3718 loader = unittest.TestLoader()
3719
3720 original_isfile = os.path.isfile
3721 def restore_isfile():
3722 os.path.isfile = original_isfile
3723
3724 os.path.isfile = lambda path: False
3725 self.addCleanup(restore_isfile)
3726
Nick Coghlanb6edf192009-10-17 08:21:21 +00003727 orig_sys_path = sys.path[:]
3728 def restore_path():
3729 sys.path[:] = orig_sys_path
3730 self.addCleanup(restore_path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003731
Nick Coghlanb6edf192009-10-17 08:21:21 +00003732 full_path = os.path.abspath(os.path.normpath('/foo'))
Michael Foordb4a81c82009-05-29 20:33:46 +00003733 with self.assertRaises(ImportError):
3734 loader.discover('/foo/bar', top_level_dir='/foo')
3735
3736 self.assertEqual(loader._top_level_dir, full_path)
3737 self.assertIn(full_path, sys.path)
3738
3739 os.path.isfile = lambda path: True
3740 _find_tests_args = []
3741 def _find_tests(start_dir, pattern):
3742 _find_tests_args.append((start_dir, pattern))
3743 return ['tests']
3744 loader._find_tests = _find_tests
3745 loader.suiteClass = str
3746
3747 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3748
3749 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3750 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3751 self.assertEqual(suite, "['tests']")
3752 self.assertEqual(loader._top_level_dir, top_level_dir)
3753 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlanb6edf192009-10-17 08:21:21 +00003754 self.assertIn(top_level_dir, sys.path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003755
Michael Foorde91ea562009-09-13 19:07:03 +00003756 def test_discover_with_modules_that_fail_to_import(self):
3757 loader = unittest.TestLoader()
3758
3759 listdir = os.listdir
3760 os.listdir = lambda _: ['test_this_does_not_exist.py']
3761 isfile = os.path.isfile
3762 os.path.isfile = lambda _: True
Nick Coghlanb6edf192009-10-17 08:21:21 +00003763 orig_sys_path = sys.path[:]
Michael Foorde91ea562009-09-13 19:07:03 +00003764 def restore():
3765 os.path.isfile = isfile
3766 os.listdir = listdir
Nick Coghlanb6edf192009-10-17 08:21:21 +00003767 sys.path[:] = orig_sys_path
Michael Foorde91ea562009-09-13 19:07:03 +00003768 self.addCleanup(restore)
3769
3770 suite = loader.discover('.')
Nick Coghlanb6edf192009-10-17 08:21:21 +00003771 self.assertIn(os.getcwd(), sys.path)
Michael Foorde91ea562009-09-13 19:07:03 +00003772 self.assertEqual(suite.countTestCases(), 1)
3773 test = list(list(suite)[0])[0] # extract test from suite
3774
3775 with self.assertRaises(ImportError):
3776 test.test_this_does_not_exist()
3777
Michael Foordb4a81c82009-05-29 20:33:46 +00003778 def test_command_line_handling_parseArgs(self):
3779 # Haha - take that uninstantiable class
3780 program = object.__new__(TestProgram)
3781
3782 args = []
3783 def do_discovery(argv):
3784 args.extend(argv)
3785 program._do_discovery = do_discovery
3786 program.parseArgs(['something', 'discover'])
3787 self.assertEqual(args, [])
3788
3789 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3790 self.assertEqual(args, ['foo', 'bar'])
3791
3792 def test_command_line_handling_do_discovery_too_many_arguments(self):
3793 class Stop(Exception):
3794 pass
3795 def usageExit():
3796 raise Stop
3797
3798 program = object.__new__(TestProgram)
3799 program.usageExit = usageExit
3800
3801 with self.assertRaises(Stop):
3802 # too many args
3803 program._do_discovery(['one', 'two', 'three', 'four'])
3804
3805
3806 def test_command_line_handling_do_discovery_calls_loader(self):
3807 program = object.__new__(TestProgram)
3808
3809 class Loader(object):
3810 args = []
3811 def discover(self, start_dir, pattern, top_level_dir):
3812 self.args.append((start_dir, pattern, top_level_dir))
3813 return 'tests'
3814
3815 program._do_discovery(['-v'], Loader=Loader)
3816 self.assertEqual(program.verbosity, 2)
3817 self.assertEqual(program.test, 'tests')
3818 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3819
3820 Loader.args = []
3821 program = object.__new__(TestProgram)
3822 program._do_discovery(['--verbose'], Loader=Loader)
3823 self.assertEqual(program.test, 'tests')
3824 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3825
3826 Loader.args = []
3827 program = object.__new__(TestProgram)
3828 program._do_discovery([], Loader=Loader)
3829 self.assertEqual(program.test, 'tests')
3830 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3831
3832 Loader.args = []
3833 program = object.__new__(TestProgram)
3834 program._do_discovery(['fish'], Loader=Loader)
3835 self.assertEqual(program.test, 'tests')
3836 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3837
3838 Loader.args = []
3839 program = object.__new__(TestProgram)
3840 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3841 self.assertEqual(program.test, 'tests')
3842 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3843
3844 Loader.args = []
3845 program = object.__new__(TestProgram)
3846 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3847 self.assertEqual(program.test, 'tests')
3848 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3849
3850 Loader.args = []
3851 program = object.__new__(TestProgram)
3852 program._do_discovery(['-s', 'fish'], Loader=Loader)
3853 self.assertEqual(program.test, 'tests')
3854 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3855
3856 Loader.args = []
3857 program = object.__new__(TestProgram)
3858 program._do_discovery(['-t', 'fish'], Loader=Loader)
3859 self.assertEqual(program.test, 'tests')
3860 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3861
3862 Loader.args = []
3863 program = object.__new__(TestProgram)
3864 program._do_discovery(['-p', 'fish'], Loader=Loader)
3865 self.assertEqual(program.test, 'tests')
3866 self.assertEqual(Loader.args, [('.', 'fish', None)])
3867
3868 Loader.args = []
3869 program = object.__new__(TestProgram)
3870 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3871 self.assertEqual(program.test, 'tests')
3872 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3873 self.assertEqual(program.verbosity, 2)
3874
3875
Jim Fultonfafd8742004-08-28 15:22:12 +00003876######################################################################
3877## Main
3878######################################################################
3879
3880def test_main():
Georg Brandl15c5ce92007-03-07 09:09:40 +00003881 test_support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003882 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Michael Foord829f6b82009-05-02 11:43:06 +00003883 Test_TestSkipping, Test_Assertions, TestLongMessage,
Michael Foordae3db0a2010-02-22 23:28:32 +00003884 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner,
3885 Test_OldTestResult)
Jim Fultonfafd8742004-08-28 15:22:12 +00003886
Georg Brandl15c5ce92007-03-07 09:09:40 +00003887if __name__ == "__main__":
Tim Petersea5962f2007-03-12 18:07:52 +00003888 test_main()