blob: 85ebf46e749223180e45603f58c841b28e74b532 [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
Gregory P. Smith28399852009-03-31 16:54:10 +00009import re
Georg Brandl15c5ce92007-03-07 09:09:40 +000010from test import test_support
Jim Fultonfafd8742004-08-28 15:22:12 +000011import unittest
Georg Brandl15c5ce92007-03-07 09:09:40 +000012from unittest import TestCase
Christian Heimesc756d002007-11-27 21:34:01 +000013import types
Jim Fultonfafd8742004-08-28 15:22:12 +000014
Georg Brandl15c5ce92007-03-07 09:09:40 +000015### Support code
16################################################################
Jim Fultonfafd8742004-08-28 15:22:12 +000017
Georg Brandl15c5ce92007-03-07 09:09:40 +000018class LoggingResult(unittest.TestResult):
19 def __init__(self, log):
20 self._events = log
21 super(LoggingResult, self).__init__()
22
23 def startTest(self, test):
24 self._events.append('startTest')
25 super(LoggingResult, self).startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +000026
Georg Brandl15c5ce92007-03-07 09:09:40 +000027 def stopTest(self, test):
28 self._events.append('stopTest')
29 super(LoggingResult, self).stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +000030
Georg Brandl15c5ce92007-03-07 09:09:40 +000031 def addFailure(self, *args):
32 self._events.append('addFailure')
33 super(LoggingResult, self).addFailure(*args)
Tim Petersea5962f2007-03-12 18:07:52 +000034
Benjamin Peterson692428e2009-03-23 21:50:21 +000035 def addSuccess(self, *args):
36 self._events.append('addSuccess')
37 super(LoggingResult, self).addSuccess(*args)
38
Georg Brandl15c5ce92007-03-07 09:09:40 +000039 def addError(self, *args):
40 self._events.append('addError')
41 super(LoggingResult, self).addError(*args)
42
Benjamin Peterson692428e2009-03-23 21:50:21 +000043 def addSkip(self, *args):
44 self._events.append('addSkip')
45 super(LoggingResult, self).addSkip(*args)
46
47 def addExpectedFailure(self, *args):
48 self._events.append('addExpectedFailure')
49 super(LoggingResult, self).addExpectedFailure(*args)
50
51 def addUnexpectedSuccess(self, *args):
52 self._events.append('addUnexpectedSuccess')
53 super(LoggingResult, self).addUnexpectedSuccess(*args)
54
55
Georg Brandl15c5ce92007-03-07 09:09:40 +000056class TestEquality(object):
Tim Petersea5962f2007-03-12 18:07:52 +000057 # Check for a valid __eq__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000058 def test_eq(self):
59 for obj_1, obj_2 in self.eq_pairs:
60 self.assertEqual(obj_1, obj_2)
61 self.assertEqual(obj_2, obj_1)
Tim Petersea5962f2007-03-12 18:07:52 +000062
63 # Check for a valid __ne__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000064 def test_ne(self):
65 for obj_1, obj_2 in self.ne_pairs:
66 self.failIfEqual(obj_1, obj_2)
67 self.failIfEqual(obj_2, obj_1)
Tim Petersea5962f2007-03-12 18:07:52 +000068
Georg Brandl15c5ce92007-03-07 09:09:40 +000069class TestHashing(object):
Tim Petersea5962f2007-03-12 18:07:52 +000070 # Check for a valid __hash__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000071 def test_hash(self):
72 for obj_1, obj_2 in self.eq_pairs:
73 try:
Gregory P. Smith28399852009-03-31 16:54:10 +000074 if not hash(obj_1) == hash(obj_2):
75 self.fail("%r and %r do not hash equal" % (obj_1, obj_2))
Georg Brandl15c5ce92007-03-07 09:09:40 +000076 except KeyboardInterrupt:
77 raise
Georg Brandl15c5ce92007-03-07 09:09:40 +000078 except Exception, e:
Gregory P. Smith28399852009-03-31 16:54:10 +000079 self.fail("Problem hashing %r and %r: %s" % (obj_1, obj_2, e))
Tim Petersea5962f2007-03-12 18:07:52 +000080
Georg Brandl15c5ce92007-03-07 09:09:40 +000081 for obj_1, obj_2 in self.ne_pairs:
82 try:
Gregory P. Smith28399852009-03-31 16:54:10 +000083 if hash(obj_1) == hash(obj_2):
84 self.fail("%s and %s hash equal, but shouldn't" %
85 (obj_1, obj_2))
Georg Brandl15c5ce92007-03-07 09:09:40 +000086 except KeyboardInterrupt:
87 raise
Georg Brandl15c5ce92007-03-07 09:09:40 +000088 except Exception, e:
89 self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e))
Tim Petersea5962f2007-03-12 18:07:52 +000090
Georg Brandl15c5ce92007-03-07 09:09:40 +000091
Benjamin Peterson692428e2009-03-23 21:50:21 +000092# List subclass we can add attributes to.
93class MyClassSuite(list):
94
95 def __init__(self, tests, klass):
96 super(MyClassSuite, self).__init__(tests)
97
98
Georg Brandl15c5ce92007-03-07 09:09:40 +000099################################################################
100### /Support code
101
102class Test_TestLoader(TestCase):
103
104 ### Tests for TestLoader.loadTestsFromTestCase
105 ################################################################
106
107 # "Return a suite of all tests cases contained in the TestCase-derived
108 # class testCaseClass"
109 def test_loadTestsFromTestCase(self):
110 class Foo(unittest.TestCase):
111 def test_1(self): pass
112 def test_2(self): pass
113 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000114
Georg Brandl15c5ce92007-03-07 09:09:40 +0000115 tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +0000116
Georg Brandl15c5ce92007-03-07 09:09:40 +0000117 loader = unittest.TestLoader()
118 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +0000119
Georg Brandl15c5ce92007-03-07 09:09:40 +0000120 # "Return a suite of all tests cases contained in the TestCase-derived
121 # class testCaseClass"
122 #
Tim Petersea5962f2007-03-12 18:07:52 +0000123 # Make sure it does the right thing even if no tests were found
Georg Brandl15c5ce92007-03-07 09:09:40 +0000124 def test_loadTestsFromTestCase__no_matches(self):
125 class Foo(unittest.TestCase):
126 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000127
Georg Brandl15c5ce92007-03-07 09:09:40 +0000128 empty_suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +0000129
Georg Brandl15c5ce92007-03-07 09:09:40 +0000130 loader = unittest.TestLoader()
131 self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite)
Tim Petersea5962f2007-03-12 18:07:52 +0000132
Georg Brandl15c5ce92007-03-07 09:09:40 +0000133 # "Return a suite of all tests cases contained in the TestCase-derived
134 # class testCaseClass"
135 #
136 # What happens if loadTestsFromTestCase() is given an object
137 # that isn't a subclass of TestCase? Specifically, what happens
138 # if testCaseClass is a subclass of TestSuite?
139 #
140 # This is checked for specifically in the code, so we better add a
141 # test for it.
142 def test_loadTestsFromTestCase__TestSuite_subclass(self):
143 class NotATestCase(unittest.TestSuite):
144 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000145
Georg Brandl15c5ce92007-03-07 09:09:40 +0000146 loader = unittest.TestLoader()
147 try:
148 loader.loadTestsFromTestCase(NotATestCase)
149 except TypeError:
150 pass
151 else:
152 self.fail('Should raise TypeError')
Tim Petersea5962f2007-03-12 18:07:52 +0000153
Georg Brandl15c5ce92007-03-07 09:09:40 +0000154 # "Return a suite of all tests cases contained in the TestCase-derived
155 # class testCaseClass"
156 #
157 # Make sure loadTestsFromTestCase() picks up the default test method
158 # name (as specified by TestCase), even though the method name does
159 # not match the default TestLoader.testMethodPrefix string
160 def test_loadTestsFromTestCase__default_method_name(self):
161 class Foo(unittest.TestCase):
162 def runTest(self):
163 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000164
Georg Brandl15c5ce92007-03-07 09:09:40 +0000165 loader = unittest.TestLoader()
166 # This has to be false for the test to succeed
167 self.failIf('runTest'.startswith(loader.testMethodPrefix))
Tim Petersea5962f2007-03-12 18:07:52 +0000168
Georg Brandl15c5ce92007-03-07 09:09:40 +0000169 suite = loader.loadTestsFromTestCase(Foo)
170 self.failUnless(isinstance(suite, loader.suiteClass))
171 self.assertEqual(list(suite), [Foo('runTest')])
172
173 ################################################################
174 ### /Tests for TestLoader.loadTestsFromTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000175
Georg Brandl15c5ce92007-03-07 09:09:40 +0000176 ### Tests for TestLoader.loadTestsFromModule
177 ################################################################
178
179 # "This method searches `module` for classes derived from TestCase"
180 def test_loadTestsFromModule__TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000181 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000182 class MyTestCase(unittest.TestCase):
183 def test(self):
184 pass
185 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000186
Georg Brandl15c5ce92007-03-07 09:09:40 +0000187 loader = unittest.TestLoader()
188 suite = loader.loadTestsFromModule(m)
189 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000190
Georg Brandl15c5ce92007-03-07 09:09:40 +0000191 expected = [loader.suiteClass([MyTestCase('test')])]
192 self.assertEqual(list(suite), expected)
Tim Petersea5962f2007-03-12 18:07:52 +0000193
Georg Brandl15c5ce92007-03-07 09:09:40 +0000194 # "This method searches `module` for classes derived from TestCase"
Tim Petersea5962f2007-03-12 18:07:52 +0000195 #
Georg Brandl15c5ce92007-03-07 09:09:40 +0000196 # What happens if no tests are found (no TestCase instances)?
197 def test_loadTestsFromModule__no_TestCase_instances(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000198 m = types.ModuleType('m')
Tim Petersea5962f2007-03-12 18:07:52 +0000199
Georg Brandl15c5ce92007-03-07 09:09:40 +0000200 loader = unittest.TestLoader()
201 suite = loader.loadTestsFromModule(m)
202 self.failUnless(isinstance(suite, loader.suiteClass))
203 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000204
Georg Brandl15c5ce92007-03-07 09:09:40 +0000205 # "This method searches `module` for classes derived from TestCase"
206 #
Tim Petersea5962f2007-03-12 18:07:52 +0000207 # What happens if no tests are found (TestCases instances, but no tests)?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000208 def test_loadTestsFromModule__no_TestCase_tests(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000209 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000210 class MyTestCase(unittest.TestCase):
211 pass
212 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000213
Georg Brandl15c5ce92007-03-07 09:09:40 +0000214 loader = unittest.TestLoader()
215 suite = loader.loadTestsFromModule(m)
216 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000217
Georg Brandl15c5ce92007-03-07 09:09:40 +0000218 self.assertEqual(list(suite), [loader.suiteClass()])
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"s
221 #
222 # What happens if loadTestsFromModule() is given something other
223 # than a module?
224 #
225 # XXX Currently, it succeeds anyway. This flexibility
226 # should either be documented or loadTestsFromModule() should
227 # raise a TypeError
228 #
229 # XXX Certain people are using this behaviour. We'll add a test for it
230 def test_loadTestsFromModule__not_a_module(self):
231 class MyTestCase(unittest.TestCase):
232 def test(self):
233 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000234
Georg Brandl15c5ce92007-03-07 09:09:40 +0000235 class NotAModule(object):
236 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000237
Georg Brandl15c5ce92007-03-07 09:09:40 +0000238 loader = unittest.TestLoader()
239 suite = loader.loadTestsFromModule(NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000240
Georg Brandl15c5ce92007-03-07 09:09:40 +0000241 reference = [unittest.TestSuite([MyTestCase('test')])]
242 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000243
Georg Brandl15c5ce92007-03-07 09:09:40 +0000244 ################################################################
245 ### /Tests for TestLoader.loadTestsFromModule()
Tim Petersea5962f2007-03-12 18:07:52 +0000246
Georg Brandl15c5ce92007-03-07 09:09:40 +0000247 ### Tests for TestLoader.loadTestsFromName()
248 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000249
Georg Brandl15c5ce92007-03-07 09:09:40 +0000250 # "The specifier name is a ``dotted name'' that may resolve either to
251 # a module, a test case class, a TestSuite instance, a test method
252 # within a test case class, or a callable object which returns a
253 # TestCase or TestSuite instance."
254 #
255 # Is ValueError raised in response to an empty name?
256 def test_loadTestsFromName__empty_name(self):
257 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000258
Georg Brandl15c5ce92007-03-07 09:09:40 +0000259 try:
260 loader.loadTestsFromName('')
261 except ValueError, e:
262 self.assertEqual(str(e), "Empty module name")
263 else:
264 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000265
Georg Brandl15c5ce92007-03-07 09:09:40 +0000266 # "The specifier name is a ``dotted name'' that may resolve either to
267 # a module, a test case class, a TestSuite instance, a test method
268 # within a test case class, or a callable object which returns a
269 # TestCase or TestSuite instance."
270 #
Tim Petersea5962f2007-03-12 18:07:52 +0000271 # What happens when the name contains invalid characters?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000272 def test_loadTestsFromName__malformed_name(self):
273 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000274
Georg Brandl15c5ce92007-03-07 09:09:40 +0000275 # XXX Should this raise ValueError or ImportError?
276 try:
277 loader.loadTestsFromName('abc () //')
278 except ValueError:
279 pass
280 except ImportError:
281 pass
282 else:
283 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000284
Georg Brandl15c5ce92007-03-07 09:09:40 +0000285 # "The specifier name is a ``dotted name'' that may resolve ... to a
286 # module"
287 #
Tim Petersea5962f2007-03-12 18:07:52 +0000288 # What happens when a module by that name can't be found?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000289 def test_loadTestsFromName__unknown_module_name(self):
290 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000291
Georg Brandl15c5ce92007-03-07 09:09:40 +0000292 try:
293 loader.loadTestsFromName('sdasfasfasdf')
294 except ImportError, e:
295 self.assertEqual(str(e), "No module named sdasfasfasdf")
296 else:
297 self.fail("TestLoader.loadTestsFromName failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000298
Georg Brandl15c5ce92007-03-07 09:09:40 +0000299 # "The specifier name is a ``dotted name'' that may resolve either to
300 # a module, a test case class, a TestSuite instance, a test method
301 # within a test case class, or a callable object which returns a
302 # TestCase or TestSuite instance."
303 #
Tim Petersea5962f2007-03-12 18:07:52 +0000304 # What happens when the module is found, but the attribute can't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000305 def test_loadTestsFromName__unknown_attr_name(self):
306 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000307
Georg Brandl15c5ce92007-03-07 09:09:40 +0000308 try:
309 loader.loadTestsFromName('unittest.sdasfasfasdf')
310 except AttributeError, e:
311 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
312 else:
313 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000314
Georg Brandl15c5ce92007-03-07 09:09:40 +0000315 # "The specifier name is a ``dotted name'' that may resolve either to
316 # a module, a test case class, a TestSuite instance, a test method
317 # within a test case class, or a callable object which returns a
318 # TestCase or TestSuite instance."
319 #
320 # What happens when we provide the module, but the attribute can't be
321 # found?
322 def test_loadTestsFromName__relative_unknown_name(self):
323 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000324
Georg Brandl15c5ce92007-03-07 09:09:40 +0000325 try:
326 loader.loadTestsFromName('sdasfasfasdf', unittest)
327 except AttributeError, e:
328 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
329 else:
330 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000331
Georg Brandl15c5ce92007-03-07 09:09:40 +0000332 # "The specifier name is a ``dotted name'' that may resolve either to
333 # a module, a test case class, a TestSuite instance, a test method
334 # within a test case class, or a callable object which returns a
335 # TestCase or TestSuite instance."
336 # ...
337 # "The method optionally resolves name relative to the given module"
338 #
339 # Does loadTestsFromName raise ValueError when passed an empty
340 # name relative to a provided module?
341 #
342 # XXX Should probably raise a ValueError instead of an AttributeError
343 def test_loadTestsFromName__relative_empty_name(self):
344 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000345
Georg Brandl15c5ce92007-03-07 09:09:40 +0000346 try:
347 loader.loadTestsFromName('', unittest)
348 except AttributeError, e:
349 pass
350 else:
351 self.fail("Failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000352
Georg Brandl15c5ce92007-03-07 09:09:40 +0000353 # "The specifier name is a ``dotted name'' that may resolve either to
354 # a module, a test case class, a TestSuite instance, a test method
355 # within a test case class, or a callable object which returns a
356 # TestCase or TestSuite instance."
357 # ...
358 # "The method optionally resolves name relative to the given module"
359 #
360 # What happens when an impossible name is given, relative to the provided
361 # `module`?
362 def test_loadTestsFromName__relative_malformed_name(self):
363 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000364
Georg Brandl15c5ce92007-03-07 09:09:40 +0000365 # XXX Should this raise AttributeError or ValueError?
366 try:
367 loader.loadTestsFromName('abc () //', unittest)
368 except ValueError:
369 pass
370 except AttributeError:
371 pass
372 else:
373 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
374
375 # "The method optionally resolves name relative to the given module"
376 #
377 # Does loadTestsFromName raise TypeError when the `module` argument
378 # isn't a module object?
379 #
380 # XXX Accepts the not-a-module object, ignorning the object's type
381 # This should raise an exception or the method name should be changed
382 #
383 # XXX Some people are relying on this, so keep it for now
384 def test_loadTestsFromName__relative_not_a_module(self):
385 class MyTestCase(unittest.TestCase):
386 def test(self):
387 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000388
Georg Brandl15c5ce92007-03-07 09:09:40 +0000389 class NotAModule(object):
390 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000391
Georg Brandl15c5ce92007-03-07 09:09:40 +0000392 loader = unittest.TestLoader()
393 suite = loader.loadTestsFromName('test_2', NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000394
Georg Brandl15c5ce92007-03-07 09:09:40 +0000395 reference = [MyTestCase('test')]
396 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000397
Georg Brandl15c5ce92007-03-07 09:09:40 +0000398 # "The specifier name is a ``dotted name'' that may resolve either to
399 # a module, a test case class, a TestSuite instance, a test method
400 # within a test case class, or a callable object which returns a
401 # TestCase or TestSuite instance."
402 #
403 # Does it raise an exception if the name resolves to an invalid
404 # object?
405 def test_loadTestsFromName__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000406 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000407 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000408
Georg Brandl15c5ce92007-03-07 09:09:40 +0000409 loader = unittest.TestLoader()
410 try:
411 loader.loadTestsFromName('testcase_1', m)
412 except TypeError:
413 pass
414 else:
415 self.fail("Should have raised TypeError")
416
417 # "The specifier name is a ``dotted name'' that may
418 # resolve either to ... a test case class"
419 def test_loadTestsFromName__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000420 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000421 class MyTestCase(unittest.TestCase):
422 def test(self):
423 pass
424 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000425
Georg Brandl15c5ce92007-03-07 09:09:40 +0000426 loader = unittest.TestLoader()
427 suite = loader.loadTestsFromName('testcase_1', m)
428 self.failUnless(isinstance(suite, loader.suiteClass))
429 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000430
Georg Brandl15c5ce92007-03-07 09:09:40 +0000431 # "The specifier name is a ``dotted name'' that may resolve either to
432 # a module, a test case class, a TestSuite instance, a test method
433 # within a test case class, or a callable object which returns a
434 # TestCase or TestSuite instance."
435 def test_loadTestsFromName__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000436 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000437 class MyTestCase(unittest.TestCase):
438 def test(self):
439 pass
440 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000441
Georg Brandl15c5ce92007-03-07 09:09:40 +0000442 loader = unittest.TestLoader()
443 suite = loader.loadTestsFromName('testsuite', m)
444 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000445
Georg Brandl15c5ce92007-03-07 09:09:40 +0000446 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000447
Georg Brandl15c5ce92007-03-07 09:09:40 +0000448 # "The specifier name is a ``dotted name'' that may resolve ... to
449 # ... a test method within a test case class"
450 def test_loadTestsFromName__relative_testmethod(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.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000456
Georg Brandl15c5ce92007-03-07 09:09:40 +0000457 loader = unittest.TestLoader()
458 suite = loader.loadTestsFromName('testcase_1.test', 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 either to
464 # a module, a test case class, a TestSuite instance, a test method
465 # within a test case class, or a callable object which returns a
466 # TestCase or TestSuite instance."
467 #
468 # Does loadTestsFromName() raise the proper exception when trying to
469 # resolve "a test method within a test case class" that doesn't exist
470 # for the given name (relative to a provided module)?
471 def test_loadTestsFromName__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000472 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000473 class MyTestCase(unittest.TestCase):
474 def test(self):
475 pass
476 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000477
Georg Brandl15c5ce92007-03-07 09:09:40 +0000478 loader = unittest.TestLoader()
479 try:
480 loader.loadTestsFromName('testcase_1.testfoo', m)
481 except AttributeError, e:
482 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
483 else:
484 self.fail("Failed to raise AttributeError")
485
486 # "The specifier name is a ``dotted name'' that may resolve ... to
487 # ... a callable object which returns a ... TestSuite instance"
488 def test_loadTestsFromName__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000489 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000490 testcase_1 = unittest.FunctionTestCase(lambda: None)
491 testcase_2 = unittest.FunctionTestCase(lambda: None)
492 def return_TestSuite():
493 return unittest.TestSuite([testcase_1, testcase_2])
494 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000495
Georg Brandl15c5ce92007-03-07 09:09:40 +0000496 loader = unittest.TestLoader()
497 suite = loader.loadTestsFromName('return_TestSuite', m)
498 self.failUnless(isinstance(suite, loader.suiteClass))
499 self.assertEqual(list(suite), [testcase_1, testcase_2])
Tim Petersea5962f2007-03-12 18:07:52 +0000500
Georg Brandl15c5ce92007-03-07 09:09:40 +0000501 # "The specifier name is a ``dotted name'' that may resolve ... to
502 # ... a callable object which returns a TestCase ... instance"
503 def test_loadTestsFromName__callable__TestCase_instance(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 def return_TestCase():
507 return testcase_1
508 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000509
Georg Brandl15c5ce92007-03-07 09:09:40 +0000510 loader = unittest.TestLoader()
511 suite = loader.loadTestsFromName('return_TestCase', m)
512 self.failUnless(isinstance(suite, loader.suiteClass))
513 self.assertEqual(list(suite), [testcase_1])
Tim Petersea5962f2007-03-12 18:07:52 +0000514
Georg Brandl15c5ce92007-03-07 09:09:40 +0000515 # "The specifier name is a ``dotted name'' that may resolve ... to
516 # ... a callable object which returns a TestCase or TestSuite instance"
517 #
518 # What happens if the callable returns something else?
519 def test_loadTestsFromName__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000520 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000521 def return_wrong():
522 return 6
523 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000524
Georg Brandl15c5ce92007-03-07 09:09:40 +0000525 loader = unittest.TestLoader()
526 try:
527 suite = loader.loadTestsFromName('return_wrong', m)
528 except TypeError:
529 pass
530 else:
531 self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000532
Georg Brandl15c5ce92007-03-07 09:09:40 +0000533 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +0000534 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +0000535 def test_loadTestsFromName__module_not_loaded(self):
536 # We're going to try to load this module as a side-effect, so it
537 # better not be loaded before we try.
538 #
539 # Why pick audioop? Google shows it isn't used very often, so there's
540 # a good chance that it won't be imported when this test is run
541 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +0000542
Georg Brandl15c5ce92007-03-07 09:09:40 +0000543 import sys
544 if module_name in sys.modules:
545 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000546
Georg Brandl15c5ce92007-03-07 09:09:40 +0000547 loader = unittest.TestLoader()
548 try:
549 suite = loader.loadTestsFromName(module_name)
550
551 self.failUnless(isinstance(suite, loader.suiteClass))
552 self.assertEqual(list(suite), [])
553
554 # audioop should now be loaded, thanks to loadTestsFromName()
555 self.failUnless(module_name in sys.modules)
556 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000557 if module_name in sys.modules:
558 del sys.modules[module_name]
Georg Brandl15c5ce92007-03-07 09:09:40 +0000559
560 ################################################################
561 ### Tests for TestLoader.loadTestsFromName()
562
563 ### Tests for TestLoader.loadTestsFromNames()
564 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000565
Georg Brandl15c5ce92007-03-07 09:09:40 +0000566 # "Similar to loadTestsFromName(), but takes a sequence of names rather
567 # than a single name."
568 #
569 # What happens if that sequence of names is empty?
570 def test_loadTestsFromNames__empty_name_list(self):
571 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000572
Georg Brandl15c5ce92007-03-07 09:09:40 +0000573 suite = loader.loadTestsFromNames([])
574 self.failUnless(isinstance(suite, loader.suiteClass))
575 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000576
Georg Brandl15c5ce92007-03-07 09:09:40 +0000577 # "Similar to loadTestsFromName(), but takes a sequence of names rather
578 # than a single name."
579 # ...
580 # "The method optionally resolves name relative to the given module"
581 #
582 # What happens if that sequence of names is empty?
583 #
584 # XXX Should this raise a ValueError or just return an empty TestSuite?
585 def test_loadTestsFromNames__relative_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([], unittest)
589 self.failUnless(isinstance(suite, loader.suiteClass))
590 self.assertEqual(list(suite), [])
591
592 # "The specifier name is a ``dotted name'' that may resolve either to
593 # a module, a test case class, a TestSuite instance, a test method
594 # within a test case class, or a callable object which returns a
595 # TestCase or TestSuite instance."
596 #
597 # Is ValueError raised in response to an empty name?
598 def test_loadTestsFromNames__empty_name(self):
599 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000600
Georg Brandl15c5ce92007-03-07 09:09:40 +0000601 try:
602 loader.loadTestsFromNames([''])
603 except ValueError, e:
604 self.assertEqual(str(e), "Empty module name")
605 else:
606 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000607
Georg Brandl15c5ce92007-03-07 09:09:40 +0000608 # "The specifier name is a ``dotted name'' that may resolve either to
609 # a module, a test case class, a TestSuite instance, a test method
610 # within a test case class, or a callable object which returns a
611 # TestCase or TestSuite instance."
612 #
Tim Petersea5962f2007-03-12 18:07:52 +0000613 # What happens when presented with an impossible module name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000614 def test_loadTestsFromNames__malformed_name(self):
615 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000616
Georg Brandl15c5ce92007-03-07 09:09:40 +0000617 # XXX Should this raise ValueError or ImportError?
618 try:
619 loader.loadTestsFromNames(['abc () //'])
620 except ValueError:
621 pass
622 except ImportError:
623 pass
624 else:
625 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000626
Georg Brandl15c5ce92007-03-07 09:09:40 +0000627 # "The specifier name is a ``dotted name'' that may resolve either to
628 # a module, a test case class, a TestSuite instance, a test method
629 # within a test case class, or a callable object which returns a
630 # TestCase or TestSuite instance."
631 #
Tim Petersea5962f2007-03-12 18:07:52 +0000632 # What happens when no module can be found for the given name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000633 def test_loadTestsFromNames__unknown_module_name(self):
634 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000635
Georg Brandl15c5ce92007-03-07 09:09:40 +0000636 try:
637 loader.loadTestsFromNames(['sdasfasfasdf'])
638 except ImportError, e:
639 self.assertEqual(str(e), "No module named sdasfasfasdf")
640 else:
641 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000642
Georg Brandl15c5ce92007-03-07 09:09:40 +0000643 # "The specifier name is a ``dotted name'' that may resolve either to
644 # a module, a test case class, a TestSuite instance, a test method
645 # within a test case class, or a callable object which returns a
646 # TestCase or TestSuite instance."
647 #
Tim Petersea5962f2007-03-12 18:07:52 +0000648 # What happens when the module can be found, but not the attribute?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000649 def test_loadTestsFromNames__unknown_attr_name(self):
650 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000651
Georg Brandl15c5ce92007-03-07 09:09:40 +0000652 try:
653 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
654 except AttributeError, e:
655 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
656 else:
657 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000658
Georg Brandl15c5ce92007-03-07 09:09:40 +0000659 # "The specifier name is a ``dotted name'' that may resolve either to
660 # a module, a test case class, a TestSuite instance, a test method
661 # within a test case class, or a callable object which returns a
662 # TestCase or TestSuite instance."
663 # ...
664 # "The method optionally resolves name relative to the given module"
665 #
666 # What happens when given an unknown attribute on a specified `module`
667 # argument?
668 def test_loadTestsFromNames__unknown_name_relative_1(self):
669 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000670
Georg Brandl15c5ce92007-03-07 09:09:40 +0000671 try:
672 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
673 except AttributeError, e:
674 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
675 else:
676 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000677
Georg Brandl15c5ce92007-03-07 09:09:40 +0000678 # "The specifier name is a ``dotted name'' that may resolve either to
679 # a module, a test case class, a TestSuite instance, a test method
680 # within a test case class, or a callable object which returns a
681 # TestCase or TestSuite instance."
682 # ...
683 # "The method optionally resolves name relative to the given module"
684 #
685 # Do unknown attributes (relative to a provided module) still raise an
Tim Petersea5962f2007-03-12 18:07:52 +0000686 # exception even in the presence of valid attribute names?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000687 def test_loadTestsFromNames__unknown_name_relative_2(self):
688 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000689
Georg Brandl15c5ce92007-03-07 09:09:40 +0000690 try:
691 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
692 except AttributeError, e:
693 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
694 else:
695 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
696
697 # "The specifier name is a ``dotted name'' that may resolve either to
698 # a module, a test case class, a TestSuite instance, a test method
699 # within a test case class, or a callable object which returns a
700 # TestCase or TestSuite instance."
701 # ...
702 # "The method optionally resolves name relative to the given module"
703 #
704 # What happens when faced with the empty string?
705 #
706 # XXX This currently raises AttributeError, though ValueError is probably
707 # more appropriate
708 def test_loadTestsFromNames__relative_empty_name(self):
709 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000710
Georg Brandl15c5ce92007-03-07 09:09:40 +0000711 try:
712 loader.loadTestsFromNames([''], unittest)
713 except AttributeError:
714 pass
715 else:
716 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000717
Georg Brandl15c5ce92007-03-07 09:09:40 +0000718 # "The specifier name is a ``dotted name'' that may resolve either to
719 # a module, a test case class, a TestSuite instance, a test method
720 # within a test case class, or a callable object which returns a
721 # TestCase or TestSuite instance."
722 # ...
723 # "The method optionally resolves name relative to the given module"
724 #
Tim Petersea5962f2007-03-12 18:07:52 +0000725 # What happens when presented with an impossible attribute name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000726 def test_loadTestsFromNames__relative_malformed_name(self):
727 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000728
Georg Brandl15c5ce92007-03-07 09:09:40 +0000729 # XXX Should this raise AttributeError or ValueError?
730 try:
731 loader.loadTestsFromNames(['abc () //'], unittest)
732 except AttributeError:
733 pass
734 except ValueError:
735 pass
736 else:
737 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
738
739 # "The method optionally resolves name relative to the given module"
740 #
741 # Does loadTestsFromNames() make sure the provided `module` is in fact
742 # a module?
743 #
744 # XXX This validation is currently not done. This flexibility should
745 # either be documented or a TypeError should be raised.
746 def test_loadTestsFromNames__relative_not_a_module(self):
747 class MyTestCase(unittest.TestCase):
748 def test(self):
749 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000750
Georg Brandl15c5ce92007-03-07 09:09:40 +0000751 class NotAModule(object):
752 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000753
Georg Brandl15c5ce92007-03-07 09:09:40 +0000754 loader = unittest.TestLoader()
755 suite = loader.loadTestsFromNames(['test_2'], NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000756
Georg Brandl15c5ce92007-03-07 09:09:40 +0000757 reference = [unittest.TestSuite([MyTestCase('test')])]
758 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000759
Georg Brandl15c5ce92007-03-07 09:09:40 +0000760 # "The specifier name is a ``dotted name'' that may resolve either to
761 # a module, a test case class, a TestSuite instance, a test method
762 # within a test case class, or a callable object which returns a
763 # TestCase or TestSuite instance."
764 #
765 # Does it raise an exception if the name resolves to an invalid
766 # object?
767 def test_loadTestsFromNames__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000768 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000769 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000770
Georg Brandl15c5ce92007-03-07 09:09:40 +0000771 loader = unittest.TestLoader()
772 try:
773 loader.loadTestsFromNames(['testcase_1'], m)
774 except TypeError:
775 pass
776 else:
777 self.fail("Should have raised TypeError")
778
779 # "The specifier name is a ``dotted name'' that may resolve ... to
780 # ... a test case class"
781 def test_loadTestsFromNames__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000782 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000783 class MyTestCase(unittest.TestCase):
784 def test(self):
785 pass
786 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000787
Georg Brandl15c5ce92007-03-07 09:09:40 +0000788 loader = unittest.TestLoader()
789 suite = loader.loadTestsFromNames(['testcase_1'], m)
790 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000791
Georg Brandl15c5ce92007-03-07 09:09:40 +0000792 expected = loader.suiteClass([MyTestCase('test')])
793 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000794
Georg Brandl15c5ce92007-03-07 09:09:40 +0000795 # "The specifier name is a ``dotted name'' that may resolve ... to
796 # ... a TestSuite instance"
797 def test_loadTestsFromNames__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000798 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000799 class MyTestCase(unittest.TestCase):
800 def test(self):
801 pass
802 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000803
Georg Brandl15c5ce92007-03-07 09:09:40 +0000804 loader = unittest.TestLoader()
805 suite = loader.loadTestsFromNames(['testsuite'], m)
806 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000807
Georg Brandl15c5ce92007-03-07 09:09:40 +0000808 self.assertEqual(list(suite), [m.testsuite])
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 ... a
811 # test method within a test case class"
812 def test_loadTestsFromNames__relative_testmethod(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.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000818
Georg Brandl15c5ce92007-03-07 09:09:40 +0000819 loader = unittest.TestLoader()
820 suite = loader.loadTestsFromNames(['testcase_1.test'], m)
821 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000822
Georg Brandl15c5ce92007-03-07 09:09:40 +0000823 ref_suite = unittest.TestSuite([MyTestCase('test')])
824 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000825
Georg Brandl15c5ce92007-03-07 09:09:40 +0000826 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
827 # test method within a test case class"
828 #
829 # Does the method gracefully handle names that initially look like they
Tim Petersea5962f2007-03-12 18:07:52 +0000830 # resolve to "a test method within a test case class" but don't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000831 def test_loadTestsFromNames__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000832 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000833 class MyTestCase(unittest.TestCase):
834 def test(self):
835 pass
836 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000837
Georg Brandl15c5ce92007-03-07 09:09:40 +0000838 loader = unittest.TestLoader()
839 try:
840 loader.loadTestsFromNames(['testcase_1.testfoo'], m)
841 except AttributeError, e:
842 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
843 else:
844 self.fail("Failed to raise AttributeError")
845
846 # "The specifier name is a ``dotted name'' that may resolve ... to
847 # ... a callable object which returns a ... TestSuite instance"
848 def test_loadTestsFromNames__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000849 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000850 testcase_1 = unittest.FunctionTestCase(lambda: None)
851 testcase_2 = unittest.FunctionTestCase(lambda: None)
852 def return_TestSuite():
853 return unittest.TestSuite([testcase_1, testcase_2])
854 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000855
Georg Brandl15c5ce92007-03-07 09:09:40 +0000856 loader = unittest.TestLoader()
857 suite = loader.loadTestsFromNames(['return_TestSuite'], m)
858 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000859
Georg Brandl15c5ce92007-03-07 09:09:40 +0000860 expected = unittest.TestSuite([testcase_1, testcase_2])
861 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000862
Georg Brandl15c5ce92007-03-07 09:09:40 +0000863 # "The specifier name is a ``dotted name'' that may resolve ... to
864 # ... a callable object which returns a TestCase ... instance"
865 def test_loadTestsFromNames__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000866 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000867 testcase_1 = unittest.FunctionTestCase(lambda: None)
868 def return_TestCase():
869 return testcase_1
870 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000871
Georg Brandl15c5ce92007-03-07 09:09:40 +0000872 loader = unittest.TestLoader()
873 suite = loader.loadTestsFromNames(['return_TestCase'], m)
874 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000875
Georg Brandl15c5ce92007-03-07 09:09:40 +0000876 ref_suite = unittest.TestSuite([testcase_1])
877 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000878
Georg Brandl15c5ce92007-03-07 09:09:40 +0000879 # "The specifier name is a ``dotted name'' that may resolve ... to
880 # ... a callable object which returns a TestCase or TestSuite instance"
881 #
Tim Petersea5962f2007-03-12 18:07:52 +0000882 # Are staticmethods handled correctly?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000883 def test_loadTestsFromNames__callable__call_staticmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000884 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000885 class Test1(unittest.TestCase):
886 def test(self):
887 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000888
Georg Brandl15c5ce92007-03-07 09:09:40 +0000889 testcase_1 = Test1('test')
890 class Foo(unittest.TestCase):
891 @staticmethod
892 def foo():
893 return testcase_1
894 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +0000895
Georg Brandl15c5ce92007-03-07 09:09:40 +0000896 loader = unittest.TestLoader()
897 suite = loader.loadTestsFromNames(['Foo.foo'], m)
898 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000899
Georg Brandl15c5ce92007-03-07 09:09:40 +0000900 ref_suite = unittest.TestSuite([testcase_1])
901 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000902
Georg Brandl15c5ce92007-03-07 09:09:40 +0000903 # "The specifier name is a ``dotted name'' that may resolve ... to
904 # ... a callable object which returns a TestCase or TestSuite instance"
905 #
906 # What happens when the callable returns something else?
907 def test_loadTestsFromNames__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000908 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000909 def return_wrong():
910 return 6
911 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000912
Georg Brandl15c5ce92007-03-07 09:09:40 +0000913 loader = unittest.TestLoader()
914 try:
915 suite = loader.loadTestsFromNames(['return_wrong'], m)
916 except TypeError:
917 pass
918 else:
919 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000920
Georg Brandl15c5ce92007-03-07 09:09:40 +0000921 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +0000922 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +0000923 def test_loadTestsFromNames__module_not_loaded(self):
924 # We're going to try to load this module as a side-effect, so it
925 # better not be loaded before we try.
926 #
927 # Why pick audioop? Google shows it isn't used very often, so there's
928 # a good chance that it won't be imported when this test is run
929 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +0000930
Georg Brandl15c5ce92007-03-07 09:09:40 +0000931 import sys
932 if module_name in sys.modules:
933 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000934
Georg Brandl15c5ce92007-03-07 09:09:40 +0000935 loader = unittest.TestLoader()
936 try:
937 suite = loader.loadTestsFromNames([module_name])
938
939 self.failUnless(isinstance(suite, loader.suiteClass))
940 self.assertEqual(list(suite), [unittest.TestSuite()])
941
942 # audioop should now be loaded, thanks to loadTestsFromName()
943 self.failUnless(module_name in sys.modules)
944 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000945 if module_name in sys.modules:
946 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000947
Georg Brandl15c5ce92007-03-07 09:09:40 +0000948 ################################################################
949 ### /Tests for TestLoader.loadTestsFromNames()
950
951 ### Tests for TestLoader.getTestCaseNames()
952 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000953
Georg Brandl15c5ce92007-03-07 09:09:40 +0000954 # "Return a sorted sequence of method names found within testCaseClass"
955 #
956 # Test.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +0000957 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +0000958 def test_getTestCaseNames(self):
959 class Test(unittest.TestCase):
960 def test_1(self): pass
961 def test_2(self): pass
962 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000963
Georg Brandl15c5ce92007-03-07 09:09:40 +0000964 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000965
Georg Brandl15c5ce92007-03-07 09:09:40 +0000966 self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])
Tim Petersea5962f2007-03-12 18:07:52 +0000967
Georg Brandl15c5ce92007-03-07 09:09:40 +0000968 # "Return a sorted sequence of method names found within testCaseClass"
969 #
Tim Petersea5962f2007-03-12 18:07:52 +0000970 # Does getTestCaseNames() behave appropriately if no tests are found?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000971 def test_getTestCaseNames__no_tests(self):
972 class Test(unittest.TestCase):
973 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000974
Georg Brandl15c5ce92007-03-07 09:09:40 +0000975 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000976
Georg Brandl15c5ce92007-03-07 09:09:40 +0000977 self.assertEqual(loader.getTestCaseNames(Test), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000978
Georg Brandl15c5ce92007-03-07 09:09:40 +0000979 # "Return a sorted sequence of method names found within testCaseClass"
980 #
981 # Are not-TestCases handled gracefully?
982 #
983 # XXX This should raise a TypeError, not return a list
984 #
985 # XXX It's too late in the 2.5 release cycle to fix this, but it should
986 # probably be revisited for 2.6
987 def test_getTestCaseNames__not_a_TestCase(self):
988 class BadCase(int):
989 def test_foo(self):
990 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000991
Georg Brandl15c5ce92007-03-07 09:09:40 +0000992 loader = unittest.TestLoader()
993 names = loader.getTestCaseNames(BadCase)
Tim Petersea5962f2007-03-12 18:07:52 +0000994
Georg Brandl15c5ce92007-03-07 09:09:40 +0000995 self.assertEqual(names, ['test_foo'])
Tim Petersea5962f2007-03-12 18:07:52 +0000996
Georg Brandl15c5ce92007-03-07 09:09:40 +0000997 # "Return a sorted sequence of method names found within testCaseClass"
998 #
999 # Make sure inherited names are handled.
1000 #
1001 # TestP.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +00001002 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +00001003 def test_getTestCaseNames__inheritance(self):
1004 class TestP(unittest.TestCase):
1005 def test_1(self): pass
1006 def test_2(self): pass
1007 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001008
Georg Brandl15c5ce92007-03-07 09:09:40 +00001009 class TestC(TestP):
1010 def test_1(self): pass
1011 def test_3(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001012
Georg Brandl15c5ce92007-03-07 09:09:40 +00001013 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001014
Georg Brandl15c5ce92007-03-07 09:09:40 +00001015 names = ['test_1', 'test_2', 'test_3']
1016 self.assertEqual(loader.getTestCaseNames(TestC), names)
Tim Petersea5962f2007-03-12 18:07:52 +00001017
1018 ################################################################
Georg Brandl15c5ce92007-03-07 09:09:40 +00001019 ### /Tests for TestLoader.getTestCaseNames()
1020
1021 ### Tests for TestLoader.testMethodPrefix
1022 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001023
Georg Brandl15c5ce92007-03-07 09:09:40 +00001024 # "String giving the prefix of method names which will be interpreted as
1025 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001026 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001027 # Implicit in the documentation is that testMethodPrefix is respected by
1028 # all loadTestsFrom* methods.
1029 def test_testMethodPrefix__loadTestsFromTestCase(self):
1030 class Foo(unittest.TestCase):
1031 def test_1(self): pass
1032 def test_2(self): pass
1033 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001034
Georg Brandl15c5ce92007-03-07 09:09:40 +00001035 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1036 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001037
Georg Brandl15c5ce92007-03-07 09:09:40 +00001038 loader = unittest.TestLoader()
1039 loader.testMethodPrefix = 'foo'
1040 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
1041
1042 loader.testMethodPrefix = 'test'
1043 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001044
Georg Brandl15c5ce92007-03-07 09:09:40 +00001045 # "String giving the prefix of method names which will be interpreted as
1046 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001047 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001048 # Implicit in the documentation is that testMethodPrefix is respected by
1049 # all loadTestsFrom* methods.
1050 def test_testMethodPrefix__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001051 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001052 class Foo(unittest.TestCase):
1053 def test_1(self): pass
1054 def test_2(self): pass
1055 def foo_bar(self): pass
1056 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001057
Georg Brandl15c5ce92007-03-07 09:09:40 +00001058 tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
1059 tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]
Tim Petersea5962f2007-03-12 18:07:52 +00001060
Georg Brandl15c5ce92007-03-07 09:09:40 +00001061 loader = unittest.TestLoader()
1062 loader.testMethodPrefix = 'foo'
1063 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
1064
1065 loader.testMethodPrefix = 'test'
1066 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001067
Georg Brandl15c5ce92007-03-07 09:09:40 +00001068 # "String giving the prefix of method names which will be interpreted as
1069 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001070 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001071 # Implicit in the documentation is that testMethodPrefix is respected by
1072 # all loadTestsFrom* methods.
1073 def test_testMethodPrefix__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001074 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001075 class Foo(unittest.TestCase):
1076 def test_1(self): pass
1077 def test_2(self): pass
1078 def foo_bar(self): pass
1079 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001080
Georg Brandl15c5ce92007-03-07 09:09:40 +00001081 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1082 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001083
Georg Brandl15c5ce92007-03-07 09:09:40 +00001084 loader = unittest.TestLoader()
1085 loader.testMethodPrefix = 'foo'
1086 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
1087
1088 loader.testMethodPrefix = 'test'
1089 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001090
Georg Brandl15c5ce92007-03-07 09:09:40 +00001091 # "String giving the prefix of method names which will be interpreted as
1092 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001093 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001094 # Implicit in the documentation is that testMethodPrefix is respected by
1095 # all loadTestsFrom* methods.
1096 def test_testMethodPrefix__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001097 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001098 class Foo(unittest.TestCase):
1099 def test_1(self): pass
1100 def test_2(self): pass
1101 def foo_bar(self): pass
1102 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001103
Georg Brandl15c5ce92007-03-07 09:09:40 +00001104 tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
1105 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1106 tests_2 = unittest.TestSuite([tests_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001107
Georg Brandl15c5ce92007-03-07 09:09:40 +00001108 loader = unittest.TestLoader()
1109 loader.testMethodPrefix = 'foo'
1110 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)
1111
1112 loader.testMethodPrefix = 'test'
1113 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001114
Georg Brandl15c5ce92007-03-07 09:09:40 +00001115 # "The default value is 'test'"
1116 def test_testMethodPrefix__default_value(self):
1117 loader = unittest.TestLoader()
1118 self.failUnless(loader.testMethodPrefix == 'test')
Tim Petersea5962f2007-03-12 18:07:52 +00001119
Georg Brandl15c5ce92007-03-07 09:09:40 +00001120 ################################################################
1121 ### /Tests for TestLoader.testMethodPrefix
1122
Tim Petersea5962f2007-03-12 18:07:52 +00001123 ### Tests for TestLoader.sortTestMethodsUsing
Georg Brandl15c5ce92007-03-07 09:09:40 +00001124 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001125
Georg Brandl15c5ce92007-03-07 09:09:40 +00001126 # "Function to be used to compare method names when sorting them in
1127 # getTestCaseNames() and all the loadTestsFromX() methods"
1128 def test_sortTestMethodsUsing__loadTestsFromTestCase(self):
1129 def reversed_cmp(x, y):
1130 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001131
Georg Brandl15c5ce92007-03-07 09:09:40 +00001132 class Foo(unittest.TestCase):
1133 def test_1(self): pass
1134 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001135
Georg Brandl15c5ce92007-03-07 09:09:40 +00001136 loader = unittest.TestLoader()
1137 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001138
Georg Brandl15c5ce92007-03-07 09:09:40 +00001139 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1140 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001141
Georg Brandl15c5ce92007-03-07 09:09:40 +00001142 # "Function to be used to compare method names when sorting them in
1143 # getTestCaseNames() and all the loadTestsFromX() methods"
1144 def test_sortTestMethodsUsing__loadTestsFromModule(self):
1145 def reversed_cmp(x, y):
1146 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001147
Christian Heimesc756d002007-11-27 21:34:01 +00001148 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001149 class Foo(unittest.TestCase):
1150 def test_1(self): pass
1151 def test_2(self): pass
1152 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001153
Georg Brandl15c5ce92007-03-07 09:09:40 +00001154 loader = unittest.TestLoader()
1155 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001156
Georg Brandl15c5ce92007-03-07 09:09:40 +00001157 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1158 self.assertEqual(list(loader.loadTestsFromModule(m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001159
Georg Brandl15c5ce92007-03-07 09:09:40 +00001160 # "Function to be used to compare method names when sorting them in
1161 # getTestCaseNames() and all the loadTestsFromX() methods"
1162 def test_sortTestMethodsUsing__loadTestsFromName(self):
1163 def reversed_cmp(x, y):
1164 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001165
Christian Heimesc756d002007-11-27 21:34:01 +00001166 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001167 class Foo(unittest.TestCase):
1168 def test_1(self): pass
1169 def test_2(self): pass
1170 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001171
Georg Brandl15c5ce92007-03-07 09:09:40 +00001172 loader = unittest.TestLoader()
1173 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001174
Georg Brandl15c5ce92007-03-07 09:09:40 +00001175 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1176 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001177
Georg Brandl15c5ce92007-03-07 09:09:40 +00001178 # "Function to be used to compare method names when sorting them in
1179 # getTestCaseNames() and all the loadTestsFromX() methods"
1180 def test_sortTestMethodsUsing__loadTestsFromNames(self):
1181 def reversed_cmp(x, y):
1182 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001183
Christian Heimesc756d002007-11-27 21:34:01 +00001184 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001185 class Foo(unittest.TestCase):
1186 def test_1(self): pass
1187 def test_2(self): pass
1188 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001189
Georg Brandl15c5ce92007-03-07 09:09:40 +00001190 loader = unittest.TestLoader()
1191 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001192
Georg Brandl15c5ce92007-03-07 09:09:40 +00001193 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1194 self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001195
Georg Brandl15c5ce92007-03-07 09:09:40 +00001196 # "Function to be used to compare method names when sorting them in
1197 # getTestCaseNames()"
1198 #
1199 # Does it actually affect getTestCaseNames()?
1200 def test_sortTestMethodsUsing__getTestCaseNames(self):
1201 def reversed_cmp(x, y):
1202 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001203
Georg Brandl15c5ce92007-03-07 09:09:40 +00001204 class Foo(unittest.TestCase):
1205 def test_1(self): pass
1206 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001207
Georg Brandl15c5ce92007-03-07 09:09:40 +00001208 loader = unittest.TestLoader()
1209 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001210
Georg Brandl15c5ce92007-03-07 09:09:40 +00001211 test_names = ['test_2', 'test_1']
1212 self.assertEqual(loader.getTestCaseNames(Foo), test_names)
Tim Petersea5962f2007-03-12 18:07:52 +00001213
Georg Brandl15c5ce92007-03-07 09:09:40 +00001214 # "The default value is the built-in cmp() function"
1215 def test_sortTestMethodsUsing__default_value(self):
1216 loader = unittest.TestLoader()
1217 self.failUnless(loader.sortTestMethodsUsing is cmp)
Tim Petersea5962f2007-03-12 18:07:52 +00001218
Georg Brandl15c5ce92007-03-07 09:09:40 +00001219 # "it can be set to None to disable the sort."
1220 #
1221 # XXX How is this different from reassigning cmp? Are the tests returned
1222 # in a random order or something? This behaviour should die
1223 def test_sortTestMethodsUsing__None(self):
1224 class Foo(unittest.TestCase):
1225 def test_1(self): pass
1226 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001227
Georg Brandl15c5ce92007-03-07 09:09:40 +00001228 loader = unittest.TestLoader()
1229 loader.sortTestMethodsUsing = None
Tim Petersea5962f2007-03-12 18:07:52 +00001230
Georg Brandl15c5ce92007-03-07 09:09:40 +00001231 test_names = ['test_2', 'test_1']
1232 self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))
Tim Petersea5962f2007-03-12 18:07:52 +00001233
Georg Brandl15c5ce92007-03-07 09:09:40 +00001234 ################################################################
1235 ### /Tests for TestLoader.sortTestMethodsUsing
Tim Petersea5962f2007-03-12 18:07:52 +00001236
Georg Brandl15c5ce92007-03-07 09:09:40 +00001237 ### Tests for TestLoader.suiteClass
1238 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001239
Georg Brandl15c5ce92007-03-07 09:09:40 +00001240 # "Callable object that constructs a test suite from a list of tests."
1241 def test_suiteClass__loadTestsFromTestCase(self):
1242 class Foo(unittest.TestCase):
1243 def test_1(self): pass
1244 def test_2(self): pass
1245 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001246
Georg Brandl15c5ce92007-03-07 09:09:40 +00001247 tests = [Foo('test_1'), Foo('test_2')]
1248
1249 loader = unittest.TestLoader()
Benjamin Peterson692428e2009-03-23 21:50:21 +00001250 loader.classSuiteClass = MyClassSuite
Georg Brandl15c5ce92007-03-07 09:09:40 +00001251 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001252
Georg Brandl15c5ce92007-03-07 09:09:40 +00001253 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001254 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001255 def test_suiteClass__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001256 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001257 class Foo(unittest.TestCase):
1258 def test_1(self): pass
1259 def test_2(self): pass
1260 def foo_bar(self): pass
1261 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001262
Benjamin Peterson692428e2009-03-23 21:50:21 +00001263 tests = [unittest.ClassTestSuite([Foo('test_1'), Foo('test_2')], Foo)]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001264
1265 loader = unittest.TestLoader()
1266 loader.suiteClass = list
1267 self.assertEqual(loader.loadTestsFromModule(m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001268
Georg Brandl15c5ce92007-03-07 09:09:40 +00001269 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001270 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001271 def test_suiteClass__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001272 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001273 class Foo(unittest.TestCase):
1274 def test_1(self): pass
1275 def test_2(self): pass
1276 def foo_bar(self): pass
1277 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001278
Georg Brandl15c5ce92007-03-07 09:09:40 +00001279 tests = [Foo('test_1'), Foo('test_2')]
1280
1281 loader = unittest.TestLoader()
Benjamin Peterson692428e2009-03-23 21:50:21 +00001282 loader.classSuiteClass = MyClassSuite
Georg Brandl15c5ce92007-03-07 09:09:40 +00001283 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001284
Georg Brandl15c5ce92007-03-07 09:09:40 +00001285 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001286 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001287 def test_suiteClass__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001288 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001289 class Foo(unittest.TestCase):
1290 def test_1(self): pass
1291 def test_2(self): pass
1292 def foo_bar(self): pass
1293 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001294
Benjamin Peterson692428e2009-03-23 21:50:21 +00001295 tests = [unittest.ClassTestSuite([Foo('test_1'), Foo('test_2')], Foo)]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001296
1297 loader = unittest.TestLoader()
1298 loader.suiteClass = list
1299 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001300
Georg Brandl15c5ce92007-03-07 09:09:40 +00001301 # "The default value is the TestSuite class"
1302 def test_suiteClass__default_value(self):
1303 loader = unittest.TestLoader()
1304 self.failUnless(loader.suiteClass is unittest.TestSuite)
Tim Petersea5962f2007-03-12 18:07:52 +00001305
Georg Brandl15c5ce92007-03-07 09:09:40 +00001306 ################################################################
1307 ### /Tests for TestLoader.suiteClass
1308
1309### Support code for Test_TestSuite
1310################################################################
1311
1312class Foo(unittest.TestCase):
1313 def test_1(self): pass
1314 def test_2(self): pass
1315 def test_3(self): pass
1316 def runTest(self): pass
1317
1318def _mk_TestSuite(*names):
1319 return unittest.TestSuite(Foo(n) for n in names)
Tim Petersea5962f2007-03-12 18:07:52 +00001320
Georg Brandl15c5ce92007-03-07 09:09:40 +00001321################################################################
1322### /Support code for Test_TestSuite
1323
1324class Test_TestSuite(TestCase, TestEquality):
1325
1326 ### Set up attributes needed by inherited tests
1327 ################################################################
1328
1329 # Used by TestEquality.test_eq
1330 eq_pairs = [(unittest.TestSuite(), unittest.TestSuite())
1331 ,(unittest.TestSuite(), unittest.TestSuite([]))
1332 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001333
1334 # Used by TestEquality.test_ne
Georg Brandl15c5ce92007-03-07 09:09:40 +00001335 ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1'))
1336 ,(unittest.TestSuite([]), _mk_TestSuite('test_1'))
1337 ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3'))
1338 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001339
Georg Brandl15c5ce92007-03-07 09:09:40 +00001340 ################################################################
1341 ### /Set up attributes needed by inherited tests
1342
1343 ### Tests for TestSuite.__init__
1344 ################################################################
1345
1346 # "class TestSuite([tests])"
1347 #
1348 # The tests iterable should be optional
1349 def test_init__tests_optional(self):
1350 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001351
Georg Brandl15c5ce92007-03-07 09:09:40 +00001352 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001353
Georg Brandl15c5ce92007-03-07 09:09:40 +00001354 # "class TestSuite([tests])"
1355 # ...
1356 # "If tests is given, it must be an iterable of individual test cases
1357 # or other test suites that will be used to build the suite initially"
1358 #
1359 # TestSuite should deal with empty tests iterables by allowing the
Tim Petersea5962f2007-03-12 18:07:52 +00001360 # creation of an empty suite
Georg Brandl15c5ce92007-03-07 09:09:40 +00001361 def test_init__empty_tests(self):
1362 suite = unittest.TestSuite([])
Tim Petersea5962f2007-03-12 18:07:52 +00001363
Georg Brandl15c5ce92007-03-07 09:09:40 +00001364 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001365
Georg Brandl15c5ce92007-03-07 09:09:40 +00001366 # "class TestSuite([tests])"
1367 # ...
1368 # "If tests is given, it must be an iterable of individual test cases
1369 # or other test suites that will be used to build the suite initially"
1370 #
Tim Petersea5962f2007-03-12 18:07:52 +00001371 # TestSuite should allow any iterable to provide tests
Georg Brandl15c5ce92007-03-07 09:09:40 +00001372 def test_init__tests_from_any_iterable(self):
1373 def tests():
1374 yield unittest.FunctionTestCase(lambda: None)
1375 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001376
Georg Brandl15c5ce92007-03-07 09:09:40 +00001377 suite_1 = unittest.TestSuite(tests())
1378 self.assertEqual(suite_1.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001379
Georg Brandl15c5ce92007-03-07 09:09:40 +00001380 suite_2 = unittest.TestSuite(suite_1)
1381 self.assertEqual(suite_2.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001382
Georg Brandl15c5ce92007-03-07 09:09:40 +00001383 suite_3 = unittest.TestSuite(set(suite_1))
1384 self.assertEqual(suite_3.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001385
Georg Brandl15c5ce92007-03-07 09:09:40 +00001386 # "class TestSuite([tests])"
1387 # ...
1388 # "If tests is given, it must be an iterable of individual test cases
1389 # or other test suites that will be used to build the suite initially"
1390 #
1391 # Does TestSuite() also allow other TestSuite() instances to be present
1392 # in the tests iterable?
1393 def test_init__TestSuite_instances_in_tests(self):
1394 def tests():
1395 ftc = unittest.FunctionTestCase(lambda: None)
1396 yield unittest.TestSuite([ftc])
1397 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001398
Georg Brandl15c5ce92007-03-07 09:09:40 +00001399 suite = unittest.TestSuite(tests())
1400 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001401
Georg Brandl15c5ce92007-03-07 09:09:40 +00001402 ################################################################
1403 ### /Tests for TestSuite.__init__
1404
1405 # Container types should support the iter protocol
1406 def test_iter(self):
1407 test1 = unittest.FunctionTestCase(lambda: None)
1408 test2 = unittest.FunctionTestCase(lambda: None)
1409 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001410
Georg Brandl15c5ce92007-03-07 09:09:40 +00001411 self.assertEqual(list(suite), [test1, test2])
Tim Petersea5962f2007-03-12 18:07:52 +00001412
Georg Brandl15c5ce92007-03-07 09:09:40 +00001413 # "Return the number of tests represented by the this test object.
1414 # ...this method is also implemented by the TestSuite class, which can
1415 # return larger [greater than 1] values"
1416 #
Tim Petersea5962f2007-03-12 18:07:52 +00001417 # Presumably an empty TestSuite returns 0?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001418 def test_countTestCases_zero_simple(self):
1419 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001420
Georg Brandl15c5ce92007-03-07 09:09:40 +00001421 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001422
Georg Brandl15c5ce92007-03-07 09:09:40 +00001423 # "Return the number of tests represented by the this test object.
1424 # ...this method is also implemented by the TestSuite class, which can
1425 # return larger [greater than 1] values"
1426 #
1427 # Presumably an empty TestSuite (even if it contains other empty
1428 # TestSuite instances) returns 0?
1429 def test_countTestCases_zero_nested(self):
1430 class Test1(unittest.TestCase):
1431 def test(self):
1432 pass
1433
1434 suite = unittest.TestSuite([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 def test_countTestCases_simple(self):
1442 test1 = unittest.FunctionTestCase(lambda: None)
1443 test2 = unittest.FunctionTestCase(lambda: None)
1444 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001445
Georg Brandl15c5ce92007-03-07 09:09:40 +00001446 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001447
Georg Brandl15c5ce92007-03-07 09:09:40 +00001448 # "Return the number of tests represented by the this test object.
1449 # ...this method is also implemented by the TestSuite class, which can
1450 # return larger [greater than 1] values"
1451 #
1452 # Make sure this holds for nested TestSuite instances, too
1453 def test_countTestCases_nested(self):
1454 class Test1(unittest.TestCase):
1455 def test1(self): pass
1456 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001457
Georg Brandl15c5ce92007-03-07 09:09:40 +00001458 test2 = unittest.FunctionTestCase(lambda: None)
1459 test3 = unittest.FunctionTestCase(lambda: None)
1460 child = unittest.TestSuite((Test1('test2'), test2))
1461 parent = unittest.TestSuite((test3, child, Test1('test1')))
Tim Petersea5962f2007-03-12 18:07:52 +00001462
Georg Brandl15c5ce92007-03-07 09:09:40 +00001463 self.assertEqual(parent.countTestCases(), 4)
Tim Petersea5962f2007-03-12 18:07:52 +00001464
Georg Brandl15c5ce92007-03-07 09:09:40 +00001465 # "Run the tests associated with this suite, collecting the result into
1466 # the test result object passed as result."
1467 #
1468 # And if there are no tests? What then?
1469 def test_run__empty_suite(self):
1470 events = []
1471 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001472
Georg Brandl15c5ce92007-03-07 09:09:40 +00001473 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001474
Georg Brandl15c5ce92007-03-07 09:09:40 +00001475 suite.run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001476
Georg Brandl15c5ce92007-03-07 09:09:40 +00001477 self.assertEqual(events, [])
Tim Petersea5962f2007-03-12 18:07:52 +00001478
Georg Brandl15c5ce92007-03-07 09:09:40 +00001479 # "Note that unlike TestCase.run(), TestSuite.run() requires the
1480 # "result object to be passed in."
1481 def test_run__requires_result(self):
1482 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001483
Georg Brandl15c5ce92007-03-07 09:09:40 +00001484 try:
1485 suite.run()
1486 except TypeError:
1487 pass
1488 else:
1489 self.fail("Failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +00001490
Georg Brandl15c5ce92007-03-07 09:09:40 +00001491 # "Run the tests associated with this suite, collecting the result into
Tim Petersea5962f2007-03-12 18:07:52 +00001492 # the test result object passed as result."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001493 def test_run(self):
1494 events = []
1495 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001496
Georg Brandl15c5ce92007-03-07 09:09:40 +00001497 class LoggingCase(unittest.TestCase):
1498 def run(self, result):
1499 events.append('run %s' % self._testMethodName)
Tim Petersea5962f2007-03-12 18:07:52 +00001500
Georg Brandl15c5ce92007-03-07 09:09:40 +00001501 def test1(self): pass
1502 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001503
1504 tests = [LoggingCase('test1'), LoggingCase('test2')]
1505
Georg Brandl15c5ce92007-03-07 09:09:40 +00001506 unittest.TestSuite(tests).run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001507
Georg Brandl15c5ce92007-03-07 09:09:40 +00001508 self.assertEqual(events, ['run test1', 'run test2'])
Tim Petersea5962f2007-03-12 18:07:52 +00001509
1510 # "Add a TestCase ... to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001511 def test_addTest__TestCase(self):
1512 class Foo(unittest.TestCase):
1513 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001514
Georg Brandl15c5ce92007-03-07 09:09:40 +00001515 test = Foo('test')
1516 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001517
Georg Brandl15c5ce92007-03-07 09:09:40 +00001518 suite.addTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001519
Georg Brandl15c5ce92007-03-07 09:09:40 +00001520 self.assertEqual(suite.countTestCases(), 1)
1521 self.assertEqual(list(suite), [test])
Tim Petersea5962f2007-03-12 18:07:52 +00001522
1523 # "Add a ... TestSuite to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001524 def test_addTest__TestSuite(self):
1525 class Foo(unittest.TestCase):
1526 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001527
Georg Brandl15c5ce92007-03-07 09:09:40 +00001528 suite_2 = unittest.TestSuite([Foo('test')])
Tim Petersea5962f2007-03-12 18:07:52 +00001529
Georg Brandl15c5ce92007-03-07 09:09:40 +00001530 suite = unittest.TestSuite()
1531 suite.addTest(suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001532
Georg Brandl15c5ce92007-03-07 09:09:40 +00001533 self.assertEqual(suite.countTestCases(), 1)
1534 self.assertEqual(list(suite), [suite_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001535
Georg Brandl15c5ce92007-03-07 09:09:40 +00001536 # "Add all the tests from an iterable of TestCase and TestSuite
1537 # instances to this test suite."
Tim Petersea5962f2007-03-12 18:07:52 +00001538 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001539 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001540 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001541 def test_addTests(self):
1542 class Foo(unittest.TestCase):
1543 def test_1(self): pass
1544 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001545
Georg Brandl15c5ce92007-03-07 09:09:40 +00001546 test_1 = Foo('test_1')
1547 test_2 = Foo('test_2')
1548 inner_suite = unittest.TestSuite([test_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001549
Georg Brandl15c5ce92007-03-07 09:09:40 +00001550 def gen():
1551 yield test_1
1552 yield test_2
1553 yield inner_suite
Tim Petersea5962f2007-03-12 18:07:52 +00001554
Georg Brandl15c5ce92007-03-07 09:09:40 +00001555 suite_1 = unittest.TestSuite()
1556 suite_1.addTests(gen())
Tim Petersea5962f2007-03-12 18:07:52 +00001557
Georg Brandl15c5ce92007-03-07 09:09:40 +00001558 self.assertEqual(list(suite_1), list(gen()))
Tim Petersea5962f2007-03-12 18:07:52 +00001559
Georg Brandl15c5ce92007-03-07 09:09:40 +00001560 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001561 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001562 suite_2 = unittest.TestSuite()
1563 for t in gen():
1564 suite_2.addTest(t)
Tim Petersea5962f2007-03-12 18:07:52 +00001565
Georg Brandl15c5ce92007-03-07 09:09:40 +00001566 self.assertEqual(suite_1, suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001567
Georg Brandl15c5ce92007-03-07 09:09:40 +00001568 # "Add all the tests from an iterable of TestCase and TestSuite
1569 # instances to this test suite."
1570 #
Tim Petersea5962f2007-03-12 18:07:52 +00001571 # What happens if it doesn't get an iterable?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001572 def test_addTest__noniterable(self):
1573 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001574
Georg Brandl15c5ce92007-03-07 09:09:40 +00001575 try:
1576 suite.addTests(5)
1577 except TypeError:
1578 pass
1579 else:
1580 self.fail("Failed to raise TypeError")
Georg Brandld9e50262007-03-07 11:54:49 +00001581
1582 def test_addTest__noncallable(self):
1583 suite = unittest.TestSuite()
1584 self.assertRaises(TypeError, suite.addTest, 5)
1585
1586 def test_addTest__casesuiteclass(self):
1587 suite = unittest.TestSuite()
1588 self.assertRaises(TypeError, suite.addTest, Test_TestSuite)
1589 self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)
1590
1591 def test_addTests__string(self):
1592 suite = unittest.TestSuite()
1593 self.assertRaises(TypeError, suite.addTests, "foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001594
1595
Georg Brandl15c5ce92007-03-07 09:09:40 +00001596class Test_FunctionTestCase(TestCase):
Tim Petersea5962f2007-03-12 18:07:52 +00001597
Georg Brandl15c5ce92007-03-07 09:09:40 +00001598 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00001599 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001600 def test_countTestCases(self):
1601 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001602
Georg Brandl15c5ce92007-03-07 09:09:40 +00001603 self.assertEqual(test.countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00001604
Georg Brandl15c5ce92007-03-07 09:09:40 +00001605 # "When a setUp() method is defined, the test runner will run that method
1606 # prior to each test. Likewise, if a tearDown() method is defined, the
1607 # test runner will invoke that method after each test. In the example,
1608 # setUp() was used to create a fresh sequence for each test."
1609 #
1610 # Make sure the proper call order is maintained, even if setUp() raises
1611 # an exception.
1612 def test_run_call_order__error_in_setUp(self):
1613 events = []
1614 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001615
Georg Brandl15c5ce92007-03-07 09:09:40 +00001616 def setUp():
1617 events.append('setUp')
1618 raise RuntimeError('raised by setUp')
1619
1620 def test():
1621 events.append('test')
1622
1623 def tearDown():
1624 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001625
1626 expected = ['startTest', 'setUp', 'addError', 'stopTest']
Georg Brandl15c5ce92007-03-07 09:09:40 +00001627 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1628 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001629
Georg Brandl15c5ce92007-03-07 09:09:40 +00001630 # "When a setUp() method is defined, the test runner will run that method
1631 # prior to each test. Likewise, if a tearDown() method is defined, the
1632 # test runner will invoke that method after each test. In the example,
1633 # setUp() was used to create a fresh sequence for each test."
1634 #
1635 # Make sure the proper call order is maintained, even if the test raises
1636 # an error (as opposed to a failure).
1637 def test_run_call_order__error_in_test(self):
1638 events = []
1639 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001640
Georg Brandl15c5ce92007-03-07 09:09:40 +00001641 def setUp():
1642 events.append('setUp')
1643
1644 def test():
1645 events.append('test')
1646 raise RuntimeError('raised by test')
1647
1648 def tearDown():
1649 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001650
Georg Brandl15c5ce92007-03-07 09:09:40 +00001651 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
1652 'stopTest']
1653 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1654 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001655
Georg Brandl15c5ce92007-03-07 09:09:40 +00001656 # "When a setUp() method is defined, the test runner will run that method
1657 # prior to each test. Likewise, if a tearDown() method is defined, the
1658 # test runner will invoke that method after each test. In the example,
1659 # setUp() was used to create a fresh sequence for each test."
1660 #
1661 # Make sure the proper call order is maintained, even if the test signals
1662 # a failure (as opposed to an error).
1663 def test_run_call_order__failure_in_test(self):
1664 events = []
1665 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001666
Georg Brandl15c5ce92007-03-07 09:09:40 +00001667 def setUp():
1668 events.append('setUp')
1669
1670 def test():
1671 events.append('test')
1672 self.fail('raised by test')
1673
1674 def tearDown():
1675 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001676
Georg Brandl15c5ce92007-03-07 09:09:40 +00001677 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
1678 'stopTest']
1679 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1680 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001681
Georg Brandl15c5ce92007-03-07 09:09:40 +00001682 # "When a setUp() method is defined, the test runner will run that method
1683 # prior to each test. Likewise, if a tearDown() method is defined, the
1684 # test runner will invoke that method after each test. In the example,
1685 # setUp() was used to create a fresh sequence for each test."
1686 #
1687 # Make sure the proper call order is maintained, even if tearDown() raises
1688 # an exception.
1689 def test_run_call_order__error_in_tearDown(self):
1690 events = []
1691 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001692
Georg Brandl15c5ce92007-03-07 09:09:40 +00001693 def setUp():
1694 events.append('setUp')
1695
1696 def test():
1697 events.append('test')
1698
1699 def tearDown():
1700 events.append('tearDown')
1701 raise RuntimeError('raised by tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001702
Georg Brandl15c5ce92007-03-07 09:09:40 +00001703 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
1704 'stopTest']
1705 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1706 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001707
Georg Brandl15c5ce92007-03-07 09:09:40 +00001708 # "Return a string identifying the specific test case."
1709 #
1710 # Because of the vague nature of the docs, I'm not going to lock this
1711 # test down too much. Really all that can be asserted is that the id()
1712 # will be a string (either 8-byte or unicode -- again, because the docs
1713 # just say "string")
1714 def test_id(self):
1715 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001716
Georg Brandl15c5ce92007-03-07 09:09:40 +00001717 self.failUnless(isinstance(test.id(), basestring))
Tim Petersea5962f2007-03-12 18:07:52 +00001718
Georg Brandl15c5ce92007-03-07 09:09:40 +00001719 # "Returns a one-line description of the test, or None if no description
1720 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001721 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001722 def test_shortDescription__no_docstring(self):
1723 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001724
Georg Brandl15c5ce92007-03-07 09:09:40 +00001725 self.assertEqual(test.shortDescription(), None)
Tim Petersea5962f2007-03-12 18:07:52 +00001726
Georg Brandl15c5ce92007-03-07 09:09:40 +00001727 # "Returns a one-line description of the test, or None if no description
1728 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001729 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001730 def test_shortDescription__singleline_docstring(self):
1731 desc = "this tests foo"
1732 test = unittest.FunctionTestCase(lambda: None, description=desc)
Tim Petersea5962f2007-03-12 18:07:52 +00001733
Georg Brandl15c5ce92007-03-07 09:09:40 +00001734 self.assertEqual(test.shortDescription(), "this tests foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001735
Georg Brandl15c5ce92007-03-07 09:09:40 +00001736class Test_TestResult(TestCase):
1737 # Note: there are not separate tests for TestResult.wasSuccessful(),
1738 # TestResult.errors, TestResult.failures, TestResult.testsRun or
1739 # TestResult.shouldStop because these only have meaning in terms of
1740 # other TestResult methods.
1741 #
1742 # Accordingly, tests for the aforenamed attributes are incorporated
1743 # in with the tests for the defining methods.
1744 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001745
Georg Brandl15c5ce92007-03-07 09:09:40 +00001746 def test_init(self):
1747 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001748
Georg Brandl15c5ce92007-03-07 09:09:40 +00001749 self.failUnless(result.wasSuccessful())
1750 self.assertEqual(len(result.errors), 0)
1751 self.assertEqual(len(result.failures), 0)
1752 self.assertEqual(result.testsRun, 0)
1753 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001754
Georg Brandl15c5ce92007-03-07 09:09:40 +00001755 # "This method can be called to signal that the set of tests being
1756 # run should be aborted by setting the TestResult's shouldStop
Tim Petersea5962f2007-03-12 18:07:52 +00001757 # attribute to True."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001758 def test_stop(self):
1759 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001760
Georg Brandl15c5ce92007-03-07 09:09:40 +00001761 result.stop()
Tim Petersea5962f2007-03-12 18:07:52 +00001762
Georg Brandl15c5ce92007-03-07 09:09:40 +00001763 self.assertEqual(result.shouldStop, True)
Tim Petersea5962f2007-03-12 18:07:52 +00001764
Georg Brandl15c5ce92007-03-07 09:09:40 +00001765 # "Called when the test case test is about to be run. The default
1766 # implementation simply increments the instance's testsRun counter."
1767 def test_startTest(self):
1768 class Foo(unittest.TestCase):
1769 def test_1(self):
1770 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001771
Georg Brandl15c5ce92007-03-07 09:09:40 +00001772 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001773
Georg Brandl15c5ce92007-03-07 09:09:40 +00001774 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001775
Georg Brandl15c5ce92007-03-07 09:09:40 +00001776 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001777
Georg Brandl15c5ce92007-03-07 09:09:40 +00001778 self.failUnless(result.wasSuccessful())
1779 self.assertEqual(len(result.errors), 0)
1780 self.assertEqual(len(result.failures), 0)
1781 self.assertEqual(result.testsRun, 1)
1782 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001783
Georg Brandl15c5ce92007-03-07 09:09:40 +00001784 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001785
Georg Brandl15c5ce92007-03-07 09:09:40 +00001786 # "Called after the test case test has been executed, regardless of
1787 # the outcome. The default implementation does nothing."
1788 def test_stopTest(self):
1789 class Foo(unittest.TestCase):
1790 def test_1(self):
1791 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001792
Georg Brandl15c5ce92007-03-07 09:09:40 +00001793 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001794
Georg Brandl15c5ce92007-03-07 09:09:40 +00001795 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001796
Georg Brandl15c5ce92007-03-07 09:09:40 +00001797 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001798
Georg Brandl15c5ce92007-03-07 09:09:40 +00001799 self.failUnless(result.wasSuccessful())
1800 self.assertEqual(len(result.errors), 0)
1801 self.assertEqual(len(result.failures), 0)
1802 self.assertEqual(result.testsRun, 1)
1803 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001804
Georg Brandl15c5ce92007-03-07 09:09:40 +00001805 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001806
Georg Brandl15c5ce92007-03-07 09:09:40 +00001807 # Same tests as above; make sure nothing has changed
1808 self.failUnless(result.wasSuccessful())
1809 self.assertEqual(len(result.errors), 0)
1810 self.assertEqual(len(result.failures), 0)
1811 self.assertEqual(result.testsRun, 1)
1812 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001813
Georg Brandl15c5ce92007-03-07 09:09:40 +00001814 # "addSuccess(test)"
1815 # ...
1816 # "Called when the test case test succeeds"
1817 # ...
1818 # "wasSuccessful() - Returns True if all tests run so far have passed,
1819 # otherwise returns False"
1820 # ...
1821 # "testsRun - The total number of tests run so far."
1822 # ...
1823 # "errors - A list containing 2-tuples of TestCase instances and
1824 # formatted tracebacks. Each tuple represents a test which raised an
1825 # unexpected exception. Contains formatted
1826 # tracebacks instead of sys.exc_info() results."
1827 # ...
1828 # "failures - A list containing 2-tuples of TestCase instances and
1829 # formatted tracebacks. Each tuple represents a test where a failure was
1830 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1831 # methods. Contains formatted tracebacks instead
1832 # of sys.exc_info() results."
1833 def test_addSuccess(self):
1834 class Foo(unittest.TestCase):
1835 def test_1(self):
1836 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001837
Georg Brandl15c5ce92007-03-07 09:09:40 +00001838 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001839
Georg Brandl15c5ce92007-03-07 09:09:40 +00001840 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001841
Georg Brandl15c5ce92007-03-07 09:09:40 +00001842 result.startTest(test)
1843 result.addSuccess(test)
1844 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001845
Georg Brandl15c5ce92007-03-07 09:09:40 +00001846 self.failUnless(result.wasSuccessful())
1847 self.assertEqual(len(result.errors), 0)
1848 self.assertEqual(len(result.failures), 0)
1849 self.assertEqual(result.testsRun, 1)
1850 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001851
Georg Brandl15c5ce92007-03-07 09:09:40 +00001852 # "addFailure(test, err)"
1853 # ...
1854 # "Called when the test case test signals a failure. err is a tuple of
1855 # the form returned by sys.exc_info(): (type, value, traceback)"
1856 # ...
1857 # "wasSuccessful() - Returns True if all tests run so far have passed,
1858 # otherwise returns False"
1859 # ...
1860 # "testsRun - The total number of tests run so far."
1861 # ...
1862 # "errors - A list containing 2-tuples of TestCase instances and
1863 # formatted tracebacks. Each tuple represents a test which raised an
1864 # unexpected exception. Contains formatted
1865 # tracebacks instead of sys.exc_info() results."
1866 # ...
1867 # "failures - A list containing 2-tuples of TestCase instances and
1868 # formatted tracebacks. Each tuple represents a test where a failure was
1869 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1870 # methods. Contains formatted tracebacks instead
1871 # of sys.exc_info() results."
1872 def test_addFailure(self):
1873 import sys
Tim Petersea5962f2007-03-12 18:07:52 +00001874
Georg Brandl15c5ce92007-03-07 09:09:40 +00001875 class Foo(unittest.TestCase):
1876 def test_1(self):
1877 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001878
Georg Brandl15c5ce92007-03-07 09:09:40 +00001879 test = Foo('test_1')
1880 try:
1881 test.fail("foo")
1882 except:
1883 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00001884
Georg Brandl15c5ce92007-03-07 09:09:40 +00001885 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001886
Georg Brandl15c5ce92007-03-07 09:09:40 +00001887 result.startTest(test)
1888 result.addFailure(test, exc_info_tuple)
1889 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001890
Georg Brandl15c5ce92007-03-07 09:09:40 +00001891 self.failIf(result.wasSuccessful())
1892 self.assertEqual(len(result.errors), 0)
1893 self.assertEqual(len(result.failures), 1)
1894 self.assertEqual(result.testsRun, 1)
1895 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001896
Georg Brandl15c5ce92007-03-07 09:09:40 +00001897 test_case, formatted_exc = result.failures[0]
1898 self.failUnless(test_case is test)
1899 self.failUnless(isinstance(formatted_exc, str))
Tim Petersea5962f2007-03-12 18:07:52 +00001900
Georg Brandl15c5ce92007-03-07 09:09:40 +00001901 # "addError(test, err)"
1902 # ...
1903 # "Called when the test case test raises an unexpected exception err
1904 # is a tuple of the form returned by sys.exc_info():
1905 # (type, value, traceback)"
1906 # ...
1907 # "wasSuccessful() - Returns True if all tests run so far have passed,
1908 # otherwise returns False"
1909 # ...
1910 # "testsRun - The total number of tests run so far."
1911 # ...
1912 # "errors - A list containing 2-tuples of TestCase instances and
1913 # formatted tracebacks. Each tuple represents a test which raised an
1914 # unexpected exception. Contains formatted
1915 # tracebacks instead of sys.exc_info() results."
1916 # ...
1917 # "failures - A list containing 2-tuples of TestCase instances and
1918 # formatted tracebacks. Each tuple represents a test where a failure was
1919 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1920 # methods. Contains formatted tracebacks instead
1921 # of sys.exc_info() results."
1922 def test_addError(self):
1923 import sys
Tim Petersea5962f2007-03-12 18:07:52 +00001924
Georg Brandl15c5ce92007-03-07 09:09:40 +00001925 class Foo(unittest.TestCase):
1926 def test_1(self):
1927 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001928
Georg Brandl15c5ce92007-03-07 09:09:40 +00001929 test = Foo('test_1')
1930 try:
1931 raise TypeError()
1932 except:
1933 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00001934
Georg Brandl15c5ce92007-03-07 09:09:40 +00001935 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001936
Georg Brandl15c5ce92007-03-07 09:09:40 +00001937 result.startTest(test)
1938 result.addError(test, exc_info_tuple)
1939 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001940
Georg Brandl15c5ce92007-03-07 09:09:40 +00001941 self.failIf(result.wasSuccessful())
1942 self.assertEqual(len(result.errors), 1)
1943 self.assertEqual(len(result.failures), 0)
1944 self.assertEqual(result.testsRun, 1)
1945 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001946
Georg Brandl15c5ce92007-03-07 09:09:40 +00001947 test_case, formatted_exc = result.errors[0]
1948 self.failUnless(test_case is test)
1949 self.failUnless(isinstance(formatted_exc, str))
1950
1951### Support code for Test_TestCase
1952################################################################
1953
1954class Foo(unittest.TestCase):
1955 def runTest(self): pass
1956 def test1(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001957
Georg Brandl15c5ce92007-03-07 09:09:40 +00001958class Bar(Foo):
1959 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001960
Georg Brandl15c5ce92007-03-07 09:09:40 +00001961################################################################
1962### /Support code for Test_TestCase
1963
1964class Test_TestCase(TestCase, TestEquality, TestHashing):
1965
1966 ### Set up attributes used by inherited tests
1967 ################################################################
1968
1969 # Used by TestHashing.test_hash and TestEquality.test_eq
1970 eq_pairs = [(Foo('test1'), Foo('test1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001971
Georg Brandl15c5ce92007-03-07 09:09:40 +00001972 # Used by TestEquality.test_ne
1973 ne_pairs = [(Foo('test1'), Foo('runTest'))
1974 ,(Foo('test1'), Bar('test1'))
1975 ,(Foo('test1'), Bar('test2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001976
Georg Brandl15c5ce92007-03-07 09:09:40 +00001977 ################################################################
1978 ### /Set up attributes used by inherited tests
Tim Petersea5962f2007-03-12 18:07:52 +00001979
Georg Brandl15c5ce92007-03-07 09:09:40 +00001980
1981 # "class TestCase([methodName])"
1982 # ...
1983 # "Each instance of TestCase will run a single test method: the
1984 # method named methodName."
1985 # ...
1986 # "methodName defaults to "runTest"."
1987 #
1988 # Make sure it really is optional, and that it defaults to the proper
1989 # thing.
1990 def test_init__no_test_name(self):
1991 class Test(unittest.TestCase):
1992 def runTest(self): raise MyException()
1993 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001994
Georg Brandl15c5ce92007-03-07 09:09:40 +00001995 self.assertEqual(Test().id()[-13:], '.Test.runTest')
Tim Petersea5962f2007-03-12 18:07:52 +00001996
Georg Brandl15c5ce92007-03-07 09:09:40 +00001997 # "class TestCase([methodName])"
1998 # ...
1999 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002000 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002001 def test_init__test_name__valid(self):
2002 class Test(unittest.TestCase):
2003 def runTest(self): raise MyException()
2004 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002005
Georg Brandl15c5ce92007-03-07 09:09:40 +00002006 self.assertEqual(Test('test').id()[-10:], '.Test.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002007
Georg Brandl15c5ce92007-03-07 09:09:40 +00002008 # "class TestCase([methodName])"
2009 # ...
2010 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002011 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002012 def test_init__test_name__invalid(self):
2013 class Test(unittest.TestCase):
2014 def runTest(self): raise MyException()
2015 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002016
Georg Brandl15c5ce92007-03-07 09:09:40 +00002017 try:
2018 Test('testfoo')
2019 except ValueError:
2020 pass
2021 else:
2022 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +00002023
Georg Brandl15c5ce92007-03-07 09:09:40 +00002024 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00002025 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00002026 def test_countTestCases(self):
2027 class Foo(unittest.TestCase):
2028 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002029
Georg Brandl15c5ce92007-03-07 09:09:40 +00002030 self.assertEqual(Foo('test').countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00002031
Georg Brandl15c5ce92007-03-07 09:09:40 +00002032 # "Return the default type of test result object to be used to run this
2033 # test. For TestCase instances, this will always be
2034 # unittest.TestResult; subclasses of TestCase should
2035 # override this as necessary."
2036 def test_defaultTestResult(self):
2037 class Foo(unittest.TestCase):
2038 def runTest(self):
2039 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002040
Georg Brandl15c5ce92007-03-07 09:09:40 +00002041 result = Foo().defaultTestResult()
2042 self.assertEqual(type(result), unittest.TestResult)
2043
2044 # "When a setUp() method is defined, the test runner will run that method
2045 # prior to each test. Likewise, if a tearDown() method is defined, the
2046 # test runner will invoke that method after each test. In the example,
2047 # setUp() was used to create a fresh sequence for each test."
2048 #
2049 # Make sure the proper call order is maintained, even if setUp() raises
2050 # an exception.
2051 def test_run_call_order__error_in_setUp(self):
2052 events = []
2053 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002054
Georg Brandl15c5ce92007-03-07 09:09:40 +00002055 class Foo(unittest.TestCase):
2056 def setUp(self):
2057 events.append('setUp')
2058 raise RuntimeError('raised by Foo.setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002059
Georg Brandl15c5ce92007-03-07 09:09:40 +00002060 def test(self):
2061 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002062
Georg Brandl15c5ce92007-03-07 09:09:40 +00002063 def tearDown(self):
2064 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002065
Georg Brandl15c5ce92007-03-07 09:09:40 +00002066 Foo('test').run(result)
2067 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2068 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002069
Georg Brandl15c5ce92007-03-07 09:09:40 +00002070 # "When a setUp() method is defined, the test runner will run that method
2071 # prior to each test. Likewise, if a tearDown() method is defined, the
2072 # test runner will invoke that method after each test. In the example,
2073 # setUp() was used to create a fresh sequence for each test."
2074 #
2075 # Make sure the proper call order is maintained, even if the test raises
2076 # an error (as opposed to a failure).
2077 def test_run_call_order__error_in_test(self):
2078 events = []
2079 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002080
Georg Brandl15c5ce92007-03-07 09:09:40 +00002081 class Foo(unittest.TestCase):
2082 def setUp(self):
2083 events.append('setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002084
Georg Brandl15c5ce92007-03-07 09:09:40 +00002085 def test(self):
2086 events.append('test')
2087 raise RuntimeError('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002088
Georg Brandl15c5ce92007-03-07 09:09:40 +00002089 def tearDown(self):
2090 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002091
Georg Brandl15c5ce92007-03-07 09:09:40 +00002092 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2093 'stopTest']
2094 Foo('test').run(result)
2095 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002096
Georg Brandl15c5ce92007-03-07 09:09:40 +00002097 # "When a setUp() method is defined, the test runner will run that method
2098 # prior to each test. Likewise, if a tearDown() method is defined, the
2099 # test runner will invoke that method after each test. In the example,
2100 # setUp() was used to create a fresh sequence for each test."
2101 #
2102 # Make sure the proper call order is maintained, even if the test signals
2103 # a failure (as opposed to an error).
2104 def test_run_call_order__failure_in_test(self):
2105 events = []
2106 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002107
Georg Brandl15c5ce92007-03-07 09:09:40 +00002108 class Foo(unittest.TestCase):
2109 def setUp(self):
2110 events.append('setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002111
Georg Brandl15c5ce92007-03-07 09:09:40 +00002112 def test(self):
2113 events.append('test')
2114 self.fail('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002115
Georg Brandl15c5ce92007-03-07 09:09:40 +00002116 def tearDown(self):
2117 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002118
Georg Brandl15c5ce92007-03-07 09:09:40 +00002119 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2120 'stopTest']
2121 Foo('test').run(result)
2122 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002123
Georg Brandl15c5ce92007-03-07 09:09:40 +00002124 # "When a setUp() method is defined, the test runner will run that method
2125 # prior to each test. Likewise, if a tearDown() method is defined, the
2126 # test runner will invoke that method after each test. In the example,
2127 # setUp() was used to create a fresh sequence for each test."
2128 #
2129 # Make sure the proper call order is maintained, even if tearDown() raises
2130 # an exception.
2131 def test_run_call_order__error_in_tearDown(self):
2132 events = []
2133 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002134
Georg Brandl15c5ce92007-03-07 09:09:40 +00002135 class Foo(unittest.TestCase):
2136 def setUp(self):
2137 events.append('setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002138
Georg Brandl15c5ce92007-03-07 09:09:40 +00002139 def test(self):
2140 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002141
Georg Brandl15c5ce92007-03-07 09:09:40 +00002142 def tearDown(self):
2143 events.append('tearDown')
2144 raise RuntimeError('raised by Foo.tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002145
Georg Brandl15c5ce92007-03-07 09:09:40 +00002146 Foo('test').run(result)
2147 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2148 'stopTest']
2149 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002150
Georg Brandl15c5ce92007-03-07 09:09:40 +00002151 # "This class attribute gives the exception raised by the test() method.
2152 # If a test framework needs to use a specialized exception, possibly to
2153 # carry additional information, it must subclass this exception in
2154 # order to ``play fair'' with the framework. The initial value of this
2155 # attribute is AssertionError"
2156 def test_failureException__default(self):
2157 class Foo(unittest.TestCase):
2158 def test(self):
2159 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002160
Georg Brandl15c5ce92007-03-07 09:09:40 +00002161 self.failUnless(Foo('test').failureException is AssertionError)
Tim Petersea5962f2007-03-12 18:07:52 +00002162
Georg Brandl15c5ce92007-03-07 09:09:40 +00002163 # "This class attribute gives the exception raised by the test() method.
2164 # If a test framework needs to use a specialized exception, possibly to
2165 # carry additional information, it must subclass this exception in
2166 # order to ``play fair'' with the framework."
2167 #
2168 # Make sure TestCase.run() respects the designated failureException
2169 def test_failureException__subclassing__explicit_raise(self):
2170 events = []
2171 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002172
Georg Brandl15c5ce92007-03-07 09:09:40 +00002173 class Foo(unittest.TestCase):
2174 def test(self):
2175 raise RuntimeError()
Tim Petersea5962f2007-03-12 18:07:52 +00002176
Georg Brandl15c5ce92007-03-07 09:09:40 +00002177 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002178
Georg Brandl15c5ce92007-03-07 09:09:40 +00002179 self.failUnless(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002180
2181
Georg Brandl15c5ce92007-03-07 09:09:40 +00002182 Foo('test').run(result)
2183 expected = ['startTest', 'addFailure', 'stopTest']
2184 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002185
Georg Brandl15c5ce92007-03-07 09:09:40 +00002186 # "This class attribute gives the exception raised by the test() method.
2187 # If a test framework needs to use a specialized exception, possibly to
2188 # carry additional information, it must subclass this exception in
2189 # order to ``play fair'' with the framework."
2190 #
2191 # Make sure TestCase.run() respects the designated failureException
2192 def test_failureException__subclassing__implicit_raise(self):
2193 events = []
2194 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002195
Georg Brandl15c5ce92007-03-07 09:09:40 +00002196 class Foo(unittest.TestCase):
2197 def test(self):
2198 self.fail("foo")
Tim Petersea5962f2007-03-12 18:07:52 +00002199
Georg Brandl15c5ce92007-03-07 09:09:40 +00002200 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002201
Georg Brandl15c5ce92007-03-07 09:09:40 +00002202 self.failUnless(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002203
2204
Georg Brandl15c5ce92007-03-07 09:09:40 +00002205 Foo('test').run(result)
2206 expected = ['startTest', 'addFailure', 'stopTest']
2207 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002208
2209 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002210 def test_setUp(self):
2211 class Foo(unittest.TestCase):
2212 def runTest(self):
2213 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002214
Georg Brandl15c5ce92007-03-07 09:09:40 +00002215 # ... and nothing should happen
2216 Foo().setUp()
Tim Petersea5962f2007-03-12 18:07:52 +00002217
2218 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002219 def test_tearDown(self):
2220 class Foo(unittest.TestCase):
2221 def runTest(self):
2222 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002223
Georg Brandl15c5ce92007-03-07 09:09:40 +00002224 # ... and nothing should happen
2225 Foo().tearDown()
Tim Petersea5962f2007-03-12 18:07:52 +00002226
Georg Brandl15c5ce92007-03-07 09:09:40 +00002227 # "Return a string identifying the specific test case."
2228 #
2229 # Because of the vague nature of the docs, I'm not going to lock this
2230 # test down too much. Really all that can be asserted is that the id()
2231 # will be a string (either 8-byte or unicode -- again, because the docs
2232 # just say "string")
2233 def test_id(self):
2234 class Foo(unittest.TestCase):
2235 def runTest(self):
2236 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002237
Georg Brandl15c5ce92007-03-07 09:09:40 +00002238 self.failUnless(isinstance(Foo().id(), basestring))
Tim Petersea5962f2007-03-12 18:07:52 +00002239
Georg Brandl15c5ce92007-03-07 09:09:40 +00002240 # "If result is omitted or None, a temporary result object is created
Tim Petersea5962f2007-03-12 18:07:52 +00002241 # and used, but is not made available to the caller"
Georg Brandl15c5ce92007-03-07 09:09:40 +00002242 def test_run__uses_defaultTestResult(self):
2243 events = []
Tim Petersea5962f2007-03-12 18:07:52 +00002244
Georg Brandl15c5ce92007-03-07 09:09:40 +00002245 class Foo(unittest.TestCase):
2246 def test(self):
2247 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002248
Georg Brandl15c5ce92007-03-07 09:09:40 +00002249 def defaultTestResult(self):
2250 return LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002251
2252 # Make run() find a result object on its own
Georg Brandl15c5ce92007-03-07 09:09:40 +00002253 Foo('test').run()
Tim Petersea5962f2007-03-12 18:07:52 +00002254
Benjamin Peterson692428e2009-03-23 21:50:21 +00002255 expected = ['startTest', 'test', 'addSuccess', 'stopTest']
Georg Brandl15c5ce92007-03-07 09:09:40 +00002256 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002257
Gregory P. Smith28399852009-03-31 16:54:10 +00002258 def testShortDescriptionWithoutDocstring(self):
2259 self.assertEqual(
2260 self.shortDescription(),
2261 'testShortDescriptionWithoutDocstring (' + __name__ +
2262 '.Test_TestCase)')
2263
2264 def testShortDescriptionWithOneLineDocstring(self):
2265 """Tests shortDescription() for a method with a docstring."""
2266 self.assertEqual(
2267 self.shortDescription(),
2268 ('testShortDescriptionWithOneLineDocstring '
2269 '(' + __name__ + '.Test_TestCase)\n'
2270 'Tests shortDescription() for a method with a docstring.'))
2271
2272 def testShortDescriptionWithMultiLineDocstring(self):
2273 """Tests shortDescription() for a method with a longer docstring.
2274
2275 This method ensures that only the first line of a docstring is
2276 returned used in the short description, no matter how long the
2277 whole thing is.
2278 """
2279 self.assertEqual(
2280 self.shortDescription(),
2281 ('testShortDescriptionWithMultiLineDocstring '
2282 '(' + __name__ + '.Test_TestCase)\n'
2283 'Tests shortDescription() for a method with a longer '
2284 'docstring.'))
2285
2286
2287 def testAddTypeEqualityFunc(self):
2288 class SadSnake(object):
2289 """Dummy class for test_addTypeEqualityFunc."""
2290 s1, s2 = SadSnake(), SadSnake()
2291 self.assertFalse(s1 == s2)
2292 def AllSnakesCreatedEqual(a, b, msg=None):
2293 return type(a) == type(b) == SadSnake
2294 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2295 self.assertEqual(s1, s2)
2296 # No this doesn't clean up and remove the SadSnake equality func
2297 # from this TestCase instance but since its a local nothing else
2298 # will ever notice that.
2299
2300 def testAssertIn(self):
2301 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2302
2303 self.assertIn('a', 'abc')
2304 self.assertIn(2, [1, 2, 3])
2305 self.assertIn('monkey', animals)
2306
2307 self.assertNotIn('d', 'abc')
2308 self.assertNotIn(0, [1, 2, 3])
2309 self.assertNotIn('otter', animals)
2310
2311 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2312 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2313 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2314 animals)
2315
2316 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2317 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2318 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2319 animals)
2320
2321 def testAssertDictContainsSubset(self):
2322 self.assertDictContainsSubset({}, {})
2323 self.assertDictContainsSubset({}, {'a': 1})
2324 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2325 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2326 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2327
2328 self.assertRaises(unittest.TestCase.failureException,
2329 self.assertDictContainsSubset, {'a': 2}, {'a': 1},
2330 '.*Mismatched values:.*')
2331
2332 self.assertRaises(unittest.TestCase.failureException,
2333 self.assertDictContainsSubset, {'c': 1}, {'a': 1},
2334 '.*Missing:.*')
2335
2336 self.assertRaises(unittest.TestCase.failureException,
2337 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2338 {'a': 1}, '.*Missing:.*')
2339
2340 self.assertRaises(unittest.TestCase.failureException,
2341 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2342 {'a': 1}, '.*Missing:.*Mismatched values:.*')
2343
2344 def testAssertEqual(self):
2345 equal_pairs = [
2346 ((), ()),
2347 ({}, {}),
2348 ([], []),
2349 (set(), set()),
2350 (frozenset(), frozenset())]
2351 for a, b in equal_pairs:
2352 # This mess of try excepts is to test the assertEqual behavior
2353 # itself.
2354 try:
2355 self.assertEqual(a, b)
2356 except self.failureException:
2357 self.fail('assertEqual(%r, %r) failed' % (a, b))
2358 try:
2359 self.assertEqual(a, b, msg='foo')
2360 except self.failureException:
2361 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2362 try:
2363 self.assertEqual(a, b, 'foo')
2364 except self.failureException:
2365 self.fail('assertEqual(%r, %r) with third parameter failed' %
2366 (a, b))
2367
2368 unequal_pairs = [
2369 ((), []),
2370 ({}, set()),
2371 (set([4,1]), frozenset([4,2])),
2372 (frozenset([4,5]), set([2,3])),
2373 (set([3,4]), set([5,4]))]
2374 for a, b in unequal_pairs:
2375 self.assertRaises(self.failureException, self.assertEqual, a, b)
2376 self.assertRaises(self.failureException, self.assertEqual, a, b,
2377 'foo')
2378 self.assertRaises(self.failureException, self.assertEqual, a, b,
2379 msg='foo')
2380
2381 def testEquality(self):
2382 self.assertListEqual([], [])
2383 self.assertTupleEqual((), ())
2384 self.assertSequenceEqual([], ())
2385
2386 a = [0, 'a', []]
2387 b = []
2388 self.assertRaises(unittest.TestCase.failureException,
2389 self.assertListEqual, a, b)
2390 self.assertRaises(unittest.TestCase.failureException,
2391 self.assertListEqual, tuple(a), tuple(b))
2392 self.assertRaises(unittest.TestCase.failureException,
2393 self.assertSequenceEqual, a, tuple(b))
2394
2395 b.extend(a)
2396 self.assertListEqual(a, b)
2397 self.assertTupleEqual(tuple(a), tuple(b))
2398 self.assertSequenceEqual(a, tuple(b))
2399 self.assertSequenceEqual(tuple(a), b)
2400
2401 self.assertRaises(self.failureException, self.assertListEqual,
2402 a, tuple(b))
2403 self.assertRaises(self.failureException, self.assertTupleEqual,
2404 tuple(a), b)
2405 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2406 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2407 tuple(b))
2408 self.assertRaises(self.failureException, self.assertSequenceEqual,
2409 None, tuple(b))
2410 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2411 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2412 self.assertRaises(self.failureException, self.assertSequenceEqual,
2413 1, 1)
2414
2415 self.assertDictEqual({}, {})
2416
2417 c = { 'x': 1 }
2418 d = {}
2419 self.assertRaises(unittest.TestCase.failureException,
2420 self.assertDictEqual, c, d)
2421
2422 d.update(c)
2423 self.assertDictEqual(c, d)
2424
2425 d['x'] = 0
2426 self.assertRaises(unittest.TestCase.failureException,
2427 self.assertDictEqual, c, d, 'These are unequal')
2428
2429 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2430 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2431 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2432
2433 self.assertSameElements([1, 2, 3], [3, 2, 1])
2434 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2435 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2436 self.assertRaises(self.failureException, self.assertSameElements,
2437 [10], [10, 11])
2438 self.assertRaises(self.failureException, self.assertSameElements,
2439 [10, 11], [10])
2440
2441 # Test that sequences of unhashable objects can be tested for sameness:
2442 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
2443 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2444 self.assertRaises(self.failureException, self.assertSameElements,
2445 [[1]], [[2]])
2446
2447 def testAssertSetEqual(self):
2448 set1 = set()
2449 set2 = set()
2450 self.assertSetEqual(set1, set2)
2451
2452 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2453 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2454 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2455 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2456
2457 set1 = set(['a'])
2458 set2 = set()
2459 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2460
2461 set1 = set(['a'])
2462 set2 = set(['a'])
2463 self.assertSetEqual(set1, set2)
2464
2465 set1 = set(['a'])
2466 set2 = set(['a', 'b'])
2467 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2468
2469 set1 = set(['a'])
2470 set2 = frozenset(['a', 'b'])
2471 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2472
2473 set1 = set(['a', 'b'])
2474 set2 = frozenset(['a', 'b'])
2475 self.assertSetEqual(set1, set2)
2476
2477 set1 = set()
2478 set2 = "foo"
2479 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2480 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2481
2482 # make sure any string formatting is tuple-safe
2483 set1 = set([(0, 1), (2, 3)])
2484 set2 = set([(4, 5)])
2485 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2486
2487 def testInequality(self):
2488 # Try ints
2489 self.assertGreater(2, 1)
2490 self.assertGreaterEqual(2, 1)
2491 self.assertGreaterEqual(1, 1)
2492 self.assertLess(1, 2)
2493 self.assertLessEqual(1, 2)
2494 self.assertLessEqual(1, 1)
2495 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2496 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2497 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2498 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2499 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2500 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2501
2502 # Try Floats
2503 self.assertGreater(1.1, 1.0)
2504 self.assertGreaterEqual(1.1, 1.0)
2505 self.assertGreaterEqual(1.0, 1.0)
2506 self.assertLess(1.0, 1.1)
2507 self.assertLessEqual(1.0, 1.1)
2508 self.assertLessEqual(1.0, 1.0)
2509 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2510 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2511 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2512 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2513 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2514 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2515
2516 # Try Strings
2517 self.assertGreater('bug', 'ant')
2518 self.assertGreaterEqual('bug', 'ant')
2519 self.assertGreaterEqual('ant', 'ant')
2520 self.assertLess('ant', 'bug')
2521 self.assertLessEqual('ant', 'bug')
2522 self.assertLessEqual('ant', 'ant')
2523 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2524 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2525 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2526 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2527 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2528 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2529
2530 # Try Unicode
2531 self.assertGreater(u'bug', u'ant')
2532 self.assertGreaterEqual(u'bug', u'ant')
2533 self.assertGreaterEqual(u'ant', u'ant')
2534 self.assertLess(u'ant', u'bug')
2535 self.assertLessEqual(u'ant', u'bug')
2536 self.assertLessEqual(u'ant', u'ant')
2537 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug')
2538 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant')
2539 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2540 u'bug')
2541 self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant')
2542 self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant')
2543 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant')
2544
2545 # Try Mixed String/Unicode
2546 self.assertGreater('bug', u'ant')
2547 self.assertGreater(u'bug', 'ant')
2548 self.assertGreaterEqual('bug', u'ant')
2549 self.assertGreaterEqual(u'bug', 'ant')
2550 self.assertGreaterEqual('ant', u'ant')
2551 self.assertGreaterEqual(u'ant', 'ant')
2552 self.assertLess('ant', u'bug')
2553 self.assertLess(u'ant', 'bug')
2554 self.assertLessEqual('ant', u'bug')
2555 self.assertLessEqual(u'ant', 'bug')
2556 self.assertLessEqual('ant', u'ant')
2557 self.assertLessEqual(u'ant', 'ant')
2558 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug')
2559 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug')
2560 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant')
2561 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant')
2562 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant',
2563 u'bug')
2564 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2565 'bug')
2566 self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant')
2567 self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant')
2568 self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant')
2569 self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant')
2570 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant')
2571 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant')
2572
2573 def testAssertMultiLineEqual(self):
2574 sample_text = b"""\
2575http://www.python.org/doc/2.3/lib/module-unittest.html
2576test case
2577 A test case is the smallest unit of testing. [...]
2578"""
2579 revised_sample_text = b"""\
2580http://www.python.org/doc/2.4.1/lib/module-unittest.html
2581test case
2582 A test case is the smallest unit of testing. [...] You may provide your
2583 own implementation that does not subclass from TestCase, of course.
2584"""
2585 sample_text_error = b"""
2586- http://www.python.org/doc/2.3/lib/module-unittest.html
2587? ^
2588+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2589? ^^^
2590 test case
2591- A test case is the smallest unit of testing. [...]
2592+ A test case is the smallest unit of testing. [...] You may provide your
2593? +++++++++++++++++++++
2594+ own implementation that does not subclass from TestCase, of course.
2595"""
2596
2597 for type_changer in (lambda x: x, lambda x: x.decode('utf8')):
2598 try:
2599 self.assertMultiLineEqual(type_changer(sample_text),
2600 type_changer(revised_sample_text))
2601 except self.failureException, e:
2602 # no fair testing ourself with ourself, use assertEqual..
2603 self.assertEqual(sample_text_error, str(e).encode('utf8'))
2604
2605 def testAssertIsNone(self):
2606 self.assertIsNone(None)
2607 self.assertRaises(self.failureException, self.assertIsNone, False)
2608 self.assertIsNotNone('DjZoPloGears on Rails')
2609 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2610
2611 def testAssertRegexpMatches(self):
2612 self.assertRegexpMatches('asdfabasdf', r'ab+')
2613 self.assertRaises(self.failureException, self.assertRegexpMatches,
2614 'saaas', r'aaaa')
2615
2616 def testAssertRaisesRegexp(self):
2617 class ExceptionMock(Exception):
2618 pass
2619
2620 def Stub():
2621 raise ExceptionMock('We expect')
2622
2623 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2624 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2625 self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
2626
2627 def testAssertNotRaisesRegexp(self):
2628 self.assertRaisesRegexp(
2629 self.failureException, '^Exception not raised$',
2630 self.assertRaisesRegexp, Exception, re.compile('x'),
2631 lambda: None)
2632 self.assertRaisesRegexp(
2633 self.failureException, '^Exception not raised$',
2634 self.assertRaisesRegexp, Exception, 'x',
2635 lambda: None)
2636 self.assertRaisesRegexp(
2637 self.failureException, '^Exception not raised$',
2638 self.assertRaisesRegexp, Exception, u'x',
2639 lambda: None)
2640
2641 def testAssertRaisesRegexpMismatch(self):
2642 def Stub():
2643 raise Exception('Unexpected')
2644
2645 self.assertRaisesRegexp(
2646 self.failureException,
2647 r'"\^Expected\$" does not match "Unexpected"',
2648 self.assertRaisesRegexp, Exception, '^Expected$',
2649 Stub)
2650 self.assertRaisesRegexp(
2651 self.failureException,
2652 r'"\^Expected\$" does not match "Unexpected"',
2653 self.assertRaisesRegexp, Exception, u'^Expected$',
2654 Stub)
2655 self.assertRaisesRegexp(
2656 self.failureException,
2657 r'"\^Expected\$" does not match "Unexpected"',
2658 self.assertRaisesRegexp, Exception,
2659 re.compile('^Expected$'), Stub)
2660
Benjamin Peterson692428e2009-03-23 21:50:21 +00002661
2662class Test_TestSkipping(TestCase):
2663
2664 def test_skipping(self):
2665 class Foo(unittest.TestCase):
2666 def test_skip_me(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002667 self.skipTest("skip")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002668 events = []
2669 result = LoggingResult(events)
2670 test = Foo("test_skip_me")
2671 test.run(result)
2672 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2673 self.assertEqual(result.skipped, [(test, "skip")])
2674
2675 # Try letting setUp skip the test now.
2676 class Foo(unittest.TestCase):
2677 def setUp(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002678 self.skipTest("testing")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002679 def test_nothing(self): pass
2680 events = []
2681 result = LoggingResult(events)
2682 test = Foo("test_nothing")
2683 test.run(result)
2684 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2685 self.assertEqual(result.skipped, [(test, "testing")])
2686 self.assertEqual(result.testsRun, 1)
2687
2688 def test_skipping_decorators(self):
2689 op_table = ((unittest.skipUnless, False, True),
2690 (unittest.skipIf, True, False))
2691 for deco, do_skip, dont_skip in op_table:
2692 class Foo(unittest.TestCase):
2693 @deco(do_skip, "testing")
2694 def test_skip(self): pass
2695
2696 @deco(dont_skip, "testing")
2697 def test_dont_skip(self): pass
2698 test_do_skip = Foo("test_skip")
2699 test_dont_skip = Foo("test_dont_skip")
2700 suite = unittest.ClassTestSuite([test_do_skip, test_dont_skip], Foo)
2701 events = []
2702 result = LoggingResult(events)
2703 suite.run(result)
2704 self.assertEqual(len(result.skipped), 1)
2705 expected = ['startTest', 'addSkip', 'stopTest',
2706 'startTest', 'addSuccess', 'stopTest']
2707 self.assertEqual(events, expected)
2708 self.assertEqual(result.testsRun, 2)
2709 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
2710 self.assertTrue(result.wasSuccessful())
2711
2712 def test_skip_class(self):
2713 @unittest.skip("testing")
2714 class Foo(unittest.TestCase):
2715 def test_1(self):
2716 record.append(1)
2717 record = []
2718 result = unittest.TestResult()
2719 suite = unittest.ClassTestSuite([Foo("test_1")], Foo)
2720 suite.run(result)
2721 self.assertEqual(result.skipped, [(suite, "testing")])
2722 self.assertEqual(record, [])
2723
2724 def test_expected_failure(self):
2725 class Foo(unittest.TestCase):
2726 @unittest.expectedFailure
2727 def test_die(self):
2728 self.fail("help me!")
2729 events = []
2730 result = LoggingResult(events)
2731 test = Foo("test_die")
2732 test.run(result)
2733 self.assertEqual(events,
2734 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00002735 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00002736 self.assertTrue(result.wasSuccessful())
2737
2738 def test_unexpected_success(self):
2739 class Foo(unittest.TestCase):
2740 @unittest.expectedFailure
2741 def test_die(self):
2742 pass
2743 events = []
2744 result = LoggingResult(events)
2745 test = Foo("test_die")
2746 test.run(result)
2747 self.assertEqual(events,
2748 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
2749 self.assertFalse(result.failures)
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00002750 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002751 self.assertTrue(result.wasSuccessful())
2752
2753
2754
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002755class Test_Assertions(TestCase):
2756 def test_AlmostEqual(self):
2757 self.failUnlessAlmostEqual(1.00000001, 1.0)
2758 self.failIfAlmostEqual(1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00002759 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002760 self.failUnlessAlmostEqual, 1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00002761 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002762 self.failIfAlmostEqual, 1.00000001, 1.0)
2763
2764 self.failUnlessAlmostEqual(1.1, 1.0, places=0)
Gregory P. Smith28399852009-03-31 16:54:10 +00002765 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002766 self.failUnlessAlmostEqual, 1.1, 1.0, places=1)
2767
2768 self.failUnlessAlmostEqual(0, .1+.1j, places=0)
2769 self.failIfAlmostEqual(0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00002770 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002771 self.failUnlessAlmostEqual, 0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00002772 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002773 self.failIfAlmostEqual, 0, .1+.1j, places=0)
2774
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00002775 def test_assertRaises(self):
2776 def _raise(e):
2777 raise e
2778 self.assertRaises(KeyError, _raise, KeyError)
2779 self.assertRaises(KeyError, _raise, KeyError("key"))
2780 try:
2781 self.assertRaises(KeyError, lambda: None)
Gregory P. Smith28399852009-03-31 16:54:10 +00002782 except self.failureException as e:
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00002783 self.assert_("KeyError not raised" in e, str(e))
2784 else:
2785 self.fail("assertRaises() didn't fail")
2786 try:
2787 self.assertRaises(KeyError, _raise, ValueError)
2788 except ValueError:
2789 pass
2790 else:
2791 self.fail("assertRaises() didn't let exception pass through")
2792 with self.assertRaises(KeyError):
2793 raise KeyError
2794 with self.assertRaises(KeyError):
2795 raise KeyError("key")
2796 try:
2797 with self.assertRaises(KeyError):
2798 pass
Gregory P. Smith28399852009-03-31 16:54:10 +00002799 except self.failureException as e:
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00002800 self.assert_("KeyError not raised" in e, str(e))
2801 else:
2802 self.fail("assertRaises() didn't fail")
2803 try:
2804 with self.assertRaises(KeyError):
2805 raise ValueError
2806 except ValueError:
2807 pass
2808 else:
2809 self.fail("assertRaises() didn't let exception pass through")
2810
2811
Jim Fultonfafd8742004-08-28 15:22:12 +00002812######################################################################
2813## Main
2814######################################################################
2815
2816def test_main():
Georg Brandl15c5ce92007-03-07 09:09:40 +00002817 test_support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002818 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Benjamin Peterson692428e2009-03-23 21:50:21 +00002819 Test_TestSkipping, Test_Assertions)
Jim Fultonfafd8742004-08-28 15:22:12 +00002820
Georg Brandl15c5ce92007-03-07 09:09:40 +00002821if __name__ == "__main__":
Tim Petersea5962f2007-03-12 18:07:52 +00002822 test_main()