blob: a0f40f8418fe4d482a559062a3b0dae10fba5e49 [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 Foord07ef4872009-05-02 22:43:34 +00009from StringIO import StringIO
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +000010import __builtin__
Michael Foordb4a81c82009-05-29 20:33:46 +000011import os
Gregory P. Smith28399852009-03-31 16:54:10 +000012import re
Michael Foordb4a81c82009-05-29 20:33:46 +000013import sys
Georg Brandl15c5ce92007-03-07 09:09:40 +000014from test import test_support
Jim Fultonfafd8742004-08-28 15:22:12 +000015import unittest
Michael Foord829f6b82009-05-02 11:43:06 +000016from unittest import TestCase, TestProgram
Christian Heimesc756d002007-11-27 21:34:01 +000017import types
Michael Foorde2942d02009-04-02 05:51:54 +000018from copy import deepcopy
Michael Foord829f6b82009-05-02 11:43:06 +000019from cStringIO import StringIO
Antoine Pitrou0734c632009-11-10 20:49:30 +000020import pickle
Jim Fultonfafd8742004-08-28 15:22:12 +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):
275 load_tests_args.extend((loader, tests, pattern))
276 return tests
277 m.load_tests = load_tests
278
279 loader = unittest.TestLoader()
280 suite = loader.loadTestsFromModule(m)
281 self.assertEquals(load_tests_args, [loader, suite, None])
282
283 load_tests_args = []
284 suite = loader.loadTestsFromModule(m, use_load_tests=False)
285 self.assertEquals(load_tests_args, [])
286
Georg Brandl15c5ce92007-03-07 09:09:40 +0000287 ################################################################
288 ### /Tests for TestLoader.loadTestsFromModule()
Tim Petersea5962f2007-03-12 18:07:52 +0000289
Georg Brandl15c5ce92007-03-07 09:09:40 +0000290 ### Tests for TestLoader.loadTestsFromName()
291 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000292
Georg Brandl15c5ce92007-03-07 09:09:40 +0000293 # "The specifier name is a ``dotted name'' that may resolve either to
294 # a module, a test case class, a TestSuite instance, a test method
295 # within a test case class, or a callable object which returns a
296 # TestCase or TestSuite instance."
297 #
298 # Is ValueError raised in response to an empty name?
299 def test_loadTestsFromName__empty_name(self):
300 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000301
Georg Brandl15c5ce92007-03-07 09:09:40 +0000302 try:
303 loader.loadTestsFromName('')
304 except ValueError, e:
305 self.assertEqual(str(e), "Empty module name")
306 else:
307 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000308
Georg Brandl15c5ce92007-03-07 09:09:40 +0000309 # "The specifier name is a ``dotted name'' that may resolve either to
310 # a module, a test case class, a TestSuite instance, a test method
311 # within a test case class, or a callable object which returns a
312 # TestCase or TestSuite instance."
313 #
Tim Petersea5962f2007-03-12 18:07:52 +0000314 # What happens when the name contains invalid characters?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000315 def test_loadTestsFromName__malformed_name(self):
316 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000317
Georg Brandl15c5ce92007-03-07 09:09:40 +0000318 # XXX Should this raise ValueError or ImportError?
319 try:
320 loader.loadTestsFromName('abc () //')
321 except ValueError:
322 pass
323 except ImportError:
324 pass
325 else:
326 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000327
Georg Brandl15c5ce92007-03-07 09:09:40 +0000328 # "The specifier name is a ``dotted name'' that may resolve ... to a
329 # module"
330 #
Tim Petersea5962f2007-03-12 18:07:52 +0000331 # What happens when a module by that name can't be found?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000332 def test_loadTestsFromName__unknown_module_name(self):
333 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000334
Georg Brandl15c5ce92007-03-07 09:09:40 +0000335 try:
336 loader.loadTestsFromName('sdasfasfasdf')
337 except ImportError, e:
338 self.assertEqual(str(e), "No module named sdasfasfasdf")
339 else:
340 self.fail("TestLoader.loadTestsFromName failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000341
Georg Brandl15c5ce92007-03-07 09:09:40 +0000342 # "The specifier name is a ``dotted name'' that may resolve either to
343 # a module, a test case class, a TestSuite instance, a test method
344 # within a test case class, or a callable object which returns a
345 # TestCase or TestSuite instance."
346 #
Tim Petersea5962f2007-03-12 18:07:52 +0000347 # What happens when the module is found, but the attribute can't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000348 def test_loadTestsFromName__unknown_attr_name(self):
349 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000350
Georg Brandl15c5ce92007-03-07 09:09:40 +0000351 try:
352 loader.loadTestsFromName('unittest.sdasfasfasdf')
353 except AttributeError, e:
354 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
355 else:
356 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000357
Georg Brandl15c5ce92007-03-07 09:09:40 +0000358 # "The specifier name is a ``dotted name'' that may resolve either to
359 # a module, a test case class, a TestSuite instance, a test method
360 # within a test case class, or a callable object which returns a
361 # TestCase or TestSuite instance."
362 #
363 # What happens when we provide the module, but the attribute can't be
364 # found?
365 def test_loadTestsFromName__relative_unknown_name(self):
366 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000367
Georg Brandl15c5ce92007-03-07 09:09:40 +0000368 try:
369 loader.loadTestsFromName('sdasfasfasdf', unittest)
370 except AttributeError, e:
371 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
372 else:
373 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000374
Georg Brandl15c5ce92007-03-07 09:09:40 +0000375 # "The specifier name is a ``dotted name'' that may resolve either to
376 # a module, a test case class, a TestSuite instance, a test method
377 # within a test case class, or a callable object which returns a
378 # TestCase or TestSuite instance."
379 # ...
380 # "The method optionally resolves name relative to the given module"
381 #
382 # Does loadTestsFromName raise ValueError when passed an empty
383 # name relative to a provided module?
384 #
385 # XXX Should probably raise a ValueError instead of an AttributeError
386 def test_loadTestsFromName__relative_empty_name(self):
387 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000388
Georg Brandl15c5ce92007-03-07 09:09:40 +0000389 try:
390 loader.loadTestsFromName('', unittest)
391 except AttributeError, e:
392 pass
393 else:
394 self.fail("Failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000395
Georg Brandl15c5ce92007-03-07 09:09:40 +0000396 # "The specifier name is a ``dotted name'' that may resolve either to
397 # a module, a test case class, a TestSuite instance, a test method
398 # within a test case class, or a callable object which returns a
399 # TestCase or TestSuite instance."
400 # ...
401 # "The method optionally resolves name relative to the given module"
402 #
403 # What happens when an impossible name is given, relative to the provided
404 # `module`?
405 def test_loadTestsFromName__relative_malformed_name(self):
406 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000407
Georg Brandl15c5ce92007-03-07 09:09:40 +0000408 # XXX Should this raise AttributeError or ValueError?
409 try:
410 loader.loadTestsFromName('abc () //', unittest)
411 except ValueError:
412 pass
413 except AttributeError:
414 pass
415 else:
416 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
417
418 # "The method optionally resolves name relative to the given module"
419 #
420 # Does loadTestsFromName raise TypeError when the `module` argument
421 # isn't a module object?
422 #
423 # XXX Accepts the not-a-module object, ignorning the object's type
424 # This should raise an exception or the method name should be changed
425 #
426 # XXX Some people are relying on this, so keep it for now
427 def test_loadTestsFromName__relative_not_a_module(self):
428 class MyTestCase(unittest.TestCase):
429 def test(self):
430 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000431
Georg Brandl15c5ce92007-03-07 09:09:40 +0000432 class NotAModule(object):
433 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000434
Georg Brandl15c5ce92007-03-07 09:09:40 +0000435 loader = unittest.TestLoader()
436 suite = loader.loadTestsFromName('test_2', NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000437
Georg Brandl15c5ce92007-03-07 09:09:40 +0000438 reference = [MyTestCase('test')]
439 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000440
Georg Brandl15c5ce92007-03-07 09:09:40 +0000441 # "The specifier name is a ``dotted name'' that may resolve either to
442 # a module, a test case class, a TestSuite instance, a test method
443 # within a test case class, or a callable object which returns a
444 # TestCase or TestSuite instance."
445 #
446 # Does it raise an exception if the name resolves to an invalid
447 # object?
448 def test_loadTestsFromName__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000449 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000450 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000451
Georg Brandl15c5ce92007-03-07 09:09:40 +0000452 loader = unittest.TestLoader()
453 try:
454 loader.loadTestsFromName('testcase_1', m)
455 except TypeError:
456 pass
457 else:
458 self.fail("Should have raised TypeError")
459
460 # "The specifier name is a ``dotted name'' that may
461 # resolve either to ... a test case class"
462 def test_loadTestsFromName__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000463 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000464 class MyTestCase(unittest.TestCase):
465 def test(self):
466 pass
467 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000468
Georg Brandl15c5ce92007-03-07 09:09:40 +0000469 loader = unittest.TestLoader()
470 suite = loader.loadTestsFromName('testcase_1', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000471 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000472 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000473
Georg Brandl15c5ce92007-03-07 09:09:40 +0000474 # "The specifier name is a ``dotted name'' that may resolve either to
475 # a module, a test case class, a TestSuite instance, a test method
476 # within a test case class, or a callable object which returns a
477 # TestCase or TestSuite instance."
478 def test_loadTestsFromName__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000479 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000480 class MyTestCase(unittest.TestCase):
481 def test(self):
482 pass
483 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000484
Georg Brandl15c5ce92007-03-07 09:09:40 +0000485 loader = unittest.TestLoader()
486 suite = loader.loadTestsFromName('testsuite', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000487 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000488
Georg Brandl15c5ce92007-03-07 09:09:40 +0000489 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000490
Georg Brandl15c5ce92007-03-07 09:09:40 +0000491 # "The specifier name is a ``dotted name'' that may resolve ... to
492 # ... a test method within a test case class"
493 def test_loadTestsFromName__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000494 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000495 class MyTestCase(unittest.TestCase):
496 def test(self):
497 pass
498 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000499
Georg Brandl15c5ce92007-03-07 09:09:40 +0000500 loader = unittest.TestLoader()
501 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000502 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000503
Georg Brandl15c5ce92007-03-07 09:09:40 +0000504 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000505
Georg Brandl15c5ce92007-03-07 09:09:40 +0000506 # "The specifier name is a ``dotted name'' that may resolve either to
507 # a module, a test case class, a TestSuite instance, a test method
508 # within a test case class, or a callable object which returns a
509 # TestCase or TestSuite instance."
510 #
511 # Does loadTestsFromName() raise the proper exception when trying to
512 # resolve "a test method within a test case class" that doesn't exist
513 # for the given name (relative to a provided module)?
514 def test_loadTestsFromName__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000515 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000516 class MyTestCase(unittest.TestCase):
517 def test(self):
518 pass
519 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000520
Georg Brandl15c5ce92007-03-07 09:09:40 +0000521 loader = unittest.TestLoader()
522 try:
523 loader.loadTestsFromName('testcase_1.testfoo', m)
524 except AttributeError, e:
525 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
526 else:
527 self.fail("Failed to raise AttributeError")
528
529 # "The specifier name is a ``dotted name'' that may resolve ... to
530 # ... a callable object which returns a ... TestSuite instance"
531 def test_loadTestsFromName__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000532 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000533 testcase_1 = unittest.FunctionTestCase(lambda: None)
534 testcase_2 = unittest.FunctionTestCase(lambda: None)
535 def return_TestSuite():
536 return unittest.TestSuite([testcase_1, testcase_2])
537 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000538
Georg Brandl15c5ce92007-03-07 09:09:40 +0000539 loader = unittest.TestLoader()
540 suite = loader.loadTestsFromName('return_TestSuite', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000541 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000542 self.assertEqual(list(suite), [testcase_1, testcase_2])
Tim Petersea5962f2007-03-12 18:07:52 +0000543
Georg Brandl15c5ce92007-03-07 09:09:40 +0000544 # "The specifier name is a ``dotted name'' that may resolve ... to
545 # ... a callable object which returns a TestCase ... instance"
546 def test_loadTestsFromName__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000547 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000548 testcase_1 = unittest.FunctionTestCase(lambda: None)
549 def return_TestCase():
550 return testcase_1
551 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000552
Georg Brandl15c5ce92007-03-07 09:09:40 +0000553 loader = unittest.TestLoader()
554 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000555 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000556 self.assertEqual(list(suite), [testcase_1])
Tim Petersea5962f2007-03-12 18:07:52 +0000557
Georg Brandl15c5ce92007-03-07 09:09:40 +0000558 # "The specifier name is a ``dotted name'' that may resolve ... to
Michael Foord5a9719d2009-09-13 17:28:35 +0000559 # ... a callable object which returns a TestCase ... instance"
560 #*****************************************************************
561 #Override the suiteClass attribute to ensure that the suiteClass
562 #attribute is used
563 def test_loadTestsFromName__callable__TestCase_instance_ProperSuiteClass(self):
564 class SubTestSuite(unittest.TestSuite):
565 pass
566 m = types.ModuleType('m')
567 testcase_1 = unittest.FunctionTestCase(lambda: None)
568 def return_TestCase():
569 return testcase_1
570 m.return_TestCase = return_TestCase
571
572 loader = unittest.TestLoader()
573 loader.suiteClass = SubTestSuite
574 suite = loader.loadTestsFromName('return_TestCase', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000575 self.assertIsInstance(suite, loader.suiteClass)
Michael Foord5a9719d2009-09-13 17:28:35 +0000576 self.assertEqual(list(suite), [testcase_1])
577
578 # "The specifier name is a ``dotted name'' that may resolve ... to
579 # ... a test method within a test case class"
580 #*****************************************************************
581 #Override the suiteClass attribute to ensure that the suiteClass
582 #attribute is used
583 def test_loadTestsFromName__relative_testmethod_ProperSuiteClass(self):
584 class SubTestSuite(unittest.TestSuite):
585 pass
586 m = types.ModuleType('m')
587 class MyTestCase(unittest.TestCase):
588 def test(self):
589 pass
590 m.testcase_1 = MyTestCase
591
592 loader = unittest.TestLoader()
593 loader.suiteClass=SubTestSuite
594 suite = loader.loadTestsFromName('testcase_1.test', m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000595 self.assertIsInstance(suite, loader.suiteClass)
Michael Foord5a9719d2009-09-13 17:28:35 +0000596
597 self.assertEqual(list(suite), [MyTestCase('test')])
598
599 # "The specifier name is a ``dotted name'' that may resolve ... to
Georg Brandl15c5ce92007-03-07 09:09:40 +0000600 # ... a callable object which returns a TestCase or TestSuite instance"
601 #
602 # What happens if the callable returns something else?
603 def test_loadTestsFromName__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000604 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000605 def return_wrong():
606 return 6
607 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000608
Georg Brandl15c5ce92007-03-07 09:09:40 +0000609 loader = unittest.TestLoader()
610 try:
611 suite = loader.loadTestsFromName('return_wrong', m)
612 except TypeError:
613 pass
614 else:
615 self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000616
Georg Brandl15c5ce92007-03-07 09:09:40 +0000617 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +0000618 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +0000619 def test_loadTestsFromName__module_not_loaded(self):
620 # We're going to try to load this module as a side-effect, so it
621 # better not be loaded before we try.
622 #
623 # Why pick audioop? Google shows it isn't used very often, so there's
624 # a good chance that it won't be imported when this test is run
625 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +0000626
Georg Brandl15c5ce92007-03-07 09:09:40 +0000627 import sys
628 if module_name in sys.modules:
629 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000630
Georg Brandl15c5ce92007-03-07 09:09:40 +0000631 loader = unittest.TestLoader()
632 try:
633 suite = loader.loadTestsFromName(module_name)
634
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000635 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000636 self.assertEqual(list(suite), [])
637
638 # audioop should now be loaded, thanks to loadTestsFromName()
Ezio Melottiaa980582010-01-23 23:04:36 +0000639 self.assertIn(module_name, sys.modules)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000640 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000641 if module_name in sys.modules:
642 del sys.modules[module_name]
Georg Brandl15c5ce92007-03-07 09:09:40 +0000643
644 ################################################################
645 ### Tests for TestLoader.loadTestsFromName()
646
647 ### Tests for TestLoader.loadTestsFromNames()
648 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000649
Georg Brandl15c5ce92007-03-07 09:09:40 +0000650 # "Similar to loadTestsFromName(), but takes a sequence of names rather
651 # than a single name."
652 #
653 # What happens if that sequence of names is empty?
654 def test_loadTestsFromNames__empty_name_list(self):
655 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000656
Georg Brandl15c5ce92007-03-07 09:09:40 +0000657 suite = loader.loadTestsFromNames([])
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000658 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000659 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000660
Georg Brandl15c5ce92007-03-07 09:09:40 +0000661 # "Similar to loadTestsFromName(), but takes a sequence of names rather
662 # than a single name."
663 # ...
664 # "The method optionally resolves name relative to the given module"
665 #
666 # What happens if that sequence of names is empty?
667 #
668 # XXX Should this raise a ValueError or just return an empty TestSuite?
669 def test_loadTestsFromNames__relative_empty_name_list(self):
670 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000671
Georg Brandl15c5ce92007-03-07 09:09:40 +0000672 suite = loader.loadTestsFromNames([], unittest)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000673 self.assertIsInstance(suite, loader.suiteClass)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000674 self.assertEqual(list(suite), [])
675
676 # "The specifier name is a ``dotted name'' that may resolve either to
677 # a module, a test case class, a TestSuite instance, a test method
678 # within a test case class, or a callable object which returns a
679 # TestCase or TestSuite instance."
680 #
681 # Is ValueError raised in response to an empty name?
682 def test_loadTestsFromNames__empty_name(self):
683 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000684
Georg Brandl15c5ce92007-03-07 09:09:40 +0000685 try:
686 loader.loadTestsFromNames([''])
687 except ValueError, e:
688 self.assertEqual(str(e), "Empty module name")
689 else:
690 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000691
Georg Brandl15c5ce92007-03-07 09:09:40 +0000692 # "The specifier name is a ``dotted name'' that may resolve either to
693 # a module, a test case class, a TestSuite instance, a test method
694 # within a test case class, or a callable object which returns a
695 # TestCase or TestSuite instance."
696 #
Tim Petersea5962f2007-03-12 18:07:52 +0000697 # What happens when presented with an impossible module name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000698 def test_loadTestsFromNames__malformed_name(self):
699 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000700
Georg Brandl15c5ce92007-03-07 09:09:40 +0000701 # XXX Should this raise ValueError or ImportError?
702 try:
703 loader.loadTestsFromNames(['abc () //'])
704 except ValueError:
705 pass
706 except ImportError:
707 pass
708 else:
709 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000710
Georg Brandl15c5ce92007-03-07 09:09:40 +0000711 # "The specifier name is a ``dotted name'' that may resolve either to
712 # a module, a test case class, a TestSuite instance, a test method
713 # within a test case class, or a callable object which returns a
714 # TestCase or TestSuite instance."
715 #
Tim Petersea5962f2007-03-12 18:07:52 +0000716 # What happens when no module can be found for the given name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000717 def test_loadTestsFromNames__unknown_module_name(self):
718 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000719
Georg Brandl15c5ce92007-03-07 09:09:40 +0000720 try:
721 loader.loadTestsFromNames(['sdasfasfasdf'])
722 except ImportError, e:
723 self.assertEqual(str(e), "No module named sdasfasfasdf")
724 else:
725 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000726
Georg Brandl15c5ce92007-03-07 09:09:40 +0000727 # "The specifier name is a ``dotted name'' that may resolve either to
728 # a module, a test case class, a TestSuite instance, a test method
729 # within a test case class, or a callable object which returns a
730 # TestCase or TestSuite instance."
731 #
Tim Petersea5962f2007-03-12 18:07:52 +0000732 # What happens when the module can be found, but not the attribute?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000733 def test_loadTestsFromNames__unknown_attr_name(self):
734 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000735
Georg Brandl15c5ce92007-03-07 09:09:40 +0000736 try:
737 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
738 except AttributeError, e:
739 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
740 else:
741 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000742
Georg Brandl15c5ce92007-03-07 09:09:40 +0000743 # "The specifier name is a ``dotted name'' that may resolve either to
744 # a module, a test case class, a TestSuite instance, a test method
745 # within a test case class, or a callable object which returns a
746 # TestCase or TestSuite instance."
747 # ...
748 # "The method optionally resolves name relative to the given module"
749 #
750 # What happens when given an unknown attribute on a specified `module`
751 # argument?
752 def test_loadTestsFromNames__unknown_name_relative_1(self):
753 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000754
Georg Brandl15c5ce92007-03-07 09:09:40 +0000755 try:
756 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
757 except AttributeError, e:
758 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
759 else:
760 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000761
Georg Brandl15c5ce92007-03-07 09:09:40 +0000762 # "The specifier name is a ``dotted name'' that may resolve either to
763 # a module, a test case class, a TestSuite instance, a test method
764 # within a test case class, or a callable object which returns a
765 # TestCase or TestSuite instance."
766 # ...
767 # "The method optionally resolves name relative to the given module"
768 #
769 # Do unknown attributes (relative to a provided module) still raise an
Tim Petersea5962f2007-03-12 18:07:52 +0000770 # exception even in the presence of valid attribute names?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000771 def test_loadTestsFromNames__unknown_name_relative_2(self):
772 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000773
Georg Brandl15c5ce92007-03-07 09:09:40 +0000774 try:
775 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
776 except AttributeError, e:
777 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
778 else:
779 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
780
781 # "The specifier name is a ``dotted name'' that may resolve either to
782 # a module, a test case class, a TestSuite instance, a test method
783 # within a test case class, or a callable object which returns a
784 # TestCase or TestSuite instance."
785 # ...
786 # "The method optionally resolves name relative to the given module"
787 #
788 # What happens when faced with the empty string?
789 #
790 # XXX This currently raises AttributeError, though ValueError is probably
791 # more appropriate
792 def test_loadTestsFromNames__relative_empty_name(self):
793 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000794
Georg Brandl15c5ce92007-03-07 09:09:40 +0000795 try:
796 loader.loadTestsFromNames([''], unittest)
797 except AttributeError:
798 pass
799 else:
800 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000801
Georg Brandl15c5ce92007-03-07 09:09:40 +0000802 # "The specifier name is a ``dotted name'' that may resolve either to
803 # a module, a test case class, a TestSuite instance, a test method
804 # within a test case class, or a callable object which returns a
805 # TestCase or TestSuite instance."
806 # ...
807 # "The method optionally resolves name relative to the given module"
808 #
Tim Petersea5962f2007-03-12 18:07:52 +0000809 # What happens when presented with an impossible attribute name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000810 def test_loadTestsFromNames__relative_malformed_name(self):
811 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000812
Georg Brandl15c5ce92007-03-07 09:09:40 +0000813 # XXX Should this raise AttributeError or ValueError?
814 try:
815 loader.loadTestsFromNames(['abc () //'], unittest)
816 except AttributeError:
817 pass
818 except ValueError:
819 pass
820 else:
821 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
822
823 # "The method optionally resolves name relative to the given module"
824 #
825 # Does loadTestsFromNames() make sure the provided `module` is in fact
826 # a module?
827 #
828 # XXX This validation is currently not done. This flexibility should
829 # either be documented or a TypeError should be raised.
830 def test_loadTestsFromNames__relative_not_a_module(self):
831 class MyTestCase(unittest.TestCase):
832 def test(self):
833 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000834
Georg Brandl15c5ce92007-03-07 09:09:40 +0000835 class NotAModule(object):
836 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000837
Georg Brandl15c5ce92007-03-07 09:09:40 +0000838 loader = unittest.TestLoader()
839 suite = loader.loadTestsFromNames(['test_2'], NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000840
Georg Brandl15c5ce92007-03-07 09:09:40 +0000841 reference = [unittest.TestSuite([MyTestCase('test')])]
842 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000843
Georg Brandl15c5ce92007-03-07 09:09:40 +0000844 # "The specifier name is a ``dotted name'' that may resolve either to
845 # a module, a test case class, a TestSuite instance, a test method
846 # within a test case class, or a callable object which returns a
847 # TestCase or TestSuite instance."
848 #
849 # Does it raise an exception if the name resolves to an invalid
850 # object?
851 def test_loadTestsFromNames__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000852 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000853 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000854
Georg Brandl15c5ce92007-03-07 09:09:40 +0000855 loader = unittest.TestLoader()
856 try:
857 loader.loadTestsFromNames(['testcase_1'], m)
858 except TypeError:
859 pass
860 else:
861 self.fail("Should have raised TypeError")
862
863 # "The specifier name is a ``dotted name'' that may resolve ... to
864 # ... a test case class"
865 def test_loadTestsFromNames__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000866 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000867 class MyTestCase(unittest.TestCase):
868 def test(self):
869 pass
870 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000871
Georg Brandl15c5ce92007-03-07 09:09:40 +0000872 loader = unittest.TestLoader()
873 suite = loader.loadTestsFromNames(['testcase_1'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000874 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000875
Georg Brandl15c5ce92007-03-07 09:09:40 +0000876 expected = loader.suiteClass([MyTestCase('test')])
877 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000878
Georg Brandl15c5ce92007-03-07 09:09:40 +0000879 # "The specifier name is a ``dotted name'' that may resolve ... to
880 # ... a TestSuite instance"
881 def test_loadTestsFromNames__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000882 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000883 class MyTestCase(unittest.TestCase):
884 def test(self):
885 pass
886 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000887
Georg Brandl15c5ce92007-03-07 09:09:40 +0000888 loader = unittest.TestLoader()
889 suite = loader.loadTestsFromNames(['testsuite'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000890 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000891
Georg Brandl15c5ce92007-03-07 09:09:40 +0000892 self.assertEqual(list(suite), [m.testsuite])
Tim Petersea5962f2007-03-12 18:07:52 +0000893
Georg Brandl15c5ce92007-03-07 09:09:40 +0000894 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
895 # test method within a test case class"
896 def test_loadTestsFromNames__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000897 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000898 class MyTestCase(unittest.TestCase):
899 def test(self):
900 pass
901 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000902
Georg Brandl15c5ce92007-03-07 09:09:40 +0000903 loader = unittest.TestLoader()
904 suite = loader.loadTestsFromNames(['testcase_1.test'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000905 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000906
Georg Brandl15c5ce92007-03-07 09:09:40 +0000907 ref_suite = unittest.TestSuite([MyTestCase('test')])
908 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000909
Georg Brandl15c5ce92007-03-07 09:09:40 +0000910 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
911 # test method within a test case class"
912 #
913 # Does the method gracefully handle names that initially look like they
Tim Petersea5962f2007-03-12 18:07:52 +0000914 # resolve to "a test method within a test case class" but don't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000915 def test_loadTestsFromNames__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000916 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000917 class MyTestCase(unittest.TestCase):
918 def test(self):
919 pass
920 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000921
Georg Brandl15c5ce92007-03-07 09:09:40 +0000922 loader = unittest.TestLoader()
923 try:
924 loader.loadTestsFromNames(['testcase_1.testfoo'], m)
925 except AttributeError, e:
926 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
927 else:
928 self.fail("Failed to raise AttributeError")
929
930 # "The specifier name is a ``dotted name'' that may resolve ... to
931 # ... a callable object which returns a ... TestSuite instance"
932 def test_loadTestsFromNames__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000933 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000934 testcase_1 = unittest.FunctionTestCase(lambda: None)
935 testcase_2 = unittest.FunctionTestCase(lambda: None)
936 def return_TestSuite():
937 return unittest.TestSuite([testcase_1, testcase_2])
938 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000939
Georg Brandl15c5ce92007-03-07 09:09:40 +0000940 loader = unittest.TestLoader()
941 suite = loader.loadTestsFromNames(['return_TestSuite'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000942 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000943
Georg Brandl15c5ce92007-03-07 09:09:40 +0000944 expected = unittest.TestSuite([testcase_1, testcase_2])
945 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000946
Georg Brandl15c5ce92007-03-07 09:09:40 +0000947 # "The specifier name is a ``dotted name'' that may resolve ... to
948 # ... a callable object which returns a TestCase ... instance"
949 def test_loadTestsFromNames__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000950 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000951 testcase_1 = unittest.FunctionTestCase(lambda: None)
952 def return_TestCase():
953 return testcase_1
954 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000955
Georg Brandl15c5ce92007-03-07 09:09:40 +0000956 loader = unittest.TestLoader()
957 suite = loader.loadTestsFromNames(['return_TestCase'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000958 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000959
Georg Brandl15c5ce92007-03-07 09:09:40 +0000960 ref_suite = unittest.TestSuite([testcase_1])
961 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000962
Georg Brandl15c5ce92007-03-07 09:09:40 +0000963 # "The specifier name is a ``dotted name'' that may resolve ... to
964 # ... a callable object which returns a TestCase or TestSuite instance"
965 #
Tim Petersea5962f2007-03-12 18:07:52 +0000966 # Are staticmethods handled correctly?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000967 def test_loadTestsFromNames__callable__call_staticmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000968 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000969 class Test1(unittest.TestCase):
970 def test(self):
971 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000972
Georg Brandl15c5ce92007-03-07 09:09:40 +0000973 testcase_1 = Test1('test')
974 class Foo(unittest.TestCase):
975 @staticmethod
976 def foo():
977 return testcase_1
978 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +0000979
Georg Brandl15c5ce92007-03-07 09:09:40 +0000980 loader = unittest.TestLoader()
981 suite = loader.loadTestsFromNames(['Foo.foo'], m)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000982 self.assertIsInstance(suite, loader.suiteClass)
Tim Petersea5962f2007-03-12 18:07:52 +0000983
Georg Brandl15c5ce92007-03-07 09:09:40 +0000984 ref_suite = unittest.TestSuite([testcase_1])
985 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000986
Georg Brandl15c5ce92007-03-07 09:09:40 +0000987 # "The specifier name is a ``dotted name'' that may resolve ... to
988 # ... a callable object which returns a TestCase or TestSuite instance"
989 #
990 # What happens when the callable returns something else?
991 def test_loadTestsFromNames__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000992 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000993 def return_wrong():
994 return 6
995 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000996
Georg Brandl15c5ce92007-03-07 09:09:40 +0000997 loader = unittest.TestLoader()
998 try:
999 suite = loader.loadTestsFromNames(['return_wrong'], m)
1000 except TypeError:
1001 pass
1002 else:
1003 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +00001004
Georg Brandl15c5ce92007-03-07 09:09:40 +00001005 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +00001006 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001007 def test_loadTestsFromNames__module_not_loaded(self):
1008 # We're going to try to load this module as a side-effect, so it
1009 # better not be loaded before we try.
1010 #
1011 # Why pick audioop? Google shows it isn't used very often, so there's
1012 # a good chance that it won't be imported when this test is run
1013 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +00001014
Georg Brandl15c5ce92007-03-07 09:09:40 +00001015 import sys
1016 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):
1963 import sys
Tim Petersea5962f2007-03-12 18:07:52 +00001964
Georg Brandl15c5ce92007-03-07 09:09:40 +00001965 class Foo(unittest.TestCase):
1966 def test_1(self):
1967 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001968
Georg Brandl15c5ce92007-03-07 09:09:40 +00001969 test = Foo('test_1')
1970 try:
1971 test.fail("foo")
1972 except:
1973 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00001974
Georg Brandl15c5ce92007-03-07 09:09:40 +00001975 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001976
Georg Brandl15c5ce92007-03-07 09:09:40 +00001977 result.startTest(test)
1978 result.addFailure(test, exc_info_tuple)
1979 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001980
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001981 self.assertFalse(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00001982 self.assertEqual(len(result.errors), 0)
1983 self.assertEqual(len(result.failures), 1)
1984 self.assertEqual(result.testsRun, 1)
1985 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001986
Georg Brandl15c5ce92007-03-07 09:09:40 +00001987 test_case, formatted_exc = result.failures[0]
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00001988 self.assertTrue(test_case is test)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001989 self.assertIsInstance(formatted_exc, str)
Tim Petersea5962f2007-03-12 18:07:52 +00001990
Georg Brandl15c5ce92007-03-07 09:09:40 +00001991 # "addError(test, err)"
1992 # ...
1993 # "Called when the test case test raises an unexpected exception err
1994 # is a tuple of the form returned by sys.exc_info():
1995 # (type, value, traceback)"
1996 # ...
1997 # "wasSuccessful() - Returns True if all tests run so far have passed,
1998 # otherwise returns False"
1999 # ...
2000 # "testsRun - The total number of tests run so far."
2001 # ...
2002 # "errors - A list containing 2-tuples of TestCase instances and
2003 # formatted tracebacks. Each tuple represents a test which raised an
2004 # unexpected exception. Contains formatted
2005 # tracebacks instead of sys.exc_info() results."
2006 # ...
2007 # "failures - A list containing 2-tuples of TestCase instances and
2008 # formatted tracebacks. Each tuple represents a test where a failure was
2009 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
2010 # methods. Contains formatted tracebacks instead
2011 # of sys.exc_info() results."
2012 def test_addError(self):
2013 import sys
Tim Petersea5962f2007-03-12 18:07:52 +00002014
Georg Brandl15c5ce92007-03-07 09:09:40 +00002015 class Foo(unittest.TestCase):
2016 def test_1(self):
2017 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002018
Georg Brandl15c5ce92007-03-07 09:09:40 +00002019 test = Foo('test_1')
2020 try:
2021 raise TypeError()
2022 except:
2023 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00002024
Georg Brandl15c5ce92007-03-07 09:09:40 +00002025 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00002026
Georg Brandl15c5ce92007-03-07 09:09:40 +00002027 result.startTest(test)
2028 result.addError(test, exc_info_tuple)
2029 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00002030
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002031 self.assertFalse(result.wasSuccessful())
Georg Brandl15c5ce92007-03-07 09:09:40 +00002032 self.assertEqual(len(result.errors), 1)
2033 self.assertEqual(len(result.failures), 0)
2034 self.assertEqual(result.testsRun, 1)
2035 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00002036
Georg Brandl15c5ce92007-03-07 09:09:40 +00002037 test_case, formatted_exc = result.errors[0]
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002038 self.assertTrue(test_case is test)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002039 self.assertIsInstance(formatted_exc, str)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002040
2041### Support code for Test_TestCase
2042################################################################
2043
2044class Foo(unittest.TestCase):
2045 def runTest(self): pass
2046 def test1(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002047
Georg Brandl15c5ce92007-03-07 09:09:40 +00002048class Bar(Foo):
2049 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002050
Michael Foord07ef4872009-05-02 22:43:34 +00002051class LoggingTestCase(unittest.TestCase):
2052 """A test case which logs its calls."""
2053
2054 def __init__(self, events):
2055 super(LoggingTestCase, self).__init__('test')
2056 self.events = events
2057
2058 def setUp(self):
2059 self.events.append('setUp')
2060
2061 def test(self):
2062 self.events.append('test')
2063
2064 def tearDown(self):
2065 self.events.append('tearDown')
2066
2067class ResultWithNoStartTestRunStopTestRun(object):
2068 """An object honouring TestResult before startTestRun/stopTestRun."""
2069
2070 def __init__(self):
2071 self.failures = []
2072 self.errors = []
2073 self.testsRun = 0
2074 self.skipped = []
2075 self.expectedFailures = []
2076 self.unexpectedSuccesses = []
2077 self.shouldStop = False
2078
2079 def startTest(self, test):
2080 pass
2081
2082 def stopTest(self, test):
2083 pass
2084
2085 def addError(self, test):
2086 pass
2087
2088 def addFailure(self, test):
2089 pass
2090
2091 def addSuccess(self, test):
2092 pass
2093
2094 def wasSuccessful(self):
2095 return True
2096
2097
Georg Brandl15c5ce92007-03-07 09:09:40 +00002098################################################################
2099### /Support code for Test_TestCase
2100
2101class Test_TestCase(TestCase, TestEquality, TestHashing):
2102
2103 ### Set up attributes used by inherited tests
2104 ################################################################
2105
2106 # Used by TestHashing.test_hash and TestEquality.test_eq
2107 eq_pairs = [(Foo('test1'), Foo('test1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002108
Georg Brandl15c5ce92007-03-07 09:09:40 +00002109 # Used by TestEquality.test_ne
2110 ne_pairs = [(Foo('test1'), Foo('runTest'))
2111 ,(Foo('test1'), Bar('test1'))
2112 ,(Foo('test1'), Bar('test2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002113
Georg Brandl15c5ce92007-03-07 09:09:40 +00002114 ################################################################
2115 ### /Set up attributes used by inherited tests
Tim Petersea5962f2007-03-12 18:07:52 +00002116
Georg Brandl15c5ce92007-03-07 09:09:40 +00002117
2118 # "class TestCase([methodName])"
2119 # ...
2120 # "Each instance of TestCase will run a single test method: the
2121 # method named methodName."
2122 # ...
2123 # "methodName defaults to "runTest"."
2124 #
2125 # Make sure it really is optional, and that it defaults to the proper
2126 # thing.
2127 def test_init__no_test_name(self):
2128 class Test(unittest.TestCase):
2129 def runTest(self): raise MyException()
2130 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002131
Georg Brandl15c5ce92007-03-07 09:09:40 +00002132 self.assertEqual(Test().id()[-13:], '.Test.runTest')
Tim Petersea5962f2007-03-12 18:07:52 +00002133
Georg Brandl15c5ce92007-03-07 09:09:40 +00002134 # "class TestCase([methodName])"
2135 # ...
2136 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002137 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002138 def test_init__test_name__valid(self):
2139 class Test(unittest.TestCase):
2140 def runTest(self): raise MyException()
2141 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002142
Georg Brandl15c5ce92007-03-07 09:09:40 +00002143 self.assertEqual(Test('test').id()[-10:], '.Test.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002144
Georg Brandl15c5ce92007-03-07 09:09:40 +00002145 # "class TestCase([methodName])"
2146 # ...
2147 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002148 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002149 def test_init__test_name__invalid(self):
2150 class Test(unittest.TestCase):
2151 def runTest(self): raise MyException()
2152 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002153
Georg Brandl15c5ce92007-03-07 09:09:40 +00002154 try:
2155 Test('testfoo')
2156 except ValueError:
2157 pass
2158 else:
2159 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +00002160
Georg Brandl15c5ce92007-03-07 09:09:40 +00002161 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00002162 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00002163 def test_countTestCases(self):
2164 class Foo(unittest.TestCase):
2165 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002166
Georg Brandl15c5ce92007-03-07 09:09:40 +00002167 self.assertEqual(Foo('test').countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00002168
Georg Brandl15c5ce92007-03-07 09:09:40 +00002169 # "Return the default type of test result object to be used to run this
2170 # test. For TestCase instances, this will always be
2171 # unittest.TestResult; subclasses of TestCase should
2172 # override this as necessary."
2173 def test_defaultTestResult(self):
2174 class Foo(unittest.TestCase):
2175 def runTest(self):
2176 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002177
Georg Brandl15c5ce92007-03-07 09:09:40 +00002178 result = Foo().defaultTestResult()
2179 self.assertEqual(type(result), unittest.TestResult)
2180
2181 # "When a setUp() method is defined, the test runner will run that method
2182 # prior to each test. Likewise, if a tearDown() method is defined, the
2183 # test runner will invoke that method after each test. In the example,
2184 # setUp() was used to create a fresh sequence for each test."
2185 #
2186 # Make sure the proper call order is maintained, even if setUp() raises
2187 # an exception.
2188 def test_run_call_order__error_in_setUp(self):
2189 events = []
2190 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002191
Michael Foord07ef4872009-05-02 22:43:34 +00002192 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002193 def setUp(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002194 super(Foo, self).setUp()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002195 raise RuntimeError('raised by Foo.setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002196
Michael Foord07ef4872009-05-02 22:43:34 +00002197 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002198 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2199 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002200
Michael Foord07ef4872009-05-02 22:43:34 +00002201 # "With a temporary result stopTestRun is called when setUp errors.
2202 def test_run_call_order__error_in_setUp_default_result(self):
2203 events = []
2204
2205 class Foo(LoggingTestCase):
2206 def defaultTestResult(self):
2207 return LoggingResult(self.events)
2208
2209 def setUp(self):
2210 super(Foo, self).setUp()
2211 raise RuntimeError('raised by Foo.setUp')
2212
2213 Foo(events).run()
2214 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2215 'stopTest', 'stopTestRun']
2216 self.assertEqual(events, expected)
2217
Georg Brandl15c5ce92007-03-07 09:09:40 +00002218 # "When a setUp() method is defined, the test runner will run that method
2219 # prior to each test. Likewise, if a tearDown() method is defined, the
2220 # test runner will invoke that method after each test. In the example,
2221 # setUp() was used to create a fresh sequence for each test."
2222 #
2223 # Make sure the proper call order is maintained, even if the test raises
2224 # an error (as opposed to a failure).
2225 def test_run_call_order__error_in_test(self):
2226 events = []
2227 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002228
Michael Foord07ef4872009-05-02 22:43:34 +00002229 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002230 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002231 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002232 raise RuntimeError('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002233
Georg Brandl15c5ce92007-03-07 09:09:40 +00002234 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2235 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002236 Foo(events).run(result)
2237 self.assertEqual(events, expected)
2238
2239 # "With a default result, an error in the test still results in stopTestRun
2240 # being called."
2241 def test_run_call_order__error_in_test_default_result(self):
2242 events = []
2243
2244 class Foo(LoggingTestCase):
2245 def defaultTestResult(self):
2246 return LoggingResult(self.events)
2247
2248 def test(self):
2249 super(Foo, self).test()
2250 raise RuntimeError('raised by Foo.test')
2251
2252 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2253 'tearDown', 'stopTest', 'stopTestRun']
2254 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002255 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002256
Georg Brandl15c5ce92007-03-07 09:09:40 +00002257 # "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 the test signals
2263 # a failure (as opposed to an error).
2264 def test_run_call_order__failure_in_test(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 test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002270 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002271 self.fail('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002272
Georg Brandl15c5ce92007-03-07 09:09:40 +00002273 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2274 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002275 Foo(events).run(result)
2276 self.assertEqual(events, expected)
2277
2278 # "When a test fails with a default result stopTestRun is still called."
2279 def test_run_call_order__failure_in_test_default_result(self):
2280
2281 class Foo(LoggingTestCase):
2282 def defaultTestResult(self):
2283 return LoggingResult(self.events)
2284 def test(self):
2285 super(Foo, self).test()
2286 self.fail('raised by Foo.test')
2287
2288 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2289 'tearDown', 'stopTest', 'stopTestRun']
2290 events = []
2291 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002292 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002293
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 tearDown() raises
2300 # an exception.
2301 def test_run_call_order__error_in_tearDown(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 tearDown(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002307 super(Foo, self).tearDown()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002308 raise RuntimeError('raised by Foo.tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002309
Michael Foord07ef4872009-05-02 22:43:34 +00002310 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002311 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2312 'stopTest']
2313 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002314
Michael Foord07ef4872009-05-02 22:43:34 +00002315 # "When tearDown errors with a default result stopTestRun is still called."
2316 def test_run_call_order__error_in_tearDown_default_result(self):
2317
2318 class Foo(LoggingTestCase):
2319 def defaultTestResult(self):
2320 return LoggingResult(self.events)
2321 def tearDown(self):
2322 super(Foo, self).tearDown()
2323 raise RuntimeError('raised by Foo.tearDown')
2324
2325 events = []
2326 Foo(events).run()
2327 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2328 'addError', 'stopTest', 'stopTestRun']
2329 self.assertEqual(events, expected)
2330
2331 # "TestCase.run() still works when the defaultTestResult is a TestResult
2332 # that does not support startTestRun and stopTestRun.
2333 def test_run_call_order_default_result(self):
2334
2335 class Foo(unittest.TestCase):
2336 def defaultTestResult(self):
2337 return ResultWithNoStartTestRunStopTestRun()
2338 def test(self):
2339 pass
2340
2341 Foo('test').run()
2342
Georg Brandl15c5ce92007-03-07 09:09:40 +00002343 # "This class attribute gives the exception raised by the test() method.
2344 # If a test framework needs to use a specialized exception, possibly to
2345 # carry additional information, it must subclass this exception in
2346 # order to ``play fair'' with the framework. The initial value of this
2347 # attribute is AssertionError"
2348 def test_failureException__default(self):
2349 class Foo(unittest.TestCase):
2350 def test(self):
2351 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002352
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002353 self.assertTrue(Foo('test').failureException is AssertionError)
Tim Petersea5962f2007-03-12 18:07:52 +00002354
Georg Brandl15c5ce92007-03-07 09:09:40 +00002355 # "This class attribute gives the exception raised by the test() method.
2356 # If a test framework needs to use a specialized exception, possibly to
2357 # carry additional information, it must subclass this exception in
2358 # order to ``play fair'' with the framework."
2359 #
2360 # Make sure TestCase.run() respects the designated failureException
2361 def test_failureException__subclassing__explicit_raise(self):
2362 events = []
2363 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002364
Georg Brandl15c5ce92007-03-07 09:09:40 +00002365 class Foo(unittest.TestCase):
2366 def test(self):
2367 raise RuntimeError()
Tim Petersea5962f2007-03-12 18:07:52 +00002368
Georg Brandl15c5ce92007-03-07 09:09:40 +00002369 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002370
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002371 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002372
2373
Georg Brandl15c5ce92007-03-07 09:09:40 +00002374 Foo('test').run(result)
2375 expected = ['startTest', 'addFailure', 'stopTest']
2376 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002377
Georg Brandl15c5ce92007-03-07 09:09:40 +00002378 # "This class attribute gives the exception raised by the test() method.
2379 # If a test framework needs to use a specialized exception, possibly to
2380 # carry additional information, it must subclass this exception in
2381 # order to ``play fair'' with the framework."
2382 #
2383 # Make sure TestCase.run() respects the designated failureException
2384 def test_failureException__subclassing__implicit_raise(self):
2385 events = []
2386 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002387
Georg Brandl15c5ce92007-03-07 09:09:40 +00002388 class Foo(unittest.TestCase):
2389 def test(self):
2390 self.fail("foo")
Tim Petersea5962f2007-03-12 18:07:52 +00002391
Georg Brandl15c5ce92007-03-07 09:09:40 +00002392 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002393
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00002394 self.assertTrue(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002395
2396
Georg Brandl15c5ce92007-03-07 09:09:40 +00002397 Foo('test').run(result)
2398 expected = ['startTest', 'addFailure', 'stopTest']
2399 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002400
2401 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002402 def test_setUp(self):
2403 class Foo(unittest.TestCase):
2404 def runTest(self):
2405 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002406
Georg Brandl15c5ce92007-03-07 09:09:40 +00002407 # ... and nothing should happen
2408 Foo().setUp()
Tim Petersea5962f2007-03-12 18:07:52 +00002409
2410 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002411 def test_tearDown(self):
2412 class Foo(unittest.TestCase):
2413 def runTest(self):
2414 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002415
Georg Brandl15c5ce92007-03-07 09:09:40 +00002416 # ... and nothing should happen
2417 Foo().tearDown()
Tim Petersea5962f2007-03-12 18:07:52 +00002418
Georg Brandl15c5ce92007-03-07 09:09:40 +00002419 # "Return a string identifying the specific test case."
2420 #
2421 # Because of the vague nature of the docs, I'm not going to lock this
2422 # test down too much. Really all that can be asserted is that the id()
2423 # will be a string (either 8-byte or unicode -- again, because the docs
2424 # just say "string")
2425 def test_id(self):
2426 class Foo(unittest.TestCase):
2427 def runTest(self):
2428 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002429
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002430 self.assertIsInstance(Foo().id(), basestring)
Tim Petersea5962f2007-03-12 18:07:52 +00002431
Georg Brandl15c5ce92007-03-07 09:09:40 +00002432 # "If result is omitted or None, a temporary result object is created
Michael Foord07ef4872009-05-02 22:43:34 +00002433 # and used, but is not made available to the caller. As TestCase owns the
2434 # temporary result startTestRun and stopTestRun are called.
2435
Georg Brandl15c5ce92007-03-07 09:09:40 +00002436 def test_run__uses_defaultTestResult(self):
2437 events = []
Tim Petersea5962f2007-03-12 18:07:52 +00002438
Georg Brandl15c5ce92007-03-07 09:09:40 +00002439 class Foo(unittest.TestCase):
2440 def test(self):
2441 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002442
Georg Brandl15c5ce92007-03-07 09:09:40 +00002443 def defaultTestResult(self):
2444 return LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002445
2446 # Make run() find a result object on its own
Georg Brandl15c5ce92007-03-07 09:09:40 +00002447 Foo('test').run()
Tim Petersea5962f2007-03-12 18:07:52 +00002448
Michael Foord07ef4872009-05-02 22:43:34 +00002449 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2450 'stopTest', 'stopTestRun']
Georg Brandl15c5ce92007-03-07 09:09:40 +00002451 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002452
Gregory P. Smith28399852009-03-31 16:54:10 +00002453 def testShortDescriptionWithoutDocstring(self):
2454 self.assertEqual(
2455 self.shortDescription(),
2456 'testShortDescriptionWithoutDocstring (' + __name__ +
2457 '.Test_TestCase)')
2458
2459 def testShortDescriptionWithOneLineDocstring(self):
2460 """Tests shortDescription() for a method with a docstring."""
2461 self.assertEqual(
2462 self.shortDescription(),
2463 ('testShortDescriptionWithOneLineDocstring '
2464 '(' + __name__ + '.Test_TestCase)\n'
2465 'Tests shortDescription() for a method with a docstring.'))
2466
2467 def testShortDescriptionWithMultiLineDocstring(self):
2468 """Tests shortDescription() for a method with a longer docstring.
2469
2470 This method ensures that only the first line of a docstring is
2471 returned used in the short description, no matter how long the
2472 whole thing is.
2473 """
2474 self.assertEqual(
2475 self.shortDescription(),
2476 ('testShortDescriptionWithMultiLineDocstring '
2477 '(' + __name__ + '.Test_TestCase)\n'
2478 'Tests shortDescription() for a method with a longer '
2479 'docstring.'))
2480
Gregory P. Smith28399852009-03-31 16:54:10 +00002481 def testAddTypeEqualityFunc(self):
2482 class SadSnake(object):
2483 """Dummy class for test_addTypeEqualityFunc."""
2484 s1, s2 = SadSnake(), SadSnake()
2485 self.assertFalse(s1 == s2)
2486 def AllSnakesCreatedEqual(a, b, msg=None):
2487 return type(a) == type(b) == SadSnake
2488 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2489 self.assertEqual(s1, s2)
2490 # No this doesn't clean up and remove the SadSnake equality func
2491 # from this TestCase instance but since its a local nothing else
2492 # will ever notice that.
2493
Michael Foordf2dfef12009-04-05 19:19:28 +00002494 def testAssertIs(self):
2495 thing = object()
2496 self.assertIs(thing, thing)
2497 self.assertRaises(self.failureException, self.assertIs, thing, object())
2498
2499 def testAssertIsNot(self):
2500 thing = object()
2501 self.assertIsNot(thing, object())
2502 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2503
Georg Brandlf895cf52009-10-01 20:59:31 +00002504 def testAssertIsInstance(self):
2505 thing = []
2506 self.assertIsInstance(thing, list)
2507 self.assertRaises(self.failureException, self.assertIsInstance,
2508 thing, dict)
2509
2510 def testAssertNotIsInstance(self):
2511 thing = []
2512 self.assertNotIsInstance(thing, dict)
2513 self.assertRaises(self.failureException, self.assertNotIsInstance,
2514 thing, list)
2515
Gregory P. Smith28399852009-03-31 16:54:10 +00002516 def testAssertIn(self):
2517 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2518
2519 self.assertIn('a', 'abc')
2520 self.assertIn(2, [1, 2, 3])
2521 self.assertIn('monkey', animals)
2522
2523 self.assertNotIn('d', 'abc')
2524 self.assertNotIn(0, [1, 2, 3])
2525 self.assertNotIn('otter', animals)
2526
2527 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2528 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2529 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2530 animals)
2531
2532 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2533 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2534 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2535 animals)
2536
2537 def testAssertDictContainsSubset(self):
2538 self.assertDictContainsSubset({}, {})
2539 self.assertDictContainsSubset({}, {'a': 1})
2540 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2541 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2542 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2543
2544 self.assertRaises(unittest.TestCase.failureException,
2545 self.assertDictContainsSubset, {'a': 2}, {'a': 1},
2546 '.*Mismatched values:.*')
2547
2548 self.assertRaises(unittest.TestCase.failureException,
2549 self.assertDictContainsSubset, {'c': 1}, {'a': 1},
2550 '.*Missing:.*')
2551
2552 self.assertRaises(unittest.TestCase.failureException,
2553 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2554 {'a': 1}, '.*Missing:.*')
2555
2556 self.assertRaises(unittest.TestCase.failureException,
2557 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2558 {'a': 1}, '.*Missing:.*Mismatched values:.*')
2559
2560 def testAssertEqual(self):
2561 equal_pairs = [
2562 ((), ()),
2563 ({}, {}),
2564 ([], []),
2565 (set(), set()),
2566 (frozenset(), frozenset())]
2567 for a, b in equal_pairs:
2568 # This mess of try excepts is to test the assertEqual behavior
2569 # itself.
2570 try:
2571 self.assertEqual(a, b)
2572 except self.failureException:
2573 self.fail('assertEqual(%r, %r) failed' % (a, b))
2574 try:
2575 self.assertEqual(a, b, msg='foo')
2576 except self.failureException:
2577 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2578 try:
2579 self.assertEqual(a, b, 'foo')
2580 except self.failureException:
2581 self.fail('assertEqual(%r, %r) with third parameter failed' %
2582 (a, b))
2583
2584 unequal_pairs = [
2585 ((), []),
2586 ({}, set()),
2587 (set([4,1]), frozenset([4,2])),
2588 (frozenset([4,5]), set([2,3])),
2589 (set([3,4]), set([5,4]))]
2590 for a, b in unequal_pairs:
2591 self.assertRaises(self.failureException, self.assertEqual, a, b)
2592 self.assertRaises(self.failureException, self.assertEqual, a, b,
2593 'foo')
2594 self.assertRaises(self.failureException, self.assertEqual, a, b,
2595 msg='foo')
2596
2597 def testEquality(self):
2598 self.assertListEqual([], [])
2599 self.assertTupleEqual((), ())
2600 self.assertSequenceEqual([], ())
2601
2602 a = [0, 'a', []]
2603 b = []
2604 self.assertRaises(unittest.TestCase.failureException,
2605 self.assertListEqual, a, b)
2606 self.assertRaises(unittest.TestCase.failureException,
2607 self.assertListEqual, tuple(a), tuple(b))
2608 self.assertRaises(unittest.TestCase.failureException,
2609 self.assertSequenceEqual, a, tuple(b))
2610
2611 b.extend(a)
2612 self.assertListEqual(a, b)
2613 self.assertTupleEqual(tuple(a), tuple(b))
2614 self.assertSequenceEqual(a, tuple(b))
2615 self.assertSequenceEqual(tuple(a), b)
2616
2617 self.assertRaises(self.failureException, self.assertListEqual,
2618 a, tuple(b))
2619 self.assertRaises(self.failureException, self.assertTupleEqual,
2620 tuple(a), b)
2621 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2622 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2623 tuple(b))
2624 self.assertRaises(self.failureException, self.assertSequenceEqual,
2625 None, tuple(b))
2626 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2627 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2628 self.assertRaises(self.failureException, self.assertSequenceEqual,
2629 1, 1)
2630
2631 self.assertDictEqual({}, {})
2632
2633 c = { 'x': 1 }
2634 d = {}
2635 self.assertRaises(unittest.TestCase.failureException,
2636 self.assertDictEqual, c, d)
2637
2638 d.update(c)
2639 self.assertDictEqual(c, d)
2640
2641 d['x'] = 0
2642 self.assertRaises(unittest.TestCase.failureException,
2643 self.assertDictEqual, c, d, 'These are unequal')
2644
2645 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2646 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2647 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2648
2649 self.assertSameElements([1, 2, 3], [3, 2, 1])
2650 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2651 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2652 self.assertRaises(self.failureException, self.assertSameElements,
2653 [10], [10, 11])
2654 self.assertRaises(self.failureException, self.assertSameElements,
2655 [10, 11], [10])
2656
2657 # Test that sequences of unhashable objects can be tested for sameness:
2658 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Michael Foordf2dfef12009-04-05 19:19:28 +00002659
Gregory P. Smith28399852009-03-31 16:54:10 +00002660 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2661 self.assertRaises(self.failureException, self.assertSameElements,
2662 [[1]], [[2]])
2663
2664 def testAssertSetEqual(self):
2665 set1 = set()
2666 set2 = set()
2667 self.assertSetEqual(set1, set2)
2668
2669 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2670 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2671 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2672 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2673
2674 set1 = set(['a'])
2675 set2 = set()
2676 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2677
2678 set1 = set(['a'])
2679 set2 = set(['a'])
2680 self.assertSetEqual(set1, set2)
2681
2682 set1 = set(['a'])
2683 set2 = set(['a', 'b'])
2684 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2685
2686 set1 = set(['a'])
2687 set2 = frozenset(['a', 'b'])
2688 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2689
2690 set1 = set(['a', 'b'])
2691 set2 = frozenset(['a', 'b'])
2692 self.assertSetEqual(set1, set2)
2693
2694 set1 = set()
2695 set2 = "foo"
2696 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2697 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2698
2699 # make sure any string formatting is tuple-safe
2700 set1 = set([(0, 1), (2, 3)])
2701 set2 = set([(4, 5)])
2702 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2703
2704 def testInequality(self):
2705 # Try ints
2706 self.assertGreater(2, 1)
2707 self.assertGreaterEqual(2, 1)
2708 self.assertGreaterEqual(1, 1)
2709 self.assertLess(1, 2)
2710 self.assertLessEqual(1, 2)
2711 self.assertLessEqual(1, 1)
2712 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2713 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2714 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2715 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2716 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2717 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2718
2719 # Try Floats
2720 self.assertGreater(1.1, 1.0)
2721 self.assertGreaterEqual(1.1, 1.0)
2722 self.assertGreaterEqual(1.0, 1.0)
2723 self.assertLess(1.0, 1.1)
2724 self.assertLessEqual(1.0, 1.1)
2725 self.assertLessEqual(1.0, 1.0)
2726 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2727 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2728 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2729 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2730 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2731 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2732
2733 # Try Strings
2734 self.assertGreater('bug', 'ant')
2735 self.assertGreaterEqual('bug', 'ant')
2736 self.assertGreaterEqual('ant', 'ant')
2737 self.assertLess('ant', 'bug')
2738 self.assertLessEqual('ant', 'bug')
2739 self.assertLessEqual('ant', 'ant')
2740 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2741 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2742 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2743 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2744 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2745 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2746
2747 # Try Unicode
2748 self.assertGreater(u'bug', u'ant')
2749 self.assertGreaterEqual(u'bug', u'ant')
2750 self.assertGreaterEqual(u'ant', u'ant')
2751 self.assertLess(u'ant', u'bug')
2752 self.assertLessEqual(u'ant', u'bug')
2753 self.assertLessEqual(u'ant', u'ant')
2754 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug')
2755 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant')
2756 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2757 u'bug')
2758 self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant')
2759 self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant')
2760 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant')
2761
2762 # Try Mixed String/Unicode
2763 self.assertGreater('bug', u'ant')
2764 self.assertGreater(u'bug', 'ant')
2765 self.assertGreaterEqual('bug', u'ant')
2766 self.assertGreaterEqual(u'bug', 'ant')
2767 self.assertGreaterEqual('ant', u'ant')
2768 self.assertGreaterEqual(u'ant', 'ant')
2769 self.assertLess('ant', u'bug')
2770 self.assertLess(u'ant', 'bug')
2771 self.assertLessEqual('ant', u'bug')
2772 self.assertLessEqual(u'ant', 'bug')
2773 self.assertLessEqual('ant', u'ant')
2774 self.assertLessEqual(u'ant', 'ant')
2775 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug')
2776 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug')
2777 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant')
2778 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant')
2779 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant',
2780 u'bug')
2781 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2782 'bug')
2783 self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant')
2784 self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant')
2785 self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant')
2786 self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant')
2787 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant')
2788 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant')
2789
2790 def testAssertMultiLineEqual(self):
2791 sample_text = b"""\
2792http://www.python.org/doc/2.3/lib/module-unittest.html
2793test case
2794 A test case is the smallest unit of testing. [...]
2795"""
2796 revised_sample_text = b"""\
2797http://www.python.org/doc/2.4.1/lib/module-unittest.html
2798test case
2799 A test case is the smallest unit of testing. [...] You may provide your
2800 own implementation that does not subclass from TestCase, of course.
2801"""
2802 sample_text_error = b"""
2803- http://www.python.org/doc/2.3/lib/module-unittest.html
2804? ^
2805+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2806? ^^^
2807 test case
2808- A test case is the smallest unit of testing. [...]
2809+ A test case is the smallest unit of testing. [...] You may provide your
2810? +++++++++++++++++++++
2811+ own implementation that does not subclass from TestCase, of course.
2812"""
2813
2814 for type_changer in (lambda x: x, lambda x: x.decode('utf8')):
2815 try:
2816 self.assertMultiLineEqual(type_changer(sample_text),
2817 type_changer(revised_sample_text))
2818 except self.failureException, e:
2819 # no fair testing ourself with ourself, use assertEqual..
2820 self.assertEqual(sample_text_error, str(e).encode('utf8'))
2821
2822 def testAssertIsNone(self):
2823 self.assertIsNone(None)
2824 self.assertRaises(self.failureException, self.assertIsNone, False)
2825 self.assertIsNotNone('DjZoPloGears on Rails')
2826 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2827
2828 def testAssertRegexpMatches(self):
2829 self.assertRegexpMatches('asdfabasdf', r'ab+')
2830 self.assertRaises(self.failureException, self.assertRegexpMatches,
2831 'saaas', r'aaaa')
2832
2833 def testAssertRaisesRegexp(self):
2834 class ExceptionMock(Exception):
2835 pass
2836
2837 def Stub():
2838 raise ExceptionMock('We expect')
2839
2840 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2841 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2842 self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
2843
2844 def testAssertNotRaisesRegexp(self):
2845 self.assertRaisesRegexp(
2846 self.failureException, '^Exception not raised$',
2847 self.assertRaisesRegexp, Exception, re.compile('x'),
2848 lambda: None)
2849 self.assertRaisesRegexp(
2850 self.failureException, '^Exception not raised$',
2851 self.assertRaisesRegexp, Exception, 'x',
2852 lambda: None)
2853 self.assertRaisesRegexp(
2854 self.failureException, '^Exception not raised$',
2855 self.assertRaisesRegexp, Exception, u'x',
2856 lambda: None)
2857
2858 def testAssertRaisesRegexpMismatch(self):
2859 def Stub():
2860 raise Exception('Unexpected')
2861
2862 self.assertRaisesRegexp(
2863 self.failureException,
2864 r'"\^Expected\$" does not match "Unexpected"',
2865 self.assertRaisesRegexp, Exception, '^Expected$',
2866 Stub)
2867 self.assertRaisesRegexp(
2868 self.failureException,
2869 r'"\^Expected\$" does not match "Unexpected"',
2870 self.assertRaisesRegexp, Exception, u'^Expected$',
2871 Stub)
2872 self.assertRaisesRegexp(
2873 self.failureException,
2874 r'"\^Expected\$" does not match "Unexpected"',
2875 self.assertRaisesRegexp, Exception,
2876 re.compile('^Expected$'), Stub)
2877
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00002878 def testAssertRaisesExcValue(self):
2879 class ExceptionMock(Exception):
2880 pass
2881
2882 def Stub(foo):
2883 raise ExceptionMock(foo)
2884 v = "particular value"
2885
2886 ctx = self.assertRaises(ExceptionMock)
2887 with ctx:
2888 Stub(v)
2889 e = ctx.exc_value
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002890 self.assertIsInstance(e, ExceptionMock)
Kristján Valur Jónssone2a77982009-08-27 22:20:21 +00002891 self.assertEqual(e.args[0], v)
2892
Gregory P. Smith7558d572009-03-31 19:03:28 +00002893 def testSynonymAssertMethodNames(self):
2894 """Test undocumented method name synonyms.
2895
2896 Please do not use these methods names in your own code.
2897
2898 This test confirms their continued existence and functionality
2899 in order to avoid breaking existing code.
2900 """
2901 self.assertNotEquals(3, 5)
2902 self.assertEquals(3, 3)
2903 self.assertAlmostEquals(2.0, 2.0)
2904 self.assertNotAlmostEquals(3.0, 5.0)
2905 self.assert_(True)
2906
2907 def testPendingDeprecationMethodNames(self):
2908 """Test fail* methods pending deprecation, they will warn in 3.2.
2909
2910 Do not use these methods. They will go away in 3.3.
2911 """
2912 self.failIfEqual(3, 5)
2913 self.failUnlessEqual(3, 3)
2914 self.failUnlessAlmostEqual(2.0, 2.0)
2915 self.failIfAlmostEqual(3.0, 5.0)
2916 self.failUnless(True)
2917 self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam')
2918 self.failIf(False)
2919
Michael Foorde2942d02009-04-02 05:51:54 +00002920 def testDeepcopy(self):
2921 # Issue: 5660
2922 class TestableTest(TestCase):
2923 def testNothing(self):
2924 pass
2925
2926 test = TestableTest('testNothing')
2927
2928 # This shouldn't blow up
2929 deepcopy(test)
2930
Benjamin Peterson692428e2009-03-23 21:50:21 +00002931
2932class Test_TestSkipping(TestCase):
2933
2934 def test_skipping(self):
2935 class Foo(unittest.TestCase):
2936 def test_skip_me(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002937 self.skipTest("skip")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002938 events = []
2939 result = LoggingResult(events)
2940 test = Foo("test_skip_me")
2941 test.run(result)
2942 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2943 self.assertEqual(result.skipped, [(test, "skip")])
2944
2945 # Try letting setUp skip the test now.
2946 class Foo(unittest.TestCase):
2947 def setUp(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002948 self.skipTest("testing")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002949 def test_nothing(self): pass
2950 events = []
2951 result = LoggingResult(events)
2952 test = Foo("test_nothing")
2953 test.run(result)
2954 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2955 self.assertEqual(result.skipped, [(test, "testing")])
2956 self.assertEqual(result.testsRun, 1)
2957
2958 def test_skipping_decorators(self):
2959 op_table = ((unittest.skipUnless, False, True),
2960 (unittest.skipIf, True, False))
2961 for deco, do_skip, dont_skip in op_table:
2962 class Foo(unittest.TestCase):
2963 @deco(do_skip, "testing")
2964 def test_skip(self): pass
2965
2966 @deco(dont_skip, "testing")
2967 def test_dont_skip(self): pass
2968 test_do_skip = Foo("test_skip")
2969 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002970 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002971 events = []
2972 result = LoggingResult(events)
2973 suite.run(result)
2974 self.assertEqual(len(result.skipped), 1)
2975 expected = ['startTest', 'addSkip', 'stopTest',
2976 'startTest', 'addSuccess', 'stopTest']
2977 self.assertEqual(events, expected)
2978 self.assertEqual(result.testsRun, 2)
2979 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
2980 self.assertTrue(result.wasSuccessful())
2981
2982 def test_skip_class(self):
2983 @unittest.skip("testing")
2984 class Foo(unittest.TestCase):
2985 def test_1(self):
2986 record.append(1)
2987 record = []
2988 result = unittest.TestResult()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002989 test = Foo("test_1")
2990 suite = unittest.TestSuite([test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002991 suite.run(result)
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002992 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002993 self.assertEqual(record, [])
2994
2995 def test_expected_failure(self):
2996 class Foo(unittest.TestCase):
2997 @unittest.expectedFailure
2998 def test_die(self):
2999 self.fail("help me!")
3000 events = []
3001 result = LoggingResult(events)
3002 test = Foo("test_die")
3003 test.run(result)
3004 self.assertEqual(events,
3005 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003006 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00003007 self.assertTrue(result.wasSuccessful())
3008
3009 def test_unexpected_success(self):
3010 class Foo(unittest.TestCase):
3011 @unittest.expectedFailure
3012 def test_die(self):
3013 pass
3014 events = []
3015 result = LoggingResult(events)
3016 test = Foo("test_die")
3017 test.run(result)
3018 self.assertEqual(events,
3019 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
3020 self.assertFalse(result.failures)
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00003021 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00003022 self.assertTrue(result.wasSuccessful())
3023
3024
3025
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003026class Test_Assertions(TestCase):
3027 def test_AlmostEqual(self):
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003028 self.assertAlmostEqual(1.00000001, 1.0)
3029 self.assertNotAlmostEqual(1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003030 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003031 self.assertAlmostEqual, 1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003032 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003033 self.assertNotAlmostEqual, 1.00000001, 1.0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003034
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003035 self.assertAlmostEqual(1.1, 1.0, places=0)
Gregory P. Smith28399852009-03-31 16:54:10 +00003036 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003037 self.assertAlmostEqual, 1.1, 1.0, places=1)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003038
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003039 self.assertAlmostEqual(0, .1+.1j, places=0)
3040 self.assertNotAlmostEqual(0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003041 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003042 self.assertAlmostEqual, 0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00003043 self.assertRaises(self.failureException,
Benjamin Peterson6b0032f2009-06-30 23:30:12 +00003044 self.assertNotAlmostEqual, 0, .1+.1j, places=0)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003045
Michael Foordc3f79372009-09-13 16:40:02 +00003046 self.assertAlmostEqual(float('inf'), float('inf'))
3047 self.assertRaises(self.failureException, self.assertNotAlmostEqual,
3048 float('inf'), float('inf'))
3049
3050
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003051 def test_assertRaises(self):
3052 def _raise(e):
3053 raise e
3054 self.assertRaises(KeyError, _raise, KeyError)
3055 self.assertRaises(KeyError, _raise, KeyError("key"))
3056 try:
3057 self.assertRaises(KeyError, lambda: None)
Gregory P. Smith28399852009-03-31 16:54:10 +00003058 except self.failureException as e:
Ezio Melottiaa980582010-01-23 23:04:36 +00003059 self.assertIn("KeyError not raised", e)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003060 else:
3061 self.fail("assertRaises() didn't fail")
3062 try:
3063 self.assertRaises(KeyError, _raise, ValueError)
3064 except ValueError:
3065 pass
3066 else:
3067 self.fail("assertRaises() didn't let exception pass through")
3068 with self.assertRaises(KeyError):
3069 raise KeyError
3070 with self.assertRaises(KeyError):
3071 raise KeyError("key")
3072 try:
3073 with self.assertRaises(KeyError):
3074 pass
Gregory P. Smith28399852009-03-31 16:54:10 +00003075 except self.failureException as e:
Ezio Melottiaa980582010-01-23 23:04:36 +00003076 self.assertIn("KeyError not raised", e)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003077 else:
3078 self.fail("assertRaises() didn't fail")
3079 try:
3080 with self.assertRaises(KeyError):
3081 raise ValueError
3082 except ValueError:
3083 pass
3084 else:
3085 self.fail("assertRaises() didn't let exception pass through")
3086
3087
Michael Foord345b2fe2009-04-02 03:20:38 +00003088class TestLongMessage(TestCase):
3089 """Test that the individual asserts honour longMessage.
3090 This actually tests all the message behaviour for
3091 asserts that use longMessage."""
3092
3093 def setUp(self):
3094 class TestableTestFalse(TestCase):
3095 longMessage = False
3096 failureException = self.failureException
3097
3098 def testTest(self):
3099 pass
3100
3101 class TestableTestTrue(TestCase):
3102 longMessage = True
3103 failureException = self.failureException
3104
3105 def testTest(self):
3106 pass
3107
3108 self.testableTrue = TestableTestTrue('testTest')
3109 self.testableFalse = TestableTestFalse('testTest')
3110
3111 def testDefault(self):
3112 self.assertFalse(TestCase.longMessage)
3113
3114 def test_formatMsg(self):
3115 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3116 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3117
3118 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3119 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3120
3121 def assertMessages(self, methodName, args, errors):
3122 def getMethod(i):
3123 useTestableFalse = i < 2
3124 if useTestableFalse:
3125 test = self.testableFalse
3126 else:
3127 test = self.testableTrue
3128 return getattr(test, methodName)
3129
3130 for i, expected_regexp in enumerate(errors):
3131 testMethod = getMethod(i)
3132 kwargs = {}
3133 withMsg = i % 2
3134 if withMsg:
3135 kwargs = {"msg": "oops"}
3136
3137 with self.assertRaisesRegexp(self.failureException,
3138 expected_regexp=expected_regexp):
3139 testMethod(*args, **kwargs)
3140
3141 def testAssertTrue(self):
3142 self.assertMessages('assertTrue', (False,),
3143 ["^False is not True$", "^oops$", "^False is not True$",
3144 "^False is not True : oops$"])
3145
3146 def testAssertFalse(self):
3147 self.assertMessages('assertFalse', (True,),
3148 ["^True is not False$", "^oops$", "^True is not False$",
3149 "^True is not False : oops$"])
3150
3151 def testNotEqual(self):
3152 self.assertMessages('assertNotEqual', (1, 1),
3153 ["^1 == 1$", "^oops$", "^1 == 1$",
3154 "^1 == 1 : oops$"])
3155
3156 def testAlmostEqual(self):
3157 self.assertMessages('assertAlmostEqual', (1, 2),
3158 ["^1 != 2 within 7 places$", "^oops$",
3159 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3160
3161 def testNotAlmostEqual(self):
3162 self.assertMessages('assertNotAlmostEqual', (1, 1),
3163 ["^1 == 1 within 7 places$", "^oops$",
3164 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3165
3166 def test_baseAssertEqual(self):
3167 self.assertMessages('_baseAssertEqual', (1, 2),
3168 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3169
3170 def testAssertSequenceEqual(self):
3171 # Error messages are multiline so not testing on full message
3172 # assertTupleEqual and assertListEqual delegate to this method
3173 self.assertMessages('assertSequenceEqual', ([], [None]),
3174 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3175 r"\+ \[None\] : oops$"])
3176
3177 def testAssertSetEqual(self):
3178 self.assertMessages('assertSetEqual', (set(), set([None])),
3179 ["None$", "^oops$", "None$",
3180 "None : oops$"])
3181
3182 def testAssertIn(self):
3183 self.assertMessages('assertIn', (None, []),
3184 ['^None not found in \[\]$', "^oops$",
3185 '^None not found in \[\]$',
3186 '^None not found in \[\] : oops$'])
3187
3188 def testAssertNotIn(self):
3189 self.assertMessages('assertNotIn', (None, [None]),
3190 ['^None unexpectedly found in \[None\]$', "^oops$",
3191 '^None unexpectedly found in \[None\]$',
3192 '^None unexpectedly found in \[None\] : oops$'])
3193
3194 def testAssertDictEqual(self):
3195 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3196 [r"\+ \{'key': 'value'\}$", "^oops$",
3197 "\+ \{'key': 'value'\}$",
3198 "\+ \{'key': 'value'\} : oops$"])
3199
3200 def testAssertDictContainsSubset(self):
3201 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3202 ["^Missing: 'key'$", "^oops$",
3203 "^Missing: 'key'$",
3204 "^Missing: 'key' : oops$"])
3205
3206 def testAssertSameElements(self):
3207 self.assertMessages('assertSameElements', ([], [None]),
3208 [r"\[None\]$", "^oops$",
3209 r"\[None\]$",
3210 r"\[None\] : oops$"])
3211
3212 def testAssertMultiLineEqual(self):
3213 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3214 [r"\+ foo$", "^oops$",
3215 r"\+ foo$",
3216 r"\+ foo : oops$"])
3217
3218 def testAssertLess(self):
3219 self.assertMessages('assertLess', (2, 1),
3220 ["^2 not less than 1$", "^oops$",
3221 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3222
3223 def testAssertLessEqual(self):
3224 self.assertMessages('assertLessEqual', (2, 1),
3225 ["^2 not less than or equal to 1$", "^oops$",
3226 "^2 not less than or equal to 1$",
3227 "^2 not less than or equal to 1 : oops$"])
3228
3229 def testAssertGreater(self):
3230 self.assertMessages('assertGreater', (1, 2),
3231 ["^1 not greater than 2$", "^oops$",
3232 "^1 not greater than 2$",
3233 "^1 not greater than 2 : oops$"])
3234
3235 def testAssertGreaterEqual(self):
3236 self.assertMessages('assertGreaterEqual', (1, 2),
3237 ["^1 not greater than or equal to 2$", "^oops$",
3238 "^1 not greater than or equal to 2$",
3239 "^1 not greater than or equal to 2 : oops$"])
3240
3241 def testAssertIsNone(self):
3242 self.assertMessages('assertIsNone', ('not None',),
3243 ["^'not None' is not None$", "^oops$",
3244 "^'not None' is not None$",
3245 "^'not None' is not None : oops$"])
3246
3247 def testAssertIsNotNone(self):
3248 self.assertMessages('assertIsNotNone', (None,),
3249 ["^unexpectedly None$", "^oops$",
3250 "^unexpectedly None$",
3251 "^unexpectedly None : oops$"])
3252
Michael Foordf2dfef12009-04-05 19:19:28 +00003253 def testAssertIs(self):
3254 self.assertMessages('assertIs', (None, 'foo'),
3255 ["^None is not 'foo'$", "^oops$",
3256 "^None is not 'foo'$",
3257 "^None is not 'foo' : oops$"])
3258
3259 def testAssertIsNot(self):
3260 self.assertMessages('assertIsNot', (None, None),
3261 ["^unexpectedly identical: None$", "^oops$",
3262 "^unexpectedly identical: None$",
3263 "^unexpectedly identical: None : oops$"])
3264
Michael Foord345b2fe2009-04-02 03:20:38 +00003265
Michael Foorde2fb98f2009-05-02 20:15:05 +00003266class TestCleanUp(TestCase):
3267
3268 def testCleanUp(self):
3269 class TestableTest(TestCase):
3270 def testNothing(self):
3271 pass
3272
3273 test = TestableTest('testNothing')
3274 self.assertEqual(test._cleanups, [])
3275
3276 cleanups = []
3277
3278 def cleanup1(*args, **kwargs):
3279 cleanups.append((1, args, kwargs))
3280
3281 def cleanup2(*args, **kwargs):
3282 cleanups.append((2, args, kwargs))
3283
3284 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3285 test.addCleanup(cleanup2)
3286
3287 self.assertEqual(test._cleanups,
3288 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3289 (cleanup2, (), {})])
3290
3291 result = test.doCleanups()
3292 self.assertTrue(result)
3293
3294 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3295
3296 def testCleanUpWithErrors(self):
3297 class TestableTest(TestCase):
3298 def testNothing(self):
3299 pass
3300
3301 class MockResult(object):
3302 errors = []
3303 def addError(self, test, exc_info):
3304 self.errors.append((test, exc_info))
3305
3306 result = MockResult()
3307 test = TestableTest('testNothing')
Michael Foorda50af062009-05-21 22:57:02 +00003308 test._resultForDoCleanups = result
Michael Foorde2fb98f2009-05-02 20:15:05 +00003309
3310 exc1 = Exception('foo')
3311 exc2 = Exception('bar')
3312 def cleanup1():
3313 raise exc1
3314
3315 def cleanup2():
3316 raise exc2
3317
3318 test.addCleanup(cleanup1)
3319 test.addCleanup(cleanup2)
3320
3321 self.assertFalse(test.doCleanups())
3322
3323 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3324 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3325 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3326
3327 def testCleanupInRun(self):
3328 blowUp = False
3329 ordering = []
3330
3331 class TestableTest(TestCase):
3332 def setUp(self):
3333 ordering.append('setUp')
3334 if blowUp:
3335 raise Exception('foo')
3336
3337 def testNothing(self):
3338 ordering.append('test')
3339
3340 def tearDown(self):
3341 ordering.append('tearDown')
3342
3343 test = TestableTest('testNothing')
3344
3345 def cleanup1():
3346 ordering.append('cleanup1')
3347 def cleanup2():
3348 ordering.append('cleanup2')
3349 test.addCleanup(cleanup1)
3350 test.addCleanup(cleanup2)
3351
3352 def success(some_test):
3353 self.assertEqual(some_test, test)
3354 ordering.append('success')
3355
3356 result = unittest.TestResult()
3357 result.addSuccess = success
3358
3359 test.run(result)
3360 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3361 'cleanup2', 'cleanup1', 'success'])
3362
3363 blowUp = True
3364 ordering = []
3365 test = TestableTest('testNothing')
3366 test.addCleanup(cleanup1)
3367 test.run(result)
3368 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3369
3370
Michael Foord829f6b82009-05-02 11:43:06 +00003371class Test_TestProgram(TestCase):
3372
3373 # Horrible white box test
3374 def testNoExit(self):
3375 result = object()
3376 test = object()
3377
3378 class FakeRunner(object):
3379 def run(self, test):
3380 self.test = test
3381 return result
3382
3383 runner = FakeRunner()
3384
Michael Foord5d31e052009-05-11 17:59:43 +00003385 oldParseArgs = TestProgram.parseArgs
3386 def restoreParseArgs():
Michael Foord829f6b82009-05-02 11:43:06 +00003387 TestProgram.parseArgs = oldParseArgs
Michael Foord5d31e052009-05-11 17:59:43 +00003388 TestProgram.parseArgs = lambda *args: None
3389 self.addCleanup(restoreParseArgs)
3390
3391 def removeTest():
Michael Foord829f6b82009-05-02 11:43:06 +00003392 del TestProgram.test
Michael Foord5d31e052009-05-11 17:59:43 +00003393 TestProgram.test = test
3394 self.addCleanup(removeTest)
3395
3396 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3397
3398 self.assertEqual(program.result, result)
3399 self.assertEqual(runner.test, test)
3400 self.assertEqual(program.verbosity, 2)
Michael Foord829f6b82009-05-02 11:43:06 +00003401
Michael Foord829f6b82009-05-02 11:43:06 +00003402 class FooBar(unittest.TestCase):
3403 def testPass(self):
3404 assert True
3405 def testFail(self):
3406 assert False
3407
3408 class FooBarLoader(unittest.TestLoader):
3409 """Test loader that returns a suite containing FooBar."""
3410 def loadTestsFromModule(self, module):
3411 return self.suiteClass(
3412 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3413
3414
3415 def test_NonExit(self):
3416 program = unittest.main(exit=False,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003417 argv=["foobar"],
3418 testRunner=unittest.TextTestRunner(stream=StringIO()),
3419 testLoader=self.FooBarLoader())
Michael Foord829f6b82009-05-02 11:43:06 +00003420 self.assertTrue(hasattr(program, 'result'))
3421
3422
3423 def test_Exit(self):
3424 self.assertRaises(
3425 SystemExit,
3426 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003427 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003428 testRunner=unittest.TextTestRunner(stream=StringIO()),
3429 exit=True,
3430 testLoader=self.FooBarLoader())
3431
3432
3433 def test_ExitAsDefault(self):
3434 self.assertRaises(
3435 SystemExit,
3436 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003437 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003438 testRunner=unittest.TextTestRunner(stream=StringIO()),
3439 testLoader=self.FooBarLoader())
3440
3441
Michael Foord07ef4872009-05-02 22:43:34 +00003442class Test_TextTestRunner(TestCase):
3443 """Tests for TextTestRunner."""
3444
3445 def test_works_with_result_without_startTestRun_stopTestRun(self):
3446 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3447 separator2 = ''
3448 def printErrors(self):
3449 pass
3450
3451 class Runner(unittest.TextTestRunner):
3452 def __init__(self):
3453 super(Runner, self).__init__(StringIO())
3454
3455 def _makeResult(self):
3456 return OldTextResult()
3457
3458 runner = Runner()
3459 runner.run(unittest.TestSuite())
3460
3461 def test_startTestRun_stopTestRun_called(self):
3462 class LoggingTextResult(LoggingResult):
3463 separator2 = ''
3464 def printErrors(self):
3465 pass
3466
3467 class LoggingRunner(unittest.TextTestRunner):
3468 def __init__(self, events):
3469 super(LoggingRunner, self).__init__(StringIO())
3470 self._events = events
3471
3472 def _makeResult(self):
3473 return LoggingTextResult(self._events)
3474
3475 events = []
3476 runner = LoggingRunner(events)
3477 runner.run(unittest.TestSuite())
3478 expected = ['startTestRun', 'stopTestRun']
3479 self.assertEqual(events, expected)
3480
Antoine Pitrou0734c632009-11-10 20:49:30 +00003481 def test_pickle_unpickle(self):
3482 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
3483 # required by test_multiprocessing under Windows (in verbose mode).
3484 import StringIO
3485 # cStringIO objects are not pickleable, but StringIO objects are.
3486 stream = StringIO.StringIO("foo")
3487 runner = unittest.TextTestRunner(stream)
3488 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
3489 s = pickle.dumps(runner, protocol=protocol)
3490 obj = pickle.loads(s)
3491 # StringIO objects never compare equal, a cheap test instead.
3492 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
3493
Michael Foord07ef4872009-05-02 22:43:34 +00003494
Michael Foordb4a81c82009-05-29 20:33:46 +00003495class TestDiscovery(TestCase):
3496
3497 # Heavily mocked tests so I can avoid hitting the filesystem
Michael Foorde91ea562009-09-13 19:07:03 +00003498 def test_get_name_from_path(self):
Michael Foordb4a81c82009-05-29 20:33:46 +00003499 loader = unittest.TestLoader()
3500
Michael Foordb4a81c82009-05-29 20:33:46 +00003501 loader._top_level_dir = '/foo'
Michael Foorde91ea562009-09-13 19:07:03 +00003502 name = loader._get_name_from_path('/foo/bar/baz.py')
3503 self.assertEqual(name, 'bar.baz')
Michael Foordb4a81c82009-05-29 20:33:46 +00003504
3505 if not __debug__:
3506 # asserts are off
3507 return
3508
3509 with self.assertRaises(AssertionError):
Michael Foorde91ea562009-09-13 19:07:03 +00003510 loader._get_name_from_path('/bar/baz.py')
Michael Foordb4a81c82009-05-29 20:33:46 +00003511
3512 def test_find_tests(self):
3513 loader = unittest.TestLoader()
3514
3515 original_listdir = os.listdir
3516 def restore_listdir():
3517 os.listdir = original_listdir
3518 original_isfile = os.path.isfile
3519 def restore_isfile():
3520 os.path.isfile = original_isfile
3521 original_isdir = os.path.isdir
3522 def restore_isdir():
3523 os.path.isdir = original_isdir
3524
3525 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
Michael Foorde91ea562009-09-13 19:07:03 +00003526 'test.foo', 'test-not-a-module.py', 'another_dir'],
Michael Foordb4a81c82009-05-29 20:33:46 +00003527 ['test3.py', 'test4.py', ]]
3528 os.listdir = lambda path: path_lists.pop(0)
3529 self.addCleanup(restore_listdir)
3530
3531 def isdir(path):
3532 return path.endswith('dir')
3533 os.path.isdir = isdir
3534 self.addCleanup(restore_isdir)
3535
3536 def isfile(path):
3537 # another_dir is not a package and so shouldn't be recursed into
3538 return not path.endswith('dir') and not 'another_dir' in path
3539 os.path.isfile = isfile
3540 self.addCleanup(restore_isfile)
3541
Michael Foorde91ea562009-09-13 19:07:03 +00003542 loader._get_module_from_name = lambda path: path + ' module'
Michael Foordb4a81c82009-05-29 20:33:46 +00003543 loader.loadTestsFromModule = lambda module: module + ' tests'
3544
3545 loader._top_level_dir = '/foo'
3546 suite = list(loader._find_tests('/foo', 'test*.py'))
3547
Michael Foorde91ea562009-09-13 19:07:03 +00003548 expected = [name + ' module tests' for name in
3549 ('test1', 'test2')]
3550 expected.extend([('test_dir.%s' % name) + ' module tests' for name in
3551 ('test3', 'test4')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003552 self.assertEqual(suite, expected)
3553
3554 def test_find_tests_with_package(self):
3555 loader = unittest.TestLoader()
3556
3557 original_listdir = os.listdir
3558 def restore_listdir():
3559 os.listdir = original_listdir
3560 original_isfile = os.path.isfile
3561 def restore_isfile():
3562 os.path.isfile = original_isfile
3563 original_isdir = os.path.isdir
3564 def restore_isdir():
3565 os.path.isdir = original_isdir
3566
3567 directories = ['a_directory', 'test_directory', 'test_directory2']
3568 path_lists = [directories, [], [], []]
3569 os.listdir = lambda path: path_lists.pop(0)
3570 self.addCleanup(restore_listdir)
3571
3572 os.path.isdir = lambda path: True
3573 self.addCleanup(restore_isdir)
3574
3575 os.path.isfile = lambda path: os.path.basename(path) not in directories
3576 self.addCleanup(restore_isfile)
3577
3578 class Module(object):
3579 paths = []
3580 load_tests_args = []
3581
3582 def __init__(self, path):
3583 self.path = path
3584 self.paths.append(path)
3585 if os.path.basename(path) == 'test_directory':
3586 def load_tests(loader, tests, pattern):
3587 self.load_tests_args.append((loader, tests, pattern))
3588 return 'load_tests'
3589 self.load_tests = load_tests
3590
3591 def __eq__(self, other):
3592 return self.path == other.path
3593
Michael Foorde91ea562009-09-13 19:07:03 +00003594 loader._get_module_from_name = lambda name: Module(name)
Michael Foordb4a81c82009-05-29 20:33:46 +00003595 def loadTestsFromModule(module, use_load_tests):
3596 if use_load_tests:
3597 raise self.failureException('use_load_tests should be False for packages')
3598 return module.path + ' module tests'
3599 loader.loadTestsFromModule = loadTestsFromModule
3600
3601 loader._top_level_dir = '/foo'
3602 # this time no '.py' on the pattern so that it can match
3603 # a test package
3604 suite = list(loader._find_tests('/foo', 'test*'))
3605
3606 # We should have loaded tests from the test_directory package by calling load_tests
3607 # and directly from the test_directory2 package
Michael Foordd53d0852009-06-05 14:14:34 +00003608 self.assertEqual(suite,
Michael Foorde91ea562009-09-13 19:07:03 +00003609 ['load_tests', 'test_directory2' + ' module tests'])
3610 self.assertEqual(Module.paths, ['test_directory', 'test_directory2'])
Michael Foordb4a81c82009-05-29 20:33:46 +00003611
3612 # load_tests should have been called once with loader, tests and pattern
3613 self.assertEqual(Module.load_tests_args,
Michael Foorde91ea562009-09-13 19:07:03 +00003614 [(loader, 'test_directory' + ' module tests', 'test*')])
Michael Foordb4a81c82009-05-29 20:33:46 +00003615
3616 def test_discover(self):
3617 loader = unittest.TestLoader()
3618
3619 original_isfile = os.path.isfile
3620 def restore_isfile():
3621 os.path.isfile = original_isfile
3622
3623 os.path.isfile = lambda path: False
3624 self.addCleanup(restore_isfile)
3625
Nick Coghlanb6edf192009-10-17 08:21:21 +00003626 orig_sys_path = sys.path[:]
3627 def restore_path():
3628 sys.path[:] = orig_sys_path
3629 self.addCleanup(restore_path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003630
Nick Coghlanb6edf192009-10-17 08:21:21 +00003631 full_path = os.path.abspath(os.path.normpath('/foo'))
Michael Foordb4a81c82009-05-29 20:33:46 +00003632 with self.assertRaises(ImportError):
3633 loader.discover('/foo/bar', top_level_dir='/foo')
3634
3635 self.assertEqual(loader._top_level_dir, full_path)
3636 self.assertIn(full_path, sys.path)
3637
3638 os.path.isfile = lambda path: True
3639 _find_tests_args = []
3640 def _find_tests(start_dir, pattern):
3641 _find_tests_args.append((start_dir, pattern))
3642 return ['tests']
3643 loader._find_tests = _find_tests
3644 loader.suiteClass = str
3645
3646 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3647
3648 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3649 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3650 self.assertEqual(suite, "['tests']")
3651 self.assertEqual(loader._top_level_dir, top_level_dir)
3652 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
Nick Coghlanb6edf192009-10-17 08:21:21 +00003653 self.assertIn(top_level_dir, sys.path)
Michael Foordb4a81c82009-05-29 20:33:46 +00003654
Michael Foorde91ea562009-09-13 19:07:03 +00003655 def test_discover_with_modules_that_fail_to_import(self):
3656 loader = unittest.TestLoader()
3657
3658 listdir = os.listdir
3659 os.listdir = lambda _: ['test_this_does_not_exist.py']
3660 isfile = os.path.isfile
3661 os.path.isfile = lambda _: True
Nick Coghlanb6edf192009-10-17 08:21:21 +00003662 orig_sys_path = sys.path[:]
Michael Foorde91ea562009-09-13 19:07:03 +00003663 def restore():
3664 os.path.isfile = isfile
3665 os.listdir = listdir
Nick Coghlanb6edf192009-10-17 08:21:21 +00003666 sys.path[:] = orig_sys_path
Michael Foorde91ea562009-09-13 19:07:03 +00003667 self.addCleanup(restore)
3668
3669 suite = loader.discover('.')
Nick Coghlanb6edf192009-10-17 08:21:21 +00003670 self.assertIn(os.getcwd(), sys.path)
Michael Foorde91ea562009-09-13 19:07:03 +00003671 self.assertEqual(suite.countTestCases(), 1)
3672 test = list(list(suite)[0])[0] # extract test from suite
3673
3674 with self.assertRaises(ImportError):
3675 test.test_this_does_not_exist()
3676
Michael Foordb4a81c82009-05-29 20:33:46 +00003677 def test_command_line_handling_parseArgs(self):
3678 # Haha - take that uninstantiable class
3679 program = object.__new__(TestProgram)
3680
3681 args = []
3682 def do_discovery(argv):
3683 args.extend(argv)
3684 program._do_discovery = do_discovery
3685 program.parseArgs(['something', 'discover'])
3686 self.assertEqual(args, [])
3687
3688 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3689 self.assertEqual(args, ['foo', 'bar'])
3690
3691 def test_command_line_handling_do_discovery_too_many_arguments(self):
3692 class Stop(Exception):
3693 pass
3694 def usageExit():
3695 raise Stop
3696
3697 program = object.__new__(TestProgram)
3698 program.usageExit = usageExit
3699
3700 with self.assertRaises(Stop):
3701 # too many args
3702 program._do_discovery(['one', 'two', 'three', 'four'])
3703
3704
3705 def test_command_line_handling_do_discovery_calls_loader(self):
3706 program = object.__new__(TestProgram)
3707
3708 class Loader(object):
3709 args = []
3710 def discover(self, start_dir, pattern, top_level_dir):
3711 self.args.append((start_dir, pattern, top_level_dir))
3712 return 'tests'
3713
3714 program._do_discovery(['-v'], Loader=Loader)
3715 self.assertEqual(program.verbosity, 2)
3716 self.assertEqual(program.test, 'tests')
3717 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3718
3719 Loader.args = []
3720 program = object.__new__(TestProgram)
3721 program._do_discovery(['--verbose'], Loader=Loader)
3722 self.assertEqual(program.test, 'tests')
3723 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3724
3725 Loader.args = []
3726 program = object.__new__(TestProgram)
3727 program._do_discovery([], Loader=Loader)
3728 self.assertEqual(program.test, 'tests')
3729 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3730
3731 Loader.args = []
3732 program = object.__new__(TestProgram)
3733 program._do_discovery(['fish'], Loader=Loader)
3734 self.assertEqual(program.test, 'tests')
3735 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3736
3737 Loader.args = []
3738 program = object.__new__(TestProgram)
3739 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3740 self.assertEqual(program.test, 'tests')
3741 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3742
3743 Loader.args = []
3744 program = object.__new__(TestProgram)
3745 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3746 self.assertEqual(program.test, 'tests')
3747 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3748
3749 Loader.args = []
3750 program = object.__new__(TestProgram)
3751 program._do_discovery(['-s', 'fish'], Loader=Loader)
3752 self.assertEqual(program.test, 'tests')
3753 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3754
3755 Loader.args = []
3756 program = object.__new__(TestProgram)
3757 program._do_discovery(['-t', 'fish'], Loader=Loader)
3758 self.assertEqual(program.test, 'tests')
3759 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3760
3761 Loader.args = []
3762 program = object.__new__(TestProgram)
3763 program._do_discovery(['-p', 'fish'], Loader=Loader)
3764 self.assertEqual(program.test, 'tests')
3765 self.assertEqual(Loader.args, [('.', 'fish', None)])
3766
3767 Loader.args = []
3768 program = object.__new__(TestProgram)
3769 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3770 self.assertEqual(program.test, 'tests')
3771 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3772 self.assertEqual(program.verbosity, 2)
3773
3774
Jim Fultonfafd8742004-08-28 15:22:12 +00003775######################################################################
3776## Main
3777######################################################################
3778
3779def test_main():
Georg Brandl15c5ce92007-03-07 09:09:40 +00003780 test_support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003781 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Michael Foord829f6b82009-05-02 11:43:06 +00003782 Test_TestSkipping, Test_Assertions, TestLongMessage,
Antoine Pitrou0734c632009-11-10 20:49:30 +00003783 Test_TestProgram, TestCleanUp, TestDiscovery, Test_TextTestRunner)
Jim Fultonfafd8742004-08-28 15:22:12 +00003784
Georg Brandl15c5ce92007-03-07 09:09:40 +00003785if __name__ == "__main__":
Tim Petersea5962f2007-03-12 18:07:52 +00003786 test_main()