blob: 950b2ca222956cfbaa1b00c0b9e86808c3f4caab [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
Michael Foordb4a81c82009-05-29 20:33:46 +000010import os
Gregory P. Smith28399852009-03-31 16:54:10 +000011import re
Michael Foordb4a81c82009-05-29 20:33:46 +000012import sys
Georg Brandl15c5ce92007-03-07 09:09:40 +000013from test import test_support
Jim Fultonfafd8742004-08-28 15:22:12 +000014import unittest
Michael Foord829f6b82009-05-02 11:43:06 +000015from unittest import TestCase, TestProgram
Christian Heimesc756d002007-11-27 21:34:01 +000016import types
Michael Foorde2942d02009-04-02 05:51:54 +000017from copy import deepcopy
Michael Foord829f6b82009-05-02 11:43:06 +000018from cStringIO import StringIO
Jim Fultonfafd8742004-08-28 15:22:12 +000019
Georg Brandl15c5ce92007-03-07 09:09:40 +000020### Support code
21################################################################
Jim Fultonfafd8742004-08-28 15:22:12 +000022
Georg Brandl15c5ce92007-03-07 09:09:40 +000023class LoggingResult(unittest.TestResult):
24 def __init__(self, log):
25 self._events = log
26 super(LoggingResult, self).__init__()
27
28 def startTest(self, test):
29 self._events.append('startTest')
30 super(LoggingResult, self).startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +000031
Michael Foord07ef4872009-05-02 22:43:34 +000032 def startTestRun(self):
33 self._events.append('startTestRun')
34 super(LoggingResult, self).startTestRun()
35
Georg Brandl15c5ce92007-03-07 09:09:40 +000036 def stopTest(self, test):
37 self._events.append('stopTest')
38 super(LoggingResult, self).stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +000039
Michael Foord07ef4872009-05-02 22:43:34 +000040 def stopTestRun(self):
41 self._events.append('stopTestRun')
42 super(LoggingResult, self).stopTestRun()
43
Georg Brandl15c5ce92007-03-07 09:09:40 +000044 def addFailure(self, *args):
45 self._events.append('addFailure')
46 super(LoggingResult, self).addFailure(*args)
Tim Petersea5962f2007-03-12 18:07:52 +000047
Benjamin Peterson692428e2009-03-23 21:50:21 +000048 def addSuccess(self, *args):
49 self._events.append('addSuccess')
50 super(LoggingResult, self).addSuccess(*args)
51
Georg Brandl15c5ce92007-03-07 09:09:40 +000052 def addError(self, *args):
53 self._events.append('addError')
54 super(LoggingResult, self).addError(*args)
55
Benjamin Peterson692428e2009-03-23 21:50:21 +000056 def addSkip(self, *args):
57 self._events.append('addSkip')
58 super(LoggingResult, self).addSkip(*args)
59
60 def addExpectedFailure(self, *args):
61 self._events.append('addExpectedFailure')
62 super(LoggingResult, self).addExpectedFailure(*args)
63
64 def addUnexpectedSuccess(self, *args):
65 self._events.append('addUnexpectedSuccess')
66 super(LoggingResult, self).addUnexpectedSuccess(*args)
67
68
Georg Brandl15c5ce92007-03-07 09:09:40 +000069class TestEquality(object):
Michael Foord345b2fe2009-04-02 03:20:38 +000070 """Used as a mixin for TestCase"""
71
Tim Petersea5962f2007-03-12 18:07:52 +000072 # Check for a valid __eq__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000073 def test_eq(self):
74 for obj_1, obj_2 in self.eq_pairs:
75 self.assertEqual(obj_1, obj_2)
76 self.assertEqual(obj_2, obj_1)
Tim Petersea5962f2007-03-12 18:07:52 +000077
78 # Check for a valid __ne__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000079 def test_ne(self):
80 for obj_1, obj_2 in self.ne_pairs:
81 self.failIfEqual(obj_1, obj_2)
82 self.failIfEqual(obj_2, obj_1)
Tim Petersea5962f2007-03-12 18:07:52 +000083
Georg Brandl15c5ce92007-03-07 09:09:40 +000084class TestHashing(object):
Michael Foord345b2fe2009-04-02 03:20:38 +000085 """Used as a mixin for TestCase"""
86
Tim Petersea5962f2007-03-12 18:07:52 +000087 # Check for a valid __hash__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000088 def test_hash(self):
89 for obj_1, obj_2 in self.eq_pairs:
90 try:
Gregory P. Smith28399852009-03-31 16:54:10 +000091 if not hash(obj_1) == hash(obj_2):
92 self.fail("%r and %r do not hash equal" % (obj_1, obj_2))
Georg Brandl15c5ce92007-03-07 09:09:40 +000093 except KeyboardInterrupt:
94 raise
Georg Brandl15c5ce92007-03-07 09:09:40 +000095 except Exception, e:
Gregory P. Smith28399852009-03-31 16:54:10 +000096 self.fail("Problem hashing %r and %r: %s" % (obj_1, obj_2, e))
Tim Petersea5962f2007-03-12 18:07:52 +000097
Georg Brandl15c5ce92007-03-07 09:09:40 +000098 for obj_1, obj_2 in self.ne_pairs:
99 try:
Gregory P. Smith28399852009-03-31 16:54:10 +0000100 if hash(obj_1) == hash(obj_2):
101 self.fail("%s and %s hash equal, but shouldn't" %
102 (obj_1, obj_2))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000103 except KeyboardInterrupt:
104 raise
Georg Brandl15c5ce92007-03-07 09:09:40 +0000105 except Exception, e:
106 self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e))
Tim Petersea5962f2007-03-12 18:07:52 +0000107
Georg Brandl15c5ce92007-03-07 09:09:40 +0000108
Benjamin Peterson692428e2009-03-23 21:50:21 +0000109# List subclass we can add attributes to.
110class MyClassSuite(list):
111
Benjamin Peterson176a56c2009-05-25 00:48:58 +0000112 def __init__(self, tests):
Benjamin Peterson692428e2009-03-23 21:50:21 +0000113 super(MyClassSuite, self).__init__(tests)
114
115
Georg Brandl15c5ce92007-03-07 09:09:40 +0000116################################################################
117### /Support code
118
119class Test_TestLoader(TestCase):
120
121 ### Tests for TestLoader.loadTestsFromTestCase
122 ################################################################
123
124 # "Return a suite of all tests cases contained in the TestCase-derived
125 # class testCaseClass"
126 def test_loadTestsFromTestCase(self):
127 class Foo(unittest.TestCase):
128 def test_1(self): pass
129 def test_2(self): pass
130 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000131
Georg Brandl15c5ce92007-03-07 09:09:40 +0000132 tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +0000133
Georg Brandl15c5ce92007-03-07 09:09:40 +0000134 loader = unittest.TestLoader()
135 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +0000136
Georg Brandl15c5ce92007-03-07 09:09:40 +0000137 # "Return a suite of all tests cases contained in the TestCase-derived
138 # class testCaseClass"
139 #
Tim Petersea5962f2007-03-12 18:07:52 +0000140 # Make sure it does the right thing even if no tests were found
Georg Brandl15c5ce92007-03-07 09:09:40 +0000141 def test_loadTestsFromTestCase__no_matches(self):
142 class Foo(unittest.TestCase):
143 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000144
Georg Brandl15c5ce92007-03-07 09:09:40 +0000145 empty_suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +0000146
Georg Brandl15c5ce92007-03-07 09:09:40 +0000147 loader = unittest.TestLoader()
148 self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite)
Tim Petersea5962f2007-03-12 18:07:52 +0000149
Georg Brandl15c5ce92007-03-07 09:09:40 +0000150 # "Return a suite of all tests cases contained in the TestCase-derived
151 # class testCaseClass"
152 #
153 # What happens if loadTestsFromTestCase() is given an object
154 # that isn't a subclass of TestCase? Specifically, what happens
155 # if testCaseClass is a subclass of TestSuite?
156 #
157 # This is checked for specifically in the code, so we better add a
158 # test for it.
159 def test_loadTestsFromTestCase__TestSuite_subclass(self):
160 class NotATestCase(unittest.TestSuite):
161 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000162
Georg Brandl15c5ce92007-03-07 09:09:40 +0000163 loader = unittest.TestLoader()
164 try:
165 loader.loadTestsFromTestCase(NotATestCase)
166 except TypeError:
167 pass
168 else:
169 self.fail('Should raise TypeError')
Tim Petersea5962f2007-03-12 18:07:52 +0000170
Georg Brandl15c5ce92007-03-07 09:09:40 +0000171 # "Return a suite of all tests cases contained in the TestCase-derived
172 # class testCaseClass"
173 #
174 # Make sure loadTestsFromTestCase() picks up the default test method
175 # name (as specified by TestCase), even though the method name does
176 # not match the default TestLoader.testMethodPrefix string
177 def test_loadTestsFromTestCase__default_method_name(self):
178 class Foo(unittest.TestCase):
179 def runTest(self):
180 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000181
Georg Brandl15c5ce92007-03-07 09:09:40 +0000182 loader = unittest.TestLoader()
183 # This has to be false for the test to succeed
184 self.failIf('runTest'.startswith(loader.testMethodPrefix))
Tim Petersea5962f2007-03-12 18:07:52 +0000185
Georg Brandl15c5ce92007-03-07 09:09:40 +0000186 suite = loader.loadTestsFromTestCase(Foo)
187 self.failUnless(isinstance(suite, loader.suiteClass))
188 self.assertEqual(list(suite), [Foo('runTest')])
189
190 ################################################################
191 ### /Tests for TestLoader.loadTestsFromTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000192
Georg Brandl15c5ce92007-03-07 09:09:40 +0000193 ### Tests for TestLoader.loadTestsFromModule
194 ################################################################
195
196 # "This method searches `module` for classes derived from TestCase"
197 def test_loadTestsFromModule__TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000198 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000199 class MyTestCase(unittest.TestCase):
200 def test(self):
201 pass
202 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000203
Georg Brandl15c5ce92007-03-07 09:09:40 +0000204 loader = unittest.TestLoader()
205 suite = loader.loadTestsFromModule(m)
206 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000207
Georg Brandl15c5ce92007-03-07 09:09:40 +0000208 expected = [loader.suiteClass([MyTestCase('test')])]
209 self.assertEqual(list(suite), expected)
Tim Petersea5962f2007-03-12 18:07:52 +0000210
Georg Brandl15c5ce92007-03-07 09:09:40 +0000211 # "This method searches `module` for classes derived from TestCase"
Tim Petersea5962f2007-03-12 18:07:52 +0000212 #
Georg Brandl15c5ce92007-03-07 09:09:40 +0000213 # What happens if no tests are found (no TestCase instances)?
214 def test_loadTestsFromModule__no_TestCase_instances(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000215 m = types.ModuleType('m')
Tim Petersea5962f2007-03-12 18:07:52 +0000216
Georg Brandl15c5ce92007-03-07 09:09:40 +0000217 loader = unittest.TestLoader()
218 suite = loader.loadTestsFromModule(m)
219 self.failUnless(isinstance(suite, loader.suiteClass))
220 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000221
Georg Brandl15c5ce92007-03-07 09:09:40 +0000222 # "This method searches `module` for classes derived from TestCase"
223 #
Tim Petersea5962f2007-03-12 18:07:52 +0000224 # What happens if no tests are found (TestCases instances, but no tests)?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000225 def test_loadTestsFromModule__no_TestCase_tests(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000226 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000227 class MyTestCase(unittest.TestCase):
228 pass
229 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000230
Georg Brandl15c5ce92007-03-07 09:09:40 +0000231 loader = unittest.TestLoader()
232 suite = loader.loadTestsFromModule(m)
233 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000234
Georg Brandl15c5ce92007-03-07 09:09:40 +0000235 self.assertEqual(list(suite), [loader.suiteClass()])
Tim Petersea5962f2007-03-12 18:07:52 +0000236
Georg Brandl15c5ce92007-03-07 09:09:40 +0000237 # "This method searches `module` for classes derived from TestCase"s
238 #
239 # What happens if loadTestsFromModule() is given something other
240 # than a module?
241 #
242 # XXX Currently, it succeeds anyway. This flexibility
243 # should either be documented or loadTestsFromModule() should
244 # raise a TypeError
245 #
246 # XXX Certain people are using this behaviour. We'll add a test for it
247 def test_loadTestsFromModule__not_a_module(self):
248 class MyTestCase(unittest.TestCase):
249 def test(self):
250 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000251
Georg Brandl15c5ce92007-03-07 09:09:40 +0000252 class NotAModule(object):
253 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000254
Georg Brandl15c5ce92007-03-07 09:09:40 +0000255 loader = unittest.TestLoader()
256 suite = loader.loadTestsFromModule(NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000257
Georg Brandl15c5ce92007-03-07 09:09:40 +0000258 reference = [unittest.TestSuite([MyTestCase('test')])]
259 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000260
Michael Foordb4a81c82009-05-29 20:33:46 +0000261
262 # Check that loadTestsFromModule honors (or not) a module
263 # with a load_tests function.
264 def test_loadTestsFromModule__load_tests(self):
265 m = types.ModuleType('m')
266 class MyTestCase(unittest.TestCase):
267 def test(self):
268 pass
269 m.testcase_1 = MyTestCase
270
271 load_tests_args = []
272 def load_tests(loader, tests, pattern):
273 load_tests_args.extend((loader, tests, pattern))
274 return tests
275 m.load_tests = load_tests
276
277 loader = unittest.TestLoader()
278 suite = loader.loadTestsFromModule(m)
279 self.assertEquals(load_tests_args, [loader, suite, None])
280
281 load_tests_args = []
282 suite = loader.loadTestsFromModule(m, use_load_tests=False)
283 self.assertEquals(load_tests_args, [])
284
Georg Brandl15c5ce92007-03-07 09:09:40 +0000285 ################################################################
286 ### /Tests for TestLoader.loadTestsFromModule()
Tim Petersea5962f2007-03-12 18:07:52 +0000287
Georg Brandl15c5ce92007-03-07 09:09:40 +0000288 ### Tests for TestLoader.loadTestsFromName()
289 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000290
Georg Brandl15c5ce92007-03-07 09:09:40 +0000291 # "The specifier name is a ``dotted name'' that may resolve either to
292 # a module, a test case class, a TestSuite instance, a test method
293 # within a test case class, or a callable object which returns a
294 # TestCase or TestSuite instance."
295 #
296 # Is ValueError raised in response to an empty name?
297 def test_loadTestsFromName__empty_name(self):
298 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000299
Georg Brandl15c5ce92007-03-07 09:09:40 +0000300 try:
301 loader.loadTestsFromName('')
302 except ValueError, e:
303 self.assertEqual(str(e), "Empty module name")
304 else:
305 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000306
Georg Brandl15c5ce92007-03-07 09:09:40 +0000307 # "The specifier name is a ``dotted name'' that may resolve either to
308 # a module, a test case class, a TestSuite instance, a test method
309 # within a test case class, or a callable object which returns a
310 # TestCase or TestSuite instance."
311 #
Tim Petersea5962f2007-03-12 18:07:52 +0000312 # What happens when the name contains invalid characters?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000313 def test_loadTestsFromName__malformed_name(self):
314 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000315
Georg Brandl15c5ce92007-03-07 09:09:40 +0000316 # XXX Should this raise ValueError or ImportError?
317 try:
318 loader.loadTestsFromName('abc () //')
319 except ValueError:
320 pass
321 except ImportError:
322 pass
323 else:
324 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000325
Georg Brandl15c5ce92007-03-07 09:09:40 +0000326 # "The specifier name is a ``dotted name'' that may resolve ... to a
327 # module"
328 #
Tim Petersea5962f2007-03-12 18:07:52 +0000329 # What happens when a module by that name can't be found?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000330 def test_loadTestsFromName__unknown_module_name(self):
331 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000332
Georg Brandl15c5ce92007-03-07 09:09:40 +0000333 try:
334 loader.loadTestsFromName('sdasfasfasdf')
335 except ImportError, e:
336 self.assertEqual(str(e), "No module named sdasfasfasdf")
337 else:
338 self.fail("TestLoader.loadTestsFromName failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000339
Georg Brandl15c5ce92007-03-07 09:09:40 +0000340 # "The specifier name is a ``dotted name'' that may resolve either to
341 # a module, a test case class, a TestSuite instance, a test method
342 # within a test case class, or a callable object which returns a
343 # TestCase or TestSuite instance."
344 #
Tim Petersea5962f2007-03-12 18:07:52 +0000345 # What happens when the module is found, but the attribute can't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000346 def test_loadTestsFromName__unknown_attr_name(self):
347 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000348
Georg Brandl15c5ce92007-03-07 09:09:40 +0000349 try:
350 loader.loadTestsFromName('unittest.sdasfasfasdf')
351 except AttributeError, e:
352 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
353 else:
354 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000355
Georg Brandl15c5ce92007-03-07 09:09:40 +0000356 # "The specifier name is a ``dotted name'' that may resolve either to
357 # a module, a test case class, a TestSuite instance, a test method
358 # within a test case class, or a callable object which returns a
359 # TestCase or TestSuite instance."
360 #
361 # What happens when we provide the module, but the attribute can't be
362 # found?
363 def test_loadTestsFromName__relative_unknown_name(self):
364 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000365
Georg Brandl15c5ce92007-03-07 09:09:40 +0000366 try:
367 loader.loadTestsFromName('sdasfasfasdf', unittest)
368 except AttributeError, e:
369 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
370 else:
371 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000372
Georg Brandl15c5ce92007-03-07 09:09:40 +0000373 # "The specifier name is a ``dotted name'' that may resolve either to
374 # a module, a test case class, a TestSuite instance, a test method
375 # within a test case class, or a callable object which returns a
376 # TestCase or TestSuite instance."
377 # ...
378 # "The method optionally resolves name relative to the given module"
379 #
380 # Does loadTestsFromName raise ValueError when passed an empty
381 # name relative to a provided module?
382 #
383 # XXX Should probably raise a ValueError instead of an AttributeError
384 def test_loadTestsFromName__relative_empty_name(self):
385 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000386
Georg Brandl15c5ce92007-03-07 09:09:40 +0000387 try:
388 loader.loadTestsFromName('', unittest)
389 except AttributeError, e:
390 pass
391 else:
392 self.fail("Failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000393
Georg Brandl15c5ce92007-03-07 09:09:40 +0000394 # "The specifier name is a ``dotted name'' that may resolve either to
395 # a module, a test case class, a TestSuite instance, a test method
396 # within a test case class, or a callable object which returns a
397 # TestCase or TestSuite instance."
398 # ...
399 # "The method optionally resolves name relative to the given module"
400 #
401 # What happens when an impossible name is given, relative to the provided
402 # `module`?
403 def test_loadTestsFromName__relative_malformed_name(self):
404 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000405
Georg Brandl15c5ce92007-03-07 09:09:40 +0000406 # XXX Should this raise AttributeError or ValueError?
407 try:
408 loader.loadTestsFromName('abc () //', unittest)
409 except ValueError:
410 pass
411 except AttributeError:
412 pass
413 else:
414 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
415
416 # "The method optionally resolves name relative to the given module"
417 #
418 # Does loadTestsFromName raise TypeError when the `module` argument
419 # isn't a module object?
420 #
421 # XXX Accepts the not-a-module object, ignorning the object's type
422 # This should raise an exception or the method name should be changed
423 #
424 # XXX Some people are relying on this, so keep it for now
425 def test_loadTestsFromName__relative_not_a_module(self):
426 class MyTestCase(unittest.TestCase):
427 def test(self):
428 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000429
Georg Brandl15c5ce92007-03-07 09:09:40 +0000430 class NotAModule(object):
431 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000432
Georg Brandl15c5ce92007-03-07 09:09:40 +0000433 loader = unittest.TestLoader()
434 suite = loader.loadTestsFromName('test_2', NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000435
Georg Brandl15c5ce92007-03-07 09:09:40 +0000436 reference = [MyTestCase('test')]
437 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000438
Georg Brandl15c5ce92007-03-07 09:09:40 +0000439 # "The specifier name is a ``dotted name'' that may resolve either to
440 # a module, a test case class, a TestSuite instance, a test method
441 # within a test case class, or a callable object which returns a
442 # TestCase or TestSuite instance."
443 #
444 # Does it raise an exception if the name resolves to an invalid
445 # object?
446 def test_loadTestsFromName__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000447 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000448 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000449
Georg Brandl15c5ce92007-03-07 09:09:40 +0000450 loader = unittest.TestLoader()
451 try:
452 loader.loadTestsFromName('testcase_1', m)
453 except TypeError:
454 pass
455 else:
456 self.fail("Should have raised TypeError")
457
458 # "The specifier name is a ``dotted name'' that may
459 # resolve either to ... a test case class"
460 def test_loadTestsFromName__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000461 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000462 class MyTestCase(unittest.TestCase):
463 def test(self):
464 pass
465 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000466
Georg Brandl15c5ce92007-03-07 09:09:40 +0000467 loader = unittest.TestLoader()
468 suite = loader.loadTestsFromName('testcase_1', m)
469 self.failUnless(isinstance(suite, loader.suiteClass))
470 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000471
Georg Brandl15c5ce92007-03-07 09:09:40 +0000472 # "The specifier name is a ``dotted name'' that may resolve either to
473 # a module, a test case class, a TestSuite instance, a test method
474 # within a test case class, or a callable object which returns a
475 # TestCase or TestSuite instance."
476 def test_loadTestsFromName__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000477 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000478 class MyTestCase(unittest.TestCase):
479 def test(self):
480 pass
481 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000482
Georg Brandl15c5ce92007-03-07 09:09:40 +0000483 loader = unittest.TestLoader()
484 suite = loader.loadTestsFromName('testsuite', m)
485 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000486
Georg Brandl15c5ce92007-03-07 09:09:40 +0000487 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000488
Georg Brandl15c5ce92007-03-07 09:09:40 +0000489 # "The specifier name is a ``dotted name'' that may resolve ... to
490 # ... a test method within a test case class"
491 def test_loadTestsFromName__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000492 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000493 class MyTestCase(unittest.TestCase):
494 def test(self):
495 pass
496 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000497
Georg Brandl15c5ce92007-03-07 09:09:40 +0000498 loader = unittest.TestLoader()
499 suite = loader.loadTestsFromName('testcase_1.test', m)
500 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000501
Georg Brandl15c5ce92007-03-07 09:09:40 +0000502 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000503
Georg Brandl15c5ce92007-03-07 09:09:40 +0000504 # "The specifier name is a ``dotted name'' that may resolve either to
505 # a module, a test case class, a TestSuite instance, a test method
506 # within a test case class, or a callable object which returns a
507 # TestCase or TestSuite instance."
508 #
509 # Does loadTestsFromName() raise the proper exception when trying to
510 # resolve "a test method within a test case class" that doesn't exist
511 # for the given name (relative to a provided module)?
512 def test_loadTestsFromName__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000513 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000514 class MyTestCase(unittest.TestCase):
515 def test(self):
516 pass
517 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000518
Georg Brandl15c5ce92007-03-07 09:09:40 +0000519 loader = unittest.TestLoader()
520 try:
521 loader.loadTestsFromName('testcase_1.testfoo', m)
522 except AttributeError, e:
523 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
524 else:
525 self.fail("Failed to raise AttributeError")
526
527 # "The specifier name is a ``dotted name'' that may resolve ... to
528 # ... a callable object which returns a ... TestSuite instance"
529 def test_loadTestsFromName__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000530 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000531 testcase_1 = unittest.FunctionTestCase(lambda: None)
532 testcase_2 = unittest.FunctionTestCase(lambda: None)
533 def return_TestSuite():
534 return unittest.TestSuite([testcase_1, testcase_2])
535 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000536
Georg Brandl15c5ce92007-03-07 09:09:40 +0000537 loader = unittest.TestLoader()
538 suite = loader.loadTestsFromName('return_TestSuite', m)
539 self.failUnless(isinstance(suite, loader.suiteClass))
540 self.assertEqual(list(suite), [testcase_1, testcase_2])
Tim Petersea5962f2007-03-12 18:07:52 +0000541
Georg Brandl15c5ce92007-03-07 09:09:40 +0000542 # "The specifier name is a ``dotted name'' that may resolve ... to
543 # ... a callable object which returns a TestCase ... instance"
544 def test_loadTestsFromName__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000545 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000546 testcase_1 = unittest.FunctionTestCase(lambda: None)
547 def return_TestCase():
548 return testcase_1
549 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000550
Georg Brandl15c5ce92007-03-07 09:09:40 +0000551 loader = unittest.TestLoader()
552 suite = loader.loadTestsFromName('return_TestCase', m)
553 self.failUnless(isinstance(suite, loader.suiteClass))
554 self.assertEqual(list(suite), [testcase_1])
Tim Petersea5962f2007-03-12 18:07:52 +0000555
Georg Brandl15c5ce92007-03-07 09:09:40 +0000556 # "The specifier name is a ``dotted name'' that may resolve ... to
557 # ... a callable object which returns a TestCase or TestSuite instance"
558 #
559 # What happens if the callable returns something else?
560 def test_loadTestsFromName__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000561 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000562 def return_wrong():
563 return 6
564 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000565
Georg Brandl15c5ce92007-03-07 09:09:40 +0000566 loader = unittest.TestLoader()
567 try:
568 suite = loader.loadTestsFromName('return_wrong', m)
569 except TypeError:
570 pass
571 else:
572 self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000573
Georg Brandl15c5ce92007-03-07 09:09:40 +0000574 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +0000575 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +0000576 def test_loadTestsFromName__module_not_loaded(self):
577 # We're going to try to load this module as a side-effect, so it
578 # better not be loaded before we try.
579 #
580 # Why pick audioop? Google shows it isn't used very often, so there's
581 # a good chance that it won't be imported when this test is run
582 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +0000583
Georg Brandl15c5ce92007-03-07 09:09:40 +0000584 import sys
585 if module_name in sys.modules:
586 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000587
Georg Brandl15c5ce92007-03-07 09:09:40 +0000588 loader = unittest.TestLoader()
589 try:
590 suite = loader.loadTestsFromName(module_name)
591
592 self.failUnless(isinstance(suite, loader.suiteClass))
593 self.assertEqual(list(suite), [])
594
595 # audioop should now be loaded, thanks to loadTestsFromName()
596 self.failUnless(module_name in sys.modules)
597 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000598 if module_name in sys.modules:
599 del sys.modules[module_name]
Georg Brandl15c5ce92007-03-07 09:09:40 +0000600
601 ################################################################
602 ### Tests for TestLoader.loadTestsFromName()
603
604 ### Tests for TestLoader.loadTestsFromNames()
605 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000606
Georg Brandl15c5ce92007-03-07 09:09:40 +0000607 # "Similar to loadTestsFromName(), but takes a sequence of names rather
608 # than a single name."
609 #
610 # What happens if that sequence of names is empty?
611 def test_loadTestsFromNames__empty_name_list(self):
612 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000613
Georg Brandl15c5ce92007-03-07 09:09:40 +0000614 suite = loader.loadTestsFromNames([])
615 self.failUnless(isinstance(suite, loader.suiteClass))
616 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000617
Georg Brandl15c5ce92007-03-07 09:09:40 +0000618 # "Similar to loadTestsFromName(), but takes a sequence of names rather
619 # than a single name."
620 # ...
621 # "The method optionally resolves name relative to the given module"
622 #
623 # What happens if that sequence of names is empty?
624 #
625 # XXX Should this raise a ValueError or just return an empty TestSuite?
626 def test_loadTestsFromNames__relative_empty_name_list(self):
627 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000628
Georg Brandl15c5ce92007-03-07 09:09:40 +0000629 suite = loader.loadTestsFromNames([], unittest)
630 self.failUnless(isinstance(suite, loader.suiteClass))
631 self.assertEqual(list(suite), [])
632
633 # "The specifier name is a ``dotted name'' that may resolve either to
634 # a module, a test case class, a TestSuite instance, a test method
635 # within a test case class, or a callable object which returns a
636 # TestCase or TestSuite instance."
637 #
638 # Is ValueError raised in response to an empty name?
639 def test_loadTestsFromNames__empty_name(self):
640 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000641
Georg Brandl15c5ce92007-03-07 09:09:40 +0000642 try:
643 loader.loadTestsFromNames([''])
644 except ValueError, e:
645 self.assertEqual(str(e), "Empty module name")
646 else:
647 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000648
Georg Brandl15c5ce92007-03-07 09:09:40 +0000649 # "The specifier name is a ``dotted name'' that may resolve either to
650 # a module, a test case class, a TestSuite instance, a test method
651 # within a test case class, or a callable object which returns a
652 # TestCase or TestSuite instance."
653 #
Tim Petersea5962f2007-03-12 18:07:52 +0000654 # What happens when presented with an impossible module name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000655 def test_loadTestsFromNames__malformed_name(self):
656 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000657
Georg Brandl15c5ce92007-03-07 09:09:40 +0000658 # XXX Should this raise ValueError or ImportError?
659 try:
660 loader.loadTestsFromNames(['abc () //'])
661 except ValueError:
662 pass
663 except ImportError:
664 pass
665 else:
666 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000667
Georg Brandl15c5ce92007-03-07 09:09:40 +0000668 # "The specifier name is a ``dotted name'' that may resolve either to
669 # a module, a test case class, a TestSuite instance, a test method
670 # within a test case class, or a callable object which returns a
671 # TestCase or TestSuite instance."
672 #
Tim Petersea5962f2007-03-12 18:07:52 +0000673 # What happens when no module can be found for the given name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000674 def test_loadTestsFromNames__unknown_module_name(self):
675 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000676
Georg Brandl15c5ce92007-03-07 09:09:40 +0000677 try:
678 loader.loadTestsFromNames(['sdasfasfasdf'])
679 except ImportError, e:
680 self.assertEqual(str(e), "No module named sdasfasfasdf")
681 else:
682 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000683
Georg Brandl15c5ce92007-03-07 09:09:40 +0000684 # "The specifier name is a ``dotted name'' that may resolve either to
685 # a module, a test case class, a TestSuite instance, a test method
686 # within a test case class, or a callable object which returns a
687 # TestCase or TestSuite instance."
688 #
Tim Petersea5962f2007-03-12 18:07:52 +0000689 # What happens when the module can be found, but not the attribute?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000690 def test_loadTestsFromNames__unknown_attr_name(self):
691 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000692
Georg Brandl15c5ce92007-03-07 09:09:40 +0000693 try:
694 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
695 except AttributeError, e:
696 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
697 else:
698 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000699
Georg Brandl15c5ce92007-03-07 09:09:40 +0000700 # "The specifier name is a ``dotted name'' that may resolve either to
701 # a module, a test case class, a TestSuite instance, a test method
702 # within a test case class, or a callable object which returns a
703 # TestCase or TestSuite instance."
704 # ...
705 # "The method optionally resolves name relative to the given module"
706 #
707 # What happens when given an unknown attribute on a specified `module`
708 # argument?
709 def test_loadTestsFromNames__unknown_name_relative_1(self):
710 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000711
Georg Brandl15c5ce92007-03-07 09:09:40 +0000712 try:
713 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
714 except AttributeError, e:
715 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
716 else:
717 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000718
Georg Brandl15c5ce92007-03-07 09:09:40 +0000719 # "The specifier name is a ``dotted name'' that may resolve either to
720 # a module, a test case class, a TestSuite instance, a test method
721 # within a test case class, or a callable object which returns a
722 # TestCase or TestSuite instance."
723 # ...
724 # "The method optionally resolves name relative to the given module"
725 #
726 # Do unknown attributes (relative to a provided module) still raise an
Tim Petersea5962f2007-03-12 18:07:52 +0000727 # exception even in the presence of valid attribute names?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000728 def test_loadTestsFromNames__unknown_name_relative_2(self):
729 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000730
Georg Brandl15c5ce92007-03-07 09:09:40 +0000731 try:
732 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
733 except AttributeError, e:
734 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
735 else:
736 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
737
738 # "The specifier name is a ``dotted name'' that may resolve either to
739 # a module, a test case class, a TestSuite instance, a test method
740 # within a test case class, or a callable object which returns a
741 # TestCase or TestSuite instance."
742 # ...
743 # "The method optionally resolves name relative to the given module"
744 #
745 # What happens when faced with the empty string?
746 #
747 # XXX This currently raises AttributeError, though ValueError is probably
748 # more appropriate
749 def test_loadTestsFromNames__relative_empty_name(self):
750 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000751
Georg Brandl15c5ce92007-03-07 09:09:40 +0000752 try:
753 loader.loadTestsFromNames([''], unittest)
754 except AttributeError:
755 pass
756 else:
757 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000758
Georg Brandl15c5ce92007-03-07 09:09:40 +0000759 # "The specifier name is a ``dotted name'' that may resolve either to
760 # a module, a test case class, a TestSuite instance, a test method
761 # within a test case class, or a callable object which returns a
762 # TestCase or TestSuite instance."
763 # ...
764 # "The method optionally resolves name relative to the given module"
765 #
Tim Petersea5962f2007-03-12 18:07:52 +0000766 # What happens when presented with an impossible attribute name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000767 def test_loadTestsFromNames__relative_malformed_name(self):
768 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000769
Georg Brandl15c5ce92007-03-07 09:09:40 +0000770 # XXX Should this raise AttributeError or ValueError?
771 try:
772 loader.loadTestsFromNames(['abc () //'], unittest)
773 except AttributeError:
774 pass
775 except ValueError:
776 pass
777 else:
778 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
779
780 # "The method optionally resolves name relative to the given module"
781 #
782 # Does loadTestsFromNames() make sure the provided `module` is in fact
783 # a module?
784 #
785 # XXX This validation is currently not done. This flexibility should
786 # either be documented or a TypeError should be raised.
787 def test_loadTestsFromNames__relative_not_a_module(self):
788 class MyTestCase(unittest.TestCase):
789 def test(self):
790 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000791
Georg Brandl15c5ce92007-03-07 09:09:40 +0000792 class NotAModule(object):
793 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000794
Georg Brandl15c5ce92007-03-07 09:09:40 +0000795 loader = unittest.TestLoader()
796 suite = loader.loadTestsFromNames(['test_2'], NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000797
Georg Brandl15c5ce92007-03-07 09:09:40 +0000798 reference = [unittest.TestSuite([MyTestCase('test')])]
799 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000800
Georg Brandl15c5ce92007-03-07 09:09:40 +0000801 # "The specifier name is a ``dotted name'' that may resolve either to
802 # a module, a test case class, a TestSuite instance, a test method
803 # within a test case class, or a callable object which returns a
804 # TestCase or TestSuite instance."
805 #
806 # Does it raise an exception if the name resolves to an invalid
807 # object?
808 def test_loadTestsFromNames__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000809 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000810 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000811
Georg Brandl15c5ce92007-03-07 09:09:40 +0000812 loader = unittest.TestLoader()
813 try:
814 loader.loadTestsFromNames(['testcase_1'], m)
815 except TypeError:
816 pass
817 else:
818 self.fail("Should have raised TypeError")
819
820 # "The specifier name is a ``dotted name'' that may resolve ... to
821 # ... a test case class"
822 def test_loadTestsFromNames__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000823 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000824 class MyTestCase(unittest.TestCase):
825 def test(self):
826 pass
827 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000828
Georg Brandl15c5ce92007-03-07 09:09:40 +0000829 loader = unittest.TestLoader()
830 suite = loader.loadTestsFromNames(['testcase_1'], m)
831 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000832
Georg Brandl15c5ce92007-03-07 09:09:40 +0000833 expected = loader.suiteClass([MyTestCase('test')])
834 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000835
Georg Brandl15c5ce92007-03-07 09:09:40 +0000836 # "The specifier name is a ``dotted name'' that may resolve ... to
837 # ... a TestSuite instance"
838 def test_loadTestsFromNames__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000839 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000840 class MyTestCase(unittest.TestCase):
841 def test(self):
842 pass
843 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000844
Georg Brandl15c5ce92007-03-07 09:09:40 +0000845 loader = unittest.TestLoader()
846 suite = loader.loadTestsFromNames(['testsuite'], m)
847 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000848
Georg Brandl15c5ce92007-03-07 09:09:40 +0000849 self.assertEqual(list(suite), [m.testsuite])
Tim Petersea5962f2007-03-12 18:07:52 +0000850
Georg Brandl15c5ce92007-03-07 09:09:40 +0000851 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
852 # test method within a test case class"
853 def test_loadTestsFromNames__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000854 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000855 class MyTestCase(unittest.TestCase):
856 def test(self):
857 pass
858 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000859
Georg Brandl15c5ce92007-03-07 09:09:40 +0000860 loader = unittest.TestLoader()
861 suite = loader.loadTestsFromNames(['testcase_1.test'], m)
862 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000863
Georg Brandl15c5ce92007-03-07 09:09:40 +0000864 ref_suite = unittest.TestSuite([MyTestCase('test')])
865 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000866
Georg Brandl15c5ce92007-03-07 09:09:40 +0000867 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
868 # test method within a test case class"
869 #
870 # Does the method gracefully handle names that initially look like they
Tim Petersea5962f2007-03-12 18:07:52 +0000871 # resolve to "a test method within a test case class" but don't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000872 def test_loadTestsFromNames__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000873 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000874 class MyTestCase(unittest.TestCase):
875 def test(self):
876 pass
877 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000878
Georg Brandl15c5ce92007-03-07 09:09:40 +0000879 loader = unittest.TestLoader()
880 try:
881 loader.loadTestsFromNames(['testcase_1.testfoo'], m)
882 except AttributeError, e:
883 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
884 else:
885 self.fail("Failed to raise AttributeError")
886
887 # "The specifier name is a ``dotted name'' that may resolve ... to
888 # ... a callable object which returns a ... TestSuite instance"
889 def test_loadTestsFromNames__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000890 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000891 testcase_1 = unittest.FunctionTestCase(lambda: None)
892 testcase_2 = unittest.FunctionTestCase(lambda: None)
893 def return_TestSuite():
894 return unittest.TestSuite([testcase_1, testcase_2])
895 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000896
Georg Brandl15c5ce92007-03-07 09:09:40 +0000897 loader = unittest.TestLoader()
898 suite = loader.loadTestsFromNames(['return_TestSuite'], m)
899 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000900
Georg Brandl15c5ce92007-03-07 09:09:40 +0000901 expected = unittest.TestSuite([testcase_1, testcase_2])
902 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000903
Georg Brandl15c5ce92007-03-07 09:09:40 +0000904 # "The specifier name is a ``dotted name'' that may resolve ... to
905 # ... a callable object which returns a TestCase ... instance"
906 def test_loadTestsFromNames__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000907 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000908 testcase_1 = unittest.FunctionTestCase(lambda: None)
909 def return_TestCase():
910 return testcase_1
911 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000912
Georg Brandl15c5ce92007-03-07 09:09:40 +0000913 loader = unittest.TestLoader()
914 suite = loader.loadTestsFromNames(['return_TestCase'], m)
915 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000916
Georg Brandl15c5ce92007-03-07 09:09:40 +0000917 ref_suite = unittest.TestSuite([testcase_1])
918 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000919
Georg Brandl15c5ce92007-03-07 09:09:40 +0000920 # "The specifier name is a ``dotted name'' that may resolve ... to
921 # ... a callable object which returns a TestCase or TestSuite instance"
922 #
Tim Petersea5962f2007-03-12 18:07:52 +0000923 # Are staticmethods handled correctly?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000924 def test_loadTestsFromNames__callable__call_staticmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000925 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000926 class Test1(unittest.TestCase):
927 def test(self):
928 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000929
Georg Brandl15c5ce92007-03-07 09:09:40 +0000930 testcase_1 = Test1('test')
931 class Foo(unittest.TestCase):
932 @staticmethod
933 def foo():
934 return testcase_1
935 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +0000936
Georg Brandl15c5ce92007-03-07 09:09:40 +0000937 loader = unittest.TestLoader()
938 suite = loader.loadTestsFromNames(['Foo.foo'], m)
939 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000940
Georg Brandl15c5ce92007-03-07 09:09:40 +0000941 ref_suite = unittest.TestSuite([testcase_1])
942 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000943
Georg Brandl15c5ce92007-03-07 09:09:40 +0000944 # "The specifier name is a ``dotted name'' that may resolve ... to
945 # ... a callable object which returns a TestCase or TestSuite instance"
946 #
947 # What happens when the callable returns something else?
948 def test_loadTestsFromNames__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000949 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000950 def return_wrong():
951 return 6
952 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000953
Georg Brandl15c5ce92007-03-07 09:09:40 +0000954 loader = unittest.TestLoader()
955 try:
956 suite = loader.loadTestsFromNames(['return_wrong'], m)
957 except TypeError:
958 pass
959 else:
960 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000961
Georg Brandl15c5ce92007-03-07 09:09:40 +0000962 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +0000963 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +0000964 def test_loadTestsFromNames__module_not_loaded(self):
965 # We're going to try to load this module as a side-effect, so it
966 # better not be loaded before we try.
967 #
968 # Why pick audioop? Google shows it isn't used very often, so there's
969 # a good chance that it won't be imported when this test is run
970 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +0000971
Georg Brandl15c5ce92007-03-07 09:09:40 +0000972 import sys
973 if module_name in sys.modules:
974 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000975
Georg Brandl15c5ce92007-03-07 09:09:40 +0000976 loader = unittest.TestLoader()
977 try:
978 suite = loader.loadTestsFromNames([module_name])
979
980 self.failUnless(isinstance(suite, loader.suiteClass))
981 self.assertEqual(list(suite), [unittest.TestSuite()])
982
983 # audioop should now be loaded, thanks to loadTestsFromName()
984 self.failUnless(module_name in sys.modules)
985 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000986 if module_name in sys.modules:
987 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000988
Georg Brandl15c5ce92007-03-07 09:09:40 +0000989 ################################################################
990 ### /Tests for TestLoader.loadTestsFromNames()
991
992 ### Tests for TestLoader.getTestCaseNames()
993 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000994
Georg Brandl15c5ce92007-03-07 09:09:40 +0000995 # "Return a sorted sequence of method names found within testCaseClass"
996 #
997 # Test.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +0000998 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +0000999 def test_getTestCaseNames(self):
1000 class Test(unittest.TestCase):
1001 def test_1(self): pass
1002 def test_2(self): pass
1003 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001004
Georg Brandl15c5ce92007-03-07 09:09:40 +00001005 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001006
Georg Brandl15c5ce92007-03-07 09:09:40 +00001007 self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])
Tim Petersea5962f2007-03-12 18:07:52 +00001008
Georg Brandl15c5ce92007-03-07 09:09:40 +00001009 # "Return a sorted sequence of method names found within testCaseClass"
1010 #
Tim Petersea5962f2007-03-12 18:07:52 +00001011 # Does getTestCaseNames() behave appropriately if no tests are found?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001012 def test_getTestCaseNames__no_tests(self):
1013 class Test(unittest.TestCase):
1014 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001015
Georg Brandl15c5ce92007-03-07 09:09:40 +00001016 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001017
Georg Brandl15c5ce92007-03-07 09:09:40 +00001018 self.assertEqual(loader.getTestCaseNames(Test), [])
Tim Petersea5962f2007-03-12 18:07:52 +00001019
Georg Brandl15c5ce92007-03-07 09:09:40 +00001020 # "Return a sorted sequence of method names found within testCaseClass"
1021 #
1022 # Are not-TestCases handled gracefully?
1023 #
1024 # XXX This should raise a TypeError, not return a list
1025 #
1026 # XXX It's too late in the 2.5 release cycle to fix this, but it should
1027 # probably be revisited for 2.6
1028 def test_getTestCaseNames__not_a_TestCase(self):
1029 class BadCase(int):
1030 def test_foo(self):
1031 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001032
Georg Brandl15c5ce92007-03-07 09:09:40 +00001033 loader = unittest.TestLoader()
1034 names = loader.getTestCaseNames(BadCase)
Tim Petersea5962f2007-03-12 18:07:52 +00001035
Georg Brandl15c5ce92007-03-07 09:09:40 +00001036 self.assertEqual(names, ['test_foo'])
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 # Make sure inherited names are handled.
1041 #
1042 # TestP.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +00001043 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +00001044 def test_getTestCaseNames__inheritance(self):
1045 class TestP(unittest.TestCase):
1046 def test_1(self): pass
1047 def test_2(self): pass
1048 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001049
Georg Brandl15c5ce92007-03-07 09:09:40 +00001050 class TestC(TestP):
1051 def test_1(self): pass
1052 def test_3(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001053
Georg Brandl15c5ce92007-03-07 09:09:40 +00001054 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001055
Georg Brandl15c5ce92007-03-07 09:09:40 +00001056 names = ['test_1', 'test_2', 'test_3']
1057 self.assertEqual(loader.getTestCaseNames(TestC), names)
Tim Petersea5962f2007-03-12 18:07:52 +00001058
1059 ################################################################
Georg Brandl15c5ce92007-03-07 09:09:40 +00001060 ### /Tests for TestLoader.getTestCaseNames()
1061
1062 ### Tests for TestLoader.testMethodPrefix
1063 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001064
Georg Brandl15c5ce92007-03-07 09:09:40 +00001065 # "String giving the prefix of method names which will be interpreted as
1066 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001067 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001068 # Implicit in the documentation is that testMethodPrefix is respected by
1069 # all loadTestsFrom* methods.
1070 def test_testMethodPrefix__loadTestsFromTestCase(self):
1071 class Foo(unittest.TestCase):
1072 def test_1(self): pass
1073 def test_2(self): pass
1074 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001075
Georg Brandl15c5ce92007-03-07 09:09:40 +00001076 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1077 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001078
Georg Brandl15c5ce92007-03-07 09:09:40 +00001079 loader = unittest.TestLoader()
1080 loader.testMethodPrefix = 'foo'
1081 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
1082
1083 loader.testMethodPrefix = 'test'
1084 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001085
Georg Brandl15c5ce92007-03-07 09:09:40 +00001086 # "String giving the prefix of method names which will be interpreted as
1087 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001088 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001089 # Implicit in the documentation is that testMethodPrefix is respected by
1090 # all loadTestsFrom* methods.
1091 def test_testMethodPrefix__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001092 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001093 class Foo(unittest.TestCase):
1094 def test_1(self): pass
1095 def test_2(self): pass
1096 def foo_bar(self): pass
1097 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001098
Georg Brandl15c5ce92007-03-07 09:09:40 +00001099 tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
1100 tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]
Tim Petersea5962f2007-03-12 18:07:52 +00001101
Georg Brandl15c5ce92007-03-07 09:09:40 +00001102 loader = unittest.TestLoader()
1103 loader.testMethodPrefix = 'foo'
1104 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
1105
1106 loader.testMethodPrefix = 'test'
1107 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001108
Georg Brandl15c5ce92007-03-07 09:09:40 +00001109 # "String giving the prefix of method names which will be interpreted as
1110 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001111 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001112 # Implicit in the documentation is that testMethodPrefix is respected by
1113 # all loadTestsFrom* methods.
1114 def test_testMethodPrefix__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001115 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001116 class Foo(unittest.TestCase):
1117 def test_1(self): pass
1118 def test_2(self): pass
1119 def foo_bar(self): pass
1120 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001121
Georg Brandl15c5ce92007-03-07 09:09:40 +00001122 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1123 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001124
Georg Brandl15c5ce92007-03-07 09:09:40 +00001125 loader = unittest.TestLoader()
1126 loader.testMethodPrefix = 'foo'
1127 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
1128
1129 loader.testMethodPrefix = 'test'
1130 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001131
Georg Brandl15c5ce92007-03-07 09:09:40 +00001132 # "String giving the prefix of method names which will be interpreted as
1133 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001134 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001135 # Implicit in the documentation is that testMethodPrefix is respected by
1136 # all loadTestsFrom* methods.
1137 def test_testMethodPrefix__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001138 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001139 class Foo(unittest.TestCase):
1140 def test_1(self): pass
1141 def test_2(self): pass
1142 def foo_bar(self): pass
1143 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001144
Georg Brandl15c5ce92007-03-07 09:09:40 +00001145 tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
1146 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1147 tests_2 = unittest.TestSuite([tests_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001148
Georg Brandl15c5ce92007-03-07 09:09:40 +00001149 loader = unittest.TestLoader()
1150 loader.testMethodPrefix = 'foo'
1151 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)
1152
1153 loader.testMethodPrefix = 'test'
1154 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001155
Georg Brandl15c5ce92007-03-07 09:09:40 +00001156 # "The default value is 'test'"
1157 def test_testMethodPrefix__default_value(self):
1158 loader = unittest.TestLoader()
1159 self.failUnless(loader.testMethodPrefix == 'test')
Tim Petersea5962f2007-03-12 18:07:52 +00001160
Georg Brandl15c5ce92007-03-07 09:09:40 +00001161 ################################################################
1162 ### /Tests for TestLoader.testMethodPrefix
1163
Tim Petersea5962f2007-03-12 18:07:52 +00001164 ### Tests for TestLoader.sortTestMethodsUsing
Georg Brandl15c5ce92007-03-07 09:09:40 +00001165 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001166
Georg Brandl15c5ce92007-03-07 09:09:40 +00001167 # "Function to be used to compare method names when sorting them in
1168 # getTestCaseNames() and all the loadTestsFromX() methods"
1169 def test_sortTestMethodsUsing__loadTestsFromTestCase(self):
1170 def reversed_cmp(x, y):
1171 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001172
Georg Brandl15c5ce92007-03-07 09:09:40 +00001173 class Foo(unittest.TestCase):
1174 def test_1(self): pass
1175 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001176
Georg Brandl15c5ce92007-03-07 09:09:40 +00001177 loader = unittest.TestLoader()
1178 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001179
Georg Brandl15c5ce92007-03-07 09:09:40 +00001180 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1181 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001182
Georg Brandl15c5ce92007-03-07 09:09:40 +00001183 # "Function to be used to compare method names when sorting them in
1184 # getTestCaseNames() and all the loadTestsFromX() methods"
1185 def test_sortTestMethodsUsing__loadTestsFromModule(self):
1186 def reversed_cmp(x, y):
1187 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001188
Christian Heimesc756d002007-11-27 21:34:01 +00001189 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001190 class Foo(unittest.TestCase):
1191 def test_1(self): pass
1192 def test_2(self): pass
1193 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001194
Georg Brandl15c5ce92007-03-07 09:09:40 +00001195 loader = unittest.TestLoader()
1196 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001197
Georg Brandl15c5ce92007-03-07 09:09:40 +00001198 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1199 self.assertEqual(list(loader.loadTestsFromModule(m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001200
Georg Brandl15c5ce92007-03-07 09:09:40 +00001201 # "Function to be used to compare method names when sorting them in
1202 # getTestCaseNames() and all the loadTestsFromX() methods"
1203 def test_sortTestMethodsUsing__loadTestsFromName(self):
1204 def reversed_cmp(x, y):
1205 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001206
Christian Heimesc756d002007-11-27 21:34:01 +00001207 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001208 class Foo(unittest.TestCase):
1209 def test_1(self): pass
1210 def test_2(self): pass
1211 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001212
Georg Brandl15c5ce92007-03-07 09:09:40 +00001213 loader = unittest.TestLoader()
1214 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001215
Georg Brandl15c5ce92007-03-07 09:09:40 +00001216 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1217 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001218
Georg Brandl15c5ce92007-03-07 09:09:40 +00001219 # "Function to be used to compare method names when sorting them in
1220 # getTestCaseNames() and all the loadTestsFromX() methods"
1221 def test_sortTestMethodsUsing__loadTestsFromNames(self):
1222 def reversed_cmp(x, y):
1223 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001224
Christian Heimesc756d002007-11-27 21:34:01 +00001225 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001226 class Foo(unittest.TestCase):
1227 def test_1(self): pass
1228 def test_2(self): pass
1229 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001230
Georg Brandl15c5ce92007-03-07 09:09:40 +00001231 loader = unittest.TestLoader()
1232 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001233
Georg Brandl15c5ce92007-03-07 09:09:40 +00001234 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1235 self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001236
Georg Brandl15c5ce92007-03-07 09:09:40 +00001237 # "Function to be used to compare method names when sorting them in
1238 # getTestCaseNames()"
1239 #
1240 # Does it actually affect getTestCaseNames()?
1241 def test_sortTestMethodsUsing__getTestCaseNames(self):
1242 def reversed_cmp(x, y):
1243 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001244
Georg Brandl15c5ce92007-03-07 09:09:40 +00001245 class Foo(unittest.TestCase):
1246 def test_1(self): pass
1247 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001248
Georg Brandl15c5ce92007-03-07 09:09:40 +00001249 loader = unittest.TestLoader()
1250 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001251
Georg Brandl15c5ce92007-03-07 09:09:40 +00001252 test_names = ['test_2', 'test_1']
1253 self.assertEqual(loader.getTestCaseNames(Foo), test_names)
Tim Petersea5962f2007-03-12 18:07:52 +00001254
Georg Brandl15c5ce92007-03-07 09:09:40 +00001255 # "The default value is the built-in cmp() function"
1256 def test_sortTestMethodsUsing__default_value(self):
1257 loader = unittest.TestLoader()
1258 self.failUnless(loader.sortTestMethodsUsing is cmp)
Tim Petersea5962f2007-03-12 18:07:52 +00001259
Georg Brandl15c5ce92007-03-07 09:09:40 +00001260 # "it can be set to None to disable the sort."
1261 #
1262 # XXX How is this different from reassigning cmp? Are the tests returned
1263 # in a random order or something? This behaviour should die
1264 def test_sortTestMethodsUsing__None(self):
1265 class Foo(unittest.TestCase):
1266 def test_1(self): pass
1267 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001268
Georg Brandl15c5ce92007-03-07 09:09:40 +00001269 loader = unittest.TestLoader()
1270 loader.sortTestMethodsUsing = None
Tim Petersea5962f2007-03-12 18:07:52 +00001271
Georg Brandl15c5ce92007-03-07 09:09:40 +00001272 test_names = ['test_2', 'test_1']
1273 self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))
Tim Petersea5962f2007-03-12 18:07:52 +00001274
Georg Brandl15c5ce92007-03-07 09:09:40 +00001275 ################################################################
1276 ### /Tests for TestLoader.sortTestMethodsUsing
Tim Petersea5962f2007-03-12 18:07:52 +00001277
Georg Brandl15c5ce92007-03-07 09:09:40 +00001278 ### Tests for TestLoader.suiteClass
1279 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001280
Georg Brandl15c5ce92007-03-07 09:09:40 +00001281 # "Callable object that constructs a test suite from a list of tests."
1282 def test_suiteClass__loadTestsFromTestCase(self):
1283 class Foo(unittest.TestCase):
1284 def test_1(self): pass
1285 def test_2(self): pass
1286 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001287
Georg Brandl15c5ce92007-03-07 09:09:40 +00001288 tests = [Foo('test_1'), Foo('test_2')]
1289
1290 loader = unittest.TestLoader()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001291 loader.suiteClass = list
Georg Brandl15c5ce92007-03-07 09:09:40 +00001292 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001293
Georg Brandl15c5ce92007-03-07 09:09:40 +00001294 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001295 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001296 def test_suiteClass__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001297 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001298 class Foo(unittest.TestCase):
1299 def test_1(self): pass
1300 def test_2(self): pass
1301 def foo_bar(self): pass
1302 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001303
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001304 tests = [[Foo('test_1'), Foo('test_2')]]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001305
1306 loader = unittest.TestLoader()
1307 loader.suiteClass = list
1308 self.assertEqual(loader.loadTestsFromModule(m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001309
Georg Brandl15c5ce92007-03-07 09:09:40 +00001310 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001311 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001312 def test_suiteClass__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001313 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001314 class Foo(unittest.TestCase):
1315 def test_1(self): pass
1316 def test_2(self): pass
1317 def foo_bar(self): pass
1318 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001319
Georg Brandl15c5ce92007-03-07 09:09:40 +00001320 tests = [Foo('test_1'), Foo('test_2')]
1321
1322 loader = unittest.TestLoader()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001323 loader.suiteClass = list
Georg Brandl15c5ce92007-03-07 09:09:40 +00001324 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001325
Georg Brandl15c5ce92007-03-07 09:09:40 +00001326 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001327 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001328 def test_suiteClass__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001329 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001330 class Foo(unittest.TestCase):
1331 def test_1(self): pass
1332 def test_2(self): pass
1333 def foo_bar(self): pass
1334 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001335
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001336 tests = [[Foo('test_1'), Foo('test_2')]]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001337
1338 loader = unittest.TestLoader()
1339 loader.suiteClass = list
1340 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001341
Georg Brandl15c5ce92007-03-07 09:09:40 +00001342 # "The default value is the TestSuite class"
1343 def test_suiteClass__default_value(self):
1344 loader = unittest.TestLoader()
1345 self.failUnless(loader.suiteClass is unittest.TestSuite)
Tim Petersea5962f2007-03-12 18:07:52 +00001346
Georg Brandl15c5ce92007-03-07 09:09:40 +00001347 ################################################################
1348 ### /Tests for TestLoader.suiteClass
1349
1350### Support code for Test_TestSuite
1351################################################################
1352
1353class Foo(unittest.TestCase):
1354 def test_1(self): pass
1355 def test_2(self): pass
1356 def test_3(self): pass
1357 def runTest(self): pass
1358
1359def _mk_TestSuite(*names):
1360 return unittest.TestSuite(Foo(n) for n in names)
Tim Petersea5962f2007-03-12 18:07:52 +00001361
Georg Brandl15c5ce92007-03-07 09:09:40 +00001362################################################################
1363### /Support code for Test_TestSuite
1364
1365class Test_TestSuite(TestCase, TestEquality):
1366
1367 ### Set up attributes needed by inherited tests
1368 ################################################################
1369
1370 # Used by TestEquality.test_eq
1371 eq_pairs = [(unittest.TestSuite(), unittest.TestSuite())
1372 ,(unittest.TestSuite(), unittest.TestSuite([]))
1373 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001374
1375 # Used by TestEquality.test_ne
Georg Brandl15c5ce92007-03-07 09:09:40 +00001376 ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1'))
1377 ,(unittest.TestSuite([]), _mk_TestSuite('test_1'))
1378 ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3'))
1379 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001380
Georg Brandl15c5ce92007-03-07 09:09:40 +00001381 ################################################################
1382 ### /Set up attributes needed by inherited tests
1383
1384 ### Tests for TestSuite.__init__
1385 ################################################################
1386
1387 # "class TestSuite([tests])"
1388 #
1389 # The tests iterable should be optional
1390 def test_init__tests_optional(self):
1391 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001392
Georg Brandl15c5ce92007-03-07 09:09:40 +00001393 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001394
Georg Brandl15c5ce92007-03-07 09:09:40 +00001395 # "class TestSuite([tests])"
1396 # ...
1397 # "If tests is given, it must be an iterable of individual test cases
1398 # or other test suites that will be used to build the suite initially"
1399 #
1400 # TestSuite should deal with empty tests iterables by allowing the
Tim Petersea5962f2007-03-12 18:07:52 +00001401 # creation of an empty suite
Georg Brandl15c5ce92007-03-07 09:09:40 +00001402 def test_init__empty_tests(self):
1403 suite = unittest.TestSuite([])
Tim Petersea5962f2007-03-12 18:07:52 +00001404
Georg Brandl15c5ce92007-03-07 09:09:40 +00001405 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001406
Georg Brandl15c5ce92007-03-07 09:09:40 +00001407 # "class TestSuite([tests])"
1408 # ...
1409 # "If tests is given, it must be an iterable of individual test cases
1410 # or other test suites that will be used to build the suite initially"
1411 #
Tim Petersea5962f2007-03-12 18:07:52 +00001412 # TestSuite should allow any iterable to provide tests
Georg Brandl15c5ce92007-03-07 09:09:40 +00001413 def test_init__tests_from_any_iterable(self):
1414 def tests():
1415 yield unittest.FunctionTestCase(lambda: None)
1416 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001417
Georg Brandl15c5ce92007-03-07 09:09:40 +00001418 suite_1 = unittest.TestSuite(tests())
1419 self.assertEqual(suite_1.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001420
Georg Brandl15c5ce92007-03-07 09:09:40 +00001421 suite_2 = unittest.TestSuite(suite_1)
1422 self.assertEqual(suite_2.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001423
Georg Brandl15c5ce92007-03-07 09:09:40 +00001424 suite_3 = unittest.TestSuite(set(suite_1))
1425 self.assertEqual(suite_3.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001426
Georg Brandl15c5ce92007-03-07 09:09:40 +00001427 # "class TestSuite([tests])"
1428 # ...
1429 # "If tests is given, it must be an iterable of individual test cases
1430 # or other test suites that will be used to build the suite initially"
1431 #
1432 # Does TestSuite() also allow other TestSuite() instances to be present
1433 # in the tests iterable?
1434 def test_init__TestSuite_instances_in_tests(self):
1435 def tests():
1436 ftc = unittest.FunctionTestCase(lambda: None)
1437 yield unittest.TestSuite([ftc])
1438 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001439
Georg Brandl15c5ce92007-03-07 09:09:40 +00001440 suite = unittest.TestSuite(tests())
1441 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001442
Georg Brandl15c5ce92007-03-07 09:09:40 +00001443 ################################################################
1444 ### /Tests for TestSuite.__init__
1445
1446 # Container types should support the iter protocol
1447 def test_iter(self):
1448 test1 = unittest.FunctionTestCase(lambda: None)
1449 test2 = unittest.FunctionTestCase(lambda: None)
1450 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001451
Georg Brandl15c5ce92007-03-07 09:09:40 +00001452 self.assertEqual(list(suite), [test1, test2])
Tim Petersea5962f2007-03-12 18:07:52 +00001453
Georg Brandl15c5ce92007-03-07 09:09:40 +00001454 # "Return the number of tests represented by the this test object.
1455 # ...this method is also implemented by the TestSuite class, which can
1456 # return larger [greater than 1] values"
1457 #
Tim Petersea5962f2007-03-12 18:07:52 +00001458 # Presumably an empty TestSuite returns 0?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001459 def test_countTestCases_zero_simple(self):
1460 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001461
Georg Brandl15c5ce92007-03-07 09:09:40 +00001462 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001463
Georg Brandl15c5ce92007-03-07 09:09:40 +00001464 # "Return the number of tests represented by the this test object.
1465 # ...this method is also implemented by the TestSuite class, which can
1466 # return larger [greater than 1] values"
1467 #
1468 # Presumably an empty TestSuite (even if it contains other empty
1469 # TestSuite instances) returns 0?
1470 def test_countTestCases_zero_nested(self):
1471 class Test1(unittest.TestCase):
1472 def test(self):
1473 pass
1474
1475 suite = unittest.TestSuite([unittest.TestSuite()])
Tim Petersea5962f2007-03-12 18:07:52 +00001476
Georg Brandl15c5ce92007-03-07 09:09:40 +00001477 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001478
Georg Brandl15c5ce92007-03-07 09:09:40 +00001479 # "Return the number of tests represented by the this test object.
1480 # ...this method is also implemented by the TestSuite class, which can
1481 # return larger [greater than 1] values"
1482 def test_countTestCases_simple(self):
1483 test1 = unittest.FunctionTestCase(lambda: None)
1484 test2 = unittest.FunctionTestCase(lambda: None)
1485 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001486
Georg Brandl15c5ce92007-03-07 09:09:40 +00001487 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001488
Georg Brandl15c5ce92007-03-07 09:09:40 +00001489 # "Return the number of tests represented by the this test object.
1490 # ...this method is also implemented by the TestSuite class, which can
1491 # return larger [greater than 1] values"
1492 #
1493 # Make sure this holds for nested TestSuite instances, too
1494 def test_countTestCases_nested(self):
1495 class Test1(unittest.TestCase):
1496 def test1(self): pass
1497 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001498
Georg Brandl15c5ce92007-03-07 09:09:40 +00001499 test2 = unittest.FunctionTestCase(lambda: None)
1500 test3 = unittest.FunctionTestCase(lambda: None)
1501 child = unittest.TestSuite((Test1('test2'), test2))
1502 parent = unittest.TestSuite((test3, child, Test1('test1')))
Tim Petersea5962f2007-03-12 18:07:52 +00001503
Georg Brandl15c5ce92007-03-07 09:09:40 +00001504 self.assertEqual(parent.countTestCases(), 4)
Tim Petersea5962f2007-03-12 18:07:52 +00001505
Georg Brandl15c5ce92007-03-07 09:09:40 +00001506 # "Run the tests associated with this suite, collecting the result into
1507 # the test result object passed as result."
1508 #
1509 # And if there are no tests? What then?
1510 def test_run__empty_suite(self):
1511 events = []
1512 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001513
Georg Brandl15c5ce92007-03-07 09:09:40 +00001514 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001515
Georg Brandl15c5ce92007-03-07 09:09:40 +00001516 suite.run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001517
Georg Brandl15c5ce92007-03-07 09:09:40 +00001518 self.assertEqual(events, [])
Tim Petersea5962f2007-03-12 18:07:52 +00001519
Georg Brandl15c5ce92007-03-07 09:09:40 +00001520 # "Note that unlike TestCase.run(), TestSuite.run() requires the
1521 # "result object to be passed in."
1522 def test_run__requires_result(self):
1523 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001524
Georg Brandl15c5ce92007-03-07 09:09:40 +00001525 try:
1526 suite.run()
1527 except TypeError:
1528 pass
1529 else:
1530 self.fail("Failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +00001531
Georg Brandl15c5ce92007-03-07 09:09:40 +00001532 # "Run the tests associated with this suite, collecting the result into
Tim Petersea5962f2007-03-12 18:07:52 +00001533 # the test result object passed as result."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001534 def test_run(self):
1535 events = []
1536 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001537
Georg Brandl15c5ce92007-03-07 09:09:40 +00001538 class LoggingCase(unittest.TestCase):
1539 def run(self, result):
1540 events.append('run %s' % self._testMethodName)
Tim Petersea5962f2007-03-12 18:07:52 +00001541
Georg Brandl15c5ce92007-03-07 09:09:40 +00001542 def test1(self): pass
1543 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001544
1545 tests = [LoggingCase('test1'), LoggingCase('test2')]
1546
Georg Brandl15c5ce92007-03-07 09:09:40 +00001547 unittest.TestSuite(tests).run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001548
Georg Brandl15c5ce92007-03-07 09:09:40 +00001549 self.assertEqual(events, ['run test1', 'run test2'])
Tim Petersea5962f2007-03-12 18:07:52 +00001550
1551 # "Add a TestCase ... to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001552 def test_addTest__TestCase(self):
1553 class Foo(unittest.TestCase):
1554 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001555
Georg Brandl15c5ce92007-03-07 09:09:40 +00001556 test = Foo('test')
1557 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001558
Georg Brandl15c5ce92007-03-07 09:09:40 +00001559 suite.addTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001560
Georg Brandl15c5ce92007-03-07 09:09:40 +00001561 self.assertEqual(suite.countTestCases(), 1)
1562 self.assertEqual(list(suite), [test])
Tim Petersea5962f2007-03-12 18:07:52 +00001563
1564 # "Add a ... TestSuite to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001565 def test_addTest__TestSuite(self):
1566 class Foo(unittest.TestCase):
1567 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001568
Georg Brandl15c5ce92007-03-07 09:09:40 +00001569 suite_2 = unittest.TestSuite([Foo('test')])
Tim Petersea5962f2007-03-12 18:07:52 +00001570
Georg Brandl15c5ce92007-03-07 09:09:40 +00001571 suite = unittest.TestSuite()
1572 suite.addTest(suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001573
Georg Brandl15c5ce92007-03-07 09:09:40 +00001574 self.assertEqual(suite.countTestCases(), 1)
1575 self.assertEqual(list(suite), [suite_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001576
Georg Brandl15c5ce92007-03-07 09:09:40 +00001577 # "Add all the tests from an iterable of TestCase and TestSuite
1578 # instances to this test suite."
Tim Petersea5962f2007-03-12 18:07:52 +00001579 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001580 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001581 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001582 def test_addTests(self):
1583 class Foo(unittest.TestCase):
1584 def test_1(self): pass
1585 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001586
Georg Brandl15c5ce92007-03-07 09:09:40 +00001587 test_1 = Foo('test_1')
1588 test_2 = Foo('test_2')
1589 inner_suite = unittest.TestSuite([test_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001590
Georg Brandl15c5ce92007-03-07 09:09:40 +00001591 def gen():
1592 yield test_1
1593 yield test_2
1594 yield inner_suite
Tim Petersea5962f2007-03-12 18:07:52 +00001595
Georg Brandl15c5ce92007-03-07 09:09:40 +00001596 suite_1 = unittest.TestSuite()
1597 suite_1.addTests(gen())
Tim Petersea5962f2007-03-12 18:07:52 +00001598
Georg Brandl15c5ce92007-03-07 09:09:40 +00001599 self.assertEqual(list(suite_1), list(gen()))
Tim Petersea5962f2007-03-12 18:07:52 +00001600
Georg Brandl15c5ce92007-03-07 09:09:40 +00001601 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001602 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001603 suite_2 = unittest.TestSuite()
1604 for t in gen():
1605 suite_2.addTest(t)
Tim Petersea5962f2007-03-12 18:07:52 +00001606
Georg Brandl15c5ce92007-03-07 09:09:40 +00001607 self.assertEqual(suite_1, suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001608
Georg Brandl15c5ce92007-03-07 09:09:40 +00001609 # "Add all the tests from an iterable of TestCase and TestSuite
1610 # instances to this test suite."
1611 #
Tim Petersea5962f2007-03-12 18:07:52 +00001612 # What happens if it doesn't get an iterable?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001613 def test_addTest__noniterable(self):
1614 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001615
Georg Brandl15c5ce92007-03-07 09:09:40 +00001616 try:
1617 suite.addTests(5)
1618 except TypeError:
1619 pass
1620 else:
1621 self.fail("Failed to raise TypeError")
Georg Brandld9e50262007-03-07 11:54:49 +00001622
1623 def test_addTest__noncallable(self):
1624 suite = unittest.TestSuite()
1625 self.assertRaises(TypeError, suite.addTest, 5)
1626
1627 def test_addTest__casesuiteclass(self):
1628 suite = unittest.TestSuite()
1629 self.assertRaises(TypeError, suite.addTest, Test_TestSuite)
1630 self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)
1631
1632 def test_addTests__string(self):
1633 suite = unittest.TestSuite()
1634 self.assertRaises(TypeError, suite.addTests, "foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001635
1636
Georg Brandl15c5ce92007-03-07 09:09:40 +00001637class Test_FunctionTestCase(TestCase):
Tim Petersea5962f2007-03-12 18:07:52 +00001638
Georg Brandl15c5ce92007-03-07 09:09:40 +00001639 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00001640 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001641 def test_countTestCases(self):
1642 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001643
Georg Brandl15c5ce92007-03-07 09:09:40 +00001644 self.assertEqual(test.countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00001645
Georg Brandl15c5ce92007-03-07 09:09:40 +00001646 # "When a setUp() method is defined, the test runner will run that method
1647 # prior to each test. Likewise, if a tearDown() method is defined, the
1648 # test runner will invoke that method after each test. In the example,
1649 # setUp() was used to create a fresh sequence for each test."
1650 #
1651 # Make sure the proper call order is maintained, even if setUp() raises
1652 # an exception.
1653 def test_run_call_order__error_in_setUp(self):
1654 events = []
1655 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001656
Georg Brandl15c5ce92007-03-07 09:09:40 +00001657 def setUp():
1658 events.append('setUp')
1659 raise RuntimeError('raised by setUp')
1660
1661 def test():
1662 events.append('test')
1663
1664 def tearDown():
1665 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001666
1667 expected = ['startTest', 'setUp', 'addError', 'stopTest']
Georg Brandl15c5ce92007-03-07 09:09:40 +00001668 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1669 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001670
Georg Brandl15c5ce92007-03-07 09:09:40 +00001671 # "When a setUp() method is defined, the test runner will run that method
1672 # prior to each test. Likewise, if a tearDown() method is defined, the
1673 # test runner will invoke that method after each test. In the example,
1674 # setUp() was used to create a fresh sequence for each test."
1675 #
1676 # Make sure the proper call order is maintained, even if the test raises
1677 # an error (as opposed to a failure).
1678 def test_run_call_order__error_in_test(self):
1679 events = []
1680 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001681
Georg Brandl15c5ce92007-03-07 09:09:40 +00001682 def setUp():
1683 events.append('setUp')
1684
1685 def test():
1686 events.append('test')
1687 raise RuntimeError('raised by test')
1688
1689 def tearDown():
1690 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001691
Georg Brandl15c5ce92007-03-07 09:09:40 +00001692 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
1693 'stopTest']
1694 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1695 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001696
Georg Brandl15c5ce92007-03-07 09:09:40 +00001697 # "When a setUp() method is defined, the test runner will run that method
1698 # prior to each test. Likewise, if a tearDown() method is defined, the
1699 # test runner will invoke that method after each test. In the example,
1700 # setUp() was used to create a fresh sequence for each test."
1701 #
1702 # Make sure the proper call order is maintained, even if the test signals
1703 # a failure (as opposed to an error).
1704 def test_run_call_order__failure_in_test(self):
1705 events = []
1706 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001707
Georg Brandl15c5ce92007-03-07 09:09:40 +00001708 def setUp():
1709 events.append('setUp')
1710
1711 def test():
1712 events.append('test')
1713 self.fail('raised by test')
1714
1715 def tearDown():
1716 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001717
Georg Brandl15c5ce92007-03-07 09:09:40 +00001718 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
1719 'stopTest']
1720 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1721 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001722
Georg Brandl15c5ce92007-03-07 09:09:40 +00001723 # "When a setUp() method is defined, the test runner will run that method
1724 # prior to each test. Likewise, if a tearDown() method is defined, the
1725 # test runner will invoke that method after each test. In the example,
1726 # setUp() was used to create a fresh sequence for each test."
1727 #
1728 # Make sure the proper call order is maintained, even if tearDown() raises
1729 # an exception.
1730 def test_run_call_order__error_in_tearDown(self):
1731 events = []
1732 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001733
Georg Brandl15c5ce92007-03-07 09:09:40 +00001734 def setUp():
1735 events.append('setUp')
1736
1737 def test():
1738 events.append('test')
1739
1740 def tearDown():
1741 events.append('tearDown')
1742 raise RuntimeError('raised by tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001743
Georg Brandl15c5ce92007-03-07 09:09:40 +00001744 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
1745 'stopTest']
1746 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1747 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001748
Georg Brandl15c5ce92007-03-07 09:09:40 +00001749 # "Return a string identifying the specific test case."
1750 #
1751 # Because of the vague nature of the docs, I'm not going to lock this
1752 # test down too much. Really all that can be asserted is that the id()
1753 # will be a string (either 8-byte or unicode -- again, because the docs
1754 # just say "string")
1755 def test_id(self):
1756 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001757
Georg Brandl15c5ce92007-03-07 09:09:40 +00001758 self.failUnless(isinstance(test.id(), basestring))
Tim Petersea5962f2007-03-12 18:07:52 +00001759
Georg Brandl15c5ce92007-03-07 09:09:40 +00001760 # "Returns a one-line description of the test, or None if no description
1761 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001762 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001763 def test_shortDescription__no_docstring(self):
1764 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001765
Georg Brandl15c5ce92007-03-07 09:09:40 +00001766 self.assertEqual(test.shortDescription(), None)
Tim Petersea5962f2007-03-12 18:07:52 +00001767
Georg Brandl15c5ce92007-03-07 09:09:40 +00001768 # "Returns a one-line description of the test, or None if no description
1769 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001770 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001771 def test_shortDescription__singleline_docstring(self):
1772 desc = "this tests foo"
1773 test = unittest.FunctionTestCase(lambda: None, description=desc)
Tim Petersea5962f2007-03-12 18:07:52 +00001774
Georg Brandl15c5ce92007-03-07 09:09:40 +00001775 self.assertEqual(test.shortDescription(), "this tests foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001776
Georg Brandl15c5ce92007-03-07 09:09:40 +00001777class Test_TestResult(TestCase):
1778 # Note: there are not separate tests for TestResult.wasSuccessful(),
1779 # TestResult.errors, TestResult.failures, TestResult.testsRun or
1780 # TestResult.shouldStop because these only have meaning in terms of
1781 # other TestResult methods.
1782 #
1783 # Accordingly, tests for the aforenamed attributes are incorporated
1784 # in with the tests for the defining methods.
1785 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001786
Georg Brandl15c5ce92007-03-07 09:09:40 +00001787 def test_init(self):
1788 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001789
Georg Brandl15c5ce92007-03-07 09:09:40 +00001790 self.failUnless(result.wasSuccessful())
1791 self.assertEqual(len(result.errors), 0)
1792 self.assertEqual(len(result.failures), 0)
1793 self.assertEqual(result.testsRun, 0)
1794 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001795
Georg Brandl15c5ce92007-03-07 09:09:40 +00001796 # "This method can be called to signal that the set of tests being
1797 # run should be aborted by setting the TestResult's shouldStop
Tim Petersea5962f2007-03-12 18:07:52 +00001798 # attribute to True."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001799 def test_stop(self):
1800 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001801
Georg Brandl15c5ce92007-03-07 09:09:40 +00001802 result.stop()
Tim Petersea5962f2007-03-12 18:07:52 +00001803
Georg Brandl15c5ce92007-03-07 09:09:40 +00001804 self.assertEqual(result.shouldStop, True)
Tim Petersea5962f2007-03-12 18:07:52 +00001805
Georg Brandl15c5ce92007-03-07 09:09:40 +00001806 # "Called when the test case test is about to be run. The default
1807 # implementation simply increments the instance's testsRun counter."
1808 def test_startTest(self):
1809 class Foo(unittest.TestCase):
1810 def test_1(self):
1811 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001812
Georg Brandl15c5ce92007-03-07 09:09:40 +00001813 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001814
Georg Brandl15c5ce92007-03-07 09:09:40 +00001815 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001816
Georg Brandl15c5ce92007-03-07 09:09:40 +00001817 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001818
Georg Brandl15c5ce92007-03-07 09:09:40 +00001819 self.failUnless(result.wasSuccessful())
1820 self.assertEqual(len(result.errors), 0)
1821 self.assertEqual(len(result.failures), 0)
1822 self.assertEqual(result.testsRun, 1)
1823 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001824
Georg Brandl15c5ce92007-03-07 09:09:40 +00001825 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001826
Georg Brandl15c5ce92007-03-07 09:09:40 +00001827 # "Called after the test case test has been executed, regardless of
1828 # the outcome. The default implementation does nothing."
1829 def test_stopTest(self):
1830 class Foo(unittest.TestCase):
1831 def test_1(self):
1832 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001833
Georg Brandl15c5ce92007-03-07 09:09:40 +00001834 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001835
Georg Brandl15c5ce92007-03-07 09:09:40 +00001836 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001837
Georg Brandl15c5ce92007-03-07 09:09:40 +00001838 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001839
Georg Brandl15c5ce92007-03-07 09:09:40 +00001840 self.failUnless(result.wasSuccessful())
1841 self.assertEqual(len(result.errors), 0)
1842 self.assertEqual(len(result.failures), 0)
1843 self.assertEqual(result.testsRun, 1)
1844 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001845
Georg Brandl15c5ce92007-03-07 09:09:40 +00001846 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001847
Georg Brandl15c5ce92007-03-07 09:09:40 +00001848 # Same tests as above; make sure nothing has changed
1849 self.failUnless(result.wasSuccessful())
1850 self.assertEqual(len(result.errors), 0)
1851 self.assertEqual(len(result.failures), 0)
1852 self.assertEqual(result.testsRun, 1)
1853 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001854
Michael Foord07ef4872009-05-02 22:43:34 +00001855 # "Called before and after tests are run. The default implementation does nothing."
1856 def test_startTestRun_stopTestRun(self):
1857 result = unittest.TestResult()
1858 result.startTestRun()
1859 result.stopTestRun()
1860
Georg Brandl15c5ce92007-03-07 09:09:40 +00001861 # "addSuccess(test)"
1862 # ...
1863 # "Called when the test case test succeeds"
1864 # ...
1865 # "wasSuccessful() - Returns True if all tests run so far have passed,
1866 # otherwise returns False"
1867 # ...
1868 # "testsRun - The total number of tests run so far."
1869 # ...
1870 # "errors - A list containing 2-tuples of TestCase instances and
1871 # formatted tracebacks. Each tuple represents a test which raised an
1872 # unexpected exception. Contains formatted
1873 # tracebacks instead of sys.exc_info() results."
1874 # ...
1875 # "failures - A list containing 2-tuples of TestCase instances and
1876 # formatted tracebacks. Each tuple represents a test where a failure was
1877 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1878 # methods. Contains formatted tracebacks instead
1879 # of sys.exc_info() results."
1880 def test_addSuccess(self):
1881 class Foo(unittest.TestCase):
1882 def test_1(self):
1883 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001884
Georg Brandl15c5ce92007-03-07 09:09:40 +00001885 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001886
Georg Brandl15c5ce92007-03-07 09:09:40 +00001887 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001888
Georg Brandl15c5ce92007-03-07 09:09:40 +00001889 result.startTest(test)
1890 result.addSuccess(test)
1891 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001892
Georg Brandl15c5ce92007-03-07 09:09:40 +00001893 self.failUnless(result.wasSuccessful())
1894 self.assertEqual(len(result.errors), 0)
1895 self.assertEqual(len(result.failures), 0)
1896 self.assertEqual(result.testsRun, 1)
1897 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001898
Georg Brandl15c5ce92007-03-07 09:09:40 +00001899 # "addFailure(test, err)"
1900 # ...
1901 # "Called when the test case test signals a failure. err is a tuple of
1902 # the form returned by sys.exc_info(): (type, value, traceback)"
1903 # ...
1904 # "wasSuccessful() - Returns True if all tests run so far have passed,
1905 # otherwise returns False"
1906 # ...
1907 # "testsRun - The total number of tests run so far."
1908 # ...
1909 # "errors - A list containing 2-tuples of TestCase instances and
1910 # formatted tracebacks. Each tuple represents a test which raised an
1911 # unexpected exception. Contains formatted
1912 # tracebacks instead of sys.exc_info() results."
1913 # ...
1914 # "failures - A list containing 2-tuples of TestCase instances and
1915 # formatted tracebacks. Each tuple represents a test where a failure was
1916 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1917 # methods. Contains formatted tracebacks instead
1918 # of sys.exc_info() results."
1919 def test_addFailure(self):
1920 import sys
Tim Petersea5962f2007-03-12 18:07:52 +00001921
Georg Brandl15c5ce92007-03-07 09:09:40 +00001922 class Foo(unittest.TestCase):
1923 def test_1(self):
1924 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001925
Georg Brandl15c5ce92007-03-07 09:09:40 +00001926 test = Foo('test_1')
1927 try:
1928 test.fail("foo")
1929 except:
1930 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00001931
Georg Brandl15c5ce92007-03-07 09:09:40 +00001932 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001933
Georg Brandl15c5ce92007-03-07 09:09:40 +00001934 result.startTest(test)
1935 result.addFailure(test, exc_info_tuple)
1936 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001937
Georg Brandl15c5ce92007-03-07 09:09:40 +00001938 self.failIf(result.wasSuccessful())
1939 self.assertEqual(len(result.errors), 0)
1940 self.assertEqual(len(result.failures), 1)
1941 self.assertEqual(result.testsRun, 1)
1942 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001943
Georg Brandl15c5ce92007-03-07 09:09:40 +00001944 test_case, formatted_exc = result.failures[0]
1945 self.failUnless(test_case is test)
1946 self.failUnless(isinstance(formatted_exc, str))
Tim Petersea5962f2007-03-12 18:07:52 +00001947
Georg Brandl15c5ce92007-03-07 09:09:40 +00001948 # "addError(test, err)"
1949 # ...
1950 # "Called when the test case test raises an unexpected exception err
1951 # is a tuple of the form returned by sys.exc_info():
1952 # (type, value, traceback)"
1953 # ...
1954 # "wasSuccessful() - Returns True if all tests run so far have passed,
1955 # otherwise returns False"
1956 # ...
1957 # "testsRun - The total number of tests run so far."
1958 # ...
1959 # "errors - A list containing 2-tuples of TestCase instances and
1960 # formatted tracebacks. Each tuple represents a test which raised an
1961 # unexpected exception. Contains formatted
1962 # tracebacks instead of sys.exc_info() results."
1963 # ...
1964 # "failures - A list containing 2-tuples of TestCase instances and
1965 # formatted tracebacks. Each tuple represents a test where a failure was
1966 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1967 # methods. Contains formatted tracebacks instead
1968 # of sys.exc_info() results."
1969 def test_addError(self):
1970 import sys
Tim Petersea5962f2007-03-12 18:07:52 +00001971
Georg Brandl15c5ce92007-03-07 09:09:40 +00001972 class Foo(unittest.TestCase):
1973 def test_1(self):
1974 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001975
Georg Brandl15c5ce92007-03-07 09:09:40 +00001976 test = Foo('test_1')
1977 try:
1978 raise TypeError()
1979 except:
1980 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00001981
Georg Brandl15c5ce92007-03-07 09:09:40 +00001982 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001983
Georg Brandl15c5ce92007-03-07 09:09:40 +00001984 result.startTest(test)
1985 result.addError(test, exc_info_tuple)
1986 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001987
Georg Brandl15c5ce92007-03-07 09:09:40 +00001988 self.failIf(result.wasSuccessful())
1989 self.assertEqual(len(result.errors), 1)
1990 self.assertEqual(len(result.failures), 0)
1991 self.assertEqual(result.testsRun, 1)
1992 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001993
Georg Brandl15c5ce92007-03-07 09:09:40 +00001994 test_case, formatted_exc = result.errors[0]
1995 self.failUnless(test_case is test)
1996 self.failUnless(isinstance(formatted_exc, str))
1997
1998### Support code for Test_TestCase
1999################################################################
2000
2001class Foo(unittest.TestCase):
2002 def runTest(self): pass
2003 def test1(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002004
Georg Brandl15c5ce92007-03-07 09:09:40 +00002005class Bar(Foo):
2006 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002007
Michael Foord07ef4872009-05-02 22:43:34 +00002008class LoggingTestCase(unittest.TestCase):
2009 """A test case which logs its calls."""
2010
2011 def __init__(self, events):
2012 super(LoggingTestCase, self).__init__('test')
2013 self.events = events
2014
2015 def setUp(self):
2016 self.events.append('setUp')
2017
2018 def test(self):
2019 self.events.append('test')
2020
2021 def tearDown(self):
2022 self.events.append('tearDown')
2023
2024class ResultWithNoStartTestRunStopTestRun(object):
2025 """An object honouring TestResult before startTestRun/stopTestRun."""
2026
2027 def __init__(self):
2028 self.failures = []
2029 self.errors = []
2030 self.testsRun = 0
2031 self.skipped = []
2032 self.expectedFailures = []
2033 self.unexpectedSuccesses = []
2034 self.shouldStop = False
2035
2036 def startTest(self, test):
2037 pass
2038
2039 def stopTest(self, test):
2040 pass
2041
2042 def addError(self, test):
2043 pass
2044
2045 def addFailure(self, test):
2046 pass
2047
2048 def addSuccess(self, test):
2049 pass
2050
2051 def wasSuccessful(self):
2052 return True
2053
2054
Georg Brandl15c5ce92007-03-07 09:09:40 +00002055################################################################
2056### /Support code for Test_TestCase
2057
2058class Test_TestCase(TestCase, TestEquality, TestHashing):
2059
2060 ### Set up attributes used by inherited tests
2061 ################################################################
2062
2063 # Used by TestHashing.test_hash and TestEquality.test_eq
2064 eq_pairs = [(Foo('test1'), Foo('test1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002065
Georg Brandl15c5ce92007-03-07 09:09:40 +00002066 # Used by TestEquality.test_ne
2067 ne_pairs = [(Foo('test1'), Foo('runTest'))
2068 ,(Foo('test1'), Bar('test1'))
2069 ,(Foo('test1'), Bar('test2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002070
Georg Brandl15c5ce92007-03-07 09:09:40 +00002071 ################################################################
2072 ### /Set up attributes used by inherited tests
Tim Petersea5962f2007-03-12 18:07:52 +00002073
Georg Brandl15c5ce92007-03-07 09:09:40 +00002074
2075 # "class TestCase([methodName])"
2076 # ...
2077 # "Each instance of TestCase will run a single test method: the
2078 # method named methodName."
2079 # ...
2080 # "methodName defaults to "runTest"."
2081 #
2082 # Make sure it really is optional, and that it defaults to the proper
2083 # thing.
2084 def test_init__no_test_name(self):
2085 class Test(unittest.TestCase):
2086 def runTest(self): raise MyException()
2087 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002088
Georg Brandl15c5ce92007-03-07 09:09:40 +00002089 self.assertEqual(Test().id()[-13:], '.Test.runTest')
Tim Petersea5962f2007-03-12 18:07:52 +00002090
Georg Brandl15c5ce92007-03-07 09:09:40 +00002091 # "class TestCase([methodName])"
2092 # ...
2093 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002094 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002095 def test_init__test_name__valid(self):
2096 class Test(unittest.TestCase):
2097 def runTest(self): raise MyException()
2098 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002099
Georg Brandl15c5ce92007-03-07 09:09:40 +00002100 self.assertEqual(Test('test').id()[-10:], '.Test.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002101
Georg Brandl15c5ce92007-03-07 09:09:40 +00002102 # "class TestCase([methodName])"
2103 # ...
2104 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002105 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002106 def test_init__test_name__invalid(self):
2107 class Test(unittest.TestCase):
2108 def runTest(self): raise MyException()
2109 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002110
Georg Brandl15c5ce92007-03-07 09:09:40 +00002111 try:
2112 Test('testfoo')
2113 except ValueError:
2114 pass
2115 else:
2116 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +00002117
Georg Brandl15c5ce92007-03-07 09:09:40 +00002118 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00002119 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00002120 def test_countTestCases(self):
2121 class Foo(unittest.TestCase):
2122 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002123
Georg Brandl15c5ce92007-03-07 09:09:40 +00002124 self.assertEqual(Foo('test').countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00002125
Georg Brandl15c5ce92007-03-07 09:09:40 +00002126 # "Return the default type of test result object to be used to run this
2127 # test. For TestCase instances, this will always be
2128 # unittest.TestResult; subclasses of TestCase should
2129 # override this as necessary."
2130 def test_defaultTestResult(self):
2131 class Foo(unittest.TestCase):
2132 def runTest(self):
2133 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002134
Georg Brandl15c5ce92007-03-07 09:09:40 +00002135 result = Foo().defaultTestResult()
2136 self.assertEqual(type(result), unittest.TestResult)
2137
2138 # "When a setUp() method is defined, the test runner will run that method
2139 # prior to each test. Likewise, if a tearDown() method is defined, the
2140 # test runner will invoke that method after each test. In the example,
2141 # setUp() was used to create a fresh sequence for each test."
2142 #
2143 # Make sure the proper call order is maintained, even if setUp() raises
2144 # an exception.
2145 def test_run_call_order__error_in_setUp(self):
2146 events = []
2147 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002148
Michael Foord07ef4872009-05-02 22:43:34 +00002149 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002150 def setUp(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002151 super(Foo, self).setUp()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002152 raise RuntimeError('raised by Foo.setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002153
Michael Foord07ef4872009-05-02 22:43:34 +00002154 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002155 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2156 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002157
Michael Foord07ef4872009-05-02 22:43:34 +00002158 # "With a temporary result stopTestRun is called when setUp errors.
2159 def test_run_call_order__error_in_setUp_default_result(self):
2160 events = []
2161
2162 class Foo(LoggingTestCase):
2163 def defaultTestResult(self):
2164 return LoggingResult(self.events)
2165
2166 def setUp(self):
2167 super(Foo, self).setUp()
2168 raise RuntimeError('raised by Foo.setUp')
2169
2170 Foo(events).run()
2171 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2172 'stopTest', 'stopTestRun']
2173 self.assertEqual(events, expected)
2174
Georg Brandl15c5ce92007-03-07 09:09:40 +00002175 # "When a setUp() method is defined, the test runner will run that method
2176 # prior to each test. Likewise, if a tearDown() method is defined, the
2177 # test runner will invoke that method after each test. In the example,
2178 # setUp() was used to create a fresh sequence for each test."
2179 #
2180 # Make sure the proper call order is maintained, even if the test raises
2181 # an error (as opposed to a failure).
2182 def test_run_call_order__error_in_test(self):
2183 events = []
2184 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002185
Michael Foord07ef4872009-05-02 22:43:34 +00002186 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002187 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002188 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002189 raise RuntimeError('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002190
Georg Brandl15c5ce92007-03-07 09:09:40 +00002191 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2192 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002193 Foo(events).run(result)
2194 self.assertEqual(events, expected)
2195
2196 # "With a default result, an error in the test still results in stopTestRun
2197 # being called."
2198 def test_run_call_order__error_in_test_default_result(self):
2199 events = []
2200
2201 class Foo(LoggingTestCase):
2202 def defaultTestResult(self):
2203 return LoggingResult(self.events)
2204
2205 def test(self):
2206 super(Foo, self).test()
2207 raise RuntimeError('raised by Foo.test')
2208
2209 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2210 'tearDown', 'stopTest', 'stopTestRun']
2211 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002212 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002213
Georg Brandl15c5ce92007-03-07 09:09:40 +00002214 # "When a setUp() method is defined, the test runner will run that method
2215 # prior to each test. Likewise, if a tearDown() method is defined, the
2216 # test runner will invoke that method after each test. In the example,
2217 # setUp() was used to create a fresh sequence for each test."
2218 #
2219 # Make sure the proper call order is maintained, even if the test signals
2220 # a failure (as opposed to an error).
2221 def test_run_call_order__failure_in_test(self):
2222 events = []
2223 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002224
Michael Foord07ef4872009-05-02 22:43:34 +00002225 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002226 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002227 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002228 self.fail('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002229
Georg Brandl15c5ce92007-03-07 09:09:40 +00002230 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2231 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002232 Foo(events).run(result)
2233 self.assertEqual(events, expected)
2234
2235 # "When a test fails with a default result stopTestRun is still called."
2236 def test_run_call_order__failure_in_test_default_result(self):
2237
2238 class Foo(LoggingTestCase):
2239 def defaultTestResult(self):
2240 return LoggingResult(self.events)
2241 def test(self):
2242 super(Foo, self).test()
2243 self.fail('raised by Foo.test')
2244
2245 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2246 'tearDown', 'stopTest', 'stopTestRun']
2247 events = []
2248 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002249 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002250
Georg Brandl15c5ce92007-03-07 09:09:40 +00002251 # "When a setUp() method is defined, the test runner will run that method
2252 # prior to each test. Likewise, if a tearDown() method is defined, the
2253 # test runner will invoke that method after each test. In the example,
2254 # setUp() was used to create a fresh sequence for each test."
2255 #
2256 # Make sure the proper call order is maintained, even if tearDown() raises
2257 # an exception.
2258 def test_run_call_order__error_in_tearDown(self):
2259 events = []
2260 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002261
Michael Foord07ef4872009-05-02 22:43:34 +00002262 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002263 def tearDown(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002264 super(Foo, self).tearDown()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002265 raise RuntimeError('raised by Foo.tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002266
Michael Foord07ef4872009-05-02 22:43:34 +00002267 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002268 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2269 'stopTest']
2270 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002271
Michael Foord07ef4872009-05-02 22:43:34 +00002272 # "When tearDown errors with a default result stopTestRun is still called."
2273 def test_run_call_order__error_in_tearDown_default_result(self):
2274
2275 class Foo(LoggingTestCase):
2276 def defaultTestResult(self):
2277 return LoggingResult(self.events)
2278 def tearDown(self):
2279 super(Foo, self).tearDown()
2280 raise RuntimeError('raised by Foo.tearDown')
2281
2282 events = []
2283 Foo(events).run()
2284 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2285 'addError', 'stopTest', 'stopTestRun']
2286 self.assertEqual(events, expected)
2287
2288 # "TestCase.run() still works when the defaultTestResult is a TestResult
2289 # that does not support startTestRun and stopTestRun.
2290 def test_run_call_order_default_result(self):
2291
2292 class Foo(unittest.TestCase):
2293 def defaultTestResult(self):
2294 return ResultWithNoStartTestRunStopTestRun()
2295 def test(self):
2296 pass
2297
2298 Foo('test').run()
2299
Georg Brandl15c5ce92007-03-07 09:09:40 +00002300 # "This class attribute gives the exception raised by the test() method.
2301 # If a test framework needs to use a specialized exception, possibly to
2302 # carry additional information, it must subclass this exception in
2303 # order to ``play fair'' with the framework. The initial value of this
2304 # attribute is AssertionError"
2305 def test_failureException__default(self):
2306 class Foo(unittest.TestCase):
2307 def test(self):
2308 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002309
Georg Brandl15c5ce92007-03-07 09:09:40 +00002310 self.failUnless(Foo('test').failureException is AssertionError)
Tim Petersea5962f2007-03-12 18:07:52 +00002311
Georg Brandl15c5ce92007-03-07 09:09:40 +00002312 # "This class attribute gives the exception raised by the test() method.
2313 # If a test framework needs to use a specialized exception, possibly to
2314 # carry additional information, it must subclass this exception in
2315 # order to ``play fair'' with the framework."
2316 #
2317 # Make sure TestCase.run() respects the designated failureException
2318 def test_failureException__subclassing__explicit_raise(self):
2319 events = []
2320 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002321
Georg Brandl15c5ce92007-03-07 09:09:40 +00002322 class Foo(unittest.TestCase):
2323 def test(self):
2324 raise RuntimeError()
Tim Petersea5962f2007-03-12 18:07:52 +00002325
Georg Brandl15c5ce92007-03-07 09:09:40 +00002326 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002327
Georg Brandl15c5ce92007-03-07 09:09:40 +00002328 self.failUnless(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002329
2330
Georg Brandl15c5ce92007-03-07 09:09:40 +00002331 Foo('test').run(result)
2332 expected = ['startTest', 'addFailure', 'stopTest']
2333 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002334
Georg Brandl15c5ce92007-03-07 09:09:40 +00002335 # "This class attribute gives the exception raised by the test() method.
2336 # If a test framework needs to use a specialized exception, possibly to
2337 # carry additional information, it must subclass this exception in
2338 # order to ``play fair'' with the framework."
2339 #
2340 # Make sure TestCase.run() respects the designated failureException
2341 def test_failureException__subclassing__implicit_raise(self):
2342 events = []
2343 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002344
Georg Brandl15c5ce92007-03-07 09:09:40 +00002345 class Foo(unittest.TestCase):
2346 def test(self):
2347 self.fail("foo")
Tim Petersea5962f2007-03-12 18:07:52 +00002348
Georg Brandl15c5ce92007-03-07 09:09:40 +00002349 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002350
Georg Brandl15c5ce92007-03-07 09:09:40 +00002351 self.failUnless(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002352
2353
Georg Brandl15c5ce92007-03-07 09:09:40 +00002354 Foo('test').run(result)
2355 expected = ['startTest', 'addFailure', 'stopTest']
2356 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002357
2358 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002359 def test_setUp(self):
2360 class Foo(unittest.TestCase):
2361 def runTest(self):
2362 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002363
Georg Brandl15c5ce92007-03-07 09:09:40 +00002364 # ... and nothing should happen
2365 Foo().setUp()
Tim Petersea5962f2007-03-12 18:07:52 +00002366
2367 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002368 def test_tearDown(self):
2369 class Foo(unittest.TestCase):
2370 def runTest(self):
2371 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002372
Georg Brandl15c5ce92007-03-07 09:09:40 +00002373 # ... and nothing should happen
2374 Foo().tearDown()
Tim Petersea5962f2007-03-12 18:07:52 +00002375
Georg Brandl15c5ce92007-03-07 09:09:40 +00002376 # "Return a string identifying the specific test case."
2377 #
2378 # Because of the vague nature of the docs, I'm not going to lock this
2379 # test down too much. Really all that can be asserted is that the id()
2380 # will be a string (either 8-byte or unicode -- again, because the docs
2381 # just say "string")
2382 def test_id(self):
2383 class Foo(unittest.TestCase):
2384 def runTest(self):
2385 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002386
Georg Brandl15c5ce92007-03-07 09:09:40 +00002387 self.failUnless(isinstance(Foo().id(), basestring))
Tim Petersea5962f2007-03-12 18:07:52 +00002388
Georg Brandl15c5ce92007-03-07 09:09:40 +00002389 # "If result is omitted or None, a temporary result object is created
Michael Foord07ef4872009-05-02 22:43:34 +00002390 # and used, but is not made available to the caller. As TestCase owns the
2391 # temporary result startTestRun and stopTestRun are called.
2392
Georg Brandl15c5ce92007-03-07 09:09:40 +00002393 def test_run__uses_defaultTestResult(self):
2394 events = []
Tim Petersea5962f2007-03-12 18:07:52 +00002395
Georg Brandl15c5ce92007-03-07 09:09:40 +00002396 class Foo(unittest.TestCase):
2397 def test(self):
2398 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002399
Georg Brandl15c5ce92007-03-07 09:09:40 +00002400 def defaultTestResult(self):
2401 return LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002402
2403 # Make run() find a result object on its own
Georg Brandl15c5ce92007-03-07 09:09:40 +00002404 Foo('test').run()
Tim Petersea5962f2007-03-12 18:07:52 +00002405
Michael Foord07ef4872009-05-02 22:43:34 +00002406 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2407 'stopTest', 'stopTestRun']
Georg Brandl15c5ce92007-03-07 09:09:40 +00002408 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002409
Gregory P. Smith28399852009-03-31 16:54:10 +00002410 def testShortDescriptionWithoutDocstring(self):
2411 self.assertEqual(
2412 self.shortDescription(),
2413 'testShortDescriptionWithoutDocstring (' + __name__ +
2414 '.Test_TestCase)')
2415
2416 def testShortDescriptionWithOneLineDocstring(self):
2417 """Tests shortDescription() for a method with a docstring."""
2418 self.assertEqual(
2419 self.shortDescription(),
2420 ('testShortDescriptionWithOneLineDocstring '
2421 '(' + __name__ + '.Test_TestCase)\n'
2422 'Tests shortDescription() for a method with a docstring.'))
2423
2424 def testShortDescriptionWithMultiLineDocstring(self):
2425 """Tests shortDescription() for a method with a longer docstring.
2426
2427 This method ensures that only the first line of a docstring is
2428 returned used in the short description, no matter how long the
2429 whole thing is.
2430 """
2431 self.assertEqual(
2432 self.shortDescription(),
2433 ('testShortDescriptionWithMultiLineDocstring '
2434 '(' + __name__ + '.Test_TestCase)\n'
2435 'Tests shortDescription() for a method with a longer '
2436 'docstring.'))
2437
Gregory P. Smith28399852009-03-31 16:54:10 +00002438 def testAddTypeEqualityFunc(self):
2439 class SadSnake(object):
2440 """Dummy class for test_addTypeEqualityFunc."""
2441 s1, s2 = SadSnake(), SadSnake()
2442 self.assertFalse(s1 == s2)
2443 def AllSnakesCreatedEqual(a, b, msg=None):
2444 return type(a) == type(b) == SadSnake
2445 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2446 self.assertEqual(s1, s2)
2447 # No this doesn't clean up and remove the SadSnake equality func
2448 # from this TestCase instance but since its a local nothing else
2449 # will ever notice that.
2450
Michael Foordf2dfef12009-04-05 19:19:28 +00002451 def testAssertIs(self):
2452 thing = object()
2453 self.assertIs(thing, thing)
2454 self.assertRaises(self.failureException, self.assertIs, thing, object())
2455
2456 def testAssertIsNot(self):
2457 thing = object()
2458 self.assertIsNot(thing, object())
2459 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2460
Gregory P. Smith28399852009-03-31 16:54:10 +00002461 def testAssertIn(self):
2462 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2463
2464 self.assertIn('a', 'abc')
2465 self.assertIn(2, [1, 2, 3])
2466 self.assertIn('monkey', animals)
2467
2468 self.assertNotIn('d', 'abc')
2469 self.assertNotIn(0, [1, 2, 3])
2470 self.assertNotIn('otter', animals)
2471
2472 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2473 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2474 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2475 animals)
2476
2477 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2478 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2479 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2480 animals)
2481
2482 def testAssertDictContainsSubset(self):
2483 self.assertDictContainsSubset({}, {})
2484 self.assertDictContainsSubset({}, {'a': 1})
2485 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2486 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2487 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2488
2489 self.assertRaises(unittest.TestCase.failureException,
2490 self.assertDictContainsSubset, {'a': 2}, {'a': 1},
2491 '.*Mismatched values:.*')
2492
2493 self.assertRaises(unittest.TestCase.failureException,
2494 self.assertDictContainsSubset, {'c': 1}, {'a': 1},
2495 '.*Missing:.*')
2496
2497 self.assertRaises(unittest.TestCase.failureException,
2498 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2499 {'a': 1}, '.*Missing:.*')
2500
2501 self.assertRaises(unittest.TestCase.failureException,
2502 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2503 {'a': 1}, '.*Missing:.*Mismatched values:.*')
2504
2505 def testAssertEqual(self):
2506 equal_pairs = [
2507 ((), ()),
2508 ({}, {}),
2509 ([], []),
2510 (set(), set()),
2511 (frozenset(), frozenset())]
2512 for a, b in equal_pairs:
2513 # This mess of try excepts is to test the assertEqual behavior
2514 # itself.
2515 try:
2516 self.assertEqual(a, b)
2517 except self.failureException:
2518 self.fail('assertEqual(%r, %r) failed' % (a, b))
2519 try:
2520 self.assertEqual(a, b, msg='foo')
2521 except self.failureException:
2522 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2523 try:
2524 self.assertEqual(a, b, 'foo')
2525 except self.failureException:
2526 self.fail('assertEqual(%r, %r) with third parameter failed' %
2527 (a, b))
2528
2529 unequal_pairs = [
2530 ((), []),
2531 ({}, set()),
2532 (set([4,1]), frozenset([4,2])),
2533 (frozenset([4,5]), set([2,3])),
2534 (set([3,4]), set([5,4]))]
2535 for a, b in unequal_pairs:
2536 self.assertRaises(self.failureException, self.assertEqual, a, b)
2537 self.assertRaises(self.failureException, self.assertEqual, a, b,
2538 'foo')
2539 self.assertRaises(self.failureException, self.assertEqual, a, b,
2540 msg='foo')
2541
2542 def testEquality(self):
2543 self.assertListEqual([], [])
2544 self.assertTupleEqual((), ())
2545 self.assertSequenceEqual([], ())
2546
2547 a = [0, 'a', []]
2548 b = []
2549 self.assertRaises(unittest.TestCase.failureException,
2550 self.assertListEqual, a, b)
2551 self.assertRaises(unittest.TestCase.failureException,
2552 self.assertListEqual, tuple(a), tuple(b))
2553 self.assertRaises(unittest.TestCase.failureException,
2554 self.assertSequenceEqual, a, tuple(b))
2555
2556 b.extend(a)
2557 self.assertListEqual(a, b)
2558 self.assertTupleEqual(tuple(a), tuple(b))
2559 self.assertSequenceEqual(a, tuple(b))
2560 self.assertSequenceEqual(tuple(a), b)
2561
2562 self.assertRaises(self.failureException, self.assertListEqual,
2563 a, tuple(b))
2564 self.assertRaises(self.failureException, self.assertTupleEqual,
2565 tuple(a), b)
2566 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2567 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2568 tuple(b))
2569 self.assertRaises(self.failureException, self.assertSequenceEqual,
2570 None, tuple(b))
2571 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2572 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2573 self.assertRaises(self.failureException, self.assertSequenceEqual,
2574 1, 1)
2575
2576 self.assertDictEqual({}, {})
2577
2578 c = { 'x': 1 }
2579 d = {}
2580 self.assertRaises(unittest.TestCase.failureException,
2581 self.assertDictEqual, c, d)
2582
2583 d.update(c)
2584 self.assertDictEqual(c, d)
2585
2586 d['x'] = 0
2587 self.assertRaises(unittest.TestCase.failureException,
2588 self.assertDictEqual, c, d, 'These are unequal')
2589
2590 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2591 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2592 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2593
2594 self.assertSameElements([1, 2, 3], [3, 2, 1])
2595 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2596 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2597 self.assertRaises(self.failureException, self.assertSameElements,
2598 [10], [10, 11])
2599 self.assertRaises(self.failureException, self.assertSameElements,
2600 [10, 11], [10])
2601
2602 # Test that sequences of unhashable objects can be tested for sameness:
2603 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Michael Foordf2dfef12009-04-05 19:19:28 +00002604
Gregory P. Smith28399852009-03-31 16:54:10 +00002605 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2606 self.assertRaises(self.failureException, self.assertSameElements,
2607 [[1]], [[2]])
2608
2609 def testAssertSetEqual(self):
2610 set1 = set()
2611 set2 = set()
2612 self.assertSetEqual(set1, set2)
2613
2614 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2615 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2616 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2617 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2618
2619 set1 = set(['a'])
2620 set2 = set()
2621 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2622
2623 set1 = set(['a'])
2624 set2 = set(['a'])
2625 self.assertSetEqual(set1, set2)
2626
2627 set1 = set(['a'])
2628 set2 = set(['a', 'b'])
2629 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2630
2631 set1 = set(['a'])
2632 set2 = frozenset(['a', 'b'])
2633 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2634
2635 set1 = set(['a', 'b'])
2636 set2 = frozenset(['a', 'b'])
2637 self.assertSetEqual(set1, set2)
2638
2639 set1 = set()
2640 set2 = "foo"
2641 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2642 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2643
2644 # make sure any string formatting is tuple-safe
2645 set1 = set([(0, 1), (2, 3)])
2646 set2 = set([(4, 5)])
2647 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2648
2649 def testInequality(self):
2650 # Try ints
2651 self.assertGreater(2, 1)
2652 self.assertGreaterEqual(2, 1)
2653 self.assertGreaterEqual(1, 1)
2654 self.assertLess(1, 2)
2655 self.assertLessEqual(1, 2)
2656 self.assertLessEqual(1, 1)
2657 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2658 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2659 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2660 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2661 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2662 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2663
2664 # Try Floats
2665 self.assertGreater(1.1, 1.0)
2666 self.assertGreaterEqual(1.1, 1.0)
2667 self.assertGreaterEqual(1.0, 1.0)
2668 self.assertLess(1.0, 1.1)
2669 self.assertLessEqual(1.0, 1.1)
2670 self.assertLessEqual(1.0, 1.0)
2671 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2672 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2673 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2674 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2675 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2676 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2677
2678 # Try Strings
2679 self.assertGreater('bug', 'ant')
2680 self.assertGreaterEqual('bug', 'ant')
2681 self.assertGreaterEqual('ant', 'ant')
2682 self.assertLess('ant', 'bug')
2683 self.assertLessEqual('ant', 'bug')
2684 self.assertLessEqual('ant', 'ant')
2685 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2686 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2687 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2688 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2689 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2690 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2691
2692 # Try Unicode
2693 self.assertGreater(u'bug', u'ant')
2694 self.assertGreaterEqual(u'bug', u'ant')
2695 self.assertGreaterEqual(u'ant', u'ant')
2696 self.assertLess(u'ant', u'bug')
2697 self.assertLessEqual(u'ant', u'bug')
2698 self.assertLessEqual(u'ant', u'ant')
2699 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug')
2700 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant')
2701 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2702 u'bug')
2703 self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant')
2704 self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant')
2705 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant')
2706
2707 # Try Mixed String/Unicode
2708 self.assertGreater('bug', u'ant')
2709 self.assertGreater(u'bug', 'ant')
2710 self.assertGreaterEqual('bug', u'ant')
2711 self.assertGreaterEqual(u'bug', 'ant')
2712 self.assertGreaterEqual('ant', u'ant')
2713 self.assertGreaterEqual(u'ant', 'ant')
2714 self.assertLess('ant', u'bug')
2715 self.assertLess(u'ant', 'bug')
2716 self.assertLessEqual('ant', u'bug')
2717 self.assertLessEqual(u'ant', 'bug')
2718 self.assertLessEqual('ant', u'ant')
2719 self.assertLessEqual(u'ant', 'ant')
2720 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug')
2721 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug')
2722 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant')
2723 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant')
2724 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant',
2725 u'bug')
2726 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2727 'bug')
2728 self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant')
2729 self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant')
2730 self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant')
2731 self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant')
2732 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant')
2733 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant')
2734
2735 def testAssertMultiLineEqual(self):
2736 sample_text = b"""\
2737http://www.python.org/doc/2.3/lib/module-unittest.html
2738test case
2739 A test case is the smallest unit of testing. [...]
2740"""
2741 revised_sample_text = b"""\
2742http://www.python.org/doc/2.4.1/lib/module-unittest.html
2743test case
2744 A test case is the smallest unit of testing. [...] You may provide your
2745 own implementation that does not subclass from TestCase, of course.
2746"""
2747 sample_text_error = b"""
2748- http://www.python.org/doc/2.3/lib/module-unittest.html
2749? ^
2750+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2751? ^^^
2752 test case
2753- A test case is the smallest unit of testing. [...]
2754+ A test case is the smallest unit of testing. [...] You may provide your
2755? +++++++++++++++++++++
2756+ own implementation that does not subclass from TestCase, of course.
2757"""
2758
2759 for type_changer in (lambda x: x, lambda x: x.decode('utf8')):
2760 try:
2761 self.assertMultiLineEqual(type_changer(sample_text),
2762 type_changer(revised_sample_text))
2763 except self.failureException, e:
2764 # no fair testing ourself with ourself, use assertEqual..
2765 self.assertEqual(sample_text_error, str(e).encode('utf8'))
2766
2767 def testAssertIsNone(self):
2768 self.assertIsNone(None)
2769 self.assertRaises(self.failureException, self.assertIsNone, False)
2770 self.assertIsNotNone('DjZoPloGears on Rails')
2771 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2772
2773 def testAssertRegexpMatches(self):
2774 self.assertRegexpMatches('asdfabasdf', r'ab+')
2775 self.assertRaises(self.failureException, self.assertRegexpMatches,
2776 'saaas', r'aaaa')
2777
2778 def testAssertRaisesRegexp(self):
2779 class ExceptionMock(Exception):
2780 pass
2781
2782 def Stub():
2783 raise ExceptionMock('We expect')
2784
2785 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2786 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2787 self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
2788
2789 def testAssertNotRaisesRegexp(self):
2790 self.assertRaisesRegexp(
2791 self.failureException, '^Exception not raised$',
2792 self.assertRaisesRegexp, Exception, re.compile('x'),
2793 lambda: None)
2794 self.assertRaisesRegexp(
2795 self.failureException, '^Exception not raised$',
2796 self.assertRaisesRegexp, Exception, 'x',
2797 lambda: None)
2798 self.assertRaisesRegexp(
2799 self.failureException, '^Exception not raised$',
2800 self.assertRaisesRegexp, Exception, u'x',
2801 lambda: None)
2802
2803 def testAssertRaisesRegexpMismatch(self):
2804 def Stub():
2805 raise Exception('Unexpected')
2806
2807 self.assertRaisesRegexp(
2808 self.failureException,
2809 r'"\^Expected\$" does not match "Unexpected"',
2810 self.assertRaisesRegexp, Exception, '^Expected$',
2811 Stub)
2812 self.assertRaisesRegexp(
2813 self.failureException,
2814 r'"\^Expected\$" does not match "Unexpected"',
2815 self.assertRaisesRegexp, Exception, u'^Expected$',
2816 Stub)
2817 self.assertRaisesRegexp(
2818 self.failureException,
2819 r'"\^Expected\$" does not match "Unexpected"',
2820 self.assertRaisesRegexp, Exception,
2821 re.compile('^Expected$'), Stub)
2822
Gregory P. Smith7558d572009-03-31 19:03:28 +00002823 def testSynonymAssertMethodNames(self):
2824 """Test undocumented method name synonyms.
2825
2826 Please do not use these methods names in your own code.
2827
2828 This test confirms their continued existence and functionality
2829 in order to avoid breaking existing code.
2830 """
2831 self.assertNotEquals(3, 5)
2832 self.assertEquals(3, 3)
2833 self.assertAlmostEquals(2.0, 2.0)
2834 self.assertNotAlmostEquals(3.0, 5.0)
2835 self.assert_(True)
2836
2837 def testPendingDeprecationMethodNames(self):
2838 """Test fail* methods pending deprecation, they will warn in 3.2.
2839
2840 Do not use these methods. They will go away in 3.3.
2841 """
2842 self.failIfEqual(3, 5)
2843 self.failUnlessEqual(3, 3)
2844 self.failUnlessAlmostEqual(2.0, 2.0)
2845 self.failIfAlmostEqual(3.0, 5.0)
2846 self.failUnless(True)
2847 self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam')
2848 self.failIf(False)
2849
Michael Foorde2942d02009-04-02 05:51:54 +00002850 def testDeepcopy(self):
2851 # Issue: 5660
2852 class TestableTest(TestCase):
2853 def testNothing(self):
2854 pass
2855
2856 test = TestableTest('testNothing')
2857
2858 # This shouldn't blow up
2859 deepcopy(test)
2860
Benjamin Peterson692428e2009-03-23 21:50:21 +00002861
2862class Test_TestSkipping(TestCase):
2863
2864 def test_skipping(self):
2865 class Foo(unittest.TestCase):
2866 def test_skip_me(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002867 self.skipTest("skip")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002868 events = []
2869 result = LoggingResult(events)
2870 test = Foo("test_skip_me")
2871 test.run(result)
2872 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2873 self.assertEqual(result.skipped, [(test, "skip")])
2874
2875 # Try letting setUp skip the test now.
2876 class Foo(unittest.TestCase):
2877 def setUp(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002878 self.skipTest("testing")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002879 def test_nothing(self): pass
2880 events = []
2881 result = LoggingResult(events)
2882 test = Foo("test_nothing")
2883 test.run(result)
2884 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2885 self.assertEqual(result.skipped, [(test, "testing")])
2886 self.assertEqual(result.testsRun, 1)
2887
2888 def test_skipping_decorators(self):
2889 op_table = ((unittest.skipUnless, False, True),
2890 (unittest.skipIf, True, False))
2891 for deco, do_skip, dont_skip in op_table:
2892 class Foo(unittest.TestCase):
2893 @deco(do_skip, "testing")
2894 def test_skip(self): pass
2895
2896 @deco(dont_skip, "testing")
2897 def test_dont_skip(self): pass
2898 test_do_skip = Foo("test_skip")
2899 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002900 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002901 events = []
2902 result = LoggingResult(events)
2903 suite.run(result)
2904 self.assertEqual(len(result.skipped), 1)
2905 expected = ['startTest', 'addSkip', 'stopTest',
2906 'startTest', 'addSuccess', 'stopTest']
2907 self.assertEqual(events, expected)
2908 self.assertEqual(result.testsRun, 2)
2909 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
2910 self.assertTrue(result.wasSuccessful())
2911
2912 def test_skip_class(self):
2913 @unittest.skip("testing")
2914 class Foo(unittest.TestCase):
2915 def test_1(self):
2916 record.append(1)
2917 record = []
2918 result = unittest.TestResult()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002919 test = Foo("test_1")
2920 suite = unittest.TestSuite([test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002921 suite.run(result)
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002922 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002923 self.assertEqual(record, [])
2924
2925 def test_expected_failure(self):
2926 class Foo(unittest.TestCase):
2927 @unittest.expectedFailure
2928 def test_die(self):
2929 self.fail("help me!")
2930 events = []
2931 result = LoggingResult(events)
2932 test = Foo("test_die")
2933 test.run(result)
2934 self.assertEqual(events,
2935 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00002936 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00002937 self.assertTrue(result.wasSuccessful())
2938
2939 def test_unexpected_success(self):
2940 class Foo(unittest.TestCase):
2941 @unittest.expectedFailure
2942 def test_die(self):
2943 pass
2944 events = []
2945 result = LoggingResult(events)
2946 test = Foo("test_die")
2947 test.run(result)
2948 self.assertEqual(events,
2949 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
2950 self.assertFalse(result.failures)
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00002951 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002952 self.assertTrue(result.wasSuccessful())
2953
2954
2955
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002956class Test_Assertions(TestCase):
2957 def test_AlmostEqual(self):
2958 self.failUnlessAlmostEqual(1.00000001, 1.0)
2959 self.failIfAlmostEqual(1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00002960 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002961 self.failUnlessAlmostEqual, 1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00002962 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002963 self.failIfAlmostEqual, 1.00000001, 1.0)
2964
2965 self.failUnlessAlmostEqual(1.1, 1.0, places=0)
Gregory P. Smith28399852009-03-31 16:54:10 +00002966 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002967 self.failUnlessAlmostEqual, 1.1, 1.0, places=1)
2968
2969 self.failUnlessAlmostEqual(0, .1+.1j, places=0)
2970 self.failIfAlmostEqual(0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00002971 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002972 self.failUnlessAlmostEqual, 0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00002973 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002974 self.failIfAlmostEqual, 0, .1+.1j, places=0)
2975
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00002976 def test_assertRaises(self):
2977 def _raise(e):
2978 raise e
2979 self.assertRaises(KeyError, _raise, KeyError)
2980 self.assertRaises(KeyError, _raise, KeyError("key"))
2981 try:
2982 self.assertRaises(KeyError, lambda: None)
Gregory P. Smith28399852009-03-31 16:54:10 +00002983 except self.failureException as e:
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00002984 self.assert_("KeyError not raised" in e, str(e))
2985 else:
2986 self.fail("assertRaises() didn't fail")
2987 try:
2988 self.assertRaises(KeyError, _raise, ValueError)
2989 except ValueError:
2990 pass
2991 else:
2992 self.fail("assertRaises() didn't let exception pass through")
2993 with self.assertRaises(KeyError):
2994 raise KeyError
2995 with self.assertRaises(KeyError):
2996 raise KeyError("key")
2997 try:
2998 with self.assertRaises(KeyError):
2999 pass
Gregory P. Smith28399852009-03-31 16:54:10 +00003000 except self.failureException as e:
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00003001 self.assert_("KeyError not raised" in e, str(e))
3002 else:
3003 self.fail("assertRaises() didn't fail")
3004 try:
3005 with self.assertRaises(KeyError):
3006 raise ValueError
3007 except ValueError:
3008 pass
3009 else:
3010 self.fail("assertRaises() didn't let exception pass through")
3011
3012
Michael Foord345b2fe2009-04-02 03:20:38 +00003013class TestLongMessage(TestCase):
3014 """Test that the individual asserts honour longMessage.
3015 This actually tests all the message behaviour for
3016 asserts that use longMessage."""
3017
3018 def setUp(self):
3019 class TestableTestFalse(TestCase):
3020 longMessage = False
3021 failureException = self.failureException
3022
3023 def testTest(self):
3024 pass
3025
3026 class TestableTestTrue(TestCase):
3027 longMessage = True
3028 failureException = self.failureException
3029
3030 def testTest(self):
3031 pass
3032
3033 self.testableTrue = TestableTestTrue('testTest')
3034 self.testableFalse = TestableTestFalse('testTest')
3035
3036 def testDefault(self):
3037 self.assertFalse(TestCase.longMessage)
3038
3039 def test_formatMsg(self):
3040 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3041 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3042
3043 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3044 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3045
3046 def assertMessages(self, methodName, args, errors):
3047 def getMethod(i):
3048 useTestableFalse = i < 2
3049 if useTestableFalse:
3050 test = self.testableFalse
3051 else:
3052 test = self.testableTrue
3053 return getattr(test, methodName)
3054
3055 for i, expected_regexp in enumerate(errors):
3056 testMethod = getMethod(i)
3057 kwargs = {}
3058 withMsg = i % 2
3059 if withMsg:
3060 kwargs = {"msg": "oops"}
3061
3062 with self.assertRaisesRegexp(self.failureException,
3063 expected_regexp=expected_regexp):
3064 testMethod(*args, **kwargs)
3065
3066 def testAssertTrue(self):
3067 self.assertMessages('assertTrue', (False,),
3068 ["^False is not True$", "^oops$", "^False is not True$",
3069 "^False is not True : oops$"])
3070
3071 def testAssertFalse(self):
3072 self.assertMessages('assertFalse', (True,),
3073 ["^True is not False$", "^oops$", "^True is not False$",
3074 "^True is not False : oops$"])
3075
3076 def testNotEqual(self):
3077 self.assertMessages('assertNotEqual', (1, 1),
3078 ["^1 == 1$", "^oops$", "^1 == 1$",
3079 "^1 == 1 : oops$"])
3080
3081 def testAlmostEqual(self):
3082 self.assertMessages('assertAlmostEqual', (1, 2),
3083 ["^1 != 2 within 7 places$", "^oops$",
3084 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3085
3086 def testNotAlmostEqual(self):
3087 self.assertMessages('assertNotAlmostEqual', (1, 1),
3088 ["^1 == 1 within 7 places$", "^oops$",
3089 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3090
3091 def test_baseAssertEqual(self):
3092 self.assertMessages('_baseAssertEqual', (1, 2),
3093 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3094
3095 def testAssertSequenceEqual(self):
3096 # Error messages are multiline so not testing on full message
3097 # assertTupleEqual and assertListEqual delegate to this method
3098 self.assertMessages('assertSequenceEqual', ([], [None]),
3099 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3100 r"\+ \[None\] : oops$"])
3101
3102 def testAssertSetEqual(self):
3103 self.assertMessages('assertSetEqual', (set(), set([None])),
3104 ["None$", "^oops$", "None$",
3105 "None : oops$"])
3106
3107 def testAssertIn(self):
3108 self.assertMessages('assertIn', (None, []),
3109 ['^None not found in \[\]$', "^oops$",
3110 '^None not found in \[\]$',
3111 '^None not found in \[\] : oops$'])
3112
3113 def testAssertNotIn(self):
3114 self.assertMessages('assertNotIn', (None, [None]),
3115 ['^None unexpectedly found in \[None\]$', "^oops$",
3116 '^None unexpectedly found in \[None\]$',
3117 '^None unexpectedly found in \[None\] : oops$'])
3118
3119 def testAssertDictEqual(self):
3120 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3121 [r"\+ \{'key': 'value'\}$", "^oops$",
3122 "\+ \{'key': 'value'\}$",
3123 "\+ \{'key': 'value'\} : oops$"])
3124
3125 def testAssertDictContainsSubset(self):
3126 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3127 ["^Missing: 'key'$", "^oops$",
3128 "^Missing: 'key'$",
3129 "^Missing: 'key' : oops$"])
3130
3131 def testAssertSameElements(self):
3132 self.assertMessages('assertSameElements', ([], [None]),
3133 [r"\[None\]$", "^oops$",
3134 r"\[None\]$",
3135 r"\[None\] : oops$"])
3136
3137 def testAssertMultiLineEqual(self):
3138 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3139 [r"\+ foo$", "^oops$",
3140 r"\+ foo$",
3141 r"\+ foo : oops$"])
3142
3143 def testAssertLess(self):
3144 self.assertMessages('assertLess', (2, 1),
3145 ["^2 not less than 1$", "^oops$",
3146 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3147
3148 def testAssertLessEqual(self):
3149 self.assertMessages('assertLessEqual', (2, 1),
3150 ["^2 not less than or equal to 1$", "^oops$",
3151 "^2 not less than or equal to 1$",
3152 "^2 not less than or equal to 1 : oops$"])
3153
3154 def testAssertGreater(self):
3155 self.assertMessages('assertGreater', (1, 2),
3156 ["^1 not greater than 2$", "^oops$",
3157 "^1 not greater than 2$",
3158 "^1 not greater than 2 : oops$"])
3159
3160 def testAssertGreaterEqual(self):
3161 self.assertMessages('assertGreaterEqual', (1, 2),
3162 ["^1 not greater than or equal to 2$", "^oops$",
3163 "^1 not greater than or equal to 2$",
3164 "^1 not greater than or equal to 2 : oops$"])
3165
3166 def testAssertIsNone(self):
3167 self.assertMessages('assertIsNone', ('not None',),
3168 ["^'not None' is not None$", "^oops$",
3169 "^'not None' is not None$",
3170 "^'not None' is not None : oops$"])
3171
3172 def testAssertIsNotNone(self):
3173 self.assertMessages('assertIsNotNone', (None,),
3174 ["^unexpectedly None$", "^oops$",
3175 "^unexpectedly None$",
3176 "^unexpectedly None : oops$"])
3177
Michael Foordf2dfef12009-04-05 19:19:28 +00003178 def testAssertIs(self):
3179 self.assertMessages('assertIs', (None, 'foo'),
3180 ["^None is not 'foo'$", "^oops$",
3181 "^None is not 'foo'$",
3182 "^None is not 'foo' : oops$"])
3183
3184 def testAssertIsNot(self):
3185 self.assertMessages('assertIsNot', (None, None),
3186 ["^unexpectedly identical: None$", "^oops$",
3187 "^unexpectedly identical: None$",
3188 "^unexpectedly identical: None : oops$"])
3189
Michael Foord345b2fe2009-04-02 03:20:38 +00003190
Michael Foorde2fb98f2009-05-02 20:15:05 +00003191class TestCleanUp(TestCase):
3192
3193 def testCleanUp(self):
3194 class TestableTest(TestCase):
3195 def testNothing(self):
3196 pass
3197
3198 test = TestableTest('testNothing')
3199 self.assertEqual(test._cleanups, [])
3200
3201 cleanups = []
3202
3203 def cleanup1(*args, **kwargs):
3204 cleanups.append((1, args, kwargs))
3205
3206 def cleanup2(*args, **kwargs):
3207 cleanups.append((2, args, kwargs))
3208
3209 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3210 test.addCleanup(cleanup2)
3211
3212 self.assertEqual(test._cleanups,
3213 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3214 (cleanup2, (), {})])
3215
3216 result = test.doCleanups()
3217 self.assertTrue(result)
3218
3219 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3220
3221 def testCleanUpWithErrors(self):
3222 class TestableTest(TestCase):
3223 def testNothing(self):
3224 pass
3225
3226 class MockResult(object):
3227 errors = []
3228 def addError(self, test, exc_info):
3229 self.errors.append((test, exc_info))
3230
3231 result = MockResult()
3232 test = TestableTest('testNothing')
Michael Foorda50af062009-05-21 22:57:02 +00003233 test._resultForDoCleanups = result
Michael Foorde2fb98f2009-05-02 20:15:05 +00003234
3235 exc1 = Exception('foo')
3236 exc2 = Exception('bar')
3237 def cleanup1():
3238 raise exc1
3239
3240 def cleanup2():
3241 raise exc2
3242
3243 test.addCleanup(cleanup1)
3244 test.addCleanup(cleanup2)
3245
3246 self.assertFalse(test.doCleanups())
3247
3248 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3249 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3250 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3251
3252 def testCleanupInRun(self):
3253 blowUp = False
3254 ordering = []
3255
3256 class TestableTest(TestCase):
3257 def setUp(self):
3258 ordering.append('setUp')
3259 if blowUp:
3260 raise Exception('foo')
3261
3262 def testNothing(self):
3263 ordering.append('test')
3264
3265 def tearDown(self):
3266 ordering.append('tearDown')
3267
3268 test = TestableTest('testNothing')
3269
3270 def cleanup1():
3271 ordering.append('cleanup1')
3272 def cleanup2():
3273 ordering.append('cleanup2')
3274 test.addCleanup(cleanup1)
3275 test.addCleanup(cleanup2)
3276
3277 def success(some_test):
3278 self.assertEqual(some_test, test)
3279 ordering.append('success')
3280
3281 result = unittest.TestResult()
3282 result.addSuccess = success
3283
3284 test.run(result)
3285 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3286 'cleanup2', 'cleanup1', 'success'])
3287
3288 blowUp = True
3289 ordering = []
3290 test = TestableTest('testNothing')
3291 test.addCleanup(cleanup1)
3292 test.run(result)
3293 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3294
3295
Michael Foord829f6b82009-05-02 11:43:06 +00003296class Test_TestProgram(TestCase):
3297
3298 # Horrible white box test
3299 def testNoExit(self):
3300 result = object()
3301 test = object()
3302
3303 class FakeRunner(object):
3304 def run(self, test):
3305 self.test = test
3306 return result
3307
3308 runner = FakeRunner()
3309
Michael Foord5d31e052009-05-11 17:59:43 +00003310 oldParseArgs = TestProgram.parseArgs
3311 def restoreParseArgs():
Michael Foord829f6b82009-05-02 11:43:06 +00003312 TestProgram.parseArgs = oldParseArgs
Michael Foord5d31e052009-05-11 17:59:43 +00003313 TestProgram.parseArgs = lambda *args: None
3314 self.addCleanup(restoreParseArgs)
3315
3316 def removeTest():
Michael Foord829f6b82009-05-02 11:43:06 +00003317 del TestProgram.test
Michael Foord5d31e052009-05-11 17:59:43 +00003318 TestProgram.test = test
3319 self.addCleanup(removeTest)
3320
3321 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3322
3323 self.assertEqual(program.result, result)
3324 self.assertEqual(runner.test, test)
3325 self.assertEqual(program.verbosity, 2)
Michael Foord829f6b82009-05-02 11:43:06 +00003326
3327
3328 class FooBar(unittest.TestCase):
3329 def testPass(self):
3330 assert True
3331 def testFail(self):
3332 assert False
3333
3334 class FooBarLoader(unittest.TestLoader):
3335 """Test loader that returns a suite containing FooBar."""
3336 def loadTestsFromModule(self, module):
3337 return self.suiteClass(
3338 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3339
3340
3341 def test_NonExit(self):
3342 program = unittest.main(exit=False,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003343 argv=["foobar"],
3344 testRunner=unittest.TextTestRunner(stream=StringIO()),
3345 testLoader=self.FooBarLoader())
Michael Foord829f6b82009-05-02 11:43:06 +00003346 self.assertTrue(hasattr(program, 'result'))
3347
3348
3349 def test_Exit(self):
3350 self.assertRaises(
3351 SystemExit,
3352 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003353 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003354 testRunner=unittest.TextTestRunner(stream=StringIO()),
3355 exit=True,
3356 testLoader=self.FooBarLoader())
3357
3358
3359 def test_ExitAsDefault(self):
3360 self.assertRaises(
3361 SystemExit,
3362 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003363 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003364 testRunner=unittest.TextTestRunner(stream=StringIO()),
3365 testLoader=self.FooBarLoader())
3366
3367
Michael Foord07ef4872009-05-02 22:43:34 +00003368class Test_TextTestRunner(TestCase):
3369 """Tests for TextTestRunner."""
3370
3371 def test_works_with_result_without_startTestRun_stopTestRun(self):
3372 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3373 separator2 = ''
3374 def printErrors(self):
3375 pass
3376
3377 class Runner(unittest.TextTestRunner):
3378 def __init__(self):
3379 super(Runner, self).__init__(StringIO())
3380
3381 def _makeResult(self):
3382 return OldTextResult()
3383
3384 runner = Runner()
3385 runner.run(unittest.TestSuite())
3386
3387 def test_startTestRun_stopTestRun_called(self):
3388 class LoggingTextResult(LoggingResult):
3389 separator2 = ''
3390 def printErrors(self):
3391 pass
3392
3393 class LoggingRunner(unittest.TextTestRunner):
3394 def __init__(self, events):
3395 super(LoggingRunner, self).__init__(StringIO())
3396 self._events = events
3397
3398 def _makeResult(self):
3399 return LoggingTextResult(self._events)
3400
3401 events = []
3402 runner = LoggingRunner(events)
3403 runner.run(unittest.TestSuite())
3404 expected = ['startTestRun', 'stopTestRun']
3405 self.assertEqual(events, expected)
3406
3407
Michael Foordb4a81c82009-05-29 20:33:46 +00003408class TestDiscovery(TestCase):
3409
3410 # Heavily mocked tests so I can avoid hitting the filesystem
3411 def test_get_module_from_path(self):
3412 loader = unittest.TestLoader()
3413
3414 def restore_import():
3415 unittest.__import__ = __import__
3416 unittest.__import__ = lambda *_: None
3417 self.addCleanup(restore_import)
3418
3419 expected_module = object()
3420 def del_module():
3421 del sys.modules['bar.baz']
3422 sys.modules['bar.baz'] = expected_module
3423 self.addCleanup(del_module)
3424
3425 loader._top_level_dir = '/foo'
3426 module = loader._get_module_from_path('/foo/bar/baz.py')
3427 self.assertEqual(module, expected_module)
3428
3429 if not __debug__:
3430 # asserts are off
3431 return
3432
3433 with self.assertRaises(AssertionError):
3434 loader._get_module_from_path('/bar/baz.py')
3435
3436 def test_find_tests(self):
3437 loader = unittest.TestLoader()
3438
3439 original_listdir = os.listdir
3440 def restore_listdir():
3441 os.listdir = original_listdir
3442 original_isfile = os.path.isfile
3443 def restore_isfile():
3444 os.path.isfile = original_isfile
3445 original_isdir = os.path.isdir
3446 def restore_isdir():
3447 os.path.isdir = original_isdir
3448
3449 path_lists = [['test1.py', 'test2.py', 'not_a_test.py', 'test_dir',
3450 'test.foo', 'another_dir'],
3451 ['test3.py', 'test4.py', ]]
3452 os.listdir = lambda path: path_lists.pop(0)
3453 self.addCleanup(restore_listdir)
3454
3455 def isdir(path):
3456 return path.endswith('dir')
3457 os.path.isdir = isdir
3458 self.addCleanup(restore_isdir)
3459
3460 def isfile(path):
3461 # another_dir is not a package and so shouldn't be recursed into
3462 return not path.endswith('dir') and not 'another_dir' in path
3463 os.path.isfile = isfile
3464 self.addCleanup(restore_isfile)
3465
3466 loader._get_module_from_path = lambda path: path + ' module'
3467 loader.loadTestsFromModule = lambda module: module + ' tests'
3468
3469 loader._top_level_dir = '/foo'
3470 suite = list(loader._find_tests('/foo', 'test*.py'))
3471
3472 expected = [os.path.join('/foo', name) + ' module tests' for name in
3473 ('test1.py', 'test2.py')]
3474 expected.extend([os.path.join('/foo', 'test_dir', name) + ' module tests' for name in
3475 ('test3.py', 'test4.py')])
3476 self.assertEqual(suite, expected)
3477
3478 def test_find_tests_with_package(self):
3479 loader = unittest.TestLoader()
3480
3481 original_listdir = os.listdir
3482 def restore_listdir():
3483 os.listdir = original_listdir
3484 original_isfile = os.path.isfile
3485 def restore_isfile():
3486 os.path.isfile = original_isfile
3487 original_isdir = os.path.isdir
3488 def restore_isdir():
3489 os.path.isdir = original_isdir
3490
3491 directories = ['a_directory', 'test_directory', 'test_directory2']
3492 path_lists = [directories, [], [], []]
3493 os.listdir = lambda path: path_lists.pop(0)
3494 self.addCleanup(restore_listdir)
3495
3496 os.path.isdir = lambda path: True
3497 self.addCleanup(restore_isdir)
3498
3499 os.path.isfile = lambda path: os.path.basename(path) not in directories
3500 self.addCleanup(restore_isfile)
3501
3502 class Module(object):
3503 paths = []
3504 load_tests_args = []
3505
3506 def __init__(self, path):
3507 self.path = path
3508 self.paths.append(path)
3509 if os.path.basename(path) == 'test_directory':
3510 def load_tests(loader, tests, pattern):
3511 self.load_tests_args.append((loader, tests, pattern))
3512 return 'load_tests'
3513 self.load_tests = load_tests
3514
3515 def __eq__(self, other):
3516 return self.path == other.path
3517
3518 loader._get_module_from_path = lambda path: Module(path)
3519 def loadTestsFromModule(module, use_load_tests):
3520 if use_load_tests:
3521 raise self.failureException('use_load_tests should be False for packages')
3522 return module.path + ' module tests'
3523 loader.loadTestsFromModule = loadTestsFromModule
3524
3525 loader._top_level_dir = '/foo'
3526 # this time no '.py' on the pattern so that it can match
3527 # a test package
3528 suite = list(loader._find_tests('/foo', 'test*'))
3529
3530 # We should have loaded tests from the test_directory package by calling load_tests
3531 # and directly from the test_directory2 package
3532 self.assertEqual(suite, ['load_tests', '/foo/test_directory2 module tests'])
3533 self.assertEqual(Module.paths, [os.path.join('/foo', 'test_directory'),
3534 os.path.join('/foo', 'test_directory2')])
3535
3536 # load_tests should have been called once with loader, tests and pattern
3537 self.assertEqual(Module.load_tests_args,
3538 [(loader, os.path.join('/foo', 'test_directory') + ' module tests',
3539 'test*')])
3540
3541 def test_discover(self):
3542 loader = unittest.TestLoader()
3543
3544 original_isfile = os.path.isfile
3545 def restore_isfile():
3546 os.path.isfile = original_isfile
3547
3548 os.path.isfile = lambda path: False
3549 self.addCleanup(restore_isfile)
3550
3551 full_path = os.path.abspath(os.path.normpath('/foo'))
3552 def clean_path():
3553 if sys.path[-1] == full_path:
3554 sys.path.pop(-1)
3555 self.addCleanup(clean_path)
3556
3557 with self.assertRaises(ImportError):
3558 loader.discover('/foo/bar', top_level_dir='/foo')
3559
3560 self.assertEqual(loader._top_level_dir, full_path)
3561 self.assertIn(full_path, sys.path)
3562
3563 os.path.isfile = lambda path: True
3564 _find_tests_args = []
3565 def _find_tests(start_dir, pattern):
3566 _find_tests_args.append((start_dir, pattern))
3567 return ['tests']
3568 loader._find_tests = _find_tests
3569 loader.suiteClass = str
3570
3571 suite = loader.discover('/foo/bar/baz', 'pattern', '/foo/bar')
3572
3573 top_level_dir = os.path.abspath(os.path.normpath('/foo/bar'))
3574 start_dir = os.path.abspath(os.path.normpath('/foo/bar/baz'))
3575 self.assertEqual(suite, "['tests']")
3576 self.assertEqual(loader._top_level_dir, top_level_dir)
3577 self.assertEqual(_find_tests_args, [(start_dir, 'pattern')])
3578
3579 def test_command_line_handling_parseArgs(self):
3580 # Haha - take that uninstantiable class
3581 program = object.__new__(TestProgram)
3582
3583 args = []
3584 def do_discovery(argv):
3585 args.extend(argv)
3586 program._do_discovery = do_discovery
3587 program.parseArgs(['something', 'discover'])
3588 self.assertEqual(args, [])
3589
3590 program.parseArgs(['something', 'discover', 'foo', 'bar'])
3591 self.assertEqual(args, ['foo', 'bar'])
3592
3593 def test_command_line_handling_do_discovery_too_many_arguments(self):
3594 class Stop(Exception):
3595 pass
3596 def usageExit():
3597 raise Stop
3598
3599 program = object.__new__(TestProgram)
3600 program.usageExit = usageExit
3601
3602 with self.assertRaises(Stop):
3603 # too many args
3604 program._do_discovery(['one', 'two', 'three', 'four'])
3605
3606
3607 def test_command_line_handling_do_discovery_calls_loader(self):
3608 program = object.__new__(TestProgram)
3609
3610 class Loader(object):
3611 args = []
3612 def discover(self, start_dir, pattern, top_level_dir):
3613 self.args.append((start_dir, pattern, top_level_dir))
3614 return 'tests'
3615
3616 program._do_discovery(['-v'], Loader=Loader)
3617 self.assertEqual(program.verbosity, 2)
3618 self.assertEqual(program.test, 'tests')
3619 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3620
3621 Loader.args = []
3622 program = object.__new__(TestProgram)
3623 program._do_discovery(['--verbose'], Loader=Loader)
3624 self.assertEqual(program.test, 'tests')
3625 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3626
3627 Loader.args = []
3628 program = object.__new__(TestProgram)
3629 program._do_discovery([], Loader=Loader)
3630 self.assertEqual(program.test, 'tests')
3631 self.assertEqual(Loader.args, [('.', 'test*.py', None)])
3632
3633 Loader.args = []
3634 program = object.__new__(TestProgram)
3635 program._do_discovery(['fish'], Loader=Loader)
3636 self.assertEqual(program.test, 'tests')
3637 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3638
3639 Loader.args = []
3640 program = object.__new__(TestProgram)
3641 program._do_discovery(['fish', 'eggs'], Loader=Loader)
3642 self.assertEqual(program.test, 'tests')
3643 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3644
3645 Loader.args = []
3646 program = object.__new__(TestProgram)
3647 program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
3648 self.assertEqual(program.test, 'tests')
3649 self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
3650
3651 Loader.args = []
3652 program = object.__new__(TestProgram)
3653 program._do_discovery(['-s', 'fish'], Loader=Loader)
3654 self.assertEqual(program.test, 'tests')
3655 self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
3656
3657 Loader.args = []
3658 program = object.__new__(TestProgram)
3659 program._do_discovery(['-t', 'fish'], Loader=Loader)
3660 self.assertEqual(program.test, 'tests')
3661 self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
3662
3663 Loader.args = []
3664 program = object.__new__(TestProgram)
3665 program._do_discovery(['-p', 'fish'], Loader=Loader)
3666 self.assertEqual(program.test, 'tests')
3667 self.assertEqual(Loader.args, [('.', 'fish', None)])
3668
3669 Loader.args = []
3670 program = object.__new__(TestProgram)
3671 program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v'], Loader=Loader)
3672 self.assertEqual(program.test, 'tests')
3673 self.assertEqual(Loader.args, [('fish', 'eggs', None)])
3674 self.assertEqual(program.verbosity, 2)
3675
3676
Jim Fultonfafd8742004-08-28 15:22:12 +00003677######################################################################
3678## Main
3679######################################################################
3680
3681def test_main():
Georg Brandl15c5ce92007-03-07 09:09:40 +00003682 test_support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003683 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Michael Foord829f6b82009-05-02 11:43:06 +00003684 Test_TestSkipping, Test_Assertions, TestLongMessage,
Michael Foordb4a81c82009-05-29 20:33:46 +00003685 Test_TestProgram, TestCleanUp, TestDiscovery)
Jim Fultonfafd8742004-08-28 15:22:12 +00003686
Georg Brandl15c5ce92007-03-07 09:09:40 +00003687if __name__ == "__main__":
Tim Petersea5962f2007-03-12 18:07:52 +00003688 test_main()