blob: 9c1fe2a3d2f6f01305bc414466def94ad8442e2f [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
Gregory P. Smith28399852009-03-31 16:54:10 +000010import re
Georg Brandl15c5ce92007-03-07 09:09:40 +000011from test import test_support
Jim Fultonfafd8742004-08-28 15:22:12 +000012import unittest
Michael Foord829f6b82009-05-02 11:43:06 +000013from unittest import TestCase, TestProgram
Christian Heimesc756d002007-11-27 21:34:01 +000014import types
Michael Foorde2942d02009-04-02 05:51:54 +000015from copy import deepcopy
Michael Foord829f6b82009-05-02 11:43:06 +000016from cStringIO import StringIO
Jim Fultonfafd8742004-08-28 15:22:12 +000017
Georg Brandl15c5ce92007-03-07 09:09:40 +000018### Support code
19################################################################
Jim Fultonfafd8742004-08-28 15:22:12 +000020
Georg Brandl15c5ce92007-03-07 09:09:40 +000021class LoggingResult(unittest.TestResult):
22 def __init__(self, log):
23 self._events = log
24 super(LoggingResult, self).__init__()
25
26 def startTest(self, test):
27 self._events.append('startTest')
28 super(LoggingResult, self).startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +000029
Michael Foord07ef4872009-05-02 22:43:34 +000030 def startTestRun(self):
31 self._events.append('startTestRun')
32 super(LoggingResult, self).startTestRun()
33
Georg Brandl15c5ce92007-03-07 09:09:40 +000034 def stopTest(self, test):
35 self._events.append('stopTest')
36 super(LoggingResult, self).stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +000037
Michael Foord07ef4872009-05-02 22:43:34 +000038 def stopTestRun(self):
39 self._events.append('stopTestRun')
40 super(LoggingResult, self).stopTestRun()
41
Georg Brandl15c5ce92007-03-07 09:09:40 +000042 def addFailure(self, *args):
43 self._events.append('addFailure')
44 super(LoggingResult, self).addFailure(*args)
Tim Petersea5962f2007-03-12 18:07:52 +000045
Benjamin Peterson692428e2009-03-23 21:50:21 +000046 def addSuccess(self, *args):
47 self._events.append('addSuccess')
48 super(LoggingResult, self).addSuccess(*args)
49
Georg Brandl15c5ce92007-03-07 09:09:40 +000050 def addError(self, *args):
51 self._events.append('addError')
52 super(LoggingResult, self).addError(*args)
53
Benjamin Peterson692428e2009-03-23 21:50:21 +000054 def addSkip(self, *args):
55 self._events.append('addSkip')
56 super(LoggingResult, self).addSkip(*args)
57
58 def addExpectedFailure(self, *args):
59 self._events.append('addExpectedFailure')
60 super(LoggingResult, self).addExpectedFailure(*args)
61
62 def addUnexpectedSuccess(self, *args):
63 self._events.append('addUnexpectedSuccess')
64 super(LoggingResult, self).addUnexpectedSuccess(*args)
65
66
Georg Brandl15c5ce92007-03-07 09:09:40 +000067class TestEquality(object):
Michael Foord345b2fe2009-04-02 03:20:38 +000068 """Used as a mixin for TestCase"""
69
Tim Petersea5962f2007-03-12 18:07:52 +000070 # Check for a valid __eq__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000071 def test_eq(self):
72 for obj_1, obj_2 in self.eq_pairs:
73 self.assertEqual(obj_1, obj_2)
74 self.assertEqual(obj_2, obj_1)
Tim Petersea5962f2007-03-12 18:07:52 +000075
76 # Check for a valid __ne__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000077 def test_ne(self):
78 for obj_1, obj_2 in self.ne_pairs:
79 self.failIfEqual(obj_1, obj_2)
80 self.failIfEqual(obj_2, obj_1)
Tim Petersea5962f2007-03-12 18:07:52 +000081
Georg Brandl15c5ce92007-03-07 09:09:40 +000082class TestHashing(object):
Michael Foord345b2fe2009-04-02 03:20:38 +000083 """Used as a mixin for TestCase"""
84
Tim Petersea5962f2007-03-12 18:07:52 +000085 # Check for a valid __hash__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000086 def test_hash(self):
87 for obj_1, obj_2 in self.eq_pairs:
88 try:
Gregory P. Smith28399852009-03-31 16:54:10 +000089 if not hash(obj_1) == hash(obj_2):
90 self.fail("%r and %r do not hash equal" % (obj_1, obj_2))
Georg Brandl15c5ce92007-03-07 09:09:40 +000091 except KeyboardInterrupt:
92 raise
Georg Brandl15c5ce92007-03-07 09:09:40 +000093 except Exception, e:
Gregory P. Smith28399852009-03-31 16:54:10 +000094 self.fail("Problem hashing %r and %r: %s" % (obj_1, obj_2, e))
Tim Petersea5962f2007-03-12 18:07:52 +000095
Georg Brandl15c5ce92007-03-07 09:09:40 +000096 for obj_1, obj_2 in self.ne_pairs:
97 try:
Gregory P. Smith28399852009-03-31 16:54:10 +000098 if hash(obj_1) == hash(obj_2):
99 self.fail("%s and %s hash equal, but shouldn't" %
100 (obj_1, obj_2))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000101 except KeyboardInterrupt:
102 raise
Georg Brandl15c5ce92007-03-07 09:09:40 +0000103 except Exception, e:
104 self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e))
Tim Petersea5962f2007-03-12 18:07:52 +0000105
Georg Brandl15c5ce92007-03-07 09:09:40 +0000106
Benjamin Peterson692428e2009-03-23 21:50:21 +0000107# List subclass we can add attributes to.
108class MyClassSuite(list):
109
Benjamin Peterson176a56c2009-05-25 00:48:58 +0000110 def __init__(self, tests):
Benjamin Peterson692428e2009-03-23 21:50:21 +0000111 super(MyClassSuite, self).__init__(tests)
112
113
Georg Brandl15c5ce92007-03-07 09:09:40 +0000114################################################################
115### /Support code
116
117class Test_TestLoader(TestCase):
118
119 ### Tests for TestLoader.loadTestsFromTestCase
120 ################################################################
121
122 # "Return a suite of all tests cases contained in the TestCase-derived
123 # class testCaseClass"
124 def test_loadTestsFromTestCase(self):
125 class Foo(unittest.TestCase):
126 def test_1(self): pass
127 def test_2(self): pass
128 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000129
Georg Brandl15c5ce92007-03-07 09:09:40 +0000130 tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +0000131
Georg Brandl15c5ce92007-03-07 09:09:40 +0000132 loader = unittest.TestLoader()
133 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +0000134
Georg Brandl15c5ce92007-03-07 09:09:40 +0000135 # "Return a suite of all tests cases contained in the TestCase-derived
136 # class testCaseClass"
137 #
Tim Petersea5962f2007-03-12 18:07:52 +0000138 # Make sure it does the right thing even if no tests were found
Georg Brandl15c5ce92007-03-07 09:09:40 +0000139 def test_loadTestsFromTestCase__no_matches(self):
140 class Foo(unittest.TestCase):
141 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000142
Georg Brandl15c5ce92007-03-07 09:09:40 +0000143 empty_suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +0000144
Georg Brandl15c5ce92007-03-07 09:09:40 +0000145 loader = unittest.TestLoader()
146 self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite)
Tim Petersea5962f2007-03-12 18:07:52 +0000147
Georg Brandl15c5ce92007-03-07 09:09:40 +0000148 # "Return a suite of all tests cases contained in the TestCase-derived
149 # class testCaseClass"
150 #
151 # What happens if loadTestsFromTestCase() is given an object
152 # that isn't a subclass of TestCase? Specifically, what happens
153 # if testCaseClass is a subclass of TestSuite?
154 #
155 # This is checked for specifically in the code, so we better add a
156 # test for it.
157 def test_loadTestsFromTestCase__TestSuite_subclass(self):
158 class NotATestCase(unittest.TestSuite):
159 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000160
Georg Brandl15c5ce92007-03-07 09:09:40 +0000161 loader = unittest.TestLoader()
162 try:
163 loader.loadTestsFromTestCase(NotATestCase)
164 except TypeError:
165 pass
166 else:
167 self.fail('Should raise TypeError')
Tim Petersea5962f2007-03-12 18:07:52 +0000168
Georg Brandl15c5ce92007-03-07 09:09:40 +0000169 # "Return a suite of all tests cases contained in the TestCase-derived
170 # class testCaseClass"
171 #
172 # Make sure loadTestsFromTestCase() picks up the default test method
173 # name (as specified by TestCase), even though the method name does
174 # not match the default TestLoader.testMethodPrefix string
175 def test_loadTestsFromTestCase__default_method_name(self):
176 class Foo(unittest.TestCase):
177 def runTest(self):
178 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000179
Georg Brandl15c5ce92007-03-07 09:09:40 +0000180 loader = unittest.TestLoader()
181 # This has to be false for the test to succeed
182 self.failIf('runTest'.startswith(loader.testMethodPrefix))
Tim Petersea5962f2007-03-12 18:07:52 +0000183
Georg Brandl15c5ce92007-03-07 09:09:40 +0000184 suite = loader.loadTestsFromTestCase(Foo)
185 self.failUnless(isinstance(suite, loader.suiteClass))
186 self.assertEqual(list(suite), [Foo('runTest')])
187
188 ################################################################
189 ### /Tests for TestLoader.loadTestsFromTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000190
Georg Brandl15c5ce92007-03-07 09:09:40 +0000191 ### Tests for TestLoader.loadTestsFromModule
192 ################################################################
193
194 # "This method searches `module` for classes derived from TestCase"
195 def test_loadTestsFromModule__TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000196 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000197 class MyTestCase(unittest.TestCase):
198 def test(self):
199 pass
200 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000201
Georg Brandl15c5ce92007-03-07 09:09:40 +0000202 loader = unittest.TestLoader()
203 suite = loader.loadTestsFromModule(m)
204 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000205
Georg Brandl15c5ce92007-03-07 09:09:40 +0000206 expected = [loader.suiteClass([MyTestCase('test')])]
207 self.assertEqual(list(suite), expected)
Tim Petersea5962f2007-03-12 18:07:52 +0000208
Georg Brandl15c5ce92007-03-07 09:09:40 +0000209 # "This method searches `module` for classes derived from TestCase"
Tim Petersea5962f2007-03-12 18:07:52 +0000210 #
Georg Brandl15c5ce92007-03-07 09:09:40 +0000211 # What happens if no tests are found (no TestCase instances)?
212 def test_loadTestsFromModule__no_TestCase_instances(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000213 m = types.ModuleType('m')
Tim Petersea5962f2007-03-12 18:07:52 +0000214
Georg Brandl15c5ce92007-03-07 09:09:40 +0000215 loader = unittest.TestLoader()
216 suite = loader.loadTestsFromModule(m)
217 self.failUnless(isinstance(suite, loader.suiteClass))
218 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000219
Georg Brandl15c5ce92007-03-07 09:09:40 +0000220 # "This method searches `module` for classes derived from TestCase"
221 #
Tim Petersea5962f2007-03-12 18:07:52 +0000222 # What happens if no tests are found (TestCases instances, but no tests)?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000223 def test_loadTestsFromModule__no_TestCase_tests(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000224 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000225 class MyTestCase(unittest.TestCase):
226 pass
227 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000228
Georg Brandl15c5ce92007-03-07 09:09:40 +0000229 loader = unittest.TestLoader()
230 suite = loader.loadTestsFromModule(m)
231 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000232
Georg Brandl15c5ce92007-03-07 09:09:40 +0000233 self.assertEqual(list(suite), [loader.suiteClass()])
Tim Petersea5962f2007-03-12 18:07:52 +0000234
Georg Brandl15c5ce92007-03-07 09:09:40 +0000235 # "This method searches `module` for classes derived from TestCase"s
236 #
237 # What happens if loadTestsFromModule() is given something other
238 # than a module?
239 #
240 # XXX Currently, it succeeds anyway. This flexibility
241 # should either be documented or loadTestsFromModule() should
242 # raise a TypeError
243 #
244 # XXX Certain people are using this behaviour. We'll add a test for it
245 def test_loadTestsFromModule__not_a_module(self):
246 class MyTestCase(unittest.TestCase):
247 def test(self):
248 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000249
Georg Brandl15c5ce92007-03-07 09:09:40 +0000250 class NotAModule(object):
251 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000252
Georg Brandl15c5ce92007-03-07 09:09:40 +0000253 loader = unittest.TestLoader()
254 suite = loader.loadTestsFromModule(NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000255
Georg Brandl15c5ce92007-03-07 09:09:40 +0000256 reference = [unittest.TestSuite([MyTestCase('test')])]
257 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000258
Georg Brandl15c5ce92007-03-07 09:09:40 +0000259 ################################################################
260 ### /Tests for TestLoader.loadTestsFromModule()
Tim Petersea5962f2007-03-12 18:07:52 +0000261
Georg Brandl15c5ce92007-03-07 09:09:40 +0000262 ### Tests for TestLoader.loadTestsFromName()
263 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000264
Georg Brandl15c5ce92007-03-07 09:09:40 +0000265 # "The specifier name is a ``dotted name'' that may resolve either to
266 # a module, a test case class, a TestSuite instance, a test method
267 # within a test case class, or a callable object which returns a
268 # TestCase or TestSuite instance."
269 #
270 # Is ValueError raised in response to an empty name?
271 def test_loadTestsFromName__empty_name(self):
272 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000273
Georg Brandl15c5ce92007-03-07 09:09:40 +0000274 try:
275 loader.loadTestsFromName('')
276 except ValueError, e:
277 self.assertEqual(str(e), "Empty module name")
278 else:
279 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000280
Georg Brandl15c5ce92007-03-07 09:09:40 +0000281 # "The specifier name is a ``dotted name'' that may resolve either to
282 # a module, a test case class, a TestSuite instance, a test method
283 # within a test case class, or a callable object which returns a
284 # TestCase or TestSuite instance."
285 #
Tim Petersea5962f2007-03-12 18:07:52 +0000286 # What happens when the name contains invalid characters?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000287 def test_loadTestsFromName__malformed_name(self):
288 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000289
Georg Brandl15c5ce92007-03-07 09:09:40 +0000290 # XXX Should this raise ValueError or ImportError?
291 try:
292 loader.loadTestsFromName('abc () //')
293 except ValueError:
294 pass
295 except ImportError:
296 pass
297 else:
298 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000299
Georg Brandl15c5ce92007-03-07 09:09:40 +0000300 # "The specifier name is a ``dotted name'' that may resolve ... to a
301 # module"
302 #
Tim Petersea5962f2007-03-12 18:07:52 +0000303 # What happens when a module by that name can't be found?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000304 def test_loadTestsFromName__unknown_module_name(self):
305 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000306
Georg Brandl15c5ce92007-03-07 09:09:40 +0000307 try:
308 loader.loadTestsFromName('sdasfasfasdf')
309 except ImportError, e:
310 self.assertEqual(str(e), "No module named sdasfasfasdf")
311 else:
312 self.fail("TestLoader.loadTestsFromName failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000313
Georg Brandl15c5ce92007-03-07 09:09:40 +0000314 # "The specifier name is a ``dotted name'' that may resolve either to
315 # a module, a test case class, a TestSuite instance, a test method
316 # within a test case class, or a callable object which returns a
317 # TestCase or TestSuite instance."
318 #
Tim Petersea5962f2007-03-12 18:07:52 +0000319 # What happens when the module is found, but the attribute can't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000320 def test_loadTestsFromName__unknown_attr_name(self):
321 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000322
Georg Brandl15c5ce92007-03-07 09:09:40 +0000323 try:
324 loader.loadTestsFromName('unittest.sdasfasfasdf')
325 except AttributeError, e:
326 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
327 else:
328 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000329
Georg Brandl15c5ce92007-03-07 09:09:40 +0000330 # "The specifier name is a ``dotted name'' that may resolve either to
331 # a module, a test case class, a TestSuite instance, a test method
332 # within a test case class, or a callable object which returns a
333 # TestCase or TestSuite instance."
334 #
335 # What happens when we provide the module, but the attribute can't be
336 # found?
337 def test_loadTestsFromName__relative_unknown_name(self):
338 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000339
Georg Brandl15c5ce92007-03-07 09:09:40 +0000340 try:
341 loader.loadTestsFromName('sdasfasfasdf', unittest)
342 except AttributeError, e:
343 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
344 else:
345 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000346
Georg Brandl15c5ce92007-03-07 09:09:40 +0000347 # "The specifier name is a ``dotted name'' that may resolve either to
348 # a module, a test case class, a TestSuite instance, a test method
349 # within a test case class, or a callable object which returns a
350 # TestCase or TestSuite instance."
351 # ...
352 # "The method optionally resolves name relative to the given module"
353 #
354 # Does loadTestsFromName raise ValueError when passed an empty
355 # name relative to a provided module?
356 #
357 # XXX Should probably raise a ValueError instead of an AttributeError
358 def test_loadTestsFromName__relative_empty_name(self):
359 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000360
Georg Brandl15c5ce92007-03-07 09:09:40 +0000361 try:
362 loader.loadTestsFromName('', unittest)
363 except AttributeError, e:
364 pass
365 else:
366 self.fail("Failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000367
Georg Brandl15c5ce92007-03-07 09:09:40 +0000368 # "The specifier name is a ``dotted name'' that may resolve either to
369 # a module, a test case class, a TestSuite instance, a test method
370 # within a test case class, or a callable object which returns a
371 # TestCase or TestSuite instance."
372 # ...
373 # "The method optionally resolves name relative to the given module"
374 #
375 # What happens when an impossible name is given, relative to the provided
376 # `module`?
377 def test_loadTestsFromName__relative_malformed_name(self):
378 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000379
Georg Brandl15c5ce92007-03-07 09:09:40 +0000380 # XXX Should this raise AttributeError or ValueError?
381 try:
382 loader.loadTestsFromName('abc () //', unittest)
383 except ValueError:
384 pass
385 except AttributeError:
386 pass
387 else:
388 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
389
390 # "The method optionally resolves name relative to the given module"
391 #
392 # Does loadTestsFromName raise TypeError when the `module` argument
393 # isn't a module object?
394 #
395 # XXX Accepts the not-a-module object, ignorning the object's type
396 # This should raise an exception or the method name should be changed
397 #
398 # XXX Some people are relying on this, so keep it for now
399 def test_loadTestsFromName__relative_not_a_module(self):
400 class MyTestCase(unittest.TestCase):
401 def test(self):
402 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000403
Georg Brandl15c5ce92007-03-07 09:09:40 +0000404 class NotAModule(object):
405 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000406
Georg Brandl15c5ce92007-03-07 09:09:40 +0000407 loader = unittest.TestLoader()
408 suite = loader.loadTestsFromName('test_2', NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000409
Georg Brandl15c5ce92007-03-07 09:09:40 +0000410 reference = [MyTestCase('test')]
411 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000412
Georg Brandl15c5ce92007-03-07 09:09:40 +0000413 # "The specifier name is a ``dotted name'' that may resolve either to
414 # a module, a test case class, a TestSuite instance, a test method
415 # within a test case class, or a callable object which returns a
416 # TestCase or TestSuite instance."
417 #
418 # Does it raise an exception if the name resolves to an invalid
419 # object?
420 def test_loadTestsFromName__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000421 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000422 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000423
Georg Brandl15c5ce92007-03-07 09:09:40 +0000424 loader = unittest.TestLoader()
425 try:
426 loader.loadTestsFromName('testcase_1', m)
427 except TypeError:
428 pass
429 else:
430 self.fail("Should have raised TypeError")
431
432 # "The specifier name is a ``dotted name'' that may
433 # resolve either to ... a test case class"
434 def test_loadTestsFromName__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000435 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000436 class MyTestCase(unittest.TestCase):
437 def test(self):
438 pass
439 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000440
Georg Brandl15c5ce92007-03-07 09:09:40 +0000441 loader = unittest.TestLoader()
442 suite = loader.loadTestsFromName('testcase_1', m)
443 self.failUnless(isinstance(suite, loader.suiteClass))
444 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000445
Georg Brandl15c5ce92007-03-07 09:09:40 +0000446 # "The specifier name is a ``dotted name'' that may resolve either to
447 # a module, a test case class, a TestSuite instance, a test method
448 # within a test case class, or a callable object which returns a
449 # TestCase or TestSuite instance."
450 def test_loadTestsFromName__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000451 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000452 class MyTestCase(unittest.TestCase):
453 def test(self):
454 pass
455 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000456
Georg Brandl15c5ce92007-03-07 09:09:40 +0000457 loader = unittest.TestLoader()
458 suite = loader.loadTestsFromName('testsuite', m)
459 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000460
Georg Brandl15c5ce92007-03-07 09:09:40 +0000461 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000462
Georg Brandl15c5ce92007-03-07 09:09:40 +0000463 # "The specifier name is a ``dotted name'' that may resolve ... to
464 # ... a test method within a test case class"
465 def test_loadTestsFromName__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000466 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000467 class MyTestCase(unittest.TestCase):
468 def test(self):
469 pass
470 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000471
Georg Brandl15c5ce92007-03-07 09:09:40 +0000472 loader = unittest.TestLoader()
473 suite = loader.loadTestsFromName('testcase_1.test', m)
474 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000475
Georg Brandl15c5ce92007-03-07 09:09:40 +0000476 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000477
Georg Brandl15c5ce92007-03-07 09:09:40 +0000478 # "The specifier name is a ``dotted name'' that may resolve either to
479 # a module, a test case class, a TestSuite instance, a test method
480 # within a test case class, or a callable object which returns a
481 # TestCase or TestSuite instance."
482 #
483 # Does loadTestsFromName() raise the proper exception when trying to
484 # resolve "a test method within a test case class" that doesn't exist
485 # for the given name (relative to a provided module)?
486 def test_loadTestsFromName__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000487 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000488 class MyTestCase(unittest.TestCase):
489 def test(self):
490 pass
491 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000492
Georg Brandl15c5ce92007-03-07 09:09:40 +0000493 loader = unittest.TestLoader()
494 try:
495 loader.loadTestsFromName('testcase_1.testfoo', m)
496 except AttributeError, e:
497 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
498 else:
499 self.fail("Failed to raise AttributeError")
500
501 # "The specifier name is a ``dotted name'' that may resolve ... to
502 # ... a callable object which returns a ... TestSuite instance"
503 def test_loadTestsFromName__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000504 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000505 testcase_1 = unittest.FunctionTestCase(lambda: None)
506 testcase_2 = unittest.FunctionTestCase(lambda: None)
507 def return_TestSuite():
508 return unittest.TestSuite([testcase_1, testcase_2])
509 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000510
Georg Brandl15c5ce92007-03-07 09:09:40 +0000511 loader = unittest.TestLoader()
512 suite = loader.loadTestsFromName('return_TestSuite', m)
513 self.failUnless(isinstance(suite, loader.suiteClass))
514 self.assertEqual(list(suite), [testcase_1, testcase_2])
Tim Petersea5962f2007-03-12 18:07:52 +0000515
Georg Brandl15c5ce92007-03-07 09:09:40 +0000516 # "The specifier name is a ``dotted name'' that may resolve ... to
517 # ... a callable object which returns a TestCase ... instance"
518 def test_loadTestsFromName__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000519 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000520 testcase_1 = unittest.FunctionTestCase(lambda: None)
521 def return_TestCase():
522 return testcase_1
523 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000524
Georg Brandl15c5ce92007-03-07 09:09:40 +0000525 loader = unittest.TestLoader()
526 suite = loader.loadTestsFromName('return_TestCase', m)
527 self.failUnless(isinstance(suite, loader.suiteClass))
528 self.assertEqual(list(suite), [testcase_1])
Tim Petersea5962f2007-03-12 18:07:52 +0000529
Georg Brandl15c5ce92007-03-07 09:09:40 +0000530 # "The specifier name is a ``dotted name'' that may resolve ... to
531 # ... a callable object which returns a TestCase or TestSuite instance"
532 #
533 # What happens if the callable returns something else?
534 def test_loadTestsFromName__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000535 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000536 def return_wrong():
537 return 6
538 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000539
Georg Brandl15c5ce92007-03-07 09:09:40 +0000540 loader = unittest.TestLoader()
541 try:
542 suite = loader.loadTestsFromName('return_wrong', m)
543 except TypeError:
544 pass
545 else:
546 self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000547
Georg Brandl15c5ce92007-03-07 09:09:40 +0000548 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +0000549 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +0000550 def test_loadTestsFromName__module_not_loaded(self):
551 # We're going to try to load this module as a side-effect, so it
552 # better not be loaded before we try.
553 #
554 # Why pick audioop? Google shows it isn't used very often, so there's
555 # a good chance that it won't be imported when this test is run
556 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +0000557
Georg Brandl15c5ce92007-03-07 09:09:40 +0000558 import sys
559 if module_name in sys.modules:
560 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000561
Georg Brandl15c5ce92007-03-07 09:09:40 +0000562 loader = unittest.TestLoader()
563 try:
564 suite = loader.loadTestsFromName(module_name)
565
566 self.failUnless(isinstance(suite, loader.suiteClass))
567 self.assertEqual(list(suite), [])
568
569 # audioop should now be loaded, thanks to loadTestsFromName()
570 self.failUnless(module_name in sys.modules)
571 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000572 if module_name in sys.modules:
573 del sys.modules[module_name]
Georg Brandl15c5ce92007-03-07 09:09:40 +0000574
575 ################################################################
576 ### Tests for TestLoader.loadTestsFromName()
577
578 ### Tests for TestLoader.loadTestsFromNames()
579 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000580
Georg Brandl15c5ce92007-03-07 09:09:40 +0000581 # "Similar to loadTestsFromName(), but takes a sequence of names rather
582 # than a single name."
583 #
584 # What happens if that sequence of names is empty?
585 def test_loadTestsFromNames__empty_name_list(self):
586 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000587
Georg Brandl15c5ce92007-03-07 09:09:40 +0000588 suite = loader.loadTestsFromNames([])
589 self.failUnless(isinstance(suite, loader.suiteClass))
590 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000591
Georg Brandl15c5ce92007-03-07 09:09:40 +0000592 # "Similar to loadTestsFromName(), but takes a sequence of names rather
593 # than a single name."
594 # ...
595 # "The method optionally resolves name relative to the given module"
596 #
597 # What happens if that sequence of names is empty?
598 #
599 # XXX Should this raise a ValueError or just return an empty TestSuite?
600 def test_loadTestsFromNames__relative_empty_name_list(self):
601 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000602
Georg Brandl15c5ce92007-03-07 09:09:40 +0000603 suite = loader.loadTestsFromNames([], unittest)
604 self.failUnless(isinstance(suite, loader.suiteClass))
605 self.assertEqual(list(suite), [])
606
607 # "The specifier name is a ``dotted name'' that may resolve either to
608 # a module, a test case class, a TestSuite instance, a test method
609 # within a test case class, or a callable object which returns a
610 # TestCase or TestSuite instance."
611 #
612 # Is ValueError raised in response to an empty name?
613 def test_loadTestsFromNames__empty_name(self):
614 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000615
Georg Brandl15c5ce92007-03-07 09:09:40 +0000616 try:
617 loader.loadTestsFromNames([''])
618 except ValueError, e:
619 self.assertEqual(str(e), "Empty module name")
620 else:
621 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000622
Georg Brandl15c5ce92007-03-07 09:09:40 +0000623 # "The specifier name is a ``dotted name'' that may resolve either to
624 # a module, a test case class, a TestSuite instance, a test method
625 # within a test case class, or a callable object which returns a
626 # TestCase or TestSuite instance."
627 #
Tim Petersea5962f2007-03-12 18:07:52 +0000628 # What happens when presented with an impossible module name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000629 def test_loadTestsFromNames__malformed_name(self):
630 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000631
Georg Brandl15c5ce92007-03-07 09:09:40 +0000632 # XXX Should this raise ValueError or ImportError?
633 try:
634 loader.loadTestsFromNames(['abc () //'])
635 except ValueError:
636 pass
637 except ImportError:
638 pass
639 else:
640 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000641
Georg Brandl15c5ce92007-03-07 09:09:40 +0000642 # "The specifier name is a ``dotted name'' that may resolve either to
643 # a module, a test case class, a TestSuite instance, a test method
644 # within a test case class, or a callable object which returns a
645 # TestCase or TestSuite instance."
646 #
Tim Petersea5962f2007-03-12 18:07:52 +0000647 # What happens when no module can be found for the given name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000648 def test_loadTestsFromNames__unknown_module_name(self):
649 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000650
Georg Brandl15c5ce92007-03-07 09:09:40 +0000651 try:
652 loader.loadTestsFromNames(['sdasfasfasdf'])
653 except ImportError, e:
654 self.assertEqual(str(e), "No module named sdasfasfasdf")
655 else:
656 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000657
Georg Brandl15c5ce92007-03-07 09:09:40 +0000658 # "The specifier name is a ``dotted name'' that may resolve either to
659 # a module, a test case class, a TestSuite instance, a test method
660 # within a test case class, or a callable object which returns a
661 # TestCase or TestSuite instance."
662 #
Tim Petersea5962f2007-03-12 18:07:52 +0000663 # What happens when the module can be found, but not the attribute?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000664 def test_loadTestsFromNames__unknown_attr_name(self):
665 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000666
Georg Brandl15c5ce92007-03-07 09:09:40 +0000667 try:
668 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
669 except AttributeError, e:
670 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
671 else:
672 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000673
Georg Brandl15c5ce92007-03-07 09:09:40 +0000674 # "The specifier name is a ``dotted name'' that may resolve either to
675 # a module, a test case class, a TestSuite instance, a test method
676 # within a test case class, or a callable object which returns a
677 # TestCase or TestSuite instance."
678 # ...
679 # "The method optionally resolves name relative to the given module"
680 #
681 # What happens when given an unknown attribute on a specified `module`
682 # argument?
683 def test_loadTestsFromNames__unknown_name_relative_1(self):
684 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000685
Georg Brandl15c5ce92007-03-07 09:09:40 +0000686 try:
687 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
688 except AttributeError, e:
689 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
690 else:
691 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000692
Georg Brandl15c5ce92007-03-07 09:09:40 +0000693 # "The specifier name is a ``dotted name'' that may resolve either to
694 # a module, a test case class, a TestSuite instance, a test method
695 # within a test case class, or a callable object which returns a
696 # TestCase or TestSuite instance."
697 # ...
698 # "The method optionally resolves name relative to the given module"
699 #
700 # Do unknown attributes (relative to a provided module) still raise an
Tim Petersea5962f2007-03-12 18:07:52 +0000701 # exception even in the presence of valid attribute names?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000702 def test_loadTestsFromNames__unknown_name_relative_2(self):
703 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000704
Georg Brandl15c5ce92007-03-07 09:09:40 +0000705 try:
706 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
707 except AttributeError, e:
708 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
709 else:
710 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
711
712 # "The specifier name is a ``dotted name'' that may resolve either to
713 # a module, a test case class, a TestSuite instance, a test method
714 # within a test case class, or a callable object which returns a
715 # TestCase or TestSuite instance."
716 # ...
717 # "The method optionally resolves name relative to the given module"
718 #
719 # What happens when faced with the empty string?
720 #
721 # XXX This currently raises AttributeError, though ValueError is probably
722 # more appropriate
723 def test_loadTestsFromNames__relative_empty_name(self):
724 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000725
Georg Brandl15c5ce92007-03-07 09:09:40 +0000726 try:
727 loader.loadTestsFromNames([''], unittest)
728 except AttributeError:
729 pass
730 else:
731 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000732
Georg Brandl15c5ce92007-03-07 09:09:40 +0000733 # "The specifier name is a ``dotted name'' that may resolve either to
734 # a module, a test case class, a TestSuite instance, a test method
735 # within a test case class, or a callable object which returns a
736 # TestCase or TestSuite instance."
737 # ...
738 # "The method optionally resolves name relative to the given module"
739 #
Tim Petersea5962f2007-03-12 18:07:52 +0000740 # What happens when presented with an impossible attribute name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000741 def test_loadTestsFromNames__relative_malformed_name(self):
742 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000743
Georg Brandl15c5ce92007-03-07 09:09:40 +0000744 # XXX Should this raise AttributeError or ValueError?
745 try:
746 loader.loadTestsFromNames(['abc () //'], unittest)
747 except AttributeError:
748 pass
749 except ValueError:
750 pass
751 else:
752 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
753
754 # "The method optionally resolves name relative to the given module"
755 #
756 # Does loadTestsFromNames() make sure the provided `module` is in fact
757 # a module?
758 #
759 # XXX This validation is currently not done. This flexibility should
760 # either be documented or a TypeError should be raised.
761 def test_loadTestsFromNames__relative_not_a_module(self):
762 class MyTestCase(unittest.TestCase):
763 def test(self):
764 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000765
Georg Brandl15c5ce92007-03-07 09:09:40 +0000766 class NotAModule(object):
767 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000768
Georg Brandl15c5ce92007-03-07 09:09:40 +0000769 loader = unittest.TestLoader()
770 suite = loader.loadTestsFromNames(['test_2'], NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000771
Georg Brandl15c5ce92007-03-07 09:09:40 +0000772 reference = [unittest.TestSuite([MyTestCase('test')])]
773 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000774
Georg Brandl15c5ce92007-03-07 09:09:40 +0000775 # "The specifier name is a ``dotted name'' that may resolve either to
776 # a module, a test case class, a TestSuite instance, a test method
777 # within a test case class, or a callable object which returns a
778 # TestCase or TestSuite instance."
779 #
780 # Does it raise an exception if the name resolves to an invalid
781 # object?
782 def test_loadTestsFromNames__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000783 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000784 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000785
Georg Brandl15c5ce92007-03-07 09:09:40 +0000786 loader = unittest.TestLoader()
787 try:
788 loader.loadTestsFromNames(['testcase_1'], m)
789 except TypeError:
790 pass
791 else:
792 self.fail("Should have raised TypeError")
793
794 # "The specifier name is a ``dotted name'' that may resolve ... to
795 # ... a test case class"
796 def test_loadTestsFromNames__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000797 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000798 class MyTestCase(unittest.TestCase):
799 def test(self):
800 pass
801 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000802
Georg Brandl15c5ce92007-03-07 09:09:40 +0000803 loader = unittest.TestLoader()
804 suite = loader.loadTestsFromNames(['testcase_1'], m)
805 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000806
Georg Brandl15c5ce92007-03-07 09:09:40 +0000807 expected = loader.suiteClass([MyTestCase('test')])
808 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000809
Georg Brandl15c5ce92007-03-07 09:09:40 +0000810 # "The specifier name is a ``dotted name'' that may resolve ... to
811 # ... a TestSuite instance"
812 def test_loadTestsFromNames__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000813 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000814 class MyTestCase(unittest.TestCase):
815 def test(self):
816 pass
817 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000818
Georg Brandl15c5ce92007-03-07 09:09:40 +0000819 loader = unittest.TestLoader()
820 suite = loader.loadTestsFromNames(['testsuite'], m)
821 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000822
Georg Brandl15c5ce92007-03-07 09:09:40 +0000823 self.assertEqual(list(suite), [m.testsuite])
Tim Petersea5962f2007-03-12 18:07:52 +0000824
Georg Brandl15c5ce92007-03-07 09:09:40 +0000825 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
826 # test method within a test case class"
827 def test_loadTestsFromNames__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000828 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000829 class MyTestCase(unittest.TestCase):
830 def test(self):
831 pass
832 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000833
Georg Brandl15c5ce92007-03-07 09:09:40 +0000834 loader = unittest.TestLoader()
835 suite = loader.loadTestsFromNames(['testcase_1.test'], m)
836 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000837
Georg Brandl15c5ce92007-03-07 09:09:40 +0000838 ref_suite = unittest.TestSuite([MyTestCase('test')])
839 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000840
Georg Brandl15c5ce92007-03-07 09:09:40 +0000841 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
842 # test method within a test case class"
843 #
844 # Does the method gracefully handle names that initially look like they
Tim Petersea5962f2007-03-12 18:07:52 +0000845 # resolve to "a test method within a test case class" but don't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000846 def test_loadTestsFromNames__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000847 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000848 class MyTestCase(unittest.TestCase):
849 def test(self):
850 pass
851 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000852
Georg Brandl15c5ce92007-03-07 09:09:40 +0000853 loader = unittest.TestLoader()
854 try:
855 loader.loadTestsFromNames(['testcase_1.testfoo'], m)
856 except AttributeError, e:
857 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
858 else:
859 self.fail("Failed to raise AttributeError")
860
861 # "The specifier name is a ``dotted name'' that may resolve ... to
862 # ... a callable object which returns a ... TestSuite instance"
863 def test_loadTestsFromNames__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000864 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000865 testcase_1 = unittest.FunctionTestCase(lambda: None)
866 testcase_2 = unittest.FunctionTestCase(lambda: None)
867 def return_TestSuite():
868 return unittest.TestSuite([testcase_1, testcase_2])
869 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000870
Georg Brandl15c5ce92007-03-07 09:09:40 +0000871 loader = unittest.TestLoader()
872 suite = loader.loadTestsFromNames(['return_TestSuite'], m)
873 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000874
Georg Brandl15c5ce92007-03-07 09:09:40 +0000875 expected = unittest.TestSuite([testcase_1, testcase_2])
876 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000877
Georg Brandl15c5ce92007-03-07 09:09:40 +0000878 # "The specifier name is a ``dotted name'' that may resolve ... to
879 # ... a callable object which returns a TestCase ... instance"
880 def test_loadTestsFromNames__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000881 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000882 testcase_1 = unittest.FunctionTestCase(lambda: None)
883 def return_TestCase():
884 return testcase_1
885 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000886
Georg Brandl15c5ce92007-03-07 09:09:40 +0000887 loader = unittest.TestLoader()
888 suite = loader.loadTestsFromNames(['return_TestCase'], m)
889 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000890
Georg Brandl15c5ce92007-03-07 09:09:40 +0000891 ref_suite = unittest.TestSuite([testcase_1])
892 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000893
Georg Brandl15c5ce92007-03-07 09:09:40 +0000894 # "The specifier name is a ``dotted name'' that may resolve ... to
895 # ... a callable object which returns a TestCase or TestSuite instance"
896 #
Tim Petersea5962f2007-03-12 18:07:52 +0000897 # Are staticmethods handled correctly?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000898 def test_loadTestsFromNames__callable__call_staticmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000899 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000900 class Test1(unittest.TestCase):
901 def test(self):
902 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000903
Georg Brandl15c5ce92007-03-07 09:09:40 +0000904 testcase_1 = Test1('test')
905 class Foo(unittest.TestCase):
906 @staticmethod
907 def foo():
908 return testcase_1
909 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +0000910
Georg Brandl15c5ce92007-03-07 09:09:40 +0000911 loader = unittest.TestLoader()
912 suite = loader.loadTestsFromNames(['Foo.foo'], m)
913 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000914
Georg Brandl15c5ce92007-03-07 09:09:40 +0000915 ref_suite = unittest.TestSuite([testcase_1])
916 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000917
Georg Brandl15c5ce92007-03-07 09:09:40 +0000918 # "The specifier name is a ``dotted name'' that may resolve ... to
919 # ... a callable object which returns a TestCase or TestSuite instance"
920 #
921 # What happens when the callable returns something else?
922 def test_loadTestsFromNames__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000923 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000924 def return_wrong():
925 return 6
926 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000927
Georg Brandl15c5ce92007-03-07 09:09:40 +0000928 loader = unittest.TestLoader()
929 try:
930 suite = loader.loadTestsFromNames(['return_wrong'], m)
931 except TypeError:
932 pass
933 else:
934 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000935
Georg Brandl15c5ce92007-03-07 09:09:40 +0000936 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +0000937 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +0000938 def test_loadTestsFromNames__module_not_loaded(self):
939 # We're going to try to load this module as a side-effect, so it
940 # better not be loaded before we try.
941 #
942 # Why pick audioop? Google shows it isn't used very often, so there's
943 # a good chance that it won't be imported when this test is run
944 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +0000945
Georg Brandl15c5ce92007-03-07 09:09:40 +0000946 import sys
947 if module_name in sys.modules:
948 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000949
Georg Brandl15c5ce92007-03-07 09:09:40 +0000950 loader = unittest.TestLoader()
951 try:
952 suite = loader.loadTestsFromNames([module_name])
953
954 self.failUnless(isinstance(suite, loader.suiteClass))
955 self.assertEqual(list(suite), [unittest.TestSuite()])
956
957 # audioop should now be loaded, thanks to loadTestsFromName()
958 self.failUnless(module_name in sys.modules)
959 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000960 if module_name in sys.modules:
961 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000962
Georg Brandl15c5ce92007-03-07 09:09:40 +0000963 ################################################################
964 ### /Tests for TestLoader.loadTestsFromNames()
965
966 ### Tests for TestLoader.getTestCaseNames()
967 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000968
Georg Brandl15c5ce92007-03-07 09:09:40 +0000969 # "Return a sorted sequence of method names found within testCaseClass"
970 #
971 # Test.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +0000972 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +0000973 def test_getTestCaseNames(self):
974 class Test(unittest.TestCase):
975 def test_1(self): pass
976 def test_2(self): pass
977 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000978
Georg Brandl15c5ce92007-03-07 09:09:40 +0000979 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000980
Georg Brandl15c5ce92007-03-07 09:09:40 +0000981 self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])
Tim Petersea5962f2007-03-12 18:07:52 +0000982
Georg Brandl15c5ce92007-03-07 09:09:40 +0000983 # "Return a sorted sequence of method names found within testCaseClass"
984 #
Tim Petersea5962f2007-03-12 18:07:52 +0000985 # Does getTestCaseNames() behave appropriately if no tests are found?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000986 def test_getTestCaseNames__no_tests(self):
987 class Test(unittest.TestCase):
988 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000989
Georg Brandl15c5ce92007-03-07 09:09:40 +0000990 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000991
Georg Brandl15c5ce92007-03-07 09:09:40 +0000992 self.assertEqual(loader.getTestCaseNames(Test), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000993
Georg Brandl15c5ce92007-03-07 09:09:40 +0000994 # "Return a sorted sequence of method names found within testCaseClass"
995 #
996 # Are not-TestCases handled gracefully?
997 #
998 # XXX This should raise a TypeError, not return a list
999 #
1000 # XXX It's too late in the 2.5 release cycle to fix this, but it should
1001 # probably be revisited for 2.6
1002 def test_getTestCaseNames__not_a_TestCase(self):
1003 class BadCase(int):
1004 def test_foo(self):
1005 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001006
Georg Brandl15c5ce92007-03-07 09:09:40 +00001007 loader = unittest.TestLoader()
1008 names = loader.getTestCaseNames(BadCase)
Tim Petersea5962f2007-03-12 18:07:52 +00001009
Georg Brandl15c5ce92007-03-07 09:09:40 +00001010 self.assertEqual(names, ['test_foo'])
Tim Petersea5962f2007-03-12 18:07:52 +00001011
Georg Brandl15c5ce92007-03-07 09:09:40 +00001012 # "Return a sorted sequence of method names found within testCaseClass"
1013 #
1014 # Make sure inherited names are handled.
1015 #
1016 # TestP.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +00001017 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +00001018 def test_getTestCaseNames__inheritance(self):
1019 class TestP(unittest.TestCase):
1020 def test_1(self): pass
1021 def test_2(self): pass
1022 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001023
Georg Brandl15c5ce92007-03-07 09:09:40 +00001024 class TestC(TestP):
1025 def test_1(self): pass
1026 def test_3(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001027
Georg Brandl15c5ce92007-03-07 09:09:40 +00001028 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001029
Georg Brandl15c5ce92007-03-07 09:09:40 +00001030 names = ['test_1', 'test_2', 'test_3']
1031 self.assertEqual(loader.getTestCaseNames(TestC), names)
Tim Petersea5962f2007-03-12 18:07:52 +00001032
1033 ################################################################
Georg Brandl15c5ce92007-03-07 09:09:40 +00001034 ### /Tests for TestLoader.getTestCaseNames()
1035
1036 ### Tests for TestLoader.testMethodPrefix
1037 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001038
Georg Brandl15c5ce92007-03-07 09:09:40 +00001039 # "String giving the prefix of method names which will be interpreted as
1040 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001041 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001042 # Implicit in the documentation is that testMethodPrefix is respected by
1043 # all loadTestsFrom* methods.
1044 def test_testMethodPrefix__loadTestsFromTestCase(self):
1045 class Foo(unittest.TestCase):
1046 def test_1(self): pass
1047 def test_2(self): pass
1048 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001049
Georg Brandl15c5ce92007-03-07 09:09:40 +00001050 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1051 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001052
Georg Brandl15c5ce92007-03-07 09:09:40 +00001053 loader = unittest.TestLoader()
1054 loader.testMethodPrefix = 'foo'
1055 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
1056
1057 loader.testMethodPrefix = 'test'
1058 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001059
Georg Brandl15c5ce92007-03-07 09:09:40 +00001060 # "String giving the prefix of method names which will be interpreted as
1061 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001062 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001063 # Implicit in the documentation is that testMethodPrefix is respected by
1064 # all loadTestsFrom* methods.
1065 def test_testMethodPrefix__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001066 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001067 class Foo(unittest.TestCase):
1068 def test_1(self): pass
1069 def test_2(self): pass
1070 def foo_bar(self): pass
1071 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001072
Georg Brandl15c5ce92007-03-07 09:09:40 +00001073 tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
1074 tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]
Tim Petersea5962f2007-03-12 18:07:52 +00001075
Georg Brandl15c5ce92007-03-07 09:09:40 +00001076 loader = unittest.TestLoader()
1077 loader.testMethodPrefix = 'foo'
1078 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
1079
1080 loader.testMethodPrefix = 'test'
1081 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001082
Georg Brandl15c5ce92007-03-07 09:09:40 +00001083 # "String giving the prefix of method names which will be interpreted as
1084 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001085 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001086 # Implicit in the documentation is that testMethodPrefix is respected by
1087 # all loadTestsFrom* methods.
1088 def test_testMethodPrefix__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001089 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001090 class Foo(unittest.TestCase):
1091 def test_1(self): pass
1092 def test_2(self): pass
1093 def foo_bar(self): pass
1094 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001095
Georg Brandl15c5ce92007-03-07 09:09:40 +00001096 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1097 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001098
Georg Brandl15c5ce92007-03-07 09:09:40 +00001099 loader = unittest.TestLoader()
1100 loader.testMethodPrefix = 'foo'
1101 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
1102
1103 loader.testMethodPrefix = 'test'
1104 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001105
Georg Brandl15c5ce92007-03-07 09:09:40 +00001106 # "String giving the prefix of method names which will be interpreted as
1107 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001108 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001109 # Implicit in the documentation is that testMethodPrefix is respected by
1110 # all loadTestsFrom* methods.
1111 def test_testMethodPrefix__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001112 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001113 class Foo(unittest.TestCase):
1114 def test_1(self): pass
1115 def test_2(self): pass
1116 def foo_bar(self): pass
1117 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001118
Georg Brandl15c5ce92007-03-07 09:09:40 +00001119 tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
1120 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1121 tests_2 = unittest.TestSuite([tests_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001122
Georg Brandl15c5ce92007-03-07 09:09:40 +00001123 loader = unittest.TestLoader()
1124 loader.testMethodPrefix = 'foo'
1125 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)
1126
1127 loader.testMethodPrefix = 'test'
1128 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001129
Georg Brandl15c5ce92007-03-07 09:09:40 +00001130 # "The default value is 'test'"
1131 def test_testMethodPrefix__default_value(self):
1132 loader = unittest.TestLoader()
1133 self.failUnless(loader.testMethodPrefix == 'test')
Tim Petersea5962f2007-03-12 18:07:52 +00001134
Georg Brandl15c5ce92007-03-07 09:09:40 +00001135 ################################################################
1136 ### /Tests for TestLoader.testMethodPrefix
1137
Tim Petersea5962f2007-03-12 18:07:52 +00001138 ### Tests for TestLoader.sortTestMethodsUsing
Georg Brandl15c5ce92007-03-07 09:09:40 +00001139 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001140
Georg Brandl15c5ce92007-03-07 09:09:40 +00001141 # "Function to be used to compare method names when sorting them in
1142 # getTestCaseNames() and all the loadTestsFromX() methods"
1143 def test_sortTestMethodsUsing__loadTestsFromTestCase(self):
1144 def reversed_cmp(x, y):
1145 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001146
Georg Brandl15c5ce92007-03-07 09:09:40 +00001147 class Foo(unittest.TestCase):
1148 def test_1(self): pass
1149 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001150
Georg Brandl15c5ce92007-03-07 09:09:40 +00001151 loader = unittest.TestLoader()
1152 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001153
Georg Brandl15c5ce92007-03-07 09:09:40 +00001154 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1155 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001156
Georg Brandl15c5ce92007-03-07 09:09:40 +00001157 # "Function to be used to compare method names when sorting them in
1158 # getTestCaseNames() and all the loadTestsFromX() methods"
1159 def test_sortTestMethodsUsing__loadTestsFromModule(self):
1160 def reversed_cmp(x, y):
1161 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001162
Christian Heimesc756d002007-11-27 21:34:01 +00001163 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001164 class Foo(unittest.TestCase):
1165 def test_1(self): pass
1166 def test_2(self): pass
1167 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001168
Georg Brandl15c5ce92007-03-07 09:09:40 +00001169 loader = unittest.TestLoader()
1170 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001171
Georg Brandl15c5ce92007-03-07 09:09:40 +00001172 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1173 self.assertEqual(list(loader.loadTestsFromModule(m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001174
Georg Brandl15c5ce92007-03-07 09:09:40 +00001175 # "Function to be used to compare method names when sorting them in
1176 # getTestCaseNames() and all the loadTestsFromX() methods"
1177 def test_sortTestMethodsUsing__loadTestsFromName(self):
1178 def reversed_cmp(x, y):
1179 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001180
Christian Heimesc756d002007-11-27 21:34:01 +00001181 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001182 class Foo(unittest.TestCase):
1183 def test_1(self): pass
1184 def test_2(self): pass
1185 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001186
Georg Brandl15c5ce92007-03-07 09:09:40 +00001187 loader = unittest.TestLoader()
1188 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001189
Georg Brandl15c5ce92007-03-07 09:09:40 +00001190 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1191 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001192
Georg Brandl15c5ce92007-03-07 09:09:40 +00001193 # "Function to be used to compare method names when sorting them in
1194 # getTestCaseNames() and all the loadTestsFromX() methods"
1195 def test_sortTestMethodsUsing__loadTestsFromNames(self):
1196 def reversed_cmp(x, y):
1197 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001198
Christian Heimesc756d002007-11-27 21:34:01 +00001199 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001200 class Foo(unittest.TestCase):
1201 def test_1(self): pass
1202 def test_2(self): pass
1203 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001204
Georg Brandl15c5ce92007-03-07 09:09:40 +00001205 loader = unittest.TestLoader()
1206 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001207
Georg Brandl15c5ce92007-03-07 09:09:40 +00001208 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1209 self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001210
Georg Brandl15c5ce92007-03-07 09:09:40 +00001211 # "Function to be used to compare method names when sorting them in
1212 # getTestCaseNames()"
1213 #
1214 # Does it actually affect getTestCaseNames()?
1215 def test_sortTestMethodsUsing__getTestCaseNames(self):
1216 def reversed_cmp(x, y):
1217 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001218
Georg Brandl15c5ce92007-03-07 09:09:40 +00001219 class Foo(unittest.TestCase):
1220 def test_1(self): pass
1221 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001222
Georg Brandl15c5ce92007-03-07 09:09:40 +00001223 loader = unittest.TestLoader()
1224 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001225
Georg Brandl15c5ce92007-03-07 09:09:40 +00001226 test_names = ['test_2', 'test_1']
1227 self.assertEqual(loader.getTestCaseNames(Foo), test_names)
Tim Petersea5962f2007-03-12 18:07:52 +00001228
Georg Brandl15c5ce92007-03-07 09:09:40 +00001229 # "The default value is the built-in cmp() function"
1230 def test_sortTestMethodsUsing__default_value(self):
1231 loader = unittest.TestLoader()
1232 self.failUnless(loader.sortTestMethodsUsing is cmp)
Tim Petersea5962f2007-03-12 18:07:52 +00001233
Georg Brandl15c5ce92007-03-07 09:09:40 +00001234 # "it can be set to None to disable the sort."
1235 #
1236 # XXX How is this different from reassigning cmp? Are the tests returned
1237 # in a random order or something? This behaviour should die
1238 def test_sortTestMethodsUsing__None(self):
1239 class Foo(unittest.TestCase):
1240 def test_1(self): pass
1241 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001242
Georg Brandl15c5ce92007-03-07 09:09:40 +00001243 loader = unittest.TestLoader()
1244 loader.sortTestMethodsUsing = None
Tim Petersea5962f2007-03-12 18:07:52 +00001245
Georg Brandl15c5ce92007-03-07 09:09:40 +00001246 test_names = ['test_2', 'test_1']
1247 self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))
Tim Petersea5962f2007-03-12 18:07:52 +00001248
Georg Brandl15c5ce92007-03-07 09:09:40 +00001249 ################################################################
1250 ### /Tests for TestLoader.sortTestMethodsUsing
Tim Petersea5962f2007-03-12 18:07:52 +00001251
Georg Brandl15c5ce92007-03-07 09:09:40 +00001252 ### Tests for TestLoader.suiteClass
1253 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001254
Georg Brandl15c5ce92007-03-07 09:09:40 +00001255 # "Callable object that constructs a test suite from a list of tests."
1256 def test_suiteClass__loadTestsFromTestCase(self):
1257 class Foo(unittest.TestCase):
1258 def test_1(self): pass
1259 def test_2(self): pass
1260 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001261
Georg Brandl15c5ce92007-03-07 09:09:40 +00001262 tests = [Foo('test_1'), Foo('test_2')]
1263
1264 loader = unittest.TestLoader()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001265 loader.suiteClass = list
Georg Brandl15c5ce92007-03-07 09:09:40 +00001266 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001267
Georg Brandl15c5ce92007-03-07 09:09:40 +00001268 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001269 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001270 def test_suiteClass__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001271 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001272 class Foo(unittest.TestCase):
1273 def test_1(self): pass
1274 def test_2(self): pass
1275 def foo_bar(self): pass
1276 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001277
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001278 tests = [[Foo('test_1'), Foo('test_2')]]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001279
1280 loader = unittest.TestLoader()
1281 loader.suiteClass = list
1282 self.assertEqual(loader.loadTestsFromModule(m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001283
Georg Brandl15c5ce92007-03-07 09:09:40 +00001284 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001285 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001286 def test_suiteClass__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001287 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001288 class Foo(unittest.TestCase):
1289 def test_1(self): pass
1290 def test_2(self): pass
1291 def foo_bar(self): pass
1292 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001293
Georg Brandl15c5ce92007-03-07 09:09:40 +00001294 tests = [Foo('test_1'), Foo('test_2')]
1295
1296 loader = unittest.TestLoader()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001297 loader.suiteClass = list
Georg Brandl15c5ce92007-03-07 09:09:40 +00001298 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001299
Georg Brandl15c5ce92007-03-07 09:09:40 +00001300 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001301 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001302 def test_suiteClass__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001303 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001304 class Foo(unittest.TestCase):
1305 def test_1(self): pass
1306 def test_2(self): pass
1307 def foo_bar(self): pass
1308 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001309
Benjamin Peterson176a56c2009-05-25 00:48:58 +00001310 tests = [[Foo('test_1'), Foo('test_2')]]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001311
1312 loader = unittest.TestLoader()
1313 loader.suiteClass = list
1314 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001315
Georg Brandl15c5ce92007-03-07 09:09:40 +00001316 # "The default value is the TestSuite class"
1317 def test_suiteClass__default_value(self):
1318 loader = unittest.TestLoader()
1319 self.failUnless(loader.suiteClass is unittest.TestSuite)
Tim Petersea5962f2007-03-12 18:07:52 +00001320
Georg Brandl15c5ce92007-03-07 09:09:40 +00001321 ################################################################
1322 ### /Tests for TestLoader.suiteClass
1323
1324### Support code for Test_TestSuite
1325################################################################
1326
1327class Foo(unittest.TestCase):
1328 def test_1(self): pass
1329 def test_2(self): pass
1330 def test_3(self): pass
1331 def runTest(self): pass
1332
1333def _mk_TestSuite(*names):
1334 return unittest.TestSuite(Foo(n) for n in names)
Tim Petersea5962f2007-03-12 18:07:52 +00001335
Georg Brandl15c5ce92007-03-07 09:09:40 +00001336################################################################
1337### /Support code for Test_TestSuite
1338
1339class Test_TestSuite(TestCase, TestEquality):
1340
1341 ### Set up attributes needed by inherited tests
1342 ################################################################
1343
1344 # Used by TestEquality.test_eq
1345 eq_pairs = [(unittest.TestSuite(), unittest.TestSuite())
1346 ,(unittest.TestSuite(), unittest.TestSuite([]))
1347 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001348
1349 # Used by TestEquality.test_ne
Georg Brandl15c5ce92007-03-07 09:09:40 +00001350 ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1'))
1351 ,(unittest.TestSuite([]), _mk_TestSuite('test_1'))
1352 ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3'))
1353 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001354
Georg Brandl15c5ce92007-03-07 09:09:40 +00001355 ################################################################
1356 ### /Set up attributes needed by inherited tests
1357
1358 ### Tests for TestSuite.__init__
1359 ################################################################
1360
1361 # "class TestSuite([tests])"
1362 #
1363 # The tests iterable should be optional
1364 def test_init__tests_optional(self):
1365 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001366
Georg Brandl15c5ce92007-03-07 09:09:40 +00001367 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001368
Georg Brandl15c5ce92007-03-07 09:09:40 +00001369 # "class TestSuite([tests])"
1370 # ...
1371 # "If tests is given, it must be an iterable of individual test cases
1372 # or other test suites that will be used to build the suite initially"
1373 #
1374 # TestSuite should deal with empty tests iterables by allowing the
Tim Petersea5962f2007-03-12 18:07:52 +00001375 # creation of an empty suite
Georg Brandl15c5ce92007-03-07 09:09:40 +00001376 def test_init__empty_tests(self):
1377 suite = unittest.TestSuite([])
Tim Petersea5962f2007-03-12 18:07:52 +00001378
Georg Brandl15c5ce92007-03-07 09:09:40 +00001379 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001380
Georg Brandl15c5ce92007-03-07 09:09:40 +00001381 # "class TestSuite([tests])"
1382 # ...
1383 # "If tests is given, it must be an iterable of individual test cases
1384 # or other test suites that will be used to build the suite initially"
1385 #
Tim Petersea5962f2007-03-12 18:07:52 +00001386 # TestSuite should allow any iterable to provide tests
Georg Brandl15c5ce92007-03-07 09:09:40 +00001387 def test_init__tests_from_any_iterable(self):
1388 def tests():
1389 yield unittest.FunctionTestCase(lambda: None)
1390 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001391
Georg Brandl15c5ce92007-03-07 09:09:40 +00001392 suite_1 = unittest.TestSuite(tests())
1393 self.assertEqual(suite_1.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001394
Georg Brandl15c5ce92007-03-07 09:09:40 +00001395 suite_2 = unittest.TestSuite(suite_1)
1396 self.assertEqual(suite_2.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001397
Georg Brandl15c5ce92007-03-07 09:09:40 +00001398 suite_3 = unittest.TestSuite(set(suite_1))
1399 self.assertEqual(suite_3.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001400
Georg Brandl15c5ce92007-03-07 09:09:40 +00001401 # "class TestSuite([tests])"
1402 # ...
1403 # "If tests is given, it must be an iterable of individual test cases
1404 # or other test suites that will be used to build the suite initially"
1405 #
1406 # Does TestSuite() also allow other TestSuite() instances to be present
1407 # in the tests iterable?
1408 def test_init__TestSuite_instances_in_tests(self):
1409 def tests():
1410 ftc = unittest.FunctionTestCase(lambda: None)
1411 yield unittest.TestSuite([ftc])
1412 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001413
Georg Brandl15c5ce92007-03-07 09:09:40 +00001414 suite = unittest.TestSuite(tests())
1415 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001416
Georg Brandl15c5ce92007-03-07 09:09:40 +00001417 ################################################################
1418 ### /Tests for TestSuite.__init__
1419
1420 # Container types should support the iter protocol
1421 def test_iter(self):
1422 test1 = unittest.FunctionTestCase(lambda: None)
1423 test2 = unittest.FunctionTestCase(lambda: None)
1424 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001425
Georg Brandl15c5ce92007-03-07 09:09:40 +00001426 self.assertEqual(list(suite), [test1, test2])
Tim Petersea5962f2007-03-12 18:07:52 +00001427
Georg Brandl15c5ce92007-03-07 09:09:40 +00001428 # "Return the number of tests represented by the this test object.
1429 # ...this method is also implemented by the TestSuite class, which can
1430 # return larger [greater than 1] values"
1431 #
Tim Petersea5962f2007-03-12 18:07:52 +00001432 # Presumably an empty TestSuite returns 0?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001433 def test_countTestCases_zero_simple(self):
1434 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001435
Georg Brandl15c5ce92007-03-07 09:09:40 +00001436 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001437
Georg Brandl15c5ce92007-03-07 09:09:40 +00001438 # "Return the number of tests represented by the this test object.
1439 # ...this method is also implemented by the TestSuite class, which can
1440 # return larger [greater than 1] values"
1441 #
1442 # Presumably an empty TestSuite (even if it contains other empty
1443 # TestSuite instances) returns 0?
1444 def test_countTestCases_zero_nested(self):
1445 class Test1(unittest.TestCase):
1446 def test(self):
1447 pass
1448
1449 suite = unittest.TestSuite([unittest.TestSuite()])
Tim Petersea5962f2007-03-12 18:07:52 +00001450
Georg Brandl15c5ce92007-03-07 09:09:40 +00001451 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001452
Georg Brandl15c5ce92007-03-07 09:09:40 +00001453 # "Return the number of tests represented by the this test object.
1454 # ...this method is also implemented by the TestSuite class, which can
1455 # return larger [greater than 1] values"
1456 def test_countTestCases_simple(self):
1457 test1 = unittest.FunctionTestCase(lambda: None)
1458 test2 = unittest.FunctionTestCase(lambda: None)
1459 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001460
Georg Brandl15c5ce92007-03-07 09:09:40 +00001461 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001462
Georg Brandl15c5ce92007-03-07 09:09:40 +00001463 # "Return the number of tests represented by the this test object.
1464 # ...this method is also implemented by the TestSuite class, which can
1465 # return larger [greater than 1] values"
1466 #
1467 # Make sure this holds for nested TestSuite instances, too
1468 def test_countTestCases_nested(self):
1469 class Test1(unittest.TestCase):
1470 def test1(self): pass
1471 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001472
Georg Brandl15c5ce92007-03-07 09:09:40 +00001473 test2 = unittest.FunctionTestCase(lambda: None)
1474 test3 = unittest.FunctionTestCase(lambda: None)
1475 child = unittest.TestSuite((Test1('test2'), test2))
1476 parent = unittest.TestSuite((test3, child, Test1('test1')))
Tim Petersea5962f2007-03-12 18:07:52 +00001477
Georg Brandl15c5ce92007-03-07 09:09:40 +00001478 self.assertEqual(parent.countTestCases(), 4)
Tim Petersea5962f2007-03-12 18:07:52 +00001479
Georg Brandl15c5ce92007-03-07 09:09:40 +00001480 # "Run the tests associated with this suite, collecting the result into
1481 # the test result object passed as result."
1482 #
1483 # And if there are no tests? What then?
1484 def test_run__empty_suite(self):
1485 events = []
1486 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001487
Georg Brandl15c5ce92007-03-07 09:09:40 +00001488 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001489
Georg Brandl15c5ce92007-03-07 09:09:40 +00001490 suite.run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001491
Georg Brandl15c5ce92007-03-07 09:09:40 +00001492 self.assertEqual(events, [])
Tim Petersea5962f2007-03-12 18:07:52 +00001493
Georg Brandl15c5ce92007-03-07 09:09:40 +00001494 # "Note that unlike TestCase.run(), TestSuite.run() requires the
1495 # "result object to be passed in."
1496 def test_run__requires_result(self):
1497 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001498
Georg Brandl15c5ce92007-03-07 09:09:40 +00001499 try:
1500 suite.run()
1501 except TypeError:
1502 pass
1503 else:
1504 self.fail("Failed to raise TypeError")
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
Tim Petersea5962f2007-03-12 18:07:52 +00001507 # the test result object passed as result."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001508 def test_run(self):
1509 events = []
1510 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001511
Georg Brandl15c5ce92007-03-07 09:09:40 +00001512 class LoggingCase(unittest.TestCase):
1513 def run(self, result):
1514 events.append('run %s' % self._testMethodName)
Tim Petersea5962f2007-03-12 18:07:52 +00001515
Georg Brandl15c5ce92007-03-07 09:09:40 +00001516 def test1(self): pass
1517 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001518
1519 tests = [LoggingCase('test1'), LoggingCase('test2')]
1520
Georg Brandl15c5ce92007-03-07 09:09:40 +00001521 unittest.TestSuite(tests).run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001522
Georg Brandl15c5ce92007-03-07 09:09:40 +00001523 self.assertEqual(events, ['run test1', 'run test2'])
Tim Petersea5962f2007-03-12 18:07:52 +00001524
1525 # "Add a TestCase ... to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001526 def test_addTest__TestCase(self):
1527 class Foo(unittest.TestCase):
1528 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001529
Georg Brandl15c5ce92007-03-07 09:09:40 +00001530 test = Foo('test')
1531 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001532
Georg Brandl15c5ce92007-03-07 09:09:40 +00001533 suite.addTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001534
Georg Brandl15c5ce92007-03-07 09:09:40 +00001535 self.assertEqual(suite.countTestCases(), 1)
1536 self.assertEqual(list(suite), [test])
Tim Petersea5962f2007-03-12 18:07:52 +00001537
1538 # "Add a ... TestSuite to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001539 def test_addTest__TestSuite(self):
1540 class Foo(unittest.TestCase):
1541 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001542
Georg Brandl15c5ce92007-03-07 09:09:40 +00001543 suite_2 = unittest.TestSuite([Foo('test')])
Tim Petersea5962f2007-03-12 18:07:52 +00001544
Georg Brandl15c5ce92007-03-07 09:09:40 +00001545 suite = unittest.TestSuite()
1546 suite.addTest(suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001547
Georg Brandl15c5ce92007-03-07 09:09:40 +00001548 self.assertEqual(suite.countTestCases(), 1)
1549 self.assertEqual(list(suite), [suite_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001550
Georg Brandl15c5ce92007-03-07 09:09:40 +00001551 # "Add all the tests from an iterable of TestCase and TestSuite
1552 # instances to this test suite."
Tim Petersea5962f2007-03-12 18:07:52 +00001553 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001554 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001555 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001556 def test_addTests(self):
1557 class Foo(unittest.TestCase):
1558 def test_1(self): pass
1559 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001560
Georg Brandl15c5ce92007-03-07 09:09:40 +00001561 test_1 = Foo('test_1')
1562 test_2 = Foo('test_2')
1563 inner_suite = unittest.TestSuite([test_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001564
Georg Brandl15c5ce92007-03-07 09:09:40 +00001565 def gen():
1566 yield test_1
1567 yield test_2
1568 yield inner_suite
Tim Petersea5962f2007-03-12 18:07:52 +00001569
Georg Brandl15c5ce92007-03-07 09:09:40 +00001570 suite_1 = unittest.TestSuite()
1571 suite_1.addTests(gen())
Tim Petersea5962f2007-03-12 18:07:52 +00001572
Georg Brandl15c5ce92007-03-07 09:09:40 +00001573 self.assertEqual(list(suite_1), list(gen()))
Tim Petersea5962f2007-03-12 18:07:52 +00001574
Georg Brandl15c5ce92007-03-07 09:09:40 +00001575 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001576 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001577 suite_2 = unittest.TestSuite()
1578 for t in gen():
1579 suite_2.addTest(t)
Tim Petersea5962f2007-03-12 18:07:52 +00001580
Georg Brandl15c5ce92007-03-07 09:09:40 +00001581 self.assertEqual(suite_1, suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001582
Georg Brandl15c5ce92007-03-07 09:09:40 +00001583 # "Add all the tests from an iterable of TestCase and TestSuite
1584 # instances to this test suite."
1585 #
Tim Petersea5962f2007-03-12 18:07:52 +00001586 # What happens if it doesn't get an iterable?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001587 def test_addTest__noniterable(self):
1588 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001589
Georg Brandl15c5ce92007-03-07 09:09:40 +00001590 try:
1591 suite.addTests(5)
1592 except TypeError:
1593 pass
1594 else:
1595 self.fail("Failed to raise TypeError")
Georg Brandld9e50262007-03-07 11:54:49 +00001596
1597 def test_addTest__noncallable(self):
1598 suite = unittest.TestSuite()
1599 self.assertRaises(TypeError, suite.addTest, 5)
1600
1601 def test_addTest__casesuiteclass(self):
1602 suite = unittest.TestSuite()
1603 self.assertRaises(TypeError, suite.addTest, Test_TestSuite)
1604 self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)
1605
1606 def test_addTests__string(self):
1607 suite = unittest.TestSuite()
1608 self.assertRaises(TypeError, suite.addTests, "foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001609
1610
Georg Brandl15c5ce92007-03-07 09:09:40 +00001611class Test_FunctionTestCase(TestCase):
Tim Petersea5962f2007-03-12 18:07:52 +00001612
Georg Brandl15c5ce92007-03-07 09:09:40 +00001613 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00001614 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001615 def test_countTestCases(self):
1616 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001617
Georg Brandl15c5ce92007-03-07 09:09:40 +00001618 self.assertEqual(test.countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00001619
Georg Brandl15c5ce92007-03-07 09:09:40 +00001620 # "When a setUp() method is defined, the test runner will run that method
1621 # prior to each test. Likewise, if a tearDown() method is defined, the
1622 # test runner will invoke that method after each test. In the example,
1623 # setUp() was used to create a fresh sequence for each test."
1624 #
1625 # Make sure the proper call order is maintained, even if setUp() raises
1626 # an exception.
1627 def test_run_call_order__error_in_setUp(self):
1628 events = []
1629 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001630
Georg Brandl15c5ce92007-03-07 09:09:40 +00001631 def setUp():
1632 events.append('setUp')
1633 raise RuntimeError('raised by setUp')
1634
1635 def test():
1636 events.append('test')
1637
1638 def tearDown():
1639 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001640
1641 expected = ['startTest', 'setUp', 'addError', 'stopTest']
Georg Brandl15c5ce92007-03-07 09:09:40 +00001642 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1643 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001644
Georg Brandl15c5ce92007-03-07 09:09:40 +00001645 # "When a setUp() method is defined, the test runner will run that method
1646 # prior to each test. Likewise, if a tearDown() method is defined, the
1647 # test runner will invoke that method after each test. In the example,
1648 # setUp() was used to create a fresh sequence for each test."
1649 #
1650 # Make sure the proper call order is maintained, even if the test raises
1651 # an error (as opposed to a failure).
1652 def test_run_call_order__error_in_test(self):
1653 events = []
1654 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001655
Georg Brandl15c5ce92007-03-07 09:09:40 +00001656 def setUp():
1657 events.append('setUp')
1658
1659 def test():
1660 events.append('test')
1661 raise RuntimeError('raised by test')
1662
1663 def tearDown():
1664 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001665
Georg Brandl15c5ce92007-03-07 09:09:40 +00001666 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
1667 'stopTest']
1668 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 signals
1677 # a failure (as opposed to an error).
1678 def test_run_call_order__failure_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 self.fail('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', 'addFailure', '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 tearDown() raises
1703 # an exception.
1704 def test_run_call_order__error_in_tearDown(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
1714 def tearDown():
1715 events.append('tearDown')
1716 raise RuntimeError('raised by tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001717
Georg Brandl15c5ce92007-03-07 09:09:40 +00001718 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
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 # "Return a string identifying the specific test case."
1724 #
1725 # Because of the vague nature of the docs, I'm not going to lock this
1726 # test down too much. Really all that can be asserted is that the id()
1727 # will be a string (either 8-byte or unicode -- again, because the docs
1728 # just say "string")
1729 def test_id(self):
1730 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001731
Georg Brandl15c5ce92007-03-07 09:09:40 +00001732 self.failUnless(isinstance(test.id(), basestring))
Tim Petersea5962f2007-03-12 18:07:52 +00001733
Georg Brandl15c5ce92007-03-07 09:09:40 +00001734 # "Returns a one-line description of the test, or None if no description
1735 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001736 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001737 def test_shortDescription__no_docstring(self):
1738 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001739
Georg Brandl15c5ce92007-03-07 09:09:40 +00001740 self.assertEqual(test.shortDescription(), None)
Tim Petersea5962f2007-03-12 18:07:52 +00001741
Georg Brandl15c5ce92007-03-07 09:09:40 +00001742 # "Returns a one-line description of the test, or None if no description
1743 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001744 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001745 def test_shortDescription__singleline_docstring(self):
1746 desc = "this tests foo"
1747 test = unittest.FunctionTestCase(lambda: None, description=desc)
Tim Petersea5962f2007-03-12 18:07:52 +00001748
Georg Brandl15c5ce92007-03-07 09:09:40 +00001749 self.assertEqual(test.shortDescription(), "this tests foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001750
Georg Brandl15c5ce92007-03-07 09:09:40 +00001751class Test_TestResult(TestCase):
1752 # Note: there are not separate tests for TestResult.wasSuccessful(),
1753 # TestResult.errors, TestResult.failures, TestResult.testsRun or
1754 # TestResult.shouldStop because these only have meaning in terms of
1755 # other TestResult methods.
1756 #
1757 # Accordingly, tests for the aforenamed attributes are incorporated
1758 # in with the tests for the defining methods.
1759 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001760
Georg Brandl15c5ce92007-03-07 09:09:40 +00001761 def test_init(self):
1762 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001763
Georg Brandl15c5ce92007-03-07 09:09:40 +00001764 self.failUnless(result.wasSuccessful())
1765 self.assertEqual(len(result.errors), 0)
1766 self.assertEqual(len(result.failures), 0)
1767 self.assertEqual(result.testsRun, 0)
1768 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001769
Georg Brandl15c5ce92007-03-07 09:09:40 +00001770 # "This method can be called to signal that the set of tests being
1771 # run should be aborted by setting the TestResult's shouldStop
Tim Petersea5962f2007-03-12 18:07:52 +00001772 # attribute to True."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001773 def test_stop(self):
1774 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001775
Georg Brandl15c5ce92007-03-07 09:09:40 +00001776 result.stop()
Tim Petersea5962f2007-03-12 18:07:52 +00001777
Georg Brandl15c5ce92007-03-07 09:09:40 +00001778 self.assertEqual(result.shouldStop, True)
Tim Petersea5962f2007-03-12 18:07:52 +00001779
Georg Brandl15c5ce92007-03-07 09:09:40 +00001780 # "Called when the test case test is about to be run. The default
1781 # implementation simply increments the instance's testsRun counter."
1782 def test_startTest(self):
1783 class Foo(unittest.TestCase):
1784 def test_1(self):
1785 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001786
Georg Brandl15c5ce92007-03-07 09:09:40 +00001787 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001788
Georg Brandl15c5ce92007-03-07 09:09:40 +00001789 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001790
Georg Brandl15c5ce92007-03-07 09:09:40 +00001791 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001792
Georg Brandl15c5ce92007-03-07 09:09:40 +00001793 self.failUnless(result.wasSuccessful())
1794 self.assertEqual(len(result.errors), 0)
1795 self.assertEqual(len(result.failures), 0)
1796 self.assertEqual(result.testsRun, 1)
1797 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001798
Georg Brandl15c5ce92007-03-07 09:09:40 +00001799 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001800
Georg Brandl15c5ce92007-03-07 09:09:40 +00001801 # "Called after the test case test has been executed, regardless of
1802 # the outcome. The default implementation does nothing."
1803 def test_stopTest(self):
1804 class Foo(unittest.TestCase):
1805 def test_1(self):
1806 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001807
Georg Brandl15c5ce92007-03-07 09:09:40 +00001808 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001809
Georg Brandl15c5ce92007-03-07 09:09:40 +00001810 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001811
Georg Brandl15c5ce92007-03-07 09:09:40 +00001812 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001813
Georg Brandl15c5ce92007-03-07 09:09:40 +00001814 self.failUnless(result.wasSuccessful())
1815 self.assertEqual(len(result.errors), 0)
1816 self.assertEqual(len(result.failures), 0)
1817 self.assertEqual(result.testsRun, 1)
1818 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001819
Georg Brandl15c5ce92007-03-07 09:09:40 +00001820 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001821
Georg Brandl15c5ce92007-03-07 09:09:40 +00001822 # Same tests as above; make sure nothing has changed
1823 self.failUnless(result.wasSuccessful())
1824 self.assertEqual(len(result.errors), 0)
1825 self.assertEqual(len(result.failures), 0)
1826 self.assertEqual(result.testsRun, 1)
1827 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001828
Michael Foord07ef4872009-05-02 22:43:34 +00001829 # "Called before and after tests are run. The default implementation does nothing."
1830 def test_startTestRun_stopTestRun(self):
1831 result = unittest.TestResult()
1832 result.startTestRun()
1833 result.stopTestRun()
1834
Georg Brandl15c5ce92007-03-07 09:09:40 +00001835 # "addSuccess(test)"
1836 # ...
1837 # "Called when the test case test succeeds"
1838 # ...
1839 # "wasSuccessful() - Returns True if all tests run so far have passed,
1840 # otherwise returns False"
1841 # ...
1842 # "testsRun - The total number of tests run so far."
1843 # ...
1844 # "errors - A list containing 2-tuples of TestCase instances and
1845 # formatted tracebacks. Each tuple represents a test which raised an
1846 # unexpected exception. Contains formatted
1847 # tracebacks instead of sys.exc_info() results."
1848 # ...
1849 # "failures - A list containing 2-tuples of TestCase instances and
1850 # formatted tracebacks. Each tuple represents a test where a failure was
1851 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1852 # methods. Contains formatted tracebacks instead
1853 # of sys.exc_info() results."
1854 def test_addSuccess(self):
1855 class Foo(unittest.TestCase):
1856 def test_1(self):
1857 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001858
Georg Brandl15c5ce92007-03-07 09:09:40 +00001859 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001860
Georg Brandl15c5ce92007-03-07 09:09:40 +00001861 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001862
Georg Brandl15c5ce92007-03-07 09:09:40 +00001863 result.startTest(test)
1864 result.addSuccess(test)
1865 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001866
Georg Brandl15c5ce92007-03-07 09:09:40 +00001867 self.failUnless(result.wasSuccessful())
1868 self.assertEqual(len(result.errors), 0)
1869 self.assertEqual(len(result.failures), 0)
1870 self.assertEqual(result.testsRun, 1)
1871 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001872
Georg Brandl15c5ce92007-03-07 09:09:40 +00001873 # "addFailure(test, err)"
1874 # ...
1875 # "Called when the test case test signals a failure. err is a tuple of
1876 # the form returned by sys.exc_info(): (type, value, traceback)"
1877 # ...
1878 # "wasSuccessful() - Returns True if all tests run so far have passed,
1879 # otherwise returns False"
1880 # ...
1881 # "testsRun - The total number of tests run so far."
1882 # ...
1883 # "errors - A list containing 2-tuples of TestCase instances and
1884 # formatted tracebacks. Each tuple represents a test which raised an
1885 # unexpected exception. Contains formatted
1886 # tracebacks instead of sys.exc_info() results."
1887 # ...
1888 # "failures - A list containing 2-tuples of TestCase instances and
1889 # formatted tracebacks. Each tuple represents a test where a failure was
1890 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1891 # methods. Contains formatted tracebacks instead
1892 # of sys.exc_info() results."
1893 def test_addFailure(self):
1894 import sys
Tim Petersea5962f2007-03-12 18:07:52 +00001895
Georg Brandl15c5ce92007-03-07 09:09:40 +00001896 class Foo(unittest.TestCase):
1897 def test_1(self):
1898 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001899
Georg Brandl15c5ce92007-03-07 09:09:40 +00001900 test = Foo('test_1')
1901 try:
1902 test.fail("foo")
1903 except:
1904 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00001905
Georg Brandl15c5ce92007-03-07 09:09:40 +00001906 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001907
Georg Brandl15c5ce92007-03-07 09:09:40 +00001908 result.startTest(test)
1909 result.addFailure(test, exc_info_tuple)
1910 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001911
Georg Brandl15c5ce92007-03-07 09:09:40 +00001912 self.failIf(result.wasSuccessful())
1913 self.assertEqual(len(result.errors), 0)
1914 self.assertEqual(len(result.failures), 1)
1915 self.assertEqual(result.testsRun, 1)
1916 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001917
Georg Brandl15c5ce92007-03-07 09:09:40 +00001918 test_case, formatted_exc = result.failures[0]
1919 self.failUnless(test_case is test)
1920 self.failUnless(isinstance(formatted_exc, str))
Tim Petersea5962f2007-03-12 18:07:52 +00001921
Georg Brandl15c5ce92007-03-07 09:09:40 +00001922 # "addError(test, err)"
1923 # ...
1924 # "Called when the test case test raises an unexpected exception err
1925 # is a tuple of the form returned by sys.exc_info():
1926 # (type, value, traceback)"
1927 # ...
1928 # "wasSuccessful() - Returns True if all tests run so far have passed,
1929 # otherwise returns False"
1930 # ...
1931 # "testsRun - The total number of tests run so far."
1932 # ...
1933 # "errors - A list containing 2-tuples of TestCase instances and
1934 # formatted tracebacks. Each tuple represents a test which raised an
1935 # unexpected exception. Contains formatted
1936 # tracebacks instead of sys.exc_info() results."
1937 # ...
1938 # "failures - A list containing 2-tuples of TestCase instances and
1939 # formatted tracebacks. Each tuple represents a test where a failure was
1940 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1941 # methods. Contains formatted tracebacks instead
1942 # of sys.exc_info() results."
1943 def test_addError(self):
1944 import sys
Tim Petersea5962f2007-03-12 18:07:52 +00001945
Georg Brandl15c5ce92007-03-07 09:09:40 +00001946 class Foo(unittest.TestCase):
1947 def test_1(self):
1948 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001949
Georg Brandl15c5ce92007-03-07 09:09:40 +00001950 test = Foo('test_1')
1951 try:
1952 raise TypeError()
1953 except:
1954 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00001955
Georg Brandl15c5ce92007-03-07 09:09:40 +00001956 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001957
Georg Brandl15c5ce92007-03-07 09:09:40 +00001958 result.startTest(test)
1959 result.addError(test, exc_info_tuple)
1960 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001961
Georg Brandl15c5ce92007-03-07 09:09:40 +00001962 self.failIf(result.wasSuccessful())
1963 self.assertEqual(len(result.errors), 1)
1964 self.assertEqual(len(result.failures), 0)
1965 self.assertEqual(result.testsRun, 1)
1966 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001967
Georg Brandl15c5ce92007-03-07 09:09:40 +00001968 test_case, formatted_exc = result.errors[0]
1969 self.failUnless(test_case is test)
1970 self.failUnless(isinstance(formatted_exc, str))
1971
1972### Support code for Test_TestCase
1973################################################################
1974
1975class Foo(unittest.TestCase):
1976 def runTest(self): pass
1977 def test1(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001978
Georg Brandl15c5ce92007-03-07 09:09:40 +00001979class Bar(Foo):
1980 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001981
Michael Foord07ef4872009-05-02 22:43:34 +00001982class LoggingTestCase(unittest.TestCase):
1983 """A test case which logs its calls."""
1984
1985 def __init__(self, events):
1986 super(LoggingTestCase, self).__init__('test')
1987 self.events = events
1988
1989 def setUp(self):
1990 self.events.append('setUp')
1991
1992 def test(self):
1993 self.events.append('test')
1994
1995 def tearDown(self):
1996 self.events.append('tearDown')
1997
1998class ResultWithNoStartTestRunStopTestRun(object):
1999 """An object honouring TestResult before startTestRun/stopTestRun."""
2000
2001 def __init__(self):
2002 self.failures = []
2003 self.errors = []
2004 self.testsRun = 0
2005 self.skipped = []
2006 self.expectedFailures = []
2007 self.unexpectedSuccesses = []
2008 self.shouldStop = False
2009
2010 def startTest(self, test):
2011 pass
2012
2013 def stopTest(self, test):
2014 pass
2015
2016 def addError(self, test):
2017 pass
2018
2019 def addFailure(self, test):
2020 pass
2021
2022 def addSuccess(self, test):
2023 pass
2024
2025 def wasSuccessful(self):
2026 return True
2027
2028
Georg Brandl15c5ce92007-03-07 09:09:40 +00002029################################################################
2030### /Support code for Test_TestCase
2031
2032class Test_TestCase(TestCase, TestEquality, TestHashing):
2033
2034 ### Set up attributes used by inherited tests
2035 ################################################################
2036
2037 # Used by TestHashing.test_hash and TestEquality.test_eq
2038 eq_pairs = [(Foo('test1'), Foo('test1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002039
Georg Brandl15c5ce92007-03-07 09:09:40 +00002040 # Used by TestEquality.test_ne
2041 ne_pairs = [(Foo('test1'), Foo('runTest'))
2042 ,(Foo('test1'), Bar('test1'))
2043 ,(Foo('test1'), Bar('test2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00002044
Georg Brandl15c5ce92007-03-07 09:09:40 +00002045 ################################################################
2046 ### /Set up attributes used by inherited tests
Tim Petersea5962f2007-03-12 18:07:52 +00002047
Georg Brandl15c5ce92007-03-07 09:09:40 +00002048
2049 # "class TestCase([methodName])"
2050 # ...
2051 # "Each instance of TestCase will run a single test method: the
2052 # method named methodName."
2053 # ...
2054 # "methodName defaults to "runTest"."
2055 #
2056 # Make sure it really is optional, and that it defaults to the proper
2057 # thing.
2058 def test_init__no_test_name(self):
2059 class Test(unittest.TestCase):
2060 def runTest(self): raise MyException()
2061 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002062
Georg Brandl15c5ce92007-03-07 09:09:40 +00002063 self.assertEqual(Test().id()[-13:], '.Test.runTest')
Tim Petersea5962f2007-03-12 18:07:52 +00002064
Georg Brandl15c5ce92007-03-07 09:09:40 +00002065 # "class TestCase([methodName])"
2066 # ...
2067 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002068 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002069 def test_init__test_name__valid(self):
2070 class Test(unittest.TestCase):
2071 def runTest(self): raise MyException()
2072 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002073
Georg Brandl15c5ce92007-03-07 09:09:40 +00002074 self.assertEqual(Test('test').id()[-10:], '.Test.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002075
Georg Brandl15c5ce92007-03-07 09:09:40 +00002076 # "class TestCase([methodName])"
2077 # ...
2078 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002079 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002080 def test_init__test_name__invalid(self):
2081 class Test(unittest.TestCase):
2082 def runTest(self): raise MyException()
2083 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002084
Georg Brandl15c5ce92007-03-07 09:09:40 +00002085 try:
2086 Test('testfoo')
2087 except ValueError:
2088 pass
2089 else:
2090 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +00002091
Georg Brandl15c5ce92007-03-07 09:09:40 +00002092 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00002093 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00002094 def test_countTestCases(self):
2095 class Foo(unittest.TestCase):
2096 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002097
Georg Brandl15c5ce92007-03-07 09:09:40 +00002098 self.assertEqual(Foo('test').countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00002099
Georg Brandl15c5ce92007-03-07 09:09:40 +00002100 # "Return the default type of test result object to be used to run this
2101 # test. For TestCase instances, this will always be
2102 # unittest.TestResult; subclasses of TestCase should
2103 # override this as necessary."
2104 def test_defaultTestResult(self):
2105 class Foo(unittest.TestCase):
2106 def runTest(self):
2107 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002108
Georg Brandl15c5ce92007-03-07 09:09:40 +00002109 result = Foo().defaultTestResult()
2110 self.assertEqual(type(result), unittest.TestResult)
2111
2112 # "When a setUp() method is defined, the test runner will run that method
2113 # prior to each test. Likewise, if a tearDown() method is defined, the
2114 # test runner will invoke that method after each test. In the example,
2115 # setUp() was used to create a fresh sequence for each test."
2116 #
2117 # Make sure the proper call order is maintained, even if setUp() raises
2118 # an exception.
2119 def test_run_call_order__error_in_setUp(self):
2120 events = []
2121 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002122
Michael Foord07ef4872009-05-02 22:43:34 +00002123 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002124 def setUp(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002125 super(Foo, self).setUp()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002126 raise RuntimeError('raised by Foo.setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002127
Michael Foord07ef4872009-05-02 22:43:34 +00002128 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002129 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2130 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002131
Michael Foord07ef4872009-05-02 22:43:34 +00002132 # "With a temporary result stopTestRun is called when setUp errors.
2133 def test_run_call_order__error_in_setUp_default_result(self):
2134 events = []
2135
2136 class Foo(LoggingTestCase):
2137 def defaultTestResult(self):
2138 return LoggingResult(self.events)
2139
2140 def setUp(self):
2141 super(Foo, self).setUp()
2142 raise RuntimeError('raised by Foo.setUp')
2143
2144 Foo(events).run()
2145 expected = ['startTestRun', 'startTest', 'setUp', 'addError',
2146 'stopTest', 'stopTestRun']
2147 self.assertEqual(events, expected)
2148
Georg Brandl15c5ce92007-03-07 09:09:40 +00002149 # "When a setUp() method is defined, the test runner will run that method
2150 # prior to each test. Likewise, if a tearDown() method is defined, the
2151 # test runner will invoke that method after each test. In the example,
2152 # setUp() was used to create a fresh sequence for each test."
2153 #
2154 # Make sure the proper call order is maintained, even if the test raises
2155 # an error (as opposed to a failure).
2156 def test_run_call_order__error_in_test(self):
2157 events = []
2158 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002159
Michael Foord07ef4872009-05-02 22:43:34 +00002160 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002161 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002162 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002163 raise RuntimeError('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002164
Georg Brandl15c5ce92007-03-07 09:09:40 +00002165 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2166 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002167 Foo(events).run(result)
2168 self.assertEqual(events, expected)
2169
2170 # "With a default result, an error in the test still results in stopTestRun
2171 # being called."
2172 def test_run_call_order__error_in_test_default_result(self):
2173 events = []
2174
2175 class Foo(LoggingTestCase):
2176 def defaultTestResult(self):
2177 return LoggingResult(self.events)
2178
2179 def test(self):
2180 super(Foo, self).test()
2181 raise RuntimeError('raised by Foo.test')
2182
2183 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
2184 'tearDown', 'stopTest', 'stopTestRun']
2185 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002186 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002187
Georg Brandl15c5ce92007-03-07 09:09:40 +00002188 # "When a setUp() method is defined, the test runner will run that method
2189 # prior to each test. Likewise, if a tearDown() method is defined, the
2190 # test runner will invoke that method after each test. In the example,
2191 # setUp() was used to create a fresh sequence for each test."
2192 #
2193 # Make sure the proper call order is maintained, even if the test signals
2194 # a failure (as opposed to an error).
2195 def test_run_call_order__failure_in_test(self):
2196 events = []
2197 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002198
Michael Foord07ef4872009-05-02 22:43:34 +00002199 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002200 def test(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002201 super(Foo, self).test()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002202 self.fail('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002203
Georg Brandl15c5ce92007-03-07 09:09:40 +00002204 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2205 'stopTest']
Michael Foord07ef4872009-05-02 22:43:34 +00002206 Foo(events).run(result)
2207 self.assertEqual(events, expected)
2208
2209 # "When a test fails with a default result stopTestRun is still called."
2210 def test_run_call_order__failure_in_test_default_result(self):
2211
2212 class Foo(LoggingTestCase):
2213 def defaultTestResult(self):
2214 return LoggingResult(self.events)
2215 def test(self):
2216 super(Foo, self).test()
2217 self.fail('raised by Foo.test')
2218
2219 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
2220 'tearDown', 'stopTest', 'stopTestRun']
2221 events = []
2222 Foo(events).run()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002223 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002224
Georg Brandl15c5ce92007-03-07 09:09:40 +00002225 # "When a setUp() method is defined, the test runner will run that method
2226 # prior to each test. Likewise, if a tearDown() method is defined, the
2227 # test runner will invoke that method after each test. In the example,
2228 # setUp() was used to create a fresh sequence for each test."
2229 #
2230 # Make sure the proper call order is maintained, even if tearDown() raises
2231 # an exception.
2232 def test_run_call_order__error_in_tearDown(self):
2233 events = []
2234 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002235
Michael Foord07ef4872009-05-02 22:43:34 +00002236 class Foo(LoggingTestCase):
Georg Brandl15c5ce92007-03-07 09:09:40 +00002237 def tearDown(self):
Michael Foord07ef4872009-05-02 22:43:34 +00002238 super(Foo, self).tearDown()
Georg Brandl15c5ce92007-03-07 09:09:40 +00002239 raise RuntimeError('raised by Foo.tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002240
Michael Foord07ef4872009-05-02 22:43:34 +00002241 Foo(events).run(result)
Georg Brandl15c5ce92007-03-07 09:09:40 +00002242 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2243 'stopTest']
2244 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002245
Michael Foord07ef4872009-05-02 22:43:34 +00002246 # "When tearDown errors with a default result stopTestRun is still called."
2247 def test_run_call_order__error_in_tearDown_default_result(self):
2248
2249 class Foo(LoggingTestCase):
2250 def defaultTestResult(self):
2251 return LoggingResult(self.events)
2252 def tearDown(self):
2253 super(Foo, self).tearDown()
2254 raise RuntimeError('raised by Foo.tearDown')
2255
2256 events = []
2257 Foo(events).run()
2258 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
2259 'addError', 'stopTest', 'stopTestRun']
2260 self.assertEqual(events, expected)
2261
2262 # "TestCase.run() still works when the defaultTestResult is a TestResult
2263 # that does not support startTestRun and stopTestRun.
2264 def test_run_call_order_default_result(self):
2265
2266 class Foo(unittest.TestCase):
2267 def defaultTestResult(self):
2268 return ResultWithNoStartTestRunStopTestRun()
2269 def test(self):
2270 pass
2271
2272 Foo('test').run()
2273
Georg Brandl15c5ce92007-03-07 09:09:40 +00002274 # "This class attribute gives the exception raised by the test() method.
2275 # If a test framework needs to use a specialized exception, possibly to
2276 # carry additional information, it must subclass this exception in
2277 # order to ``play fair'' with the framework. The initial value of this
2278 # attribute is AssertionError"
2279 def test_failureException__default(self):
2280 class Foo(unittest.TestCase):
2281 def test(self):
2282 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002283
Georg Brandl15c5ce92007-03-07 09:09:40 +00002284 self.failUnless(Foo('test').failureException is AssertionError)
Tim Petersea5962f2007-03-12 18:07:52 +00002285
Georg Brandl15c5ce92007-03-07 09:09:40 +00002286 # "This class attribute gives the exception raised by the test() method.
2287 # If a test framework needs to use a specialized exception, possibly to
2288 # carry additional information, it must subclass this exception in
2289 # order to ``play fair'' with the framework."
2290 #
2291 # Make sure TestCase.run() respects the designated failureException
2292 def test_failureException__subclassing__explicit_raise(self):
2293 events = []
2294 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002295
Georg Brandl15c5ce92007-03-07 09:09:40 +00002296 class Foo(unittest.TestCase):
2297 def test(self):
2298 raise RuntimeError()
Tim Petersea5962f2007-03-12 18:07:52 +00002299
Georg Brandl15c5ce92007-03-07 09:09:40 +00002300 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002301
Georg Brandl15c5ce92007-03-07 09:09:40 +00002302 self.failUnless(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002303
2304
Georg Brandl15c5ce92007-03-07 09:09:40 +00002305 Foo('test').run(result)
2306 expected = ['startTest', 'addFailure', 'stopTest']
2307 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002308
Georg Brandl15c5ce92007-03-07 09:09:40 +00002309 # "This class attribute gives the exception raised by the test() method.
2310 # If a test framework needs to use a specialized exception, possibly to
2311 # carry additional information, it must subclass this exception in
2312 # order to ``play fair'' with the framework."
2313 #
2314 # Make sure TestCase.run() respects the designated failureException
2315 def test_failureException__subclassing__implicit_raise(self):
2316 events = []
2317 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002318
Georg Brandl15c5ce92007-03-07 09:09:40 +00002319 class Foo(unittest.TestCase):
2320 def test(self):
2321 self.fail("foo")
Tim Petersea5962f2007-03-12 18:07:52 +00002322
Georg Brandl15c5ce92007-03-07 09:09:40 +00002323 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002324
Georg Brandl15c5ce92007-03-07 09:09:40 +00002325 self.failUnless(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002326
2327
Georg Brandl15c5ce92007-03-07 09:09:40 +00002328 Foo('test').run(result)
2329 expected = ['startTest', 'addFailure', 'stopTest']
2330 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002331
2332 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002333 def test_setUp(self):
2334 class Foo(unittest.TestCase):
2335 def runTest(self):
2336 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002337
Georg Brandl15c5ce92007-03-07 09:09:40 +00002338 # ... and nothing should happen
2339 Foo().setUp()
Tim Petersea5962f2007-03-12 18:07:52 +00002340
2341 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002342 def test_tearDown(self):
2343 class Foo(unittest.TestCase):
2344 def runTest(self):
2345 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002346
Georg Brandl15c5ce92007-03-07 09:09:40 +00002347 # ... and nothing should happen
2348 Foo().tearDown()
Tim Petersea5962f2007-03-12 18:07:52 +00002349
Georg Brandl15c5ce92007-03-07 09:09:40 +00002350 # "Return a string identifying the specific test case."
2351 #
2352 # Because of the vague nature of the docs, I'm not going to lock this
2353 # test down too much. Really all that can be asserted is that the id()
2354 # will be a string (either 8-byte or unicode -- again, because the docs
2355 # just say "string")
2356 def test_id(self):
2357 class Foo(unittest.TestCase):
2358 def runTest(self):
2359 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002360
Georg Brandl15c5ce92007-03-07 09:09:40 +00002361 self.failUnless(isinstance(Foo().id(), basestring))
Tim Petersea5962f2007-03-12 18:07:52 +00002362
Georg Brandl15c5ce92007-03-07 09:09:40 +00002363 # "If result is omitted or None, a temporary result object is created
Michael Foord07ef4872009-05-02 22:43:34 +00002364 # and used, but is not made available to the caller. As TestCase owns the
2365 # temporary result startTestRun and stopTestRun are called.
2366
Georg Brandl15c5ce92007-03-07 09:09:40 +00002367 def test_run__uses_defaultTestResult(self):
2368 events = []
Tim Petersea5962f2007-03-12 18:07:52 +00002369
Georg Brandl15c5ce92007-03-07 09:09:40 +00002370 class Foo(unittest.TestCase):
2371 def test(self):
2372 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002373
Georg Brandl15c5ce92007-03-07 09:09:40 +00002374 def defaultTestResult(self):
2375 return LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002376
2377 # Make run() find a result object on its own
Georg Brandl15c5ce92007-03-07 09:09:40 +00002378 Foo('test').run()
Tim Petersea5962f2007-03-12 18:07:52 +00002379
Michael Foord07ef4872009-05-02 22:43:34 +00002380 expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
2381 'stopTest', 'stopTestRun']
Georg Brandl15c5ce92007-03-07 09:09:40 +00002382 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002383
Gregory P. Smith28399852009-03-31 16:54:10 +00002384 def testShortDescriptionWithoutDocstring(self):
2385 self.assertEqual(
2386 self.shortDescription(),
2387 'testShortDescriptionWithoutDocstring (' + __name__ +
2388 '.Test_TestCase)')
2389
2390 def testShortDescriptionWithOneLineDocstring(self):
2391 """Tests shortDescription() for a method with a docstring."""
2392 self.assertEqual(
2393 self.shortDescription(),
2394 ('testShortDescriptionWithOneLineDocstring '
2395 '(' + __name__ + '.Test_TestCase)\n'
2396 'Tests shortDescription() for a method with a docstring.'))
2397
2398 def testShortDescriptionWithMultiLineDocstring(self):
2399 """Tests shortDescription() for a method with a longer docstring.
2400
2401 This method ensures that only the first line of a docstring is
2402 returned used in the short description, no matter how long the
2403 whole thing is.
2404 """
2405 self.assertEqual(
2406 self.shortDescription(),
2407 ('testShortDescriptionWithMultiLineDocstring '
2408 '(' + __name__ + '.Test_TestCase)\n'
2409 'Tests shortDescription() for a method with a longer '
2410 'docstring.'))
2411
Gregory P. Smith28399852009-03-31 16:54:10 +00002412 def testAddTypeEqualityFunc(self):
2413 class SadSnake(object):
2414 """Dummy class for test_addTypeEqualityFunc."""
2415 s1, s2 = SadSnake(), SadSnake()
2416 self.assertFalse(s1 == s2)
2417 def AllSnakesCreatedEqual(a, b, msg=None):
2418 return type(a) == type(b) == SadSnake
2419 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2420 self.assertEqual(s1, s2)
2421 # No this doesn't clean up and remove the SadSnake equality func
2422 # from this TestCase instance but since its a local nothing else
2423 # will ever notice that.
2424
Michael Foordf2dfef12009-04-05 19:19:28 +00002425 def testAssertIs(self):
2426 thing = object()
2427 self.assertIs(thing, thing)
2428 self.assertRaises(self.failureException, self.assertIs, thing, object())
2429
2430 def testAssertIsNot(self):
2431 thing = object()
2432 self.assertIsNot(thing, object())
2433 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2434
Gregory P. Smith28399852009-03-31 16:54:10 +00002435 def testAssertIn(self):
2436 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2437
2438 self.assertIn('a', 'abc')
2439 self.assertIn(2, [1, 2, 3])
2440 self.assertIn('monkey', animals)
2441
2442 self.assertNotIn('d', 'abc')
2443 self.assertNotIn(0, [1, 2, 3])
2444 self.assertNotIn('otter', animals)
2445
2446 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2447 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2448 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2449 animals)
2450
2451 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2452 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2453 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2454 animals)
2455
2456 def testAssertDictContainsSubset(self):
2457 self.assertDictContainsSubset({}, {})
2458 self.assertDictContainsSubset({}, {'a': 1})
2459 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2460 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2461 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2462
2463 self.assertRaises(unittest.TestCase.failureException,
2464 self.assertDictContainsSubset, {'a': 2}, {'a': 1},
2465 '.*Mismatched values:.*')
2466
2467 self.assertRaises(unittest.TestCase.failureException,
2468 self.assertDictContainsSubset, {'c': 1}, {'a': 1},
2469 '.*Missing:.*')
2470
2471 self.assertRaises(unittest.TestCase.failureException,
2472 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2473 {'a': 1}, '.*Missing:.*')
2474
2475 self.assertRaises(unittest.TestCase.failureException,
2476 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2477 {'a': 1}, '.*Missing:.*Mismatched values:.*')
2478
2479 def testAssertEqual(self):
2480 equal_pairs = [
2481 ((), ()),
2482 ({}, {}),
2483 ([], []),
2484 (set(), set()),
2485 (frozenset(), frozenset())]
2486 for a, b in equal_pairs:
2487 # This mess of try excepts is to test the assertEqual behavior
2488 # itself.
2489 try:
2490 self.assertEqual(a, b)
2491 except self.failureException:
2492 self.fail('assertEqual(%r, %r) failed' % (a, b))
2493 try:
2494 self.assertEqual(a, b, msg='foo')
2495 except self.failureException:
2496 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2497 try:
2498 self.assertEqual(a, b, 'foo')
2499 except self.failureException:
2500 self.fail('assertEqual(%r, %r) with third parameter failed' %
2501 (a, b))
2502
2503 unequal_pairs = [
2504 ((), []),
2505 ({}, set()),
2506 (set([4,1]), frozenset([4,2])),
2507 (frozenset([4,5]), set([2,3])),
2508 (set([3,4]), set([5,4]))]
2509 for a, b in unequal_pairs:
2510 self.assertRaises(self.failureException, self.assertEqual, a, b)
2511 self.assertRaises(self.failureException, self.assertEqual, a, b,
2512 'foo')
2513 self.assertRaises(self.failureException, self.assertEqual, a, b,
2514 msg='foo')
2515
2516 def testEquality(self):
2517 self.assertListEqual([], [])
2518 self.assertTupleEqual((), ())
2519 self.assertSequenceEqual([], ())
2520
2521 a = [0, 'a', []]
2522 b = []
2523 self.assertRaises(unittest.TestCase.failureException,
2524 self.assertListEqual, a, b)
2525 self.assertRaises(unittest.TestCase.failureException,
2526 self.assertListEqual, tuple(a), tuple(b))
2527 self.assertRaises(unittest.TestCase.failureException,
2528 self.assertSequenceEqual, a, tuple(b))
2529
2530 b.extend(a)
2531 self.assertListEqual(a, b)
2532 self.assertTupleEqual(tuple(a), tuple(b))
2533 self.assertSequenceEqual(a, tuple(b))
2534 self.assertSequenceEqual(tuple(a), b)
2535
2536 self.assertRaises(self.failureException, self.assertListEqual,
2537 a, tuple(b))
2538 self.assertRaises(self.failureException, self.assertTupleEqual,
2539 tuple(a), b)
2540 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2541 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2542 tuple(b))
2543 self.assertRaises(self.failureException, self.assertSequenceEqual,
2544 None, tuple(b))
2545 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2546 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2547 self.assertRaises(self.failureException, self.assertSequenceEqual,
2548 1, 1)
2549
2550 self.assertDictEqual({}, {})
2551
2552 c = { 'x': 1 }
2553 d = {}
2554 self.assertRaises(unittest.TestCase.failureException,
2555 self.assertDictEqual, c, d)
2556
2557 d.update(c)
2558 self.assertDictEqual(c, d)
2559
2560 d['x'] = 0
2561 self.assertRaises(unittest.TestCase.failureException,
2562 self.assertDictEqual, c, d, 'These are unequal')
2563
2564 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2565 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2566 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2567
2568 self.assertSameElements([1, 2, 3], [3, 2, 1])
2569 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2570 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2571 self.assertRaises(self.failureException, self.assertSameElements,
2572 [10], [10, 11])
2573 self.assertRaises(self.failureException, self.assertSameElements,
2574 [10, 11], [10])
2575
2576 # Test that sequences of unhashable objects can be tested for sameness:
2577 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Michael Foordf2dfef12009-04-05 19:19:28 +00002578
Gregory P. Smith28399852009-03-31 16:54:10 +00002579 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2580 self.assertRaises(self.failureException, self.assertSameElements,
2581 [[1]], [[2]])
2582
2583 def testAssertSetEqual(self):
2584 set1 = set()
2585 set2 = set()
2586 self.assertSetEqual(set1, set2)
2587
2588 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2589 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2590 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2591 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2592
2593 set1 = set(['a'])
2594 set2 = set()
2595 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2596
2597 set1 = set(['a'])
2598 set2 = set(['a'])
2599 self.assertSetEqual(set1, set2)
2600
2601 set1 = set(['a'])
2602 set2 = set(['a', 'b'])
2603 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2604
2605 set1 = set(['a'])
2606 set2 = frozenset(['a', 'b'])
2607 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2608
2609 set1 = set(['a', 'b'])
2610 set2 = frozenset(['a', 'b'])
2611 self.assertSetEqual(set1, set2)
2612
2613 set1 = set()
2614 set2 = "foo"
2615 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2616 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2617
2618 # make sure any string formatting is tuple-safe
2619 set1 = set([(0, 1), (2, 3)])
2620 set2 = set([(4, 5)])
2621 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2622
2623 def testInequality(self):
2624 # Try ints
2625 self.assertGreater(2, 1)
2626 self.assertGreaterEqual(2, 1)
2627 self.assertGreaterEqual(1, 1)
2628 self.assertLess(1, 2)
2629 self.assertLessEqual(1, 2)
2630 self.assertLessEqual(1, 1)
2631 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2632 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2633 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2634 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2635 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2636 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2637
2638 # Try Floats
2639 self.assertGreater(1.1, 1.0)
2640 self.assertGreaterEqual(1.1, 1.0)
2641 self.assertGreaterEqual(1.0, 1.0)
2642 self.assertLess(1.0, 1.1)
2643 self.assertLessEqual(1.0, 1.1)
2644 self.assertLessEqual(1.0, 1.0)
2645 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2646 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2647 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2648 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2649 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2650 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2651
2652 # Try Strings
2653 self.assertGreater('bug', 'ant')
2654 self.assertGreaterEqual('bug', 'ant')
2655 self.assertGreaterEqual('ant', 'ant')
2656 self.assertLess('ant', 'bug')
2657 self.assertLessEqual('ant', 'bug')
2658 self.assertLessEqual('ant', 'ant')
2659 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2660 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2661 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2662 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2663 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2664 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2665
2666 # Try Unicode
2667 self.assertGreater(u'bug', u'ant')
2668 self.assertGreaterEqual(u'bug', u'ant')
2669 self.assertGreaterEqual(u'ant', u'ant')
2670 self.assertLess(u'ant', u'bug')
2671 self.assertLessEqual(u'ant', u'bug')
2672 self.assertLessEqual(u'ant', u'ant')
2673 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug')
2674 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant')
2675 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2676 u'bug')
2677 self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant')
2678 self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant')
2679 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant')
2680
2681 # Try Mixed String/Unicode
2682 self.assertGreater('bug', u'ant')
2683 self.assertGreater(u'bug', 'ant')
2684 self.assertGreaterEqual('bug', u'ant')
2685 self.assertGreaterEqual(u'bug', 'ant')
2686 self.assertGreaterEqual('ant', u'ant')
2687 self.assertGreaterEqual(u'ant', 'ant')
2688 self.assertLess('ant', u'bug')
2689 self.assertLess(u'ant', 'bug')
2690 self.assertLessEqual('ant', u'bug')
2691 self.assertLessEqual(u'ant', 'bug')
2692 self.assertLessEqual('ant', u'ant')
2693 self.assertLessEqual(u'ant', 'ant')
2694 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug')
2695 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug')
2696 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant')
2697 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant')
2698 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant',
2699 u'bug')
2700 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2701 'bug')
2702 self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant')
2703 self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant')
2704 self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant')
2705 self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant')
2706 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant')
2707 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant')
2708
2709 def testAssertMultiLineEqual(self):
2710 sample_text = b"""\
2711http://www.python.org/doc/2.3/lib/module-unittest.html
2712test case
2713 A test case is the smallest unit of testing. [...]
2714"""
2715 revised_sample_text = b"""\
2716http://www.python.org/doc/2.4.1/lib/module-unittest.html
2717test case
2718 A test case is the smallest unit of testing. [...] You may provide your
2719 own implementation that does not subclass from TestCase, of course.
2720"""
2721 sample_text_error = b"""
2722- http://www.python.org/doc/2.3/lib/module-unittest.html
2723? ^
2724+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2725? ^^^
2726 test case
2727- A test case is the smallest unit of testing. [...]
2728+ A test case is the smallest unit of testing. [...] You may provide your
2729? +++++++++++++++++++++
2730+ own implementation that does not subclass from TestCase, of course.
2731"""
2732
2733 for type_changer in (lambda x: x, lambda x: x.decode('utf8')):
2734 try:
2735 self.assertMultiLineEqual(type_changer(sample_text),
2736 type_changer(revised_sample_text))
2737 except self.failureException, e:
2738 # no fair testing ourself with ourself, use assertEqual..
2739 self.assertEqual(sample_text_error, str(e).encode('utf8'))
2740
2741 def testAssertIsNone(self):
2742 self.assertIsNone(None)
2743 self.assertRaises(self.failureException, self.assertIsNone, False)
2744 self.assertIsNotNone('DjZoPloGears on Rails')
2745 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2746
2747 def testAssertRegexpMatches(self):
2748 self.assertRegexpMatches('asdfabasdf', r'ab+')
2749 self.assertRaises(self.failureException, self.assertRegexpMatches,
2750 'saaas', r'aaaa')
2751
2752 def testAssertRaisesRegexp(self):
2753 class ExceptionMock(Exception):
2754 pass
2755
2756 def Stub():
2757 raise ExceptionMock('We expect')
2758
2759 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2760 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2761 self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
2762
2763 def testAssertNotRaisesRegexp(self):
2764 self.assertRaisesRegexp(
2765 self.failureException, '^Exception not raised$',
2766 self.assertRaisesRegexp, Exception, re.compile('x'),
2767 lambda: None)
2768 self.assertRaisesRegexp(
2769 self.failureException, '^Exception not raised$',
2770 self.assertRaisesRegexp, Exception, 'x',
2771 lambda: None)
2772 self.assertRaisesRegexp(
2773 self.failureException, '^Exception not raised$',
2774 self.assertRaisesRegexp, Exception, u'x',
2775 lambda: None)
2776
2777 def testAssertRaisesRegexpMismatch(self):
2778 def Stub():
2779 raise Exception('Unexpected')
2780
2781 self.assertRaisesRegexp(
2782 self.failureException,
2783 r'"\^Expected\$" does not match "Unexpected"',
2784 self.assertRaisesRegexp, Exception, '^Expected$',
2785 Stub)
2786 self.assertRaisesRegexp(
2787 self.failureException,
2788 r'"\^Expected\$" does not match "Unexpected"',
2789 self.assertRaisesRegexp, Exception, u'^Expected$',
2790 Stub)
2791 self.assertRaisesRegexp(
2792 self.failureException,
2793 r'"\^Expected\$" does not match "Unexpected"',
2794 self.assertRaisesRegexp, Exception,
2795 re.compile('^Expected$'), Stub)
2796
Gregory P. Smith7558d572009-03-31 19:03:28 +00002797 def testSynonymAssertMethodNames(self):
2798 """Test undocumented method name synonyms.
2799
2800 Please do not use these methods names in your own code.
2801
2802 This test confirms their continued existence and functionality
2803 in order to avoid breaking existing code.
2804 """
2805 self.assertNotEquals(3, 5)
2806 self.assertEquals(3, 3)
2807 self.assertAlmostEquals(2.0, 2.0)
2808 self.assertNotAlmostEquals(3.0, 5.0)
2809 self.assert_(True)
2810
2811 def testPendingDeprecationMethodNames(self):
2812 """Test fail* methods pending deprecation, they will warn in 3.2.
2813
2814 Do not use these methods. They will go away in 3.3.
2815 """
2816 self.failIfEqual(3, 5)
2817 self.failUnlessEqual(3, 3)
2818 self.failUnlessAlmostEqual(2.0, 2.0)
2819 self.failIfAlmostEqual(3.0, 5.0)
2820 self.failUnless(True)
2821 self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam')
2822 self.failIf(False)
2823
Michael Foorde2942d02009-04-02 05:51:54 +00002824 def testDeepcopy(self):
2825 # Issue: 5660
2826 class TestableTest(TestCase):
2827 def testNothing(self):
2828 pass
2829
2830 test = TestableTest('testNothing')
2831
2832 # This shouldn't blow up
2833 deepcopy(test)
2834
Benjamin Peterson692428e2009-03-23 21:50:21 +00002835
2836class Test_TestSkipping(TestCase):
2837
2838 def test_skipping(self):
2839 class Foo(unittest.TestCase):
2840 def test_skip_me(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002841 self.skipTest("skip")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002842 events = []
2843 result = LoggingResult(events)
2844 test = Foo("test_skip_me")
2845 test.run(result)
2846 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2847 self.assertEqual(result.skipped, [(test, "skip")])
2848
2849 # Try letting setUp skip the test now.
2850 class Foo(unittest.TestCase):
2851 def setUp(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002852 self.skipTest("testing")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002853 def test_nothing(self): pass
2854 events = []
2855 result = LoggingResult(events)
2856 test = Foo("test_nothing")
2857 test.run(result)
2858 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2859 self.assertEqual(result.skipped, [(test, "testing")])
2860 self.assertEqual(result.testsRun, 1)
2861
2862 def test_skipping_decorators(self):
2863 op_table = ((unittest.skipUnless, False, True),
2864 (unittest.skipIf, True, False))
2865 for deco, do_skip, dont_skip in op_table:
2866 class Foo(unittest.TestCase):
2867 @deco(do_skip, "testing")
2868 def test_skip(self): pass
2869
2870 @deco(dont_skip, "testing")
2871 def test_dont_skip(self): pass
2872 test_do_skip = Foo("test_skip")
2873 test_dont_skip = Foo("test_dont_skip")
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002874 suite = unittest.TestSuite([test_do_skip, test_dont_skip])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002875 events = []
2876 result = LoggingResult(events)
2877 suite.run(result)
2878 self.assertEqual(len(result.skipped), 1)
2879 expected = ['startTest', 'addSkip', 'stopTest',
2880 'startTest', 'addSuccess', 'stopTest']
2881 self.assertEqual(events, expected)
2882 self.assertEqual(result.testsRun, 2)
2883 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
2884 self.assertTrue(result.wasSuccessful())
2885
2886 def test_skip_class(self):
2887 @unittest.skip("testing")
2888 class Foo(unittest.TestCase):
2889 def test_1(self):
2890 record.append(1)
2891 record = []
2892 result = unittest.TestResult()
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002893 test = Foo("test_1")
2894 suite = unittest.TestSuite([test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002895 suite.run(result)
Benjamin Peterson176a56c2009-05-25 00:48:58 +00002896 self.assertEqual(result.skipped, [(test, "testing")])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002897 self.assertEqual(record, [])
2898
2899 def test_expected_failure(self):
2900 class Foo(unittest.TestCase):
2901 @unittest.expectedFailure
2902 def test_die(self):
2903 self.fail("help me!")
2904 events = []
2905 result = LoggingResult(events)
2906 test = Foo("test_die")
2907 test.run(result)
2908 self.assertEqual(events,
2909 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00002910 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00002911 self.assertTrue(result.wasSuccessful())
2912
2913 def test_unexpected_success(self):
2914 class Foo(unittest.TestCase):
2915 @unittest.expectedFailure
2916 def test_die(self):
2917 pass
2918 events = []
2919 result = LoggingResult(events)
2920 test = Foo("test_die")
2921 test.run(result)
2922 self.assertEqual(events,
2923 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
2924 self.assertFalse(result.failures)
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00002925 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002926 self.assertTrue(result.wasSuccessful())
2927
2928
2929
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002930class Test_Assertions(TestCase):
2931 def test_AlmostEqual(self):
2932 self.failUnlessAlmostEqual(1.00000001, 1.0)
2933 self.failIfAlmostEqual(1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00002934 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002935 self.failUnlessAlmostEqual, 1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00002936 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002937 self.failIfAlmostEqual, 1.00000001, 1.0)
2938
2939 self.failUnlessAlmostEqual(1.1, 1.0, places=0)
Gregory P. Smith28399852009-03-31 16:54:10 +00002940 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002941 self.failUnlessAlmostEqual, 1.1, 1.0, places=1)
2942
2943 self.failUnlessAlmostEqual(0, .1+.1j, places=0)
2944 self.failIfAlmostEqual(0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00002945 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002946 self.failUnlessAlmostEqual, 0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00002947 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002948 self.failIfAlmostEqual, 0, .1+.1j, places=0)
2949
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00002950 def test_assertRaises(self):
2951 def _raise(e):
2952 raise e
2953 self.assertRaises(KeyError, _raise, KeyError)
2954 self.assertRaises(KeyError, _raise, KeyError("key"))
2955 try:
2956 self.assertRaises(KeyError, lambda: None)
Gregory P. Smith28399852009-03-31 16:54:10 +00002957 except self.failureException as e:
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00002958 self.assert_("KeyError not raised" in e, str(e))
2959 else:
2960 self.fail("assertRaises() didn't fail")
2961 try:
2962 self.assertRaises(KeyError, _raise, ValueError)
2963 except ValueError:
2964 pass
2965 else:
2966 self.fail("assertRaises() didn't let exception pass through")
2967 with self.assertRaises(KeyError):
2968 raise KeyError
2969 with self.assertRaises(KeyError):
2970 raise KeyError("key")
2971 try:
2972 with self.assertRaises(KeyError):
2973 pass
Gregory P. Smith28399852009-03-31 16:54:10 +00002974 except self.failureException as e:
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00002975 self.assert_("KeyError not raised" in e, str(e))
2976 else:
2977 self.fail("assertRaises() didn't fail")
2978 try:
2979 with self.assertRaises(KeyError):
2980 raise ValueError
2981 except ValueError:
2982 pass
2983 else:
2984 self.fail("assertRaises() didn't let exception pass through")
2985
2986
Michael Foord345b2fe2009-04-02 03:20:38 +00002987class TestLongMessage(TestCase):
2988 """Test that the individual asserts honour longMessage.
2989 This actually tests all the message behaviour for
2990 asserts that use longMessage."""
2991
2992 def setUp(self):
2993 class TestableTestFalse(TestCase):
2994 longMessage = False
2995 failureException = self.failureException
2996
2997 def testTest(self):
2998 pass
2999
3000 class TestableTestTrue(TestCase):
3001 longMessage = True
3002 failureException = self.failureException
3003
3004 def testTest(self):
3005 pass
3006
3007 self.testableTrue = TestableTestTrue('testTest')
3008 self.testableFalse = TestableTestFalse('testTest')
3009
3010 def testDefault(self):
3011 self.assertFalse(TestCase.longMessage)
3012
3013 def test_formatMsg(self):
3014 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
3015 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
3016
3017 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
3018 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
3019
3020 def assertMessages(self, methodName, args, errors):
3021 def getMethod(i):
3022 useTestableFalse = i < 2
3023 if useTestableFalse:
3024 test = self.testableFalse
3025 else:
3026 test = self.testableTrue
3027 return getattr(test, methodName)
3028
3029 for i, expected_regexp in enumerate(errors):
3030 testMethod = getMethod(i)
3031 kwargs = {}
3032 withMsg = i % 2
3033 if withMsg:
3034 kwargs = {"msg": "oops"}
3035
3036 with self.assertRaisesRegexp(self.failureException,
3037 expected_regexp=expected_regexp):
3038 testMethod(*args, **kwargs)
3039
3040 def testAssertTrue(self):
3041 self.assertMessages('assertTrue', (False,),
3042 ["^False is not True$", "^oops$", "^False is not True$",
3043 "^False is not True : oops$"])
3044
3045 def testAssertFalse(self):
3046 self.assertMessages('assertFalse', (True,),
3047 ["^True is not False$", "^oops$", "^True is not False$",
3048 "^True is not False : oops$"])
3049
3050 def testNotEqual(self):
3051 self.assertMessages('assertNotEqual', (1, 1),
3052 ["^1 == 1$", "^oops$", "^1 == 1$",
3053 "^1 == 1 : oops$"])
3054
3055 def testAlmostEqual(self):
3056 self.assertMessages('assertAlmostEqual', (1, 2),
3057 ["^1 != 2 within 7 places$", "^oops$",
3058 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
3059
3060 def testNotAlmostEqual(self):
3061 self.assertMessages('assertNotAlmostEqual', (1, 1),
3062 ["^1 == 1 within 7 places$", "^oops$",
3063 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
3064
3065 def test_baseAssertEqual(self):
3066 self.assertMessages('_baseAssertEqual', (1, 2),
3067 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
3068
3069 def testAssertSequenceEqual(self):
3070 # Error messages are multiline so not testing on full message
3071 # assertTupleEqual and assertListEqual delegate to this method
3072 self.assertMessages('assertSequenceEqual', ([], [None]),
3073 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
3074 r"\+ \[None\] : oops$"])
3075
3076 def testAssertSetEqual(self):
3077 self.assertMessages('assertSetEqual', (set(), set([None])),
3078 ["None$", "^oops$", "None$",
3079 "None : oops$"])
3080
3081 def testAssertIn(self):
3082 self.assertMessages('assertIn', (None, []),
3083 ['^None not found in \[\]$', "^oops$",
3084 '^None not found in \[\]$',
3085 '^None not found in \[\] : oops$'])
3086
3087 def testAssertNotIn(self):
3088 self.assertMessages('assertNotIn', (None, [None]),
3089 ['^None unexpectedly found in \[None\]$', "^oops$",
3090 '^None unexpectedly found in \[None\]$',
3091 '^None unexpectedly found in \[None\] : oops$'])
3092
3093 def testAssertDictEqual(self):
3094 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
3095 [r"\+ \{'key': 'value'\}$", "^oops$",
3096 "\+ \{'key': 'value'\}$",
3097 "\+ \{'key': 'value'\} : oops$"])
3098
3099 def testAssertDictContainsSubset(self):
3100 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
3101 ["^Missing: 'key'$", "^oops$",
3102 "^Missing: 'key'$",
3103 "^Missing: 'key' : oops$"])
3104
3105 def testAssertSameElements(self):
3106 self.assertMessages('assertSameElements', ([], [None]),
3107 [r"\[None\]$", "^oops$",
3108 r"\[None\]$",
3109 r"\[None\] : oops$"])
3110
3111 def testAssertMultiLineEqual(self):
3112 self.assertMessages('assertMultiLineEqual', ("", "foo"),
3113 [r"\+ foo$", "^oops$",
3114 r"\+ foo$",
3115 r"\+ foo : oops$"])
3116
3117 def testAssertLess(self):
3118 self.assertMessages('assertLess', (2, 1),
3119 ["^2 not less than 1$", "^oops$",
3120 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3121
3122 def testAssertLessEqual(self):
3123 self.assertMessages('assertLessEqual', (2, 1),
3124 ["^2 not less than or equal to 1$", "^oops$",
3125 "^2 not less than or equal to 1$",
3126 "^2 not less than or equal to 1 : oops$"])
3127
3128 def testAssertGreater(self):
3129 self.assertMessages('assertGreater', (1, 2),
3130 ["^1 not greater than 2$", "^oops$",
3131 "^1 not greater than 2$",
3132 "^1 not greater than 2 : oops$"])
3133
3134 def testAssertGreaterEqual(self):
3135 self.assertMessages('assertGreaterEqual', (1, 2),
3136 ["^1 not greater than or equal to 2$", "^oops$",
3137 "^1 not greater than or equal to 2$",
3138 "^1 not greater than or equal to 2 : oops$"])
3139
3140 def testAssertIsNone(self):
3141 self.assertMessages('assertIsNone', ('not None',),
3142 ["^'not None' is not None$", "^oops$",
3143 "^'not None' is not None$",
3144 "^'not None' is not None : oops$"])
3145
3146 def testAssertIsNotNone(self):
3147 self.assertMessages('assertIsNotNone', (None,),
3148 ["^unexpectedly None$", "^oops$",
3149 "^unexpectedly None$",
3150 "^unexpectedly None : oops$"])
3151
Michael Foordf2dfef12009-04-05 19:19:28 +00003152 def testAssertIs(self):
3153 self.assertMessages('assertIs', (None, 'foo'),
3154 ["^None is not 'foo'$", "^oops$",
3155 "^None is not 'foo'$",
3156 "^None is not 'foo' : oops$"])
3157
3158 def testAssertIsNot(self):
3159 self.assertMessages('assertIsNot', (None, None),
3160 ["^unexpectedly identical: None$", "^oops$",
3161 "^unexpectedly identical: None$",
3162 "^unexpectedly identical: None : oops$"])
3163
Michael Foord345b2fe2009-04-02 03:20:38 +00003164
Michael Foorde2fb98f2009-05-02 20:15:05 +00003165class TestCleanUp(TestCase):
3166
3167 def testCleanUp(self):
3168 class TestableTest(TestCase):
3169 def testNothing(self):
3170 pass
3171
3172 test = TestableTest('testNothing')
3173 self.assertEqual(test._cleanups, [])
3174
3175 cleanups = []
3176
3177 def cleanup1(*args, **kwargs):
3178 cleanups.append((1, args, kwargs))
3179
3180 def cleanup2(*args, **kwargs):
3181 cleanups.append((2, args, kwargs))
3182
3183 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
3184 test.addCleanup(cleanup2)
3185
3186 self.assertEqual(test._cleanups,
3187 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
3188 (cleanup2, (), {})])
3189
3190 result = test.doCleanups()
3191 self.assertTrue(result)
3192
3193 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
3194
3195 def testCleanUpWithErrors(self):
3196 class TestableTest(TestCase):
3197 def testNothing(self):
3198 pass
3199
3200 class MockResult(object):
3201 errors = []
3202 def addError(self, test, exc_info):
3203 self.errors.append((test, exc_info))
3204
3205 result = MockResult()
3206 test = TestableTest('testNothing')
Michael Foorda50af062009-05-21 22:57:02 +00003207 test._resultForDoCleanups = result
Michael Foorde2fb98f2009-05-02 20:15:05 +00003208
3209 exc1 = Exception('foo')
3210 exc2 = Exception('bar')
3211 def cleanup1():
3212 raise exc1
3213
3214 def cleanup2():
3215 raise exc2
3216
3217 test.addCleanup(cleanup1)
3218 test.addCleanup(cleanup2)
3219
3220 self.assertFalse(test.doCleanups())
3221
3222 (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
3223 self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
3224 self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
3225
3226 def testCleanupInRun(self):
3227 blowUp = False
3228 ordering = []
3229
3230 class TestableTest(TestCase):
3231 def setUp(self):
3232 ordering.append('setUp')
3233 if blowUp:
3234 raise Exception('foo')
3235
3236 def testNothing(self):
3237 ordering.append('test')
3238
3239 def tearDown(self):
3240 ordering.append('tearDown')
3241
3242 test = TestableTest('testNothing')
3243
3244 def cleanup1():
3245 ordering.append('cleanup1')
3246 def cleanup2():
3247 ordering.append('cleanup2')
3248 test.addCleanup(cleanup1)
3249 test.addCleanup(cleanup2)
3250
3251 def success(some_test):
3252 self.assertEqual(some_test, test)
3253 ordering.append('success')
3254
3255 result = unittest.TestResult()
3256 result.addSuccess = success
3257
3258 test.run(result)
3259 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
3260 'cleanup2', 'cleanup1', 'success'])
3261
3262 blowUp = True
3263 ordering = []
3264 test = TestableTest('testNothing')
3265 test.addCleanup(cleanup1)
3266 test.run(result)
3267 self.assertEqual(ordering, ['setUp', 'cleanup1'])
3268
3269
Michael Foord829f6b82009-05-02 11:43:06 +00003270class Test_TestProgram(TestCase):
3271
3272 # Horrible white box test
3273 def testNoExit(self):
3274 result = object()
3275 test = object()
3276
3277 class FakeRunner(object):
3278 def run(self, test):
3279 self.test = test
3280 return result
3281
3282 runner = FakeRunner()
3283
Michael Foord5d31e052009-05-11 17:59:43 +00003284 oldParseArgs = TestProgram.parseArgs
3285 def restoreParseArgs():
Michael Foord829f6b82009-05-02 11:43:06 +00003286 TestProgram.parseArgs = oldParseArgs
Michael Foord5d31e052009-05-11 17:59:43 +00003287 TestProgram.parseArgs = lambda *args: None
3288 self.addCleanup(restoreParseArgs)
3289
3290 def removeTest():
Michael Foord829f6b82009-05-02 11:43:06 +00003291 del TestProgram.test
Michael Foord5d31e052009-05-11 17:59:43 +00003292 TestProgram.test = test
3293 self.addCleanup(removeTest)
3294
3295 program = TestProgram(testRunner=runner, exit=False, verbosity=2)
3296
3297 self.assertEqual(program.result, result)
3298 self.assertEqual(runner.test, test)
3299 self.assertEqual(program.verbosity, 2)
Michael Foord829f6b82009-05-02 11:43:06 +00003300
3301
3302 class FooBar(unittest.TestCase):
3303 def testPass(self):
3304 assert True
3305 def testFail(self):
3306 assert False
3307
3308 class FooBarLoader(unittest.TestLoader):
3309 """Test loader that returns a suite containing FooBar."""
3310 def loadTestsFromModule(self, module):
3311 return self.suiteClass(
3312 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3313
3314
3315 def test_NonExit(self):
3316 program = unittest.main(exit=False,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003317 argv=["foobar"],
3318 testRunner=unittest.TextTestRunner(stream=StringIO()),
3319 testLoader=self.FooBarLoader())
Michael Foord829f6b82009-05-02 11:43:06 +00003320 self.assertTrue(hasattr(program, 'result'))
3321
3322
3323 def test_Exit(self):
3324 self.assertRaises(
3325 SystemExit,
3326 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003327 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003328 testRunner=unittest.TextTestRunner(stream=StringIO()),
3329 exit=True,
3330 testLoader=self.FooBarLoader())
3331
3332
3333 def test_ExitAsDefault(self):
3334 self.assertRaises(
3335 SystemExit,
3336 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003337 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003338 testRunner=unittest.TextTestRunner(stream=StringIO()),
3339 testLoader=self.FooBarLoader())
3340
3341
Michael Foord07ef4872009-05-02 22:43:34 +00003342class Test_TextTestRunner(TestCase):
3343 """Tests for TextTestRunner."""
3344
3345 def test_works_with_result_without_startTestRun_stopTestRun(self):
3346 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
3347 separator2 = ''
3348 def printErrors(self):
3349 pass
3350
3351 class Runner(unittest.TextTestRunner):
3352 def __init__(self):
3353 super(Runner, self).__init__(StringIO())
3354
3355 def _makeResult(self):
3356 return OldTextResult()
3357
3358 runner = Runner()
3359 runner.run(unittest.TestSuite())
3360
3361 def test_startTestRun_stopTestRun_called(self):
3362 class LoggingTextResult(LoggingResult):
3363 separator2 = ''
3364 def printErrors(self):
3365 pass
3366
3367 class LoggingRunner(unittest.TextTestRunner):
3368 def __init__(self, events):
3369 super(LoggingRunner, self).__init__(StringIO())
3370 self._events = events
3371
3372 def _makeResult(self):
3373 return LoggingTextResult(self._events)
3374
3375 events = []
3376 runner = LoggingRunner(events)
3377 runner.run(unittest.TestSuite())
3378 expected = ['startTestRun', 'stopTestRun']
3379 self.assertEqual(events, expected)
3380
3381
Jim Fultonfafd8742004-08-28 15:22:12 +00003382######################################################################
3383## Main
3384######################################################################
3385
3386def test_main():
Georg Brandl15c5ce92007-03-07 09:09:40 +00003387 test_support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003388 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Michael Foord829f6b82009-05-02 11:43:06 +00003389 Test_TestSkipping, Test_Assertions, TestLongMessage,
Michael Foorde2fb98f2009-05-02 20:15:05 +00003390 Test_TestProgram, TestCleanUp)
Jim Fultonfafd8742004-08-28 15:22:12 +00003391
Georg Brandl15c5ce92007-03-07 09:09:40 +00003392if __name__ == "__main__":
Tim Petersea5962f2007-03-12 18:07:52 +00003393 test_main()