blob: f28b1af988b569c7a58e9a68ee62a3b69a8a2209 [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
Michael Foorde2942d02009-04-02 05:51:54 +000014from copy import deepcopy
Jim Fultonfafd8742004-08-28 15:22:12 +000015
Georg Brandl15c5ce92007-03-07 09:09:40 +000016### Support code
17################################################################
Jim Fultonfafd8742004-08-28 15:22:12 +000018
Georg Brandl15c5ce92007-03-07 09:09:40 +000019class LoggingResult(unittest.TestResult):
20 def __init__(self, log):
21 self._events = log
22 super(LoggingResult, self).__init__()
23
24 def startTest(self, test):
25 self._events.append('startTest')
26 super(LoggingResult, self).startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +000027
Georg Brandl15c5ce92007-03-07 09:09:40 +000028 def stopTest(self, test):
29 self._events.append('stopTest')
30 super(LoggingResult, self).stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +000031
Georg Brandl15c5ce92007-03-07 09:09:40 +000032 def addFailure(self, *args):
33 self._events.append('addFailure')
34 super(LoggingResult, self).addFailure(*args)
Tim Petersea5962f2007-03-12 18:07:52 +000035
Benjamin Peterson692428e2009-03-23 21:50:21 +000036 def addSuccess(self, *args):
37 self._events.append('addSuccess')
38 super(LoggingResult, self).addSuccess(*args)
39
Georg Brandl15c5ce92007-03-07 09:09:40 +000040 def addError(self, *args):
41 self._events.append('addError')
42 super(LoggingResult, self).addError(*args)
43
Benjamin Peterson692428e2009-03-23 21:50:21 +000044 def addSkip(self, *args):
45 self._events.append('addSkip')
46 super(LoggingResult, self).addSkip(*args)
47
48 def addExpectedFailure(self, *args):
49 self._events.append('addExpectedFailure')
50 super(LoggingResult, self).addExpectedFailure(*args)
51
52 def addUnexpectedSuccess(self, *args):
53 self._events.append('addUnexpectedSuccess')
54 super(LoggingResult, self).addUnexpectedSuccess(*args)
55
56
Georg Brandl15c5ce92007-03-07 09:09:40 +000057class TestEquality(object):
Michael Foord345b2fe2009-04-02 03:20:38 +000058 """Used as a mixin for TestCase"""
59
Tim Petersea5962f2007-03-12 18:07:52 +000060 # Check for a valid __eq__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000061 def test_eq(self):
62 for obj_1, obj_2 in self.eq_pairs:
63 self.assertEqual(obj_1, obj_2)
64 self.assertEqual(obj_2, obj_1)
Tim Petersea5962f2007-03-12 18:07:52 +000065
66 # Check for a valid __ne__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000067 def test_ne(self):
68 for obj_1, obj_2 in self.ne_pairs:
69 self.failIfEqual(obj_1, obj_2)
70 self.failIfEqual(obj_2, obj_1)
Tim Petersea5962f2007-03-12 18:07:52 +000071
Georg Brandl15c5ce92007-03-07 09:09:40 +000072class TestHashing(object):
Michael Foord345b2fe2009-04-02 03:20:38 +000073 """Used as a mixin for TestCase"""
74
Tim Petersea5962f2007-03-12 18:07:52 +000075 # Check for a valid __hash__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000076 def test_hash(self):
77 for obj_1, obj_2 in self.eq_pairs:
78 try:
Gregory P. Smith28399852009-03-31 16:54:10 +000079 if not hash(obj_1) == hash(obj_2):
80 self.fail("%r and %r do not hash equal" % (obj_1, obj_2))
Georg Brandl15c5ce92007-03-07 09:09:40 +000081 except KeyboardInterrupt:
82 raise
Georg Brandl15c5ce92007-03-07 09:09:40 +000083 except Exception, e:
Gregory P. Smith28399852009-03-31 16:54:10 +000084 self.fail("Problem hashing %r and %r: %s" % (obj_1, obj_2, e))
Tim Petersea5962f2007-03-12 18:07:52 +000085
Georg Brandl15c5ce92007-03-07 09:09:40 +000086 for obj_1, obj_2 in self.ne_pairs:
87 try:
Gregory P. Smith28399852009-03-31 16:54:10 +000088 if hash(obj_1) == hash(obj_2):
89 self.fail("%s and %s hash equal, but shouldn't" %
90 (obj_1, obj_2))
Georg Brandl15c5ce92007-03-07 09:09:40 +000091 except KeyboardInterrupt:
92 raise
Georg Brandl15c5ce92007-03-07 09:09:40 +000093 except Exception, e:
94 self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e))
Tim Petersea5962f2007-03-12 18:07:52 +000095
Georg Brandl15c5ce92007-03-07 09:09:40 +000096
Benjamin Peterson692428e2009-03-23 21:50:21 +000097# List subclass we can add attributes to.
98class MyClassSuite(list):
99
100 def __init__(self, tests, klass):
101 super(MyClassSuite, self).__init__(tests)
102
103
Georg Brandl15c5ce92007-03-07 09:09:40 +0000104################################################################
105### /Support code
106
107class Test_TestLoader(TestCase):
108
109 ### Tests for TestLoader.loadTestsFromTestCase
110 ################################################################
111
112 # "Return a suite of all tests cases contained in the TestCase-derived
113 # class testCaseClass"
114 def test_loadTestsFromTestCase(self):
115 class Foo(unittest.TestCase):
116 def test_1(self): pass
117 def test_2(self): pass
118 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000119
Georg Brandl15c5ce92007-03-07 09:09:40 +0000120 tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +0000121
Georg Brandl15c5ce92007-03-07 09:09:40 +0000122 loader = unittest.TestLoader()
123 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +0000124
Georg Brandl15c5ce92007-03-07 09:09:40 +0000125 # "Return a suite of all tests cases contained in the TestCase-derived
126 # class testCaseClass"
127 #
Tim Petersea5962f2007-03-12 18:07:52 +0000128 # Make sure it does the right thing even if no tests were found
Georg Brandl15c5ce92007-03-07 09:09:40 +0000129 def test_loadTestsFromTestCase__no_matches(self):
130 class Foo(unittest.TestCase):
131 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000132
Georg Brandl15c5ce92007-03-07 09:09:40 +0000133 empty_suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +0000134
Georg Brandl15c5ce92007-03-07 09:09:40 +0000135 loader = unittest.TestLoader()
136 self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite)
Tim Petersea5962f2007-03-12 18:07:52 +0000137
Georg Brandl15c5ce92007-03-07 09:09:40 +0000138 # "Return a suite of all tests cases contained in the TestCase-derived
139 # class testCaseClass"
140 #
141 # What happens if loadTestsFromTestCase() is given an object
142 # that isn't a subclass of TestCase? Specifically, what happens
143 # if testCaseClass is a subclass of TestSuite?
144 #
145 # This is checked for specifically in the code, so we better add a
146 # test for it.
147 def test_loadTestsFromTestCase__TestSuite_subclass(self):
148 class NotATestCase(unittest.TestSuite):
149 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000150
Georg Brandl15c5ce92007-03-07 09:09:40 +0000151 loader = unittest.TestLoader()
152 try:
153 loader.loadTestsFromTestCase(NotATestCase)
154 except TypeError:
155 pass
156 else:
157 self.fail('Should raise TypeError')
Tim Petersea5962f2007-03-12 18:07:52 +0000158
Georg Brandl15c5ce92007-03-07 09:09:40 +0000159 # "Return a suite of all tests cases contained in the TestCase-derived
160 # class testCaseClass"
161 #
162 # Make sure loadTestsFromTestCase() picks up the default test method
163 # name (as specified by TestCase), even though the method name does
164 # not match the default TestLoader.testMethodPrefix string
165 def test_loadTestsFromTestCase__default_method_name(self):
166 class Foo(unittest.TestCase):
167 def runTest(self):
168 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000169
Georg Brandl15c5ce92007-03-07 09:09:40 +0000170 loader = unittest.TestLoader()
171 # This has to be false for the test to succeed
172 self.failIf('runTest'.startswith(loader.testMethodPrefix))
Tim Petersea5962f2007-03-12 18:07:52 +0000173
Georg Brandl15c5ce92007-03-07 09:09:40 +0000174 suite = loader.loadTestsFromTestCase(Foo)
175 self.failUnless(isinstance(suite, loader.suiteClass))
176 self.assertEqual(list(suite), [Foo('runTest')])
177
178 ################################################################
179 ### /Tests for TestLoader.loadTestsFromTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000180
Georg Brandl15c5ce92007-03-07 09:09:40 +0000181 ### Tests for TestLoader.loadTestsFromModule
182 ################################################################
183
184 # "This method searches `module` for classes derived from TestCase"
185 def test_loadTestsFromModule__TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000186 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000187 class MyTestCase(unittest.TestCase):
188 def test(self):
189 pass
190 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000191
Georg Brandl15c5ce92007-03-07 09:09:40 +0000192 loader = unittest.TestLoader()
193 suite = loader.loadTestsFromModule(m)
194 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000195
Georg Brandl15c5ce92007-03-07 09:09:40 +0000196 expected = [loader.suiteClass([MyTestCase('test')])]
197 self.assertEqual(list(suite), expected)
Tim Petersea5962f2007-03-12 18:07:52 +0000198
Georg Brandl15c5ce92007-03-07 09:09:40 +0000199 # "This method searches `module` for classes derived from TestCase"
Tim Petersea5962f2007-03-12 18:07:52 +0000200 #
Georg Brandl15c5ce92007-03-07 09:09:40 +0000201 # What happens if no tests are found (no TestCase instances)?
202 def test_loadTestsFromModule__no_TestCase_instances(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000203 m = types.ModuleType('m')
Tim Petersea5962f2007-03-12 18:07:52 +0000204
Georg Brandl15c5ce92007-03-07 09:09:40 +0000205 loader = unittest.TestLoader()
206 suite = loader.loadTestsFromModule(m)
207 self.failUnless(isinstance(suite, loader.suiteClass))
208 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000209
Georg Brandl15c5ce92007-03-07 09:09:40 +0000210 # "This method searches `module` for classes derived from TestCase"
211 #
Tim Petersea5962f2007-03-12 18:07:52 +0000212 # What happens if no tests are found (TestCases instances, but no tests)?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000213 def test_loadTestsFromModule__no_TestCase_tests(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000214 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000215 class MyTestCase(unittest.TestCase):
216 pass
217 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000218
Georg Brandl15c5ce92007-03-07 09:09:40 +0000219 loader = unittest.TestLoader()
220 suite = loader.loadTestsFromModule(m)
221 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000222
Georg Brandl15c5ce92007-03-07 09:09:40 +0000223 self.assertEqual(list(suite), [loader.suiteClass()])
Tim Petersea5962f2007-03-12 18:07:52 +0000224
Georg Brandl15c5ce92007-03-07 09:09:40 +0000225 # "This method searches `module` for classes derived from TestCase"s
226 #
227 # What happens if loadTestsFromModule() is given something other
228 # than a module?
229 #
230 # XXX Currently, it succeeds anyway. This flexibility
231 # should either be documented or loadTestsFromModule() should
232 # raise a TypeError
233 #
234 # XXX Certain people are using this behaviour. We'll add a test for it
235 def test_loadTestsFromModule__not_a_module(self):
236 class MyTestCase(unittest.TestCase):
237 def test(self):
238 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000239
Georg Brandl15c5ce92007-03-07 09:09:40 +0000240 class NotAModule(object):
241 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000242
Georg Brandl15c5ce92007-03-07 09:09:40 +0000243 loader = unittest.TestLoader()
244 suite = loader.loadTestsFromModule(NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000245
Georg Brandl15c5ce92007-03-07 09:09:40 +0000246 reference = [unittest.TestSuite([MyTestCase('test')])]
247 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000248
Georg Brandl15c5ce92007-03-07 09:09:40 +0000249 ################################################################
250 ### /Tests for TestLoader.loadTestsFromModule()
Tim Petersea5962f2007-03-12 18:07:52 +0000251
Georg Brandl15c5ce92007-03-07 09:09:40 +0000252 ### Tests for TestLoader.loadTestsFromName()
253 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000254
Georg Brandl15c5ce92007-03-07 09:09:40 +0000255 # "The specifier name is a ``dotted name'' that may resolve either to
256 # a module, a test case class, a TestSuite instance, a test method
257 # within a test case class, or a callable object which returns a
258 # TestCase or TestSuite instance."
259 #
260 # Is ValueError raised in response to an empty name?
261 def test_loadTestsFromName__empty_name(self):
262 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000263
Georg Brandl15c5ce92007-03-07 09:09:40 +0000264 try:
265 loader.loadTestsFromName('')
266 except ValueError, e:
267 self.assertEqual(str(e), "Empty module name")
268 else:
269 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000270
Georg Brandl15c5ce92007-03-07 09:09:40 +0000271 # "The specifier name is a ``dotted name'' that may resolve either to
272 # a module, a test case class, a TestSuite instance, a test method
273 # within a test case class, or a callable object which returns a
274 # TestCase or TestSuite instance."
275 #
Tim Petersea5962f2007-03-12 18:07:52 +0000276 # What happens when the name contains invalid characters?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000277 def test_loadTestsFromName__malformed_name(self):
278 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000279
Georg Brandl15c5ce92007-03-07 09:09:40 +0000280 # XXX Should this raise ValueError or ImportError?
281 try:
282 loader.loadTestsFromName('abc () //')
283 except ValueError:
284 pass
285 except ImportError:
286 pass
287 else:
288 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000289
Georg Brandl15c5ce92007-03-07 09:09:40 +0000290 # "The specifier name is a ``dotted name'' that may resolve ... to a
291 # module"
292 #
Tim Petersea5962f2007-03-12 18:07:52 +0000293 # What happens when a module by that name can't be found?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000294 def test_loadTestsFromName__unknown_module_name(self):
295 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000296
Georg Brandl15c5ce92007-03-07 09:09:40 +0000297 try:
298 loader.loadTestsFromName('sdasfasfasdf')
299 except ImportError, e:
300 self.assertEqual(str(e), "No module named sdasfasfasdf")
301 else:
302 self.fail("TestLoader.loadTestsFromName failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000303
Georg Brandl15c5ce92007-03-07 09:09:40 +0000304 # "The specifier name is a ``dotted name'' that may resolve either to
305 # a module, a test case class, a TestSuite instance, a test method
306 # within a test case class, or a callable object which returns a
307 # TestCase or TestSuite instance."
308 #
Tim Petersea5962f2007-03-12 18:07:52 +0000309 # What happens when the module is found, but the attribute can't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000310 def test_loadTestsFromName__unknown_attr_name(self):
311 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000312
Georg Brandl15c5ce92007-03-07 09:09:40 +0000313 try:
314 loader.loadTestsFromName('unittest.sdasfasfasdf')
315 except AttributeError, e:
316 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
317 else:
318 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000319
Georg Brandl15c5ce92007-03-07 09:09:40 +0000320 # "The specifier name is a ``dotted name'' that may resolve either to
321 # a module, a test case class, a TestSuite instance, a test method
322 # within a test case class, or a callable object which returns a
323 # TestCase or TestSuite instance."
324 #
325 # What happens when we provide the module, but the attribute can't be
326 # found?
327 def test_loadTestsFromName__relative_unknown_name(self):
328 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000329
Georg Brandl15c5ce92007-03-07 09:09:40 +0000330 try:
331 loader.loadTestsFromName('sdasfasfasdf', unittest)
332 except AttributeError, e:
333 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
334 else:
335 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000336
Georg Brandl15c5ce92007-03-07 09:09:40 +0000337 # "The specifier name is a ``dotted name'' that may resolve either to
338 # a module, a test case class, a TestSuite instance, a test method
339 # within a test case class, or a callable object which returns a
340 # TestCase or TestSuite instance."
341 # ...
342 # "The method optionally resolves name relative to the given module"
343 #
344 # Does loadTestsFromName raise ValueError when passed an empty
345 # name relative to a provided module?
346 #
347 # XXX Should probably raise a ValueError instead of an AttributeError
348 def test_loadTestsFromName__relative_empty_name(self):
349 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000350
Georg Brandl15c5ce92007-03-07 09:09:40 +0000351 try:
352 loader.loadTestsFromName('', unittest)
353 except AttributeError, e:
354 pass
355 else:
356 self.fail("Failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000357
Georg Brandl15c5ce92007-03-07 09:09:40 +0000358 # "The specifier name is a ``dotted name'' that may resolve either to
359 # a module, a test case class, a TestSuite instance, a test method
360 # within a test case class, or a callable object which returns a
361 # TestCase or TestSuite instance."
362 # ...
363 # "The method optionally resolves name relative to the given module"
364 #
365 # What happens when an impossible name is given, relative to the provided
366 # `module`?
367 def test_loadTestsFromName__relative_malformed_name(self):
368 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000369
Georg Brandl15c5ce92007-03-07 09:09:40 +0000370 # XXX Should this raise AttributeError or ValueError?
371 try:
372 loader.loadTestsFromName('abc () //', unittest)
373 except ValueError:
374 pass
375 except AttributeError:
376 pass
377 else:
378 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
379
380 # "The method optionally resolves name relative to the given module"
381 #
382 # Does loadTestsFromName raise TypeError when the `module` argument
383 # isn't a module object?
384 #
385 # XXX Accepts the not-a-module object, ignorning the object's type
386 # This should raise an exception or the method name should be changed
387 #
388 # XXX Some people are relying on this, so keep it for now
389 def test_loadTestsFromName__relative_not_a_module(self):
390 class MyTestCase(unittest.TestCase):
391 def test(self):
392 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000393
Georg Brandl15c5ce92007-03-07 09:09:40 +0000394 class NotAModule(object):
395 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000396
Georg Brandl15c5ce92007-03-07 09:09:40 +0000397 loader = unittest.TestLoader()
398 suite = loader.loadTestsFromName('test_2', NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000399
Georg Brandl15c5ce92007-03-07 09:09:40 +0000400 reference = [MyTestCase('test')]
401 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000402
Georg Brandl15c5ce92007-03-07 09:09:40 +0000403 # "The specifier name is a ``dotted name'' that may resolve either to
404 # a module, a test case class, a TestSuite instance, a test method
405 # within a test case class, or a callable object which returns a
406 # TestCase or TestSuite instance."
407 #
408 # Does it raise an exception if the name resolves to an invalid
409 # object?
410 def test_loadTestsFromName__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000411 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000412 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000413
Georg Brandl15c5ce92007-03-07 09:09:40 +0000414 loader = unittest.TestLoader()
415 try:
416 loader.loadTestsFromName('testcase_1', m)
417 except TypeError:
418 pass
419 else:
420 self.fail("Should have raised TypeError")
421
422 # "The specifier name is a ``dotted name'' that may
423 # resolve either to ... a test case class"
424 def test_loadTestsFromName__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000425 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000426 class MyTestCase(unittest.TestCase):
427 def test(self):
428 pass
429 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000430
Georg Brandl15c5ce92007-03-07 09:09:40 +0000431 loader = unittest.TestLoader()
432 suite = loader.loadTestsFromName('testcase_1', m)
433 self.failUnless(isinstance(suite, loader.suiteClass))
434 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000435
Georg Brandl15c5ce92007-03-07 09:09:40 +0000436 # "The specifier name is a ``dotted name'' that may resolve either to
437 # a module, a test case class, a TestSuite instance, a test method
438 # within a test case class, or a callable object which returns a
439 # TestCase or TestSuite instance."
440 def test_loadTestsFromName__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000441 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000442 class MyTestCase(unittest.TestCase):
443 def test(self):
444 pass
445 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000446
Georg Brandl15c5ce92007-03-07 09:09:40 +0000447 loader = unittest.TestLoader()
448 suite = loader.loadTestsFromName('testsuite', m)
449 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000450
Georg Brandl15c5ce92007-03-07 09:09:40 +0000451 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000452
Georg Brandl15c5ce92007-03-07 09:09:40 +0000453 # "The specifier name is a ``dotted name'' that may resolve ... to
454 # ... a test method within a test case class"
455 def test_loadTestsFromName__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000456 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000457 class MyTestCase(unittest.TestCase):
458 def test(self):
459 pass
460 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000461
Georg Brandl15c5ce92007-03-07 09:09:40 +0000462 loader = unittest.TestLoader()
463 suite = loader.loadTestsFromName('testcase_1.test', m)
464 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000465
Georg Brandl15c5ce92007-03-07 09:09:40 +0000466 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000467
Georg Brandl15c5ce92007-03-07 09:09:40 +0000468 # "The specifier name is a ``dotted name'' that may resolve either to
469 # a module, a test case class, a TestSuite instance, a test method
470 # within a test case class, or a callable object which returns a
471 # TestCase or TestSuite instance."
472 #
473 # Does loadTestsFromName() raise the proper exception when trying to
474 # resolve "a test method within a test case class" that doesn't exist
475 # for the given name (relative to a provided module)?
476 def test_loadTestsFromName__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000477 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000478 class MyTestCase(unittest.TestCase):
479 def test(self):
480 pass
481 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000482
Georg Brandl15c5ce92007-03-07 09:09:40 +0000483 loader = unittest.TestLoader()
484 try:
485 loader.loadTestsFromName('testcase_1.testfoo', m)
486 except AttributeError, e:
487 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
488 else:
489 self.fail("Failed to raise AttributeError")
490
491 # "The specifier name is a ``dotted name'' that may resolve ... to
492 # ... a callable object which returns a ... TestSuite instance"
493 def test_loadTestsFromName__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000494 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000495 testcase_1 = unittest.FunctionTestCase(lambda: None)
496 testcase_2 = unittest.FunctionTestCase(lambda: None)
497 def return_TestSuite():
498 return unittest.TestSuite([testcase_1, testcase_2])
499 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000500
Georg Brandl15c5ce92007-03-07 09:09:40 +0000501 loader = unittest.TestLoader()
502 suite = loader.loadTestsFromName('return_TestSuite', m)
503 self.failUnless(isinstance(suite, loader.suiteClass))
504 self.assertEqual(list(suite), [testcase_1, testcase_2])
Tim Petersea5962f2007-03-12 18:07:52 +0000505
Georg Brandl15c5ce92007-03-07 09:09:40 +0000506 # "The specifier name is a ``dotted name'' that may resolve ... to
507 # ... a callable object which returns a TestCase ... instance"
508 def test_loadTestsFromName__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000509 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000510 testcase_1 = unittest.FunctionTestCase(lambda: None)
511 def return_TestCase():
512 return testcase_1
513 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000514
Georg Brandl15c5ce92007-03-07 09:09:40 +0000515 loader = unittest.TestLoader()
516 suite = loader.loadTestsFromName('return_TestCase', m)
517 self.failUnless(isinstance(suite, loader.suiteClass))
518 self.assertEqual(list(suite), [testcase_1])
Tim Petersea5962f2007-03-12 18:07:52 +0000519
Georg Brandl15c5ce92007-03-07 09:09:40 +0000520 # "The specifier name is a ``dotted name'' that may resolve ... to
521 # ... a callable object which returns a TestCase or TestSuite instance"
522 #
523 # What happens if the callable returns something else?
524 def test_loadTestsFromName__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000525 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000526 def return_wrong():
527 return 6
528 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000529
Georg Brandl15c5ce92007-03-07 09:09:40 +0000530 loader = unittest.TestLoader()
531 try:
532 suite = loader.loadTestsFromName('return_wrong', m)
533 except TypeError:
534 pass
535 else:
536 self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000537
Georg Brandl15c5ce92007-03-07 09:09:40 +0000538 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +0000539 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +0000540 def test_loadTestsFromName__module_not_loaded(self):
541 # We're going to try to load this module as a side-effect, so it
542 # better not be loaded before we try.
543 #
544 # Why pick audioop? Google shows it isn't used very often, so there's
545 # a good chance that it won't be imported when this test is run
546 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +0000547
Georg Brandl15c5ce92007-03-07 09:09:40 +0000548 import sys
549 if module_name in sys.modules:
550 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000551
Georg Brandl15c5ce92007-03-07 09:09:40 +0000552 loader = unittest.TestLoader()
553 try:
554 suite = loader.loadTestsFromName(module_name)
555
556 self.failUnless(isinstance(suite, loader.suiteClass))
557 self.assertEqual(list(suite), [])
558
559 # audioop should now be loaded, thanks to loadTestsFromName()
560 self.failUnless(module_name in sys.modules)
561 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000562 if module_name in sys.modules:
563 del sys.modules[module_name]
Georg Brandl15c5ce92007-03-07 09:09:40 +0000564
565 ################################################################
566 ### Tests for TestLoader.loadTestsFromName()
567
568 ### Tests for TestLoader.loadTestsFromNames()
569 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000570
Georg Brandl15c5ce92007-03-07 09:09:40 +0000571 # "Similar to loadTestsFromName(), but takes a sequence of names rather
572 # than a single name."
573 #
574 # What happens if that sequence of names is empty?
575 def test_loadTestsFromNames__empty_name_list(self):
576 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000577
Georg Brandl15c5ce92007-03-07 09:09:40 +0000578 suite = loader.loadTestsFromNames([])
579 self.failUnless(isinstance(suite, loader.suiteClass))
580 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000581
Georg Brandl15c5ce92007-03-07 09:09:40 +0000582 # "Similar to loadTestsFromName(), but takes a sequence of names rather
583 # than a single name."
584 # ...
585 # "The method optionally resolves name relative to the given module"
586 #
587 # What happens if that sequence of names is empty?
588 #
589 # XXX Should this raise a ValueError or just return an empty TestSuite?
590 def test_loadTestsFromNames__relative_empty_name_list(self):
591 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000592
Georg Brandl15c5ce92007-03-07 09:09:40 +0000593 suite = loader.loadTestsFromNames([], unittest)
594 self.failUnless(isinstance(suite, loader.suiteClass))
595 self.assertEqual(list(suite), [])
596
597 # "The specifier name is a ``dotted name'' that may resolve either to
598 # a module, a test case class, a TestSuite instance, a test method
599 # within a test case class, or a callable object which returns a
600 # TestCase or TestSuite instance."
601 #
602 # Is ValueError raised in response to an empty name?
603 def test_loadTestsFromNames__empty_name(self):
604 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000605
Georg Brandl15c5ce92007-03-07 09:09:40 +0000606 try:
607 loader.loadTestsFromNames([''])
608 except ValueError, e:
609 self.assertEqual(str(e), "Empty module name")
610 else:
611 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000612
Georg Brandl15c5ce92007-03-07 09:09:40 +0000613 # "The specifier name is a ``dotted name'' that may resolve either to
614 # a module, a test case class, a TestSuite instance, a test method
615 # within a test case class, or a callable object which returns a
616 # TestCase or TestSuite instance."
617 #
Tim Petersea5962f2007-03-12 18:07:52 +0000618 # What happens when presented with an impossible module name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000619 def test_loadTestsFromNames__malformed_name(self):
620 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000621
Georg Brandl15c5ce92007-03-07 09:09:40 +0000622 # XXX Should this raise ValueError or ImportError?
623 try:
624 loader.loadTestsFromNames(['abc () //'])
625 except ValueError:
626 pass
627 except ImportError:
628 pass
629 else:
630 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000631
Georg Brandl15c5ce92007-03-07 09:09:40 +0000632 # "The specifier name is a ``dotted name'' that may resolve either to
633 # a module, a test case class, a TestSuite instance, a test method
634 # within a test case class, or a callable object which returns a
635 # TestCase or TestSuite instance."
636 #
Tim Petersea5962f2007-03-12 18:07:52 +0000637 # What happens when no module can be found for the given name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000638 def test_loadTestsFromNames__unknown_module_name(self):
639 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000640
Georg Brandl15c5ce92007-03-07 09:09:40 +0000641 try:
642 loader.loadTestsFromNames(['sdasfasfasdf'])
643 except ImportError, e:
644 self.assertEqual(str(e), "No module named sdasfasfasdf")
645 else:
646 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000647
Georg Brandl15c5ce92007-03-07 09:09:40 +0000648 # "The specifier name is a ``dotted name'' that may resolve either to
649 # a module, a test case class, a TestSuite instance, a test method
650 # within a test case class, or a callable object which returns a
651 # TestCase or TestSuite instance."
652 #
Tim Petersea5962f2007-03-12 18:07:52 +0000653 # What happens when the module can be found, but not the attribute?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000654 def test_loadTestsFromNames__unknown_attr_name(self):
655 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000656
Georg Brandl15c5ce92007-03-07 09:09:40 +0000657 try:
658 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
659 except AttributeError, e:
660 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
661 else:
662 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000663
Georg Brandl15c5ce92007-03-07 09:09:40 +0000664 # "The specifier name is a ``dotted name'' that may resolve either to
665 # a module, a test case class, a TestSuite instance, a test method
666 # within a test case class, or a callable object which returns a
667 # TestCase or TestSuite instance."
668 # ...
669 # "The method optionally resolves name relative to the given module"
670 #
671 # What happens when given an unknown attribute on a specified `module`
672 # argument?
673 def test_loadTestsFromNames__unknown_name_relative_1(self):
674 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000675
Georg Brandl15c5ce92007-03-07 09:09:40 +0000676 try:
677 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
678 except AttributeError, e:
679 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
680 else:
681 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000682
Georg Brandl15c5ce92007-03-07 09:09:40 +0000683 # "The specifier name is a ``dotted name'' that may resolve either to
684 # a module, a test case class, a TestSuite instance, a test method
685 # within a test case class, or a callable object which returns a
686 # TestCase or TestSuite instance."
687 # ...
688 # "The method optionally resolves name relative to the given module"
689 #
690 # Do unknown attributes (relative to a provided module) still raise an
Tim Petersea5962f2007-03-12 18:07:52 +0000691 # exception even in the presence of valid attribute names?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000692 def test_loadTestsFromNames__unknown_name_relative_2(self):
693 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000694
Georg Brandl15c5ce92007-03-07 09:09:40 +0000695 try:
696 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
697 except AttributeError, e:
698 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
699 else:
700 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
701
702 # "The specifier name is a ``dotted name'' that may resolve either to
703 # a module, a test case class, a TestSuite instance, a test method
704 # within a test case class, or a callable object which returns a
705 # TestCase or TestSuite instance."
706 # ...
707 # "The method optionally resolves name relative to the given module"
708 #
709 # What happens when faced with the empty string?
710 #
711 # XXX This currently raises AttributeError, though ValueError is probably
712 # more appropriate
713 def test_loadTestsFromNames__relative_empty_name(self):
714 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000715
Georg Brandl15c5ce92007-03-07 09:09:40 +0000716 try:
717 loader.loadTestsFromNames([''], unittest)
718 except AttributeError:
719 pass
720 else:
721 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000722
Georg Brandl15c5ce92007-03-07 09:09:40 +0000723 # "The specifier name is a ``dotted name'' that may resolve either to
724 # a module, a test case class, a TestSuite instance, a test method
725 # within a test case class, or a callable object which returns a
726 # TestCase or TestSuite instance."
727 # ...
728 # "The method optionally resolves name relative to the given module"
729 #
Tim Petersea5962f2007-03-12 18:07:52 +0000730 # What happens when presented with an impossible attribute name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000731 def test_loadTestsFromNames__relative_malformed_name(self):
732 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000733
Georg Brandl15c5ce92007-03-07 09:09:40 +0000734 # XXX Should this raise AttributeError or ValueError?
735 try:
736 loader.loadTestsFromNames(['abc () //'], unittest)
737 except AttributeError:
738 pass
739 except ValueError:
740 pass
741 else:
742 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
743
744 # "The method optionally resolves name relative to the given module"
745 #
746 # Does loadTestsFromNames() make sure the provided `module` is in fact
747 # a module?
748 #
749 # XXX This validation is currently not done. This flexibility should
750 # either be documented or a TypeError should be raised.
751 def test_loadTestsFromNames__relative_not_a_module(self):
752 class MyTestCase(unittest.TestCase):
753 def test(self):
754 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000755
Georg Brandl15c5ce92007-03-07 09:09:40 +0000756 class NotAModule(object):
757 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000758
Georg Brandl15c5ce92007-03-07 09:09:40 +0000759 loader = unittest.TestLoader()
760 suite = loader.loadTestsFromNames(['test_2'], NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000761
Georg Brandl15c5ce92007-03-07 09:09:40 +0000762 reference = [unittest.TestSuite([MyTestCase('test')])]
763 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000764
Georg Brandl15c5ce92007-03-07 09:09:40 +0000765 # "The specifier name is a ``dotted name'' that may resolve either to
766 # a module, a test case class, a TestSuite instance, a test method
767 # within a test case class, or a callable object which returns a
768 # TestCase or TestSuite instance."
769 #
770 # Does it raise an exception if the name resolves to an invalid
771 # object?
772 def test_loadTestsFromNames__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000773 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000774 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000775
Georg Brandl15c5ce92007-03-07 09:09:40 +0000776 loader = unittest.TestLoader()
777 try:
778 loader.loadTestsFromNames(['testcase_1'], m)
779 except TypeError:
780 pass
781 else:
782 self.fail("Should have raised TypeError")
783
784 # "The specifier name is a ``dotted name'' that may resolve ... to
785 # ... a test case class"
786 def test_loadTestsFromNames__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000787 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000788 class MyTestCase(unittest.TestCase):
789 def test(self):
790 pass
791 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000792
Georg Brandl15c5ce92007-03-07 09:09:40 +0000793 loader = unittest.TestLoader()
794 suite = loader.loadTestsFromNames(['testcase_1'], m)
795 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000796
Georg Brandl15c5ce92007-03-07 09:09:40 +0000797 expected = loader.suiteClass([MyTestCase('test')])
798 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000799
Georg Brandl15c5ce92007-03-07 09:09:40 +0000800 # "The specifier name is a ``dotted name'' that may resolve ... to
801 # ... a TestSuite instance"
802 def test_loadTestsFromNames__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000803 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000804 class MyTestCase(unittest.TestCase):
805 def test(self):
806 pass
807 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000808
Georg Brandl15c5ce92007-03-07 09:09:40 +0000809 loader = unittest.TestLoader()
810 suite = loader.loadTestsFromNames(['testsuite'], m)
811 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000812
Georg Brandl15c5ce92007-03-07 09:09:40 +0000813 self.assertEqual(list(suite), [m.testsuite])
Tim Petersea5962f2007-03-12 18:07:52 +0000814
Georg Brandl15c5ce92007-03-07 09:09:40 +0000815 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
816 # test method within a test case class"
817 def test_loadTestsFromNames__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000818 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000819 class MyTestCase(unittest.TestCase):
820 def test(self):
821 pass
822 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000823
Georg Brandl15c5ce92007-03-07 09:09:40 +0000824 loader = unittest.TestLoader()
825 suite = loader.loadTestsFromNames(['testcase_1.test'], m)
826 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000827
Georg Brandl15c5ce92007-03-07 09:09:40 +0000828 ref_suite = unittest.TestSuite([MyTestCase('test')])
829 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000830
Georg Brandl15c5ce92007-03-07 09:09:40 +0000831 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
832 # test method within a test case class"
833 #
834 # Does the method gracefully handle names that initially look like they
Tim Petersea5962f2007-03-12 18:07:52 +0000835 # resolve to "a test method within a test case class" but don't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000836 def test_loadTestsFromNames__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000837 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000838 class MyTestCase(unittest.TestCase):
839 def test(self):
840 pass
841 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000842
Georg Brandl15c5ce92007-03-07 09:09:40 +0000843 loader = unittest.TestLoader()
844 try:
845 loader.loadTestsFromNames(['testcase_1.testfoo'], m)
846 except AttributeError, e:
847 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
848 else:
849 self.fail("Failed to raise AttributeError")
850
851 # "The specifier name is a ``dotted name'' that may resolve ... to
852 # ... a callable object which returns a ... TestSuite instance"
853 def test_loadTestsFromNames__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000854 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000855 testcase_1 = unittest.FunctionTestCase(lambda: None)
856 testcase_2 = unittest.FunctionTestCase(lambda: None)
857 def return_TestSuite():
858 return unittest.TestSuite([testcase_1, testcase_2])
859 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000860
Georg Brandl15c5ce92007-03-07 09:09:40 +0000861 loader = unittest.TestLoader()
862 suite = loader.loadTestsFromNames(['return_TestSuite'], m)
863 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000864
Georg Brandl15c5ce92007-03-07 09:09:40 +0000865 expected = unittest.TestSuite([testcase_1, testcase_2])
866 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000867
Georg Brandl15c5ce92007-03-07 09:09:40 +0000868 # "The specifier name is a ``dotted name'' that may resolve ... to
869 # ... a callable object which returns a TestCase ... instance"
870 def test_loadTestsFromNames__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000871 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000872 testcase_1 = unittest.FunctionTestCase(lambda: None)
873 def return_TestCase():
874 return testcase_1
875 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000876
Georg Brandl15c5ce92007-03-07 09:09:40 +0000877 loader = unittest.TestLoader()
878 suite = loader.loadTestsFromNames(['return_TestCase'], m)
879 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000880
Georg Brandl15c5ce92007-03-07 09:09:40 +0000881 ref_suite = unittest.TestSuite([testcase_1])
882 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000883
Georg Brandl15c5ce92007-03-07 09:09:40 +0000884 # "The specifier name is a ``dotted name'' that may resolve ... to
885 # ... a callable object which returns a TestCase or TestSuite instance"
886 #
Tim Petersea5962f2007-03-12 18:07:52 +0000887 # Are staticmethods handled correctly?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000888 def test_loadTestsFromNames__callable__call_staticmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000889 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000890 class Test1(unittest.TestCase):
891 def test(self):
892 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000893
Georg Brandl15c5ce92007-03-07 09:09:40 +0000894 testcase_1 = Test1('test')
895 class Foo(unittest.TestCase):
896 @staticmethod
897 def foo():
898 return testcase_1
899 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +0000900
Georg Brandl15c5ce92007-03-07 09:09:40 +0000901 loader = unittest.TestLoader()
902 suite = loader.loadTestsFromNames(['Foo.foo'], m)
903 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000904
Georg Brandl15c5ce92007-03-07 09:09:40 +0000905 ref_suite = unittest.TestSuite([testcase_1])
906 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000907
Georg Brandl15c5ce92007-03-07 09:09:40 +0000908 # "The specifier name is a ``dotted name'' that may resolve ... to
909 # ... a callable object which returns a TestCase or TestSuite instance"
910 #
911 # What happens when the callable returns something else?
912 def test_loadTestsFromNames__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000913 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000914 def return_wrong():
915 return 6
916 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000917
Georg Brandl15c5ce92007-03-07 09:09:40 +0000918 loader = unittest.TestLoader()
919 try:
920 suite = loader.loadTestsFromNames(['return_wrong'], m)
921 except TypeError:
922 pass
923 else:
924 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000925
Georg Brandl15c5ce92007-03-07 09:09:40 +0000926 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +0000927 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +0000928 def test_loadTestsFromNames__module_not_loaded(self):
929 # We're going to try to load this module as a side-effect, so it
930 # better not be loaded before we try.
931 #
932 # Why pick audioop? Google shows it isn't used very often, so there's
933 # a good chance that it won't be imported when this test is run
934 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +0000935
Georg Brandl15c5ce92007-03-07 09:09:40 +0000936 import sys
937 if module_name in sys.modules:
938 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000939
Georg Brandl15c5ce92007-03-07 09:09:40 +0000940 loader = unittest.TestLoader()
941 try:
942 suite = loader.loadTestsFromNames([module_name])
943
944 self.failUnless(isinstance(suite, loader.suiteClass))
945 self.assertEqual(list(suite), [unittest.TestSuite()])
946
947 # audioop should now be loaded, thanks to loadTestsFromName()
948 self.failUnless(module_name in sys.modules)
949 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000950 if module_name in sys.modules:
951 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000952
Georg Brandl15c5ce92007-03-07 09:09:40 +0000953 ################################################################
954 ### /Tests for TestLoader.loadTestsFromNames()
955
956 ### Tests for TestLoader.getTestCaseNames()
957 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000958
Georg Brandl15c5ce92007-03-07 09:09:40 +0000959 # "Return a sorted sequence of method names found within testCaseClass"
960 #
961 # Test.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +0000962 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +0000963 def test_getTestCaseNames(self):
964 class Test(unittest.TestCase):
965 def test_1(self): pass
966 def test_2(self): pass
967 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000968
Georg Brandl15c5ce92007-03-07 09:09:40 +0000969 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000970
Georg Brandl15c5ce92007-03-07 09:09:40 +0000971 self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])
Tim Petersea5962f2007-03-12 18:07:52 +0000972
Georg Brandl15c5ce92007-03-07 09:09:40 +0000973 # "Return a sorted sequence of method names found within testCaseClass"
974 #
Tim Petersea5962f2007-03-12 18:07:52 +0000975 # Does getTestCaseNames() behave appropriately if no tests are found?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000976 def test_getTestCaseNames__no_tests(self):
977 class Test(unittest.TestCase):
978 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000979
Georg Brandl15c5ce92007-03-07 09:09:40 +0000980 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000981
Georg Brandl15c5ce92007-03-07 09:09:40 +0000982 self.assertEqual(loader.getTestCaseNames(Test), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000983
Georg Brandl15c5ce92007-03-07 09:09:40 +0000984 # "Return a sorted sequence of method names found within testCaseClass"
985 #
986 # Are not-TestCases handled gracefully?
987 #
988 # XXX This should raise a TypeError, not return a list
989 #
990 # XXX It's too late in the 2.5 release cycle to fix this, but it should
991 # probably be revisited for 2.6
992 def test_getTestCaseNames__not_a_TestCase(self):
993 class BadCase(int):
994 def test_foo(self):
995 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000996
Georg Brandl15c5ce92007-03-07 09:09:40 +0000997 loader = unittest.TestLoader()
998 names = loader.getTestCaseNames(BadCase)
Tim Petersea5962f2007-03-12 18:07:52 +0000999
Georg Brandl15c5ce92007-03-07 09:09:40 +00001000 self.assertEqual(names, ['test_foo'])
Tim Petersea5962f2007-03-12 18:07:52 +00001001
Georg Brandl15c5ce92007-03-07 09:09:40 +00001002 # "Return a sorted sequence of method names found within testCaseClass"
1003 #
1004 # Make sure inherited names are handled.
1005 #
1006 # TestP.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +00001007 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +00001008 def test_getTestCaseNames__inheritance(self):
1009 class TestP(unittest.TestCase):
1010 def test_1(self): pass
1011 def test_2(self): pass
1012 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001013
Georg Brandl15c5ce92007-03-07 09:09:40 +00001014 class TestC(TestP):
1015 def test_1(self): pass
1016 def test_3(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001017
Georg Brandl15c5ce92007-03-07 09:09:40 +00001018 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001019
Georg Brandl15c5ce92007-03-07 09:09:40 +00001020 names = ['test_1', 'test_2', 'test_3']
1021 self.assertEqual(loader.getTestCaseNames(TestC), names)
Tim Petersea5962f2007-03-12 18:07:52 +00001022
1023 ################################################################
Georg Brandl15c5ce92007-03-07 09:09:40 +00001024 ### /Tests for TestLoader.getTestCaseNames()
1025
1026 ### Tests for TestLoader.testMethodPrefix
1027 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001028
Georg Brandl15c5ce92007-03-07 09:09:40 +00001029 # "String giving the prefix of method names which will be interpreted as
1030 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001031 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001032 # Implicit in the documentation is that testMethodPrefix is respected by
1033 # all loadTestsFrom* methods.
1034 def test_testMethodPrefix__loadTestsFromTestCase(self):
1035 class Foo(unittest.TestCase):
1036 def test_1(self): pass
1037 def test_2(self): pass
1038 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001039
Georg Brandl15c5ce92007-03-07 09:09:40 +00001040 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1041 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001042
Georg Brandl15c5ce92007-03-07 09:09:40 +00001043 loader = unittest.TestLoader()
1044 loader.testMethodPrefix = 'foo'
1045 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
1046
1047 loader.testMethodPrefix = 'test'
1048 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001049
Georg Brandl15c5ce92007-03-07 09:09:40 +00001050 # "String giving the prefix of method names which will be interpreted as
1051 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001052 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001053 # Implicit in the documentation is that testMethodPrefix is respected by
1054 # all loadTestsFrom* methods.
1055 def test_testMethodPrefix__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001056 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001057 class Foo(unittest.TestCase):
1058 def test_1(self): pass
1059 def test_2(self): pass
1060 def foo_bar(self): pass
1061 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001062
Georg Brandl15c5ce92007-03-07 09:09:40 +00001063 tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
1064 tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]
Tim Petersea5962f2007-03-12 18:07:52 +00001065
Georg Brandl15c5ce92007-03-07 09:09:40 +00001066 loader = unittest.TestLoader()
1067 loader.testMethodPrefix = 'foo'
1068 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
1069
1070 loader.testMethodPrefix = 'test'
1071 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001072
Georg Brandl15c5ce92007-03-07 09:09:40 +00001073 # "String giving the prefix of method names which will be interpreted as
1074 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001075 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001076 # Implicit in the documentation is that testMethodPrefix is respected by
1077 # all loadTestsFrom* methods.
1078 def test_testMethodPrefix__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001079 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001080 class Foo(unittest.TestCase):
1081 def test_1(self): pass
1082 def test_2(self): pass
1083 def foo_bar(self): pass
1084 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001085
Georg Brandl15c5ce92007-03-07 09:09:40 +00001086 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1087 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001088
Georg Brandl15c5ce92007-03-07 09:09:40 +00001089 loader = unittest.TestLoader()
1090 loader.testMethodPrefix = 'foo'
1091 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
1092
1093 loader.testMethodPrefix = 'test'
1094 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001095
Georg Brandl15c5ce92007-03-07 09:09:40 +00001096 # "String giving the prefix of method names which will be interpreted as
1097 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001098 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001099 # Implicit in the documentation is that testMethodPrefix is respected by
1100 # all loadTestsFrom* methods.
1101 def test_testMethodPrefix__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001102 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001103 class Foo(unittest.TestCase):
1104 def test_1(self): pass
1105 def test_2(self): pass
1106 def foo_bar(self): pass
1107 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001108
Georg Brandl15c5ce92007-03-07 09:09:40 +00001109 tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
1110 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1111 tests_2 = unittest.TestSuite([tests_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001112
Georg Brandl15c5ce92007-03-07 09:09:40 +00001113 loader = unittest.TestLoader()
1114 loader.testMethodPrefix = 'foo'
1115 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)
1116
1117 loader.testMethodPrefix = 'test'
1118 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001119
Georg Brandl15c5ce92007-03-07 09:09:40 +00001120 # "The default value is 'test'"
1121 def test_testMethodPrefix__default_value(self):
1122 loader = unittest.TestLoader()
1123 self.failUnless(loader.testMethodPrefix == 'test')
Tim Petersea5962f2007-03-12 18:07:52 +00001124
Georg Brandl15c5ce92007-03-07 09:09:40 +00001125 ################################################################
1126 ### /Tests for TestLoader.testMethodPrefix
1127
Tim Petersea5962f2007-03-12 18:07:52 +00001128 ### Tests for TestLoader.sortTestMethodsUsing
Georg Brandl15c5ce92007-03-07 09:09:40 +00001129 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001130
Georg Brandl15c5ce92007-03-07 09:09:40 +00001131 # "Function to be used to compare method names when sorting them in
1132 # getTestCaseNames() and all the loadTestsFromX() methods"
1133 def test_sortTestMethodsUsing__loadTestsFromTestCase(self):
1134 def reversed_cmp(x, y):
1135 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001136
Georg Brandl15c5ce92007-03-07 09:09:40 +00001137 class Foo(unittest.TestCase):
1138 def test_1(self): pass
1139 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001140
Georg Brandl15c5ce92007-03-07 09:09:40 +00001141 loader = unittest.TestLoader()
1142 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001143
Georg Brandl15c5ce92007-03-07 09:09:40 +00001144 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1145 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001146
Georg Brandl15c5ce92007-03-07 09:09:40 +00001147 # "Function to be used to compare method names when sorting them in
1148 # getTestCaseNames() and all the loadTestsFromX() methods"
1149 def test_sortTestMethodsUsing__loadTestsFromModule(self):
1150 def reversed_cmp(x, y):
1151 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001152
Christian Heimesc756d002007-11-27 21:34:01 +00001153 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001154 class Foo(unittest.TestCase):
1155 def test_1(self): pass
1156 def test_2(self): pass
1157 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001158
Georg Brandl15c5ce92007-03-07 09:09:40 +00001159 loader = unittest.TestLoader()
1160 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001161
Georg Brandl15c5ce92007-03-07 09:09:40 +00001162 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1163 self.assertEqual(list(loader.loadTestsFromModule(m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001164
Georg Brandl15c5ce92007-03-07 09:09:40 +00001165 # "Function to be used to compare method names when sorting them in
1166 # getTestCaseNames() and all the loadTestsFromX() methods"
1167 def test_sortTestMethodsUsing__loadTestsFromName(self):
1168 def reversed_cmp(x, y):
1169 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001170
Christian Heimesc756d002007-11-27 21:34:01 +00001171 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001172 class Foo(unittest.TestCase):
1173 def test_1(self): pass
1174 def test_2(self): pass
1175 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001176
Georg Brandl15c5ce92007-03-07 09:09:40 +00001177 loader = unittest.TestLoader()
1178 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001179
Georg Brandl15c5ce92007-03-07 09:09:40 +00001180 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1181 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001182
Georg Brandl15c5ce92007-03-07 09:09:40 +00001183 # "Function to be used to compare method names when sorting them in
1184 # getTestCaseNames() and all the loadTestsFromX() methods"
1185 def test_sortTestMethodsUsing__loadTestsFromNames(self):
1186 def reversed_cmp(x, y):
1187 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001188
Christian Heimesc756d002007-11-27 21:34:01 +00001189 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001190 class Foo(unittest.TestCase):
1191 def test_1(self): pass
1192 def test_2(self): pass
1193 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001194
Georg Brandl15c5ce92007-03-07 09:09:40 +00001195 loader = unittest.TestLoader()
1196 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001197
Georg Brandl15c5ce92007-03-07 09:09:40 +00001198 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1199 self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001200
Georg Brandl15c5ce92007-03-07 09:09:40 +00001201 # "Function to be used to compare method names when sorting them in
1202 # getTestCaseNames()"
1203 #
1204 # Does it actually affect getTestCaseNames()?
1205 def test_sortTestMethodsUsing__getTestCaseNames(self):
1206 def reversed_cmp(x, y):
1207 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001208
Georg Brandl15c5ce92007-03-07 09:09:40 +00001209 class Foo(unittest.TestCase):
1210 def test_1(self): pass
1211 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001212
Georg Brandl15c5ce92007-03-07 09:09:40 +00001213 loader = unittest.TestLoader()
1214 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001215
Georg Brandl15c5ce92007-03-07 09:09:40 +00001216 test_names = ['test_2', 'test_1']
1217 self.assertEqual(loader.getTestCaseNames(Foo), test_names)
Tim Petersea5962f2007-03-12 18:07:52 +00001218
Georg Brandl15c5ce92007-03-07 09:09:40 +00001219 # "The default value is the built-in cmp() function"
1220 def test_sortTestMethodsUsing__default_value(self):
1221 loader = unittest.TestLoader()
1222 self.failUnless(loader.sortTestMethodsUsing is cmp)
Tim Petersea5962f2007-03-12 18:07:52 +00001223
Georg Brandl15c5ce92007-03-07 09:09:40 +00001224 # "it can be set to None to disable the sort."
1225 #
1226 # XXX How is this different from reassigning cmp? Are the tests returned
1227 # in a random order or something? This behaviour should die
1228 def test_sortTestMethodsUsing__None(self):
1229 class Foo(unittest.TestCase):
1230 def test_1(self): pass
1231 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001232
Georg Brandl15c5ce92007-03-07 09:09:40 +00001233 loader = unittest.TestLoader()
1234 loader.sortTestMethodsUsing = None
Tim Petersea5962f2007-03-12 18:07:52 +00001235
Georg Brandl15c5ce92007-03-07 09:09:40 +00001236 test_names = ['test_2', 'test_1']
1237 self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))
Tim Petersea5962f2007-03-12 18:07:52 +00001238
Georg Brandl15c5ce92007-03-07 09:09:40 +00001239 ################################################################
1240 ### /Tests for TestLoader.sortTestMethodsUsing
Tim Petersea5962f2007-03-12 18:07:52 +00001241
Georg Brandl15c5ce92007-03-07 09:09:40 +00001242 ### Tests for TestLoader.suiteClass
1243 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001244
Georg Brandl15c5ce92007-03-07 09:09:40 +00001245 # "Callable object that constructs a test suite from a list of tests."
1246 def test_suiteClass__loadTestsFromTestCase(self):
1247 class Foo(unittest.TestCase):
1248 def test_1(self): pass
1249 def test_2(self): pass
1250 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001251
Georg Brandl15c5ce92007-03-07 09:09:40 +00001252 tests = [Foo('test_1'), Foo('test_2')]
1253
1254 loader = unittest.TestLoader()
Benjamin Peterson692428e2009-03-23 21:50:21 +00001255 loader.classSuiteClass = MyClassSuite
Georg Brandl15c5ce92007-03-07 09:09:40 +00001256 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001257
Georg Brandl15c5ce92007-03-07 09:09:40 +00001258 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001259 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001260 def test_suiteClass__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001261 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001262 class Foo(unittest.TestCase):
1263 def test_1(self): pass
1264 def test_2(self): pass
1265 def foo_bar(self): pass
1266 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001267
Benjamin Peterson692428e2009-03-23 21:50:21 +00001268 tests = [unittest.ClassTestSuite([Foo('test_1'), Foo('test_2')], Foo)]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001269
1270 loader = unittest.TestLoader()
1271 loader.suiteClass = list
1272 self.assertEqual(loader.loadTestsFromModule(m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001273
Georg Brandl15c5ce92007-03-07 09:09:40 +00001274 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001275 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001276 def test_suiteClass__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001277 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001278 class Foo(unittest.TestCase):
1279 def test_1(self): pass
1280 def test_2(self): pass
1281 def foo_bar(self): pass
1282 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001283
Georg Brandl15c5ce92007-03-07 09:09:40 +00001284 tests = [Foo('test_1'), Foo('test_2')]
1285
1286 loader = unittest.TestLoader()
Benjamin Peterson692428e2009-03-23 21:50:21 +00001287 loader.classSuiteClass = MyClassSuite
Georg Brandl15c5ce92007-03-07 09:09:40 +00001288 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001289
Georg Brandl15c5ce92007-03-07 09:09:40 +00001290 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001291 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001292 def test_suiteClass__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001293 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001294 class Foo(unittest.TestCase):
1295 def test_1(self): pass
1296 def test_2(self): pass
1297 def foo_bar(self): pass
1298 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001299
Benjamin Peterson692428e2009-03-23 21:50:21 +00001300 tests = [unittest.ClassTestSuite([Foo('test_1'), Foo('test_2')], Foo)]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001301
1302 loader = unittest.TestLoader()
1303 loader.suiteClass = list
1304 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001305
Georg Brandl15c5ce92007-03-07 09:09:40 +00001306 # "The default value is the TestSuite class"
1307 def test_suiteClass__default_value(self):
1308 loader = unittest.TestLoader()
1309 self.failUnless(loader.suiteClass is unittest.TestSuite)
Tim Petersea5962f2007-03-12 18:07:52 +00001310
Georg Brandl15c5ce92007-03-07 09:09:40 +00001311 ################################################################
1312 ### /Tests for TestLoader.suiteClass
1313
1314### Support code for Test_TestSuite
1315################################################################
1316
1317class Foo(unittest.TestCase):
1318 def test_1(self): pass
1319 def test_2(self): pass
1320 def test_3(self): pass
1321 def runTest(self): pass
1322
1323def _mk_TestSuite(*names):
1324 return unittest.TestSuite(Foo(n) for n in names)
Tim Petersea5962f2007-03-12 18:07:52 +00001325
Georg Brandl15c5ce92007-03-07 09:09:40 +00001326################################################################
1327### /Support code for Test_TestSuite
1328
1329class Test_TestSuite(TestCase, TestEquality):
1330
1331 ### Set up attributes needed by inherited tests
1332 ################################################################
1333
1334 # Used by TestEquality.test_eq
1335 eq_pairs = [(unittest.TestSuite(), unittest.TestSuite())
1336 ,(unittest.TestSuite(), unittest.TestSuite([]))
1337 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001338
1339 # Used by TestEquality.test_ne
Georg Brandl15c5ce92007-03-07 09:09:40 +00001340 ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1'))
1341 ,(unittest.TestSuite([]), _mk_TestSuite('test_1'))
1342 ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3'))
1343 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001344
Georg Brandl15c5ce92007-03-07 09:09:40 +00001345 ################################################################
1346 ### /Set up attributes needed by inherited tests
1347
1348 ### Tests for TestSuite.__init__
1349 ################################################################
1350
1351 # "class TestSuite([tests])"
1352 #
1353 # The tests iterable should be optional
1354 def test_init__tests_optional(self):
1355 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001356
Georg Brandl15c5ce92007-03-07 09:09:40 +00001357 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001358
Georg Brandl15c5ce92007-03-07 09:09:40 +00001359 # "class TestSuite([tests])"
1360 # ...
1361 # "If tests is given, it must be an iterable of individual test cases
1362 # or other test suites that will be used to build the suite initially"
1363 #
1364 # TestSuite should deal with empty tests iterables by allowing the
Tim Petersea5962f2007-03-12 18:07:52 +00001365 # creation of an empty suite
Georg Brandl15c5ce92007-03-07 09:09:40 +00001366 def test_init__empty_tests(self):
1367 suite = unittest.TestSuite([])
Tim Petersea5962f2007-03-12 18:07:52 +00001368
Georg Brandl15c5ce92007-03-07 09:09:40 +00001369 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001370
Georg Brandl15c5ce92007-03-07 09:09:40 +00001371 # "class TestSuite([tests])"
1372 # ...
1373 # "If tests is given, it must be an iterable of individual test cases
1374 # or other test suites that will be used to build the suite initially"
1375 #
Tim Petersea5962f2007-03-12 18:07:52 +00001376 # TestSuite should allow any iterable to provide tests
Georg Brandl15c5ce92007-03-07 09:09:40 +00001377 def test_init__tests_from_any_iterable(self):
1378 def tests():
1379 yield unittest.FunctionTestCase(lambda: None)
1380 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001381
Georg Brandl15c5ce92007-03-07 09:09:40 +00001382 suite_1 = unittest.TestSuite(tests())
1383 self.assertEqual(suite_1.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001384
Georg Brandl15c5ce92007-03-07 09:09:40 +00001385 suite_2 = unittest.TestSuite(suite_1)
1386 self.assertEqual(suite_2.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001387
Georg Brandl15c5ce92007-03-07 09:09:40 +00001388 suite_3 = unittest.TestSuite(set(suite_1))
1389 self.assertEqual(suite_3.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001390
Georg Brandl15c5ce92007-03-07 09:09:40 +00001391 # "class TestSuite([tests])"
1392 # ...
1393 # "If tests is given, it must be an iterable of individual test cases
1394 # or other test suites that will be used to build the suite initially"
1395 #
1396 # Does TestSuite() also allow other TestSuite() instances to be present
1397 # in the tests iterable?
1398 def test_init__TestSuite_instances_in_tests(self):
1399 def tests():
1400 ftc = unittest.FunctionTestCase(lambda: None)
1401 yield unittest.TestSuite([ftc])
1402 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001403
Georg Brandl15c5ce92007-03-07 09:09:40 +00001404 suite = unittest.TestSuite(tests())
1405 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001406
Georg Brandl15c5ce92007-03-07 09:09:40 +00001407 ################################################################
1408 ### /Tests for TestSuite.__init__
1409
1410 # Container types should support the iter protocol
1411 def test_iter(self):
1412 test1 = unittest.FunctionTestCase(lambda: None)
1413 test2 = unittest.FunctionTestCase(lambda: None)
1414 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001415
Georg Brandl15c5ce92007-03-07 09:09:40 +00001416 self.assertEqual(list(suite), [test1, test2])
Tim Petersea5962f2007-03-12 18:07:52 +00001417
Georg Brandl15c5ce92007-03-07 09:09:40 +00001418 # "Return the number of tests represented by the this test object.
1419 # ...this method is also implemented by the TestSuite class, which can
1420 # return larger [greater than 1] values"
1421 #
Tim Petersea5962f2007-03-12 18:07:52 +00001422 # Presumably an empty TestSuite returns 0?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001423 def test_countTestCases_zero_simple(self):
1424 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001425
Georg Brandl15c5ce92007-03-07 09:09:40 +00001426 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001427
Georg Brandl15c5ce92007-03-07 09:09:40 +00001428 # "Return the number of tests represented by the this test object.
1429 # ...this method is also implemented by the TestSuite class, which can
1430 # return larger [greater than 1] values"
1431 #
1432 # Presumably an empty TestSuite (even if it contains other empty
1433 # TestSuite instances) returns 0?
1434 def test_countTestCases_zero_nested(self):
1435 class Test1(unittest.TestCase):
1436 def test(self):
1437 pass
1438
1439 suite = unittest.TestSuite([unittest.TestSuite()])
Tim Petersea5962f2007-03-12 18:07:52 +00001440
Georg Brandl15c5ce92007-03-07 09:09:40 +00001441 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001442
Georg Brandl15c5ce92007-03-07 09:09:40 +00001443 # "Return the number of tests represented by the this test object.
1444 # ...this method is also implemented by the TestSuite class, which can
1445 # return larger [greater than 1] values"
1446 def test_countTestCases_simple(self):
1447 test1 = unittest.FunctionTestCase(lambda: None)
1448 test2 = unittest.FunctionTestCase(lambda: None)
1449 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001450
Georg Brandl15c5ce92007-03-07 09:09:40 +00001451 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001452
Georg Brandl15c5ce92007-03-07 09:09:40 +00001453 # "Return the number of tests represented by the this test object.
1454 # ...this method is also implemented by the TestSuite class, which can
1455 # return larger [greater than 1] values"
1456 #
1457 # Make sure this holds for nested TestSuite instances, too
1458 def test_countTestCases_nested(self):
1459 class Test1(unittest.TestCase):
1460 def test1(self): pass
1461 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001462
Georg Brandl15c5ce92007-03-07 09:09:40 +00001463 test2 = unittest.FunctionTestCase(lambda: None)
1464 test3 = unittest.FunctionTestCase(lambda: None)
1465 child = unittest.TestSuite((Test1('test2'), test2))
1466 parent = unittest.TestSuite((test3, child, Test1('test1')))
Tim Petersea5962f2007-03-12 18:07:52 +00001467
Georg Brandl15c5ce92007-03-07 09:09:40 +00001468 self.assertEqual(parent.countTestCases(), 4)
Tim Petersea5962f2007-03-12 18:07:52 +00001469
Georg Brandl15c5ce92007-03-07 09:09:40 +00001470 # "Run the tests associated with this suite, collecting the result into
1471 # the test result object passed as result."
1472 #
1473 # And if there are no tests? What then?
1474 def test_run__empty_suite(self):
1475 events = []
1476 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001477
Georg Brandl15c5ce92007-03-07 09:09:40 +00001478 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001479
Georg Brandl15c5ce92007-03-07 09:09:40 +00001480 suite.run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001481
Georg Brandl15c5ce92007-03-07 09:09:40 +00001482 self.assertEqual(events, [])
Tim Petersea5962f2007-03-12 18:07:52 +00001483
Georg Brandl15c5ce92007-03-07 09:09:40 +00001484 # "Note that unlike TestCase.run(), TestSuite.run() requires the
1485 # "result object to be passed in."
1486 def test_run__requires_result(self):
1487 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001488
Georg Brandl15c5ce92007-03-07 09:09:40 +00001489 try:
1490 suite.run()
1491 except TypeError:
1492 pass
1493 else:
1494 self.fail("Failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +00001495
Georg Brandl15c5ce92007-03-07 09:09:40 +00001496 # "Run the tests associated with this suite, collecting the result into
Tim Petersea5962f2007-03-12 18:07:52 +00001497 # the test result object passed as result."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001498 def test_run(self):
1499 events = []
1500 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001501
Georg Brandl15c5ce92007-03-07 09:09:40 +00001502 class LoggingCase(unittest.TestCase):
1503 def run(self, result):
1504 events.append('run %s' % self._testMethodName)
Tim Petersea5962f2007-03-12 18:07:52 +00001505
Georg Brandl15c5ce92007-03-07 09:09:40 +00001506 def test1(self): pass
1507 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001508
1509 tests = [LoggingCase('test1'), LoggingCase('test2')]
1510
Georg Brandl15c5ce92007-03-07 09:09:40 +00001511 unittest.TestSuite(tests).run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001512
Georg Brandl15c5ce92007-03-07 09:09:40 +00001513 self.assertEqual(events, ['run test1', 'run test2'])
Tim Petersea5962f2007-03-12 18:07:52 +00001514
1515 # "Add a TestCase ... to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001516 def test_addTest__TestCase(self):
1517 class Foo(unittest.TestCase):
1518 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001519
Georg Brandl15c5ce92007-03-07 09:09:40 +00001520 test = Foo('test')
1521 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001522
Georg Brandl15c5ce92007-03-07 09:09:40 +00001523 suite.addTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001524
Georg Brandl15c5ce92007-03-07 09:09:40 +00001525 self.assertEqual(suite.countTestCases(), 1)
1526 self.assertEqual(list(suite), [test])
Tim Petersea5962f2007-03-12 18:07:52 +00001527
1528 # "Add a ... TestSuite to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001529 def test_addTest__TestSuite(self):
1530 class Foo(unittest.TestCase):
1531 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001532
Georg Brandl15c5ce92007-03-07 09:09:40 +00001533 suite_2 = unittest.TestSuite([Foo('test')])
Tim Petersea5962f2007-03-12 18:07:52 +00001534
Georg Brandl15c5ce92007-03-07 09:09:40 +00001535 suite = unittest.TestSuite()
1536 suite.addTest(suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001537
Georg Brandl15c5ce92007-03-07 09:09:40 +00001538 self.assertEqual(suite.countTestCases(), 1)
1539 self.assertEqual(list(suite), [suite_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001540
Georg Brandl15c5ce92007-03-07 09:09:40 +00001541 # "Add all the tests from an iterable of TestCase and TestSuite
1542 # instances to this test suite."
Tim Petersea5962f2007-03-12 18:07:52 +00001543 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001544 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001545 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001546 def test_addTests(self):
1547 class Foo(unittest.TestCase):
1548 def test_1(self): pass
1549 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001550
Georg Brandl15c5ce92007-03-07 09:09:40 +00001551 test_1 = Foo('test_1')
1552 test_2 = Foo('test_2')
1553 inner_suite = unittest.TestSuite([test_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001554
Georg Brandl15c5ce92007-03-07 09:09:40 +00001555 def gen():
1556 yield test_1
1557 yield test_2
1558 yield inner_suite
Tim Petersea5962f2007-03-12 18:07:52 +00001559
Georg Brandl15c5ce92007-03-07 09:09:40 +00001560 suite_1 = unittest.TestSuite()
1561 suite_1.addTests(gen())
Tim Petersea5962f2007-03-12 18:07:52 +00001562
Georg Brandl15c5ce92007-03-07 09:09:40 +00001563 self.assertEqual(list(suite_1), list(gen()))
Tim Petersea5962f2007-03-12 18:07:52 +00001564
Georg Brandl15c5ce92007-03-07 09:09:40 +00001565 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001566 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001567 suite_2 = unittest.TestSuite()
1568 for t in gen():
1569 suite_2.addTest(t)
Tim Petersea5962f2007-03-12 18:07:52 +00001570
Georg Brandl15c5ce92007-03-07 09:09:40 +00001571 self.assertEqual(suite_1, suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001572
Georg Brandl15c5ce92007-03-07 09:09:40 +00001573 # "Add all the tests from an iterable of TestCase and TestSuite
1574 # instances to this test suite."
1575 #
Tim Petersea5962f2007-03-12 18:07:52 +00001576 # What happens if it doesn't get an iterable?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001577 def test_addTest__noniterable(self):
1578 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001579
Georg Brandl15c5ce92007-03-07 09:09:40 +00001580 try:
1581 suite.addTests(5)
1582 except TypeError:
1583 pass
1584 else:
1585 self.fail("Failed to raise TypeError")
Georg Brandld9e50262007-03-07 11:54:49 +00001586
1587 def test_addTest__noncallable(self):
1588 suite = unittest.TestSuite()
1589 self.assertRaises(TypeError, suite.addTest, 5)
1590
1591 def test_addTest__casesuiteclass(self):
1592 suite = unittest.TestSuite()
1593 self.assertRaises(TypeError, suite.addTest, Test_TestSuite)
1594 self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)
1595
1596 def test_addTests__string(self):
1597 suite = unittest.TestSuite()
1598 self.assertRaises(TypeError, suite.addTests, "foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001599
1600
Georg Brandl15c5ce92007-03-07 09:09:40 +00001601class Test_FunctionTestCase(TestCase):
Tim Petersea5962f2007-03-12 18:07:52 +00001602
Georg Brandl15c5ce92007-03-07 09:09:40 +00001603 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00001604 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001605 def test_countTestCases(self):
1606 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001607
Georg Brandl15c5ce92007-03-07 09:09:40 +00001608 self.assertEqual(test.countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00001609
Georg Brandl15c5ce92007-03-07 09:09:40 +00001610 # "When a setUp() method is defined, the test runner will run that method
1611 # prior to each test. Likewise, if a tearDown() method is defined, the
1612 # test runner will invoke that method after each test. In the example,
1613 # setUp() was used to create a fresh sequence for each test."
1614 #
1615 # Make sure the proper call order is maintained, even if setUp() raises
1616 # an exception.
1617 def test_run_call_order__error_in_setUp(self):
1618 events = []
1619 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001620
Georg Brandl15c5ce92007-03-07 09:09:40 +00001621 def setUp():
1622 events.append('setUp')
1623 raise RuntimeError('raised by setUp')
1624
1625 def test():
1626 events.append('test')
1627
1628 def tearDown():
1629 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001630
1631 expected = ['startTest', 'setUp', 'addError', 'stopTest']
Georg Brandl15c5ce92007-03-07 09:09:40 +00001632 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1633 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001634
Georg Brandl15c5ce92007-03-07 09:09:40 +00001635 # "When a setUp() method is defined, the test runner will run that method
1636 # prior to each test. Likewise, if a tearDown() method is defined, the
1637 # test runner will invoke that method after each test. In the example,
1638 # setUp() was used to create a fresh sequence for each test."
1639 #
1640 # Make sure the proper call order is maintained, even if the test raises
1641 # an error (as opposed to a failure).
1642 def test_run_call_order__error_in_test(self):
1643 events = []
1644 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001645
Georg Brandl15c5ce92007-03-07 09:09:40 +00001646 def setUp():
1647 events.append('setUp')
1648
1649 def test():
1650 events.append('test')
1651 raise RuntimeError('raised by test')
1652
1653 def tearDown():
1654 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001655
Georg Brandl15c5ce92007-03-07 09:09:40 +00001656 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
1657 'stopTest']
1658 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1659 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001660
Georg Brandl15c5ce92007-03-07 09:09:40 +00001661 # "When a setUp() method is defined, the test runner will run that method
1662 # prior to each test. Likewise, if a tearDown() method is defined, the
1663 # test runner will invoke that method after each test. In the example,
1664 # setUp() was used to create a fresh sequence for each test."
1665 #
1666 # Make sure the proper call order is maintained, even if the test signals
1667 # a failure (as opposed to an error).
1668 def test_run_call_order__failure_in_test(self):
1669 events = []
1670 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001671
Georg Brandl15c5ce92007-03-07 09:09:40 +00001672 def setUp():
1673 events.append('setUp')
1674
1675 def test():
1676 events.append('test')
1677 self.fail('raised by test')
1678
1679 def tearDown():
1680 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001681
Georg Brandl15c5ce92007-03-07 09:09:40 +00001682 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
1683 'stopTest']
1684 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1685 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001686
Georg Brandl15c5ce92007-03-07 09:09:40 +00001687 # "When a setUp() method is defined, the test runner will run that method
1688 # prior to each test. Likewise, if a tearDown() method is defined, the
1689 # test runner will invoke that method after each test. In the example,
1690 # setUp() was used to create a fresh sequence for each test."
1691 #
1692 # Make sure the proper call order is maintained, even if tearDown() raises
1693 # an exception.
1694 def test_run_call_order__error_in_tearDown(self):
1695 events = []
1696 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001697
Georg Brandl15c5ce92007-03-07 09:09:40 +00001698 def setUp():
1699 events.append('setUp')
1700
1701 def test():
1702 events.append('test')
1703
1704 def tearDown():
1705 events.append('tearDown')
1706 raise RuntimeError('raised by tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001707
Georg Brandl15c5ce92007-03-07 09:09:40 +00001708 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
1709 'stopTest']
1710 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1711 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001712
Georg Brandl15c5ce92007-03-07 09:09:40 +00001713 # "Return a string identifying the specific test case."
1714 #
1715 # Because of the vague nature of the docs, I'm not going to lock this
1716 # test down too much. Really all that can be asserted is that the id()
1717 # will be a string (either 8-byte or unicode -- again, because the docs
1718 # just say "string")
1719 def test_id(self):
1720 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001721
Georg Brandl15c5ce92007-03-07 09:09:40 +00001722 self.failUnless(isinstance(test.id(), basestring))
Tim Petersea5962f2007-03-12 18:07:52 +00001723
Georg Brandl15c5ce92007-03-07 09:09:40 +00001724 # "Returns a one-line description of the test, or None if no description
1725 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001726 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001727 def test_shortDescription__no_docstring(self):
1728 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001729
Georg Brandl15c5ce92007-03-07 09:09:40 +00001730 self.assertEqual(test.shortDescription(), None)
Tim Petersea5962f2007-03-12 18:07:52 +00001731
Georg Brandl15c5ce92007-03-07 09:09:40 +00001732 # "Returns a one-line description of the test, or None if no description
1733 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001734 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001735 def test_shortDescription__singleline_docstring(self):
1736 desc = "this tests foo"
1737 test = unittest.FunctionTestCase(lambda: None, description=desc)
Tim Petersea5962f2007-03-12 18:07:52 +00001738
Georg Brandl15c5ce92007-03-07 09:09:40 +00001739 self.assertEqual(test.shortDescription(), "this tests foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001740
Georg Brandl15c5ce92007-03-07 09:09:40 +00001741class Test_TestResult(TestCase):
1742 # Note: there are not separate tests for TestResult.wasSuccessful(),
1743 # TestResult.errors, TestResult.failures, TestResult.testsRun or
1744 # TestResult.shouldStop because these only have meaning in terms of
1745 # other TestResult methods.
1746 #
1747 # Accordingly, tests for the aforenamed attributes are incorporated
1748 # in with the tests for the defining methods.
1749 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001750
Georg Brandl15c5ce92007-03-07 09:09:40 +00001751 def test_init(self):
1752 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001753
Georg Brandl15c5ce92007-03-07 09:09:40 +00001754 self.failUnless(result.wasSuccessful())
1755 self.assertEqual(len(result.errors), 0)
1756 self.assertEqual(len(result.failures), 0)
1757 self.assertEqual(result.testsRun, 0)
1758 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001759
Georg Brandl15c5ce92007-03-07 09:09:40 +00001760 # "This method can be called to signal that the set of tests being
1761 # run should be aborted by setting the TestResult's shouldStop
Tim Petersea5962f2007-03-12 18:07:52 +00001762 # attribute to True."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001763 def test_stop(self):
1764 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001765
Georg Brandl15c5ce92007-03-07 09:09:40 +00001766 result.stop()
Tim Petersea5962f2007-03-12 18:07:52 +00001767
Georg Brandl15c5ce92007-03-07 09:09:40 +00001768 self.assertEqual(result.shouldStop, True)
Tim Petersea5962f2007-03-12 18:07:52 +00001769
Georg Brandl15c5ce92007-03-07 09:09:40 +00001770 # "Called when the test case test is about to be run. The default
1771 # implementation simply increments the instance's testsRun counter."
1772 def test_startTest(self):
1773 class Foo(unittest.TestCase):
1774 def test_1(self):
1775 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001776
Georg Brandl15c5ce92007-03-07 09:09:40 +00001777 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001778
Georg Brandl15c5ce92007-03-07 09:09:40 +00001779 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001780
Georg Brandl15c5ce92007-03-07 09:09:40 +00001781 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001782
Georg Brandl15c5ce92007-03-07 09:09:40 +00001783 self.failUnless(result.wasSuccessful())
1784 self.assertEqual(len(result.errors), 0)
1785 self.assertEqual(len(result.failures), 0)
1786 self.assertEqual(result.testsRun, 1)
1787 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001788
Georg Brandl15c5ce92007-03-07 09:09:40 +00001789 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001790
Georg Brandl15c5ce92007-03-07 09:09:40 +00001791 # "Called after the test case test has been executed, regardless of
1792 # the outcome. The default implementation does nothing."
1793 def test_stopTest(self):
1794 class Foo(unittest.TestCase):
1795 def test_1(self):
1796 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001797
Georg Brandl15c5ce92007-03-07 09:09:40 +00001798 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001799
Georg Brandl15c5ce92007-03-07 09:09:40 +00001800 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001801
Georg Brandl15c5ce92007-03-07 09:09:40 +00001802 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001803
Georg Brandl15c5ce92007-03-07 09:09:40 +00001804 self.failUnless(result.wasSuccessful())
1805 self.assertEqual(len(result.errors), 0)
1806 self.assertEqual(len(result.failures), 0)
1807 self.assertEqual(result.testsRun, 1)
1808 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001809
Georg Brandl15c5ce92007-03-07 09:09:40 +00001810 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001811
Georg Brandl15c5ce92007-03-07 09:09:40 +00001812 # Same tests as above; make sure nothing has changed
1813 self.failUnless(result.wasSuccessful())
1814 self.assertEqual(len(result.errors), 0)
1815 self.assertEqual(len(result.failures), 0)
1816 self.assertEqual(result.testsRun, 1)
1817 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001818
Georg Brandl15c5ce92007-03-07 09:09:40 +00001819 # "addSuccess(test)"
1820 # ...
1821 # "Called when the test case test succeeds"
1822 # ...
1823 # "wasSuccessful() - Returns True if all tests run so far have passed,
1824 # otherwise returns False"
1825 # ...
1826 # "testsRun - The total number of tests run so far."
1827 # ...
1828 # "errors - A list containing 2-tuples of TestCase instances and
1829 # formatted tracebacks. Each tuple represents a test which raised an
1830 # unexpected exception. Contains formatted
1831 # tracebacks instead of sys.exc_info() results."
1832 # ...
1833 # "failures - A list containing 2-tuples of TestCase instances and
1834 # formatted tracebacks. Each tuple represents a test where a failure was
1835 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1836 # methods. Contains formatted tracebacks instead
1837 # of sys.exc_info() results."
1838 def test_addSuccess(self):
1839 class Foo(unittest.TestCase):
1840 def test_1(self):
1841 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001842
Georg Brandl15c5ce92007-03-07 09:09:40 +00001843 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001844
Georg Brandl15c5ce92007-03-07 09:09:40 +00001845 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001846
Georg Brandl15c5ce92007-03-07 09:09:40 +00001847 result.startTest(test)
1848 result.addSuccess(test)
1849 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001850
Georg Brandl15c5ce92007-03-07 09:09:40 +00001851 self.failUnless(result.wasSuccessful())
1852 self.assertEqual(len(result.errors), 0)
1853 self.assertEqual(len(result.failures), 0)
1854 self.assertEqual(result.testsRun, 1)
1855 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001856
Georg Brandl15c5ce92007-03-07 09:09:40 +00001857 # "addFailure(test, err)"
1858 # ...
1859 # "Called when the test case test signals a failure. err is a tuple of
1860 # the form returned by sys.exc_info(): (type, value, traceback)"
1861 # ...
1862 # "wasSuccessful() - Returns True if all tests run so far have passed,
1863 # otherwise returns False"
1864 # ...
1865 # "testsRun - The total number of tests run so far."
1866 # ...
1867 # "errors - A list containing 2-tuples of TestCase instances and
1868 # formatted tracebacks. Each tuple represents a test which raised an
1869 # unexpected exception. Contains formatted
1870 # tracebacks instead of sys.exc_info() results."
1871 # ...
1872 # "failures - A list containing 2-tuples of TestCase instances and
1873 # formatted tracebacks. Each tuple represents a test where a failure was
1874 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1875 # methods. Contains formatted tracebacks instead
1876 # of sys.exc_info() results."
1877 def test_addFailure(self):
1878 import sys
Tim Petersea5962f2007-03-12 18:07:52 +00001879
Georg Brandl15c5ce92007-03-07 09:09:40 +00001880 class Foo(unittest.TestCase):
1881 def test_1(self):
1882 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001883
Georg Brandl15c5ce92007-03-07 09:09:40 +00001884 test = Foo('test_1')
1885 try:
1886 test.fail("foo")
1887 except:
1888 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00001889
Georg Brandl15c5ce92007-03-07 09:09:40 +00001890 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001891
Georg Brandl15c5ce92007-03-07 09:09:40 +00001892 result.startTest(test)
1893 result.addFailure(test, exc_info_tuple)
1894 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001895
Georg Brandl15c5ce92007-03-07 09:09:40 +00001896 self.failIf(result.wasSuccessful())
1897 self.assertEqual(len(result.errors), 0)
1898 self.assertEqual(len(result.failures), 1)
1899 self.assertEqual(result.testsRun, 1)
1900 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001901
Georg Brandl15c5ce92007-03-07 09:09:40 +00001902 test_case, formatted_exc = result.failures[0]
1903 self.failUnless(test_case is test)
1904 self.failUnless(isinstance(formatted_exc, str))
Tim Petersea5962f2007-03-12 18:07:52 +00001905
Georg Brandl15c5ce92007-03-07 09:09:40 +00001906 # "addError(test, err)"
1907 # ...
1908 # "Called when the test case test raises an unexpected exception err
1909 # is a tuple of the form returned by sys.exc_info():
1910 # (type, value, traceback)"
1911 # ...
1912 # "wasSuccessful() - Returns True if all tests run so far have passed,
1913 # otherwise returns False"
1914 # ...
1915 # "testsRun - The total number of tests run so far."
1916 # ...
1917 # "errors - A list containing 2-tuples of TestCase instances and
1918 # formatted tracebacks. Each tuple represents a test which raised an
1919 # unexpected exception. Contains formatted
1920 # tracebacks instead of sys.exc_info() results."
1921 # ...
1922 # "failures - A list containing 2-tuples of TestCase instances and
1923 # formatted tracebacks. Each tuple represents a test where a failure was
1924 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1925 # methods. Contains formatted tracebacks instead
1926 # of sys.exc_info() results."
1927 def test_addError(self):
1928 import sys
Tim Petersea5962f2007-03-12 18:07:52 +00001929
Georg Brandl15c5ce92007-03-07 09:09:40 +00001930 class Foo(unittest.TestCase):
1931 def test_1(self):
1932 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001933
Georg Brandl15c5ce92007-03-07 09:09:40 +00001934 test = Foo('test_1')
1935 try:
1936 raise TypeError()
1937 except:
1938 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00001939
Georg Brandl15c5ce92007-03-07 09:09:40 +00001940 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001941
Georg Brandl15c5ce92007-03-07 09:09:40 +00001942 result.startTest(test)
1943 result.addError(test, exc_info_tuple)
1944 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001945
Georg Brandl15c5ce92007-03-07 09:09:40 +00001946 self.failIf(result.wasSuccessful())
1947 self.assertEqual(len(result.errors), 1)
1948 self.assertEqual(len(result.failures), 0)
1949 self.assertEqual(result.testsRun, 1)
1950 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001951
Georg Brandl15c5ce92007-03-07 09:09:40 +00001952 test_case, formatted_exc = result.errors[0]
1953 self.failUnless(test_case is test)
1954 self.failUnless(isinstance(formatted_exc, str))
1955
1956### Support code for Test_TestCase
1957################################################################
1958
1959class Foo(unittest.TestCase):
1960 def runTest(self): pass
1961 def test1(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001962
Georg Brandl15c5ce92007-03-07 09:09:40 +00001963class Bar(Foo):
1964 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001965
Georg Brandl15c5ce92007-03-07 09:09:40 +00001966################################################################
1967### /Support code for Test_TestCase
1968
1969class Test_TestCase(TestCase, TestEquality, TestHashing):
1970
1971 ### Set up attributes used by inherited tests
1972 ################################################################
1973
1974 # Used by TestHashing.test_hash and TestEquality.test_eq
1975 eq_pairs = [(Foo('test1'), Foo('test1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001976
Georg Brandl15c5ce92007-03-07 09:09:40 +00001977 # Used by TestEquality.test_ne
1978 ne_pairs = [(Foo('test1'), Foo('runTest'))
1979 ,(Foo('test1'), Bar('test1'))
1980 ,(Foo('test1'), Bar('test2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001981
Georg Brandl15c5ce92007-03-07 09:09:40 +00001982 ################################################################
1983 ### /Set up attributes used by inherited tests
Tim Petersea5962f2007-03-12 18:07:52 +00001984
Georg Brandl15c5ce92007-03-07 09:09:40 +00001985
1986 # "class TestCase([methodName])"
1987 # ...
1988 # "Each instance of TestCase will run a single test method: the
1989 # method named methodName."
1990 # ...
1991 # "methodName defaults to "runTest"."
1992 #
1993 # Make sure it really is optional, and that it defaults to the proper
1994 # thing.
1995 def test_init__no_test_name(self):
1996 class Test(unittest.TestCase):
1997 def runTest(self): raise MyException()
1998 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001999
Georg Brandl15c5ce92007-03-07 09:09:40 +00002000 self.assertEqual(Test().id()[-13:], '.Test.runTest')
Tim Petersea5962f2007-03-12 18:07:52 +00002001
Georg Brandl15c5ce92007-03-07 09:09:40 +00002002 # "class TestCase([methodName])"
2003 # ...
2004 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002005 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002006 def test_init__test_name__valid(self):
2007 class Test(unittest.TestCase):
2008 def runTest(self): raise MyException()
2009 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002010
Georg Brandl15c5ce92007-03-07 09:09:40 +00002011 self.assertEqual(Test('test').id()[-10:], '.Test.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002012
Georg Brandl15c5ce92007-03-07 09:09:40 +00002013 # "class TestCase([methodName])"
2014 # ...
2015 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002016 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002017 def test_init__test_name__invalid(self):
2018 class Test(unittest.TestCase):
2019 def runTest(self): raise MyException()
2020 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002021
Georg Brandl15c5ce92007-03-07 09:09:40 +00002022 try:
2023 Test('testfoo')
2024 except ValueError:
2025 pass
2026 else:
2027 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +00002028
Georg Brandl15c5ce92007-03-07 09:09:40 +00002029 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00002030 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00002031 def test_countTestCases(self):
2032 class Foo(unittest.TestCase):
2033 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002034
Georg Brandl15c5ce92007-03-07 09:09:40 +00002035 self.assertEqual(Foo('test').countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00002036
Georg Brandl15c5ce92007-03-07 09:09:40 +00002037 # "Return the default type of test result object to be used to run this
2038 # test. For TestCase instances, this will always be
2039 # unittest.TestResult; subclasses of TestCase should
2040 # override this as necessary."
2041 def test_defaultTestResult(self):
2042 class Foo(unittest.TestCase):
2043 def runTest(self):
2044 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002045
Georg Brandl15c5ce92007-03-07 09:09:40 +00002046 result = Foo().defaultTestResult()
2047 self.assertEqual(type(result), unittest.TestResult)
2048
2049 # "When a setUp() method is defined, the test runner will run that method
2050 # prior to each test. Likewise, if a tearDown() method is defined, the
2051 # test runner will invoke that method after each test. In the example,
2052 # setUp() was used to create a fresh sequence for each test."
2053 #
2054 # Make sure the proper call order is maintained, even if setUp() raises
2055 # an exception.
2056 def test_run_call_order__error_in_setUp(self):
2057 events = []
2058 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002059
Georg Brandl15c5ce92007-03-07 09:09:40 +00002060 class Foo(unittest.TestCase):
2061 def setUp(self):
2062 events.append('setUp')
2063 raise RuntimeError('raised by Foo.setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002064
Georg Brandl15c5ce92007-03-07 09:09:40 +00002065 def test(self):
2066 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002067
Georg Brandl15c5ce92007-03-07 09:09:40 +00002068 def tearDown(self):
2069 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002070
Georg Brandl15c5ce92007-03-07 09:09:40 +00002071 Foo('test').run(result)
2072 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2073 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002074
Georg Brandl15c5ce92007-03-07 09:09:40 +00002075 # "When a setUp() method is defined, the test runner will run that method
2076 # prior to each test. Likewise, if a tearDown() method is defined, the
2077 # test runner will invoke that method after each test. In the example,
2078 # setUp() was used to create a fresh sequence for each test."
2079 #
2080 # Make sure the proper call order is maintained, even if the test raises
2081 # an error (as opposed to a failure).
2082 def test_run_call_order__error_in_test(self):
2083 events = []
2084 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002085
Georg Brandl15c5ce92007-03-07 09:09:40 +00002086 class Foo(unittest.TestCase):
2087 def setUp(self):
2088 events.append('setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002089
Georg Brandl15c5ce92007-03-07 09:09:40 +00002090 def test(self):
2091 events.append('test')
2092 raise RuntimeError('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002093
Georg Brandl15c5ce92007-03-07 09:09:40 +00002094 def tearDown(self):
2095 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002096
Georg Brandl15c5ce92007-03-07 09:09:40 +00002097 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2098 'stopTest']
2099 Foo('test').run(result)
2100 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002101
Georg Brandl15c5ce92007-03-07 09:09:40 +00002102 # "When a setUp() method is defined, the test runner will run that method
2103 # prior to each test. Likewise, if a tearDown() method is defined, the
2104 # test runner will invoke that method after each test. In the example,
2105 # setUp() was used to create a fresh sequence for each test."
2106 #
2107 # Make sure the proper call order is maintained, even if the test signals
2108 # a failure (as opposed to an error).
2109 def test_run_call_order__failure_in_test(self):
2110 events = []
2111 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002112
Georg Brandl15c5ce92007-03-07 09:09:40 +00002113 class Foo(unittest.TestCase):
2114 def setUp(self):
2115 events.append('setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002116
Georg Brandl15c5ce92007-03-07 09:09:40 +00002117 def test(self):
2118 events.append('test')
2119 self.fail('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002120
Georg Brandl15c5ce92007-03-07 09:09:40 +00002121 def tearDown(self):
2122 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002123
Georg Brandl15c5ce92007-03-07 09:09:40 +00002124 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2125 'stopTest']
2126 Foo('test').run(result)
2127 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002128
Georg Brandl15c5ce92007-03-07 09:09:40 +00002129 # "When a setUp() method is defined, the test runner will run that method
2130 # prior to each test. Likewise, if a tearDown() method is defined, the
2131 # test runner will invoke that method after each test. In the example,
2132 # setUp() was used to create a fresh sequence for each test."
2133 #
2134 # Make sure the proper call order is maintained, even if tearDown() raises
2135 # an exception.
2136 def test_run_call_order__error_in_tearDown(self):
2137 events = []
2138 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002139
Georg Brandl15c5ce92007-03-07 09:09:40 +00002140 class Foo(unittest.TestCase):
2141 def setUp(self):
2142 events.append('setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002143
Georg Brandl15c5ce92007-03-07 09:09:40 +00002144 def test(self):
2145 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002146
Georg Brandl15c5ce92007-03-07 09:09:40 +00002147 def tearDown(self):
2148 events.append('tearDown')
2149 raise RuntimeError('raised by Foo.tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002150
Georg Brandl15c5ce92007-03-07 09:09:40 +00002151 Foo('test').run(result)
2152 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2153 'stopTest']
2154 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002155
Georg Brandl15c5ce92007-03-07 09:09:40 +00002156 # "This class attribute gives the exception raised by the test() method.
2157 # If a test framework needs to use a specialized exception, possibly to
2158 # carry additional information, it must subclass this exception in
2159 # order to ``play fair'' with the framework. The initial value of this
2160 # attribute is AssertionError"
2161 def test_failureException__default(self):
2162 class Foo(unittest.TestCase):
2163 def test(self):
2164 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002165
Georg Brandl15c5ce92007-03-07 09:09:40 +00002166 self.failUnless(Foo('test').failureException is AssertionError)
Tim Petersea5962f2007-03-12 18:07:52 +00002167
Georg Brandl15c5ce92007-03-07 09:09:40 +00002168 # "This class attribute gives the exception raised by the test() method.
2169 # If a test framework needs to use a specialized exception, possibly to
2170 # carry additional information, it must subclass this exception in
2171 # order to ``play fair'' with the framework."
2172 #
2173 # Make sure TestCase.run() respects the designated failureException
2174 def test_failureException__subclassing__explicit_raise(self):
2175 events = []
2176 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002177
Georg Brandl15c5ce92007-03-07 09:09:40 +00002178 class Foo(unittest.TestCase):
2179 def test(self):
2180 raise RuntimeError()
Tim Petersea5962f2007-03-12 18:07:52 +00002181
Georg Brandl15c5ce92007-03-07 09:09:40 +00002182 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002183
Georg Brandl15c5ce92007-03-07 09:09:40 +00002184 self.failUnless(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002185
2186
Georg Brandl15c5ce92007-03-07 09:09:40 +00002187 Foo('test').run(result)
2188 expected = ['startTest', 'addFailure', 'stopTest']
2189 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002190
Georg Brandl15c5ce92007-03-07 09:09:40 +00002191 # "This class attribute gives the exception raised by the test() method.
2192 # If a test framework needs to use a specialized exception, possibly to
2193 # carry additional information, it must subclass this exception in
2194 # order to ``play fair'' with the framework."
2195 #
2196 # Make sure TestCase.run() respects the designated failureException
2197 def test_failureException__subclassing__implicit_raise(self):
2198 events = []
2199 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002200
Georg Brandl15c5ce92007-03-07 09:09:40 +00002201 class Foo(unittest.TestCase):
2202 def test(self):
2203 self.fail("foo")
Tim Petersea5962f2007-03-12 18:07:52 +00002204
Georg Brandl15c5ce92007-03-07 09:09:40 +00002205 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002206
Georg Brandl15c5ce92007-03-07 09:09:40 +00002207 self.failUnless(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002208
2209
Georg Brandl15c5ce92007-03-07 09:09:40 +00002210 Foo('test').run(result)
2211 expected = ['startTest', 'addFailure', 'stopTest']
2212 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002213
2214 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002215 def test_setUp(self):
2216 class Foo(unittest.TestCase):
2217 def runTest(self):
2218 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002219
Georg Brandl15c5ce92007-03-07 09:09:40 +00002220 # ... and nothing should happen
2221 Foo().setUp()
Tim Petersea5962f2007-03-12 18:07:52 +00002222
2223 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002224 def test_tearDown(self):
2225 class Foo(unittest.TestCase):
2226 def runTest(self):
2227 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002228
Georg Brandl15c5ce92007-03-07 09:09:40 +00002229 # ... and nothing should happen
2230 Foo().tearDown()
Tim Petersea5962f2007-03-12 18:07:52 +00002231
Georg Brandl15c5ce92007-03-07 09:09:40 +00002232 # "Return a string identifying the specific test case."
2233 #
2234 # Because of the vague nature of the docs, I'm not going to lock this
2235 # test down too much. Really all that can be asserted is that the id()
2236 # will be a string (either 8-byte or unicode -- again, because the docs
2237 # just say "string")
2238 def test_id(self):
2239 class Foo(unittest.TestCase):
2240 def runTest(self):
2241 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002242
Georg Brandl15c5ce92007-03-07 09:09:40 +00002243 self.failUnless(isinstance(Foo().id(), basestring))
Tim Petersea5962f2007-03-12 18:07:52 +00002244
Georg Brandl15c5ce92007-03-07 09:09:40 +00002245 # "If result is omitted or None, a temporary result object is created
Tim Petersea5962f2007-03-12 18:07:52 +00002246 # and used, but is not made available to the caller"
Georg Brandl15c5ce92007-03-07 09:09:40 +00002247 def test_run__uses_defaultTestResult(self):
2248 events = []
Tim Petersea5962f2007-03-12 18:07:52 +00002249
Georg Brandl15c5ce92007-03-07 09:09:40 +00002250 class Foo(unittest.TestCase):
2251 def test(self):
2252 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002253
Georg Brandl15c5ce92007-03-07 09:09:40 +00002254 def defaultTestResult(self):
2255 return LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002256
2257 # Make run() find a result object on its own
Georg Brandl15c5ce92007-03-07 09:09:40 +00002258 Foo('test').run()
Tim Petersea5962f2007-03-12 18:07:52 +00002259
Benjamin Peterson692428e2009-03-23 21:50:21 +00002260 expected = ['startTest', 'test', 'addSuccess', 'stopTest']
Georg Brandl15c5ce92007-03-07 09:09:40 +00002261 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002262
Gregory P. Smith28399852009-03-31 16:54:10 +00002263 def testShortDescriptionWithoutDocstring(self):
2264 self.assertEqual(
2265 self.shortDescription(),
2266 'testShortDescriptionWithoutDocstring (' + __name__ +
2267 '.Test_TestCase)')
2268
2269 def testShortDescriptionWithOneLineDocstring(self):
2270 """Tests shortDescription() for a method with a docstring."""
2271 self.assertEqual(
2272 self.shortDescription(),
2273 ('testShortDescriptionWithOneLineDocstring '
2274 '(' + __name__ + '.Test_TestCase)\n'
2275 'Tests shortDescription() for a method with a docstring.'))
2276
2277 def testShortDescriptionWithMultiLineDocstring(self):
2278 """Tests shortDescription() for a method with a longer docstring.
2279
2280 This method ensures that only the first line of a docstring is
2281 returned used in the short description, no matter how long the
2282 whole thing is.
2283 """
2284 self.assertEqual(
2285 self.shortDescription(),
2286 ('testShortDescriptionWithMultiLineDocstring '
2287 '(' + __name__ + '.Test_TestCase)\n'
2288 'Tests shortDescription() for a method with a longer '
2289 'docstring.'))
2290
Gregory P. Smith28399852009-03-31 16:54:10 +00002291 def testAddTypeEqualityFunc(self):
2292 class SadSnake(object):
2293 """Dummy class for test_addTypeEqualityFunc."""
2294 s1, s2 = SadSnake(), SadSnake()
2295 self.assertFalse(s1 == s2)
2296 def AllSnakesCreatedEqual(a, b, msg=None):
2297 return type(a) == type(b) == SadSnake
2298 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2299 self.assertEqual(s1, s2)
2300 # No this doesn't clean up and remove the SadSnake equality func
2301 # from this TestCase instance but since its a local nothing else
2302 # will ever notice that.
2303
Michael Foordf2dfef12009-04-05 19:19:28 +00002304 def testAssertIs(self):
2305 thing = object()
2306 self.assertIs(thing, thing)
2307 self.assertRaises(self.failureException, self.assertIs, thing, object())
2308
2309 def testAssertIsNot(self):
2310 thing = object()
2311 self.assertIsNot(thing, object())
2312 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2313
Gregory P. Smith28399852009-03-31 16:54:10 +00002314 def testAssertIn(self):
2315 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2316
2317 self.assertIn('a', 'abc')
2318 self.assertIn(2, [1, 2, 3])
2319 self.assertIn('monkey', animals)
2320
2321 self.assertNotIn('d', 'abc')
2322 self.assertNotIn(0, [1, 2, 3])
2323 self.assertNotIn('otter', animals)
2324
2325 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2326 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2327 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2328 animals)
2329
2330 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2331 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2332 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2333 animals)
2334
2335 def testAssertDictContainsSubset(self):
2336 self.assertDictContainsSubset({}, {})
2337 self.assertDictContainsSubset({}, {'a': 1})
2338 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2339 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2340 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2341
2342 self.assertRaises(unittest.TestCase.failureException,
2343 self.assertDictContainsSubset, {'a': 2}, {'a': 1},
2344 '.*Mismatched values:.*')
2345
2346 self.assertRaises(unittest.TestCase.failureException,
2347 self.assertDictContainsSubset, {'c': 1}, {'a': 1},
2348 '.*Missing:.*')
2349
2350 self.assertRaises(unittest.TestCase.failureException,
2351 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2352 {'a': 1}, '.*Missing:.*')
2353
2354 self.assertRaises(unittest.TestCase.failureException,
2355 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2356 {'a': 1}, '.*Missing:.*Mismatched values:.*')
2357
2358 def testAssertEqual(self):
2359 equal_pairs = [
2360 ((), ()),
2361 ({}, {}),
2362 ([], []),
2363 (set(), set()),
2364 (frozenset(), frozenset())]
2365 for a, b in equal_pairs:
2366 # This mess of try excepts is to test the assertEqual behavior
2367 # itself.
2368 try:
2369 self.assertEqual(a, b)
2370 except self.failureException:
2371 self.fail('assertEqual(%r, %r) failed' % (a, b))
2372 try:
2373 self.assertEqual(a, b, msg='foo')
2374 except self.failureException:
2375 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2376 try:
2377 self.assertEqual(a, b, 'foo')
2378 except self.failureException:
2379 self.fail('assertEqual(%r, %r) with third parameter failed' %
2380 (a, b))
2381
2382 unequal_pairs = [
2383 ((), []),
2384 ({}, set()),
2385 (set([4,1]), frozenset([4,2])),
2386 (frozenset([4,5]), set([2,3])),
2387 (set([3,4]), set([5,4]))]
2388 for a, b in unequal_pairs:
2389 self.assertRaises(self.failureException, self.assertEqual, a, b)
2390 self.assertRaises(self.failureException, self.assertEqual, a, b,
2391 'foo')
2392 self.assertRaises(self.failureException, self.assertEqual, a, b,
2393 msg='foo')
2394
2395 def testEquality(self):
2396 self.assertListEqual([], [])
2397 self.assertTupleEqual((), ())
2398 self.assertSequenceEqual([], ())
2399
2400 a = [0, 'a', []]
2401 b = []
2402 self.assertRaises(unittest.TestCase.failureException,
2403 self.assertListEqual, a, b)
2404 self.assertRaises(unittest.TestCase.failureException,
2405 self.assertListEqual, tuple(a), tuple(b))
2406 self.assertRaises(unittest.TestCase.failureException,
2407 self.assertSequenceEqual, a, tuple(b))
2408
2409 b.extend(a)
2410 self.assertListEqual(a, b)
2411 self.assertTupleEqual(tuple(a), tuple(b))
2412 self.assertSequenceEqual(a, tuple(b))
2413 self.assertSequenceEqual(tuple(a), b)
2414
2415 self.assertRaises(self.failureException, self.assertListEqual,
2416 a, tuple(b))
2417 self.assertRaises(self.failureException, self.assertTupleEqual,
2418 tuple(a), b)
2419 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2420 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2421 tuple(b))
2422 self.assertRaises(self.failureException, self.assertSequenceEqual,
2423 None, tuple(b))
2424 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2425 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2426 self.assertRaises(self.failureException, self.assertSequenceEqual,
2427 1, 1)
2428
2429 self.assertDictEqual({}, {})
2430
2431 c = { 'x': 1 }
2432 d = {}
2433 self.assertRaises(unittest.TestCase.failureException,
2434 self.assertDictEqual, c, d)
2435
2436 d.update(c)
2437 self.assertDictEqual(c, d)
2438
2439 d['x'] = 0
2440 self.assertRaises(unittest.TestCase.failureException,
2441 self.assertDictEqual, c, d, 'These are unequal')
2442
2443 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2444 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2445 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2446
2447 self.assertSameElements([1, 2, 3], [3, 2, 1])
2448 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2449 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2450 self.assertRaises(self.failureException, self.assertSameElements,
2451 [10], [10, 11])
2452 self.assertRaises(self.failureException, self.assertSameElements,
2453 [10, 11], [10])
2454
2455 # Test that sequences of unhashable objects can be tested for sameness:
2456 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Michael Foordf2dfef12009-04-05 19:19:28 +00002457
Gregory P. Smith28399852009-03-31 16:54:10 +00002458 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2459 self.assertRaises(self.failureException, self.assertSameElements,
2460 [[1]], [[2]])
2461
2462 def testAssertSetEqual(self):
2463 set1 = set()
2464 set2 = set()
2465 self.assertSetEqual(set1, set2)
2466
2467 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2468 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2469 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2470 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2471
2472 set1 = set(['a'])
2473 set2 = set()
2474 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2475
2476 set1 = set(['a'])
2477 set2 = set(['a'])
2478 self.assertSetEqual(set1, set2)
2479
2480 set1 = set(['a'])
2481 set2 = set(['a', 'b'])
2482 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2483
2484 set1 = set(['a'])
2485 set2 = frozenset(['a', 'b'])
2486 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2487
2488 set1 = set(['a', 'b'])
2489 set2 = frozenset(['a', 'b'])
2490 self.assertSetEqual(set1, set2)
2491
2492 set1 = set()
2493 set2 = "foo"
2494 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2495 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2496
2497 # make sure any string formatting is tuple-safe
2498 set1 = set([(0, 1), (2, 3)])
2499 set2 = set([(4, 5)])
2500 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2501
2502 def testInequality(self):
2503 # Try ints
2504 self.assertGreater(2, 1)
2505 self.assertGreaterEqual(2, 1)
2506 self.assertGreaterEqual(1, 1)
2507 self.assertLess(1, 2)
2508 self.assertLessEqual(1, 2)
2509 self.assertLessEqual(1, 1)
2510 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2511 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2512 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2513 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2514 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2515 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2516
2517 # Try Floats
2518 self.assertGreater(1.1, 1.0)
2519 self.assertGreaterEqual(1.1, 1.0)
2520 self.assertGreaterEqual(1.0, 1.0)
2521 self.assertLess(1.0, 1.1)
2522 self.assertLessEqual(1.0, 1.1)
2523 self.assertLessEqual(1.0, 1.0)
2524 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2525 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2526 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2527 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2528 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2529 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2530
2531 # Try Strings
2532 self.assertGreater('bug', 'ant')
2533 self.assertGreaterEqual('bug', 'ant')
2534 self.assertGreaterEqual('ant', 'ant')
2535 self.assertLess('ant', 'bug')
2536 self.assertLessEqual('ant', 'bug')
2537 self.assertLessEqual('ant', 'ant')
2538 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2539 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2540 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2541 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2542 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2543 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2544
2545 # Try Unicode
2546 self.assertGreater(u'bug', u'ant')
2547 self.assertGreaterEqual(u'bug', u'ant')
2548 self.assertGreaterEqual(u'ant', u'ant')
2549 self.assertLess(u'ant', u'bug')
2550 self.assertLessEqual(u'ant', u'bug')
2551 self.assertLessEqual(u'ant', u'ant')
2552 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug')
2553 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant')
2554 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2555 u'bug')
2556 self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant')
2557 self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant')
2558 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant')
2559
2560 # Try Mixed String/Unicode
2561 self.assertGreater('bug', u'ant')
2562 self.assertGreater(u'bug', 'ant')
2563 self.assertGreaterEqual('bug', u'ant')
2564 self.assertGreaterEqual(u'bug', 'ant')
2565 self.assertGreaterEqual('ant', u'ant')
2566 self.assertGreaterEqual(u'ant', 'ant')
2567 self.assertLess('ant', u'bug')
2568 self.assertLess(u'ant', 'bug')
2569 self.assertLessEqual('ant', u'bug')
2570 self.assertLessEqual(u'ant', 'bug')
2571 self.assertLessEqual('ant', u'ant')
2572 self.assertLessEqual(u'ant', 'ant')
2573 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug')
2574 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug')
2575 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant')
2576 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant')
2577 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant',
2578 u'bug')
2579 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2580 'bug')
2581 self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant')
2582 self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant')
2583 self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant')
2584 self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant')
2585 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant')
2586 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant')
2587
2588 def testAssertMultiLineEqual(self):
2589 sample_text = b"""\
2590http://www.python.org/doc/2.3/lib/module-unittest.html
2591test case
2592 A test case is the smallest unit of testing. [...]
2593"""
2594 revised_sample_text = b"""\
2595http://www.python.org/doc/2.4.1/lib/module-unittest.html
2596test case
2597 A test case is the smallest unit of testing. [...] You may provide your
2598 own implementation that does not subclass from TestCase, of course.
2599"""
2600 sample_text_error = b"""
2601- http://www.python.org/doc/2.3/lib/module-unittest.html
2602? ^
2603+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2604? ^^^
2605 test case
2606- A test case is the smallest unit of testing. [...]
2607+ A test case is the smallest unit of testing. [...] You may provide your
2608? +++++++++++++++++++++
2609+ own implementation that does not subclass from TestCase, of course.
2610"""
2611
2612 for type_changer in (lambda x: x, lambda x: x.decode('utf8')):
2613 try:
2614 self.assertMultiLineEqual(type_changer(sample_text),
2615 type_changer(revised_sample_text))
2616 except self.failureException, e:
2617 # no fair testing ourself with ourself, use assertEqual..
2618 self.assertEqual(sample_text_error, str(e).encode('utf8'))
2619
2620 def testAssertIsNone(self):
2621 self.assertIsNone(None)
2622 self.assertRaises(self.failureException, self.assertIsNone, False)
2623 self.assertIsNotNone('DjZoPloGears on Rails')
2624 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2625
2626 def testAssertRegexpMatches(self):
2627 self.assertRegexpMatches('asdfabasdf', r'ab+')
2628 self.assertRaises(self.failureException, self.assertRegexpMatches,
2629 'saaas', r'aaaa')
2630
2631 def testAssertRaisesRegexp(self):
2632 class ExceptionMock(Exception):
2633 pass
2634
2635 def Stub():
2636 raise ExceptionMock('We expect')
2637
2638 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2639 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2640 self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
2641
2642 def testAssertNotRaisesRegexp(self):
2643 self.assertRaisesRegexp(
2644 self.failureException, '^Exception not raised$',
2645 self.assertRaisesRegexp, Exception, re.compile('x'),
2646 lambda: None)
2647 self.assertRaisesRegexp(
2648 self.failureException, '^Exception not raised$',
2649 self.assertRaisesRegexp, Exception, 'x',
2650 lambda: None)
2651 self.assertRaisesRegexp(
2652 self.failureException, '^Exception not raised$',
2653 self.assertRaisesRegexp, Exception, u'x',
2654 lambda: None)
2655
2656 def testAssertRaisesRegexpMismatch(self):
2657 def Stub():
2658 raise Exception('Unexpected')
2659
2660 self.assertRaisesRegexp(
2661 self.failureException,
2662 r'"\^Expected\$" does not match "Unexpected"',
2663 self.assertRaisesRegexp, Exception, '^Expected$',
2664 Stub)
2665 self.assertRaisesRegexp(
2666 self.failureException,
2667 r'"\^Expected\$" does not match "Unexpected"',
2668 self.assertRaisesRegexp, Exception, u'^Expected$',
2669 Stub)
2670 self.assertRaisesRegexp(
2671 self.failureException,
2672 r'"\^Expected\$" does not match "Unexpected"',
2673 self.assertRaisesRegexp, Exception,
2674 re.compile('^Expected$'), Stub)
2675
Gregory P. Smith7558d572009-03-31 19:03:28 +00002676 def testSynonymAssertMethodNames(self):
2677 """Test undocumented method name synonyms.
2678
2679 Please do not use these methods names in your own code.
2680
2681 This test confirms their continued existence and functionality
2682 in order to avoid breaking existing code.
2683 """
2684 self.assertNotEquals(3, 5)
2685 self.assertEquals(3, 3)
2686 self.assertAlmostEquals(2.0, 2.0)
2687 self.assertNotAlmostEquals(3.0, 5.0)
2688 self.assert_(True)
2689
2690 def testPendingDeprecationMethodNames(self):
2691 """Test fail* methods pending deprecation, they will warn in 3.2.
2692
2693 Do not use these methods. They will go away in 3.3.
2694 """
2695 self.failIfEqual(3, 5)
2696 self.failUnlessEqual(3, 3)
2697 self.failUnlessAlmostEqual(2.0, 2.0)
2698 self.failIfAlmostEqual(3.0, 5.0)
2699 self.failUnless(True)
2700 self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam')
2701 self.failIf(False)
2702
Michael Foorde2942d02009-04-02 05:51:54 +00002703 def testDeepcopy(self):
2704 # Issue: 5660
2705 class TestableTest(TestCase):
2706 def testNothing(self):
2707 pass
2708
2709 test = TestableTest('testNothing')
2710
2711 # This shouldn't blow up
2712 deepcopy(test)
2713
Benjamin Peterson692428e2009-03-23 21:50:21 +00002714
2715class Test_TestSkipping(TestCase):
2716
2717 def test_skipping(self):
2718 class Foo(unittest.TestCase):
2719 def test_skip_me(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002720 self.skipTest("skip")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002721 events = []
2722 result = LoggingResult(events)
2723 test = Foo("test_skip_me")
2724 test.run(result)
2725 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2726 self.assertEqual(result.skipped, [(test, "skip")])
2727
2728 # Try letting setUp skip the test now.
2729 class Foo(unittest.TestCase):
2730 def setUp(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002731 self.skipTest("testing")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002732 def test_nothing(self): pass
2733 events = []
2734 result = LoggingResult(events)
2735 test = Foo("test_nothing")
2736 test.run(result)
2737 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2738 self.assertEqual(result.skipped, [(test, "testing")])
2739 self.assertEqual(result.testsRun, 1)
2740
2741 def test_skipping_decorators(self):
2742 op_table = ((unittest.skipUnless, False, True),
2743 (unittest.skipIf, True, False))
2744 for deco, do_skip, dont_skip in op_table:
2745 class Foo(unittest.TestCase):
2746 @deco(do_skip, "testing")
2747 def test_skip(self): pass
2748
2749 @deco(dont_skip, "testing")
2750 def test_dont_skip(self): pass
2751 test_do_skip = Foo("test_skip")
2752 test_dont_skip = Foo("test_dont_skip")
2753 suite = unittest.ClassTestSuite([test_do_skip, test_dont_skip], Foo)
2754 events = []
2755 result = LoggingResult(events)
2756 suite.run(result)
2757 self.assertEqual(len(result.skipped), 1)
2758 expected = ['startTest', 'addSkip', 'stopTest',
2759 'startTest', 'addSuccess', 'stopTest']
2760 self.assertEqual(events, expected)
2761 self.assertEqual(result.testsRun, 2)
2762 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
2763 self.assertTrue(result.wasSuccessful())
2764
2765 def test_skip_class(self):
2766 @unittest.skip("testing")
2767 class Foo(unittest.TestCase):
2768 def test_1(self):
2769 record.append(1)
2770 record = []
2771 result = unittest.TestResult()
2772 suite = unittest.ClassTestSuite([Foo("test_1")], Foo)
2773 suite.run(result)
2774 self.assertEqual(result.skipped, [(suite, "testing")])
2775 self.assertEqual(record, [])
2776
2777 def test_expected_failure(self):
2778 class Foo(unittest.TestCase):
2779 @unittest.expectedFailure
2780 def test_die(self):
2781 self.fail("help me!")
2782 events = []
2783 result = LoggingResult(events)
2784 test = Foo("test_die")
2785 test.run(result)
2786 self.assertEqual(events,
2787 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00002788 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00002789 self.assertTrue(result.wasSuccessful())
2790
2791 def test_unexpected_success(self):
2792 class Foo(unittest.TestCase):
2793 @unittest.expectedFailure
2794 def test_die(self):
2795 pass
2796 events = []
2797 result = LoggingResult(events)
2798 test = Foo("test_die")
2799 test.run(result)
2800 self.assertEqual(events,
2801 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
2802 self.assertFalse(result.failures)
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00002803 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002804 self.assertTrue(result.wasSuccessful())
2805
2806
2807
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002808class Test_Assertions(TestCase):
2809 def test_AlmostEqual(self):
2810 self.failUnlessAlmostEqual(1.00000001, 1.0)
2811 self.failIfAlmostEqual(1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00002812 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002813 self.failUnlessAlmostEqual, 1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00002814 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002815 self.failIfAlmostEqual, 1.00000001, 1.0)
2816
2817 self.failUnlessAlmostEqual(1.1, 1.0, places=0)
Gregory P. Smith28399852009-03-31 16:54:10 +00002818 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002819 self.failUnlessAlmostEqual, 1.1, 1.0, places=1)
2820
2821 self.failUnlessAlmostEqual(0, .1+.1j, places=0)
2822 self.failIfAlmostEqual(0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00002823 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002824 self.failUnlessAlmostEqual, 0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00002825 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002826 self.failIfAlmostEqual, 0, .1+.1j, places=0)
2827
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00002828 def test_assertRaises(self):
2829 def _raise(e):
2830 raise e
2831 self.assertRaises(KeyError, _raise, KeyError)
2832 self.assertRaises(KeyError, _raise, KeyError("key"))
2833 try:
2834 self.assertRaises(KeyError, lambda: None)
Gregory P. Smith28399852009-03-31 16:54:10 +00002835 except self.failureException as e:
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00002836 self.assert_("KeyError not raised" in e, str(e))
2837 else:
2838 self.fail("assertRaises() didn't fail")
2839 try:
2840 self.assertRaises(KeyError, _raise, ValueError)
2841 except ValueError:
2842 pass
2843 else:
2844 self.fail("assertRaises() didn't let exception pass through")
2845 with self.assertRaises(KeyError):
2846 raise KeyError
2847 with self.assertRaises(KeyError):
2848 raise KeyError("key")
2849 try:
2850 with self.assertRaises(KeyError):
2851 pass
Gregory P. Smith28399852009-03-31 16:54:10 +00002852 except self.failureException as e:
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00002853 self.assert_("KeyError not raised" in e, str(e))
2854 else:
2855 self.fail("assertRaises() didn't fail")
2856 try:
2857 with self.assertRaises(KeyError):
2858 raise ValueError
2859 except ValueError:
2860 pass
2861 else:
2862 self.fail("assertRaises() didn't let exception pass through")
2863
2864
Michael Foord345b2fe2009-04-02 03:20:38 +00002865class TestLongMessage(TestCase):
2866 """Test that the individual asserts honour longMessage.
2867 This actually tests all the message behaviour for
2868 asserts that use longMessage."""
2869
2870 def setUp(self):
2871 class TestableTestFalse(TestCase):
2872 longMessage = False
2873 failureException = self.failureException
2874
2875 def testTest(self):
2876 pass
2877
2878 class TestableTestTrue(TestCase):
2879 longMessage = True
2880 failureException = self.failureException
2881
2882 def testTest(self):
2883 pass
2884
2885 self.testableTrue = TestableTestTrue('testTest')
2886 self.testableFalse = TestableTestFalse('testTest')
2887
2888 def testDefault(self):
2889 self.assertFalse(TestCase.longMessage)
2890
2891 def test_formatMsg(self):
2892 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
2893 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
2894
2895 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
2896 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
2897
2898 def assertMessages(self, methodName, args, errors):
2899 def getMethod(i):
2900 useTestableFalse = i < 2
2901 if useTestableFalse:
2902 test = self.testableFalse
2903 else:
2904 test = self.testableTrue
2905 return getattr(test, methodName)
2906
2907 for i, expected_regexp in enumerate(errors):
2908 testMethod = getMethod(i)
2909 kwargs = {}
2910 withMsg = i % 2
2911 if withMsg:
2912 kwargs = {"msg": "oops"}
2913
2914 with self.assertRaisesRegexp(self.failureException,
2915 expected_regexp=expected_regexp):
2916 testMethod(*args, **kwargs)
2917
2918 def testAssertTrue(self):
2919 self.assertMessages('assertTrue', (False,),
2920 ["^False is not True$", "^oops$", "^False is not True$",
2921 "^False is not True : oops$"])
2922
2923 def testAssertFalse(self):
2924 self.assertMessages('assertFalse', (True,),
2925 ["^True is not False$", "^oops$", "^True is not False$",
2926 "^True is not False : oops$"])
2927
2928 def testNotEqual(self):
2929 self.assertMessages('assertNotEqual', (1, 1),
2930 ["^1 == 1$", "^oops$", "^1 == 1$",
2931 "^1 == 1 : oops$"])
2932
2933 def testAlmostEqual(self):
2934 self.assertMessages('assertAlmostEqual', (1, 2),
2935 ["^1 != 2 within 7 places$", "^oops$",
2936 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
2937
2938 def testNotAlmostEqual(self):
2939 self.assertMessages('assertNotAlmostEqual', (1, 1),
2940 ["^1 == 1 within 7 places$", "^oops$",
2941 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
2942
2943 def test_baseAssertEqual(self):
2944 self.assertMessages('_baseAssertEqual', (1, 2),
2945 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
2946
2947 def testAssertSequenceEqual(self):
2948 # Error messages are multiline so not testing on full message
2949 # assertTupleEqual and assertListEqual delegate to this method
2950 self.assertMessages('assertSequenceEqual', ([], [None]),
2951 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
2952 r"\+ \[None\] : oops$"])
2953
2954 def testAssertSetEqual(self):
2955 self.assertMessages('assertSetEqual', (set(), set([None])),
2956 ["None$", "^oops$", "None$",
2957 "None : oops$"])
2958
2959 def testAssertIn(self):
2960 self.assertMessages('assertIn', (None, []),
2961 ['^None not found in \[\]$', "^oops$",
2962 '^None not found in \[\]$',
2963 '^None not found in \[\] : oops$'])
2964
2965 def testAssertNotIn(self):
2966 self.assertMessages('assertNotIn', (None, [None]),
2967 ['^None unexpectedly found in \[None\]$', "^oops$",
2968 '^None unexpectedly found in \[None\]$',
2969 '^None unexpectedly found in \[None\] : oops$'])
2970
2971 def testAssertDictEqual(self):
2972 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
2973 [r"\+ \{'key': 'value'\}$", "^oops$",
2974 "\+ \{'key': 'value'\}$",
2975 "\+ \{'key': 'value'\} : oops$"])
2976
2977 def testAssertDictContainsSubset(self):
2978 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
2979 ["^Missing: 'key'$", "^oops$",
2980 "^Missing: 'key'$",
2981 "^Missing: 'key' : oops$"])
2982
2983 def testAssertSameElements(self):
2984 self.assertMessages('assertSameElements', ([], [None]),
2985 [r"\[None\]$", "^oops$",
2986 r"\[None\]$",
2987 r"\[None\] : oops$"])
2988
2989 def testAssertMultiLineEqual(self):
2990 self.assertMessages('assertMultiLineEqual', ("", "foo"),
2991 [r"\+ foo$", "^oops$",
2992 r"\+ foo$",
2993 r"\+ foo : oops$"])
2994
2995 def testAssertLess(self):
2996 self.assertMessages('assertLess', (2, 1),
2997 ["^2 not less than 1$", "^oops$",
2998 "^2 not less than 1$", "^2 not less than 1 : oops$"])
2999
3000 def testAssertLessEqual(self):
3001 self.assertMessages('assertLessEqual', (2, 1),
3002 ["^2 not less than or equal to 1$", "^oops$",
3003 "^2 not less than or equal to 1$",
3004 "^2 not less than or equal to 1 : oops$"])
3005
3006 def testAssertGreater(self):
3007 self.assertMessages('assertGreater', (1, 2),
3008 ["^1 not greater than 2$", "^oops$",
3009 "^1 not greater than 2$",
3010 "^1 not greater than 2 : oops$"])
3011
3012 def testAssertGreaterEqual(self):
3013 self.assertMessages('assertGreaterEqual', (1, 2),
3014 ["^1 not greater than or equal to 2$", "^oops$",
3015 "^1 not greater than or equal to 2$",
3016 "^1 not greater than or equal to 2 : oops$"])
3017
3018 def testAssertIsNone(self):
3019 self.assertMessages('assertIsNone', ('not None',),
3020 ["^'not None' is not None$", "^oops$",
3021 "^'not None' is not None$",
3022 "^'not None' is not None : oops$"])
3023
3024 def testAssertIsNotNone(self):
3025 self.assertMessages('assertIsNotNone', (None,),
3026 ["^unexpectedly None$", "^oops$",
3027 "^unexpectedly None$",
3028 "^unexpectedly None : oops$"])
3029
Michael Foordf2dfef12009-04-05 19:19:28 +00003030 def testAssertIs(self):
3031 self.assertMessages('assertIs', (None, 'foo'),
3032 ["^None is not 'foo'$", "^oops$",
3033 "^None is not 'foo'$",
3034 "^None is not 'foo' : oops$"])
3035
3036 def testAssertIsNot(self):
3037 self.assertMessages('assertIsNot', (None, None),
3038 ["^unexpectedly identical: None$", "^oops$",
3039 "^unexpectedly identical: None$",
3040 "^unexpectedly identical: None : oops$"])
3041
Michael Foord345b2fe2009-04-02 03:20:38 +00003042
Jim Fultonfafd8742004-08-28 15:22:12 +00003043######################################################################
3044## Main
3045######################################################################
3046
3047def test_main():
Georg Brandl15c5ce92007-03-07 09:09:40 +00003048 test_support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003049 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Michael Foord345b2fe2009-04-02 03:20:38 +00003050 Test_TestSkipping, Test_Assertions, TestLongMessage)
Jim Fultonfafd8742004-08-28 15:22:12 +00003051
Georg Brandl15c5ce92007-03-07 09:09:40 +00003052if __name__ == "__main__":
Tim Petersea5962f2007-03-12 18:07:52 +00003053 test_main()