blob: bb534fcd0a002b58160797ae0727f66575f1b4bc [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
Michael Foord829f6b82009-05-02 11:43:06 +000012from unittest import TestCase, TestProgram
Christian Heimesc756d002007-11-27 21:34:01 +000013import types
Michael Foorde2942d02009-04-02 05:51:54 +000014from copy import deepcopy
Michael Foord829f6b82009-05-02 11:43:06 +000015from cStringIO import StringIO
Jim Fultonfafd8742004-08-28 15:22:12 +000016
Georg Brandl15c5ce92007-03-07 09:09:40 +000017### Support code
18################################################################
Jim Fultonfafd8742004-08-28 15:22:12 +000019
Georg Brandl15c5ce92007-03-07 09:09:40 +000020class LoggingResult(unittest.TestResult):
21 def __init__(self, log):
22 self._events = log
23 super(LoggingResult, self).__init__()
24
25 def startTest(self, test):
26 self._events.append('startTest')
27 super(LoggingResult, self).startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +000028
Georg Brandl15c5ce92007-03-07 09:09:40 +000029 def stopTest(self, test):
30 self._events.append('stopTest')
31 super(LoggingResult, self).stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +000032
Georg Brandl15c5ce92007-03-07 09:09:40 +000033 def addFailure(self, *args):
34 self._events.append('addFailure')
35 super(LoggingResult, self).addFailure(*args)
Tim Petersea5962f2007-03-12 18:07:52 +000036
Benjamin Peterson692428e2009-03-23 21:50:21 +000037 def addSuccess(self, *args):
38 self._events.append('addSuccess')
39 super(LoggingResult, self).addSuccess(*args)
40
Georg Brandl15c5ce92007-03-07 09:09:40 +000041 def addError(self, *args):
42 self._events.append('addError')
43 super(LoggingResult, self).addError(*args)
44
Benjamin Peterson692428e2009-03-23 21:50:21 +000045 def addSkip(self, *args):
46 self._events.append('addSkip')
47 super(LoggingResult, self).addSkip(*args)
48
49 def addExpectedFailure(self, *args):
50 self._events.append('addExpectedFailure')
51 super(LoggingResult, self).addExpectedFailure(*args)
52
53 def addUnexpectedSuccess(self, *args):
54 self._events.append('addUnexpectedSuccess')
55 super(LoggingResult, self).addUnexpectedSuccess(*args)
56
57
Georg Brandl15c5ce92007-03-07 09:09:40 +000058class TestEquality(object):
Michael Foord345b2fe2009-04-02 03:20:38 +000059 """Used as a mixin for TestCase"""
60
Tim Petersea5962f2007-03-12 18:07:52 +000061 # Check for a valid __eq__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000062 def test_eq(self):
63 for obj_1, obj_2 in self.eq_pairs:
64 self.assertEqual(obj_1, obj_2)
65 self.assertEqual(obj_2, obj_1)
Tim Petersea5962f2007-03-12 18:07:52 +000066
67 # Check for a valid __ne__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000068 def test_ne(self):
69 for obj_1, obj_2 in self.ne_pairs:
70 self.failIfEqual(obj_1, obj_2)
71 self.failIfEqual(obj_2, obj_1)
Tim Petersea5962f2007-03-12 18:07:52 +000072
Georg Brandl15c5ce92007-03-07 09:09:40 +000073class TestHashing(object):
Michael Foord345b2fe2009-04-02 03:20:38 +000074 """Used as a mixin for TestCase"""
75
Tim Petersea5962f2007-03-12 18:07:52 +000076 # Check for a valid __hash__ implementation
Georg Brandl15c5ce92007-03-07 09:09:40 +000077 def test_hash(self):
78 for obj_1, obj_2 in self.eq_pairs:
79 try:
Gregory P. Smith28399852009-03-31 16:54:10 +000080 if not hash(obj_1) == hash(obj_2):
81 self.fail("%r and %r do not hash equal" % (obj_1, obj_2))
Georg Brandl15c5ce92007-03-07 09:09:40 +000082 except KeyboardInterrupt:
83 raise
Georg Brandl15c5ce92007-03-07 09:09:40 +000084 except Exception, e:
Gregory P. Smith28399852009-03-31 16:54:10 +000085 self.fail("Problem hashing %r and %r: %s" % (obj_1, obj_2, e))
Tim Petersea5962f2007-03-12 18:07:52 +000086
Georg Brandl15c5ce92007-03-07 09:09:40 +000087 for obj_1, obj_2 in self.ne_pairs:
88 try:
Gregory P. Smith28399852009-03-31 16:54:10 +000089 if hash(obj_1) == hash(obj_2):
90 self.fail("%s and %s hash equal, but shouldn't" %
91 (obj_1, obj_2))
Georg Brandl15c5ce92007-03-07 09:09:40 +000092 except KeyboardInterrupt:
93 raise
Georg Brandl15c5ce92007-03-07 09:09:40 +000094 except Exception, e:
95 self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e))
Tim Petersea5962f2007-03-12 18:07:52 +000096
Georg Brandl15c5ce92007-03-07 09:09:40 +000097
Benjamin Peterson692428e2009-03-23 21:50:21 +000098# List subclass we can add attributes to.
99class MyClassSuite(list):
100
101 def __init__(self, tests, klass):
102 super(MyClassSuite, self).__init__(tests)
103
104
Georg Brandl15c5ce92007-03-07 09:09:40 +0000105################################################################
106### /Support code
107
108class Test_TestLoader(TestCase):
109
110 ### Tests for TestLoader.loadTestsFromTestCase
111 ################################################################
112
113 # "Return a suite of all tests cases contained in the TestCase-derived
114 # class testCaseClass"
115 def test_loadTestsFromTestCase(self):
116 class Foo(unittest.TestCase):
117 def test_1(self): pass
118 def test_2(self): pass
119 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000120
Georg Brandl15c5ce92007-03-07 09:09:40 +0000121 tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +0000122
Georg Brandl15c5ce92007-03-07 09:09:40 +0000123 loader = unittest.TestLoader()
124 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +0000125
Georg Brandl15c5ce92007-03-07 09:09:40 +0000126 # "Return a suite of all tests cases contained in the TestCase-derived
127 # class testCaseClass"
128 #
Tim Petersea5962f2007-03-12 18:07:52 +0000129 # Make sure it does the right thing even if no tests were found
Georg Brandl15c5ce92007-03-07 09:09:40 +0000130 def test_loadTestsFromTestCase__no_matches(self):
131 class Foo(unittest.TestCase):
132 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000133
Georg Brandl15c5ce92007-03-07 09:09:40 +0000134 empty_suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +0000135
Georg Brandl15c5ce92007-03-07 09:09:40 +0000136 loader = unittest.TestLoader()
137 self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite)
Tim Petersea5962f2007-03-12 18:07:52 +0000138
Georg Brandl15c5ce92007-03-07 09:09:40 +0000139 # "Return a suite of all tests cases contained in the TestCase-derived
140 # class testCaseClass"
141 #
142 # What happens if loadTestsFromTestCase() is given an object
143 # that isn't a subclass of TestCase? Specifically, what happens
144 # if testCaseClass is a subclass of TestSuite?
145 #
146 # This is checked for specifically in the code, so we better add a
147 # test for it.
148 def test_loadTestsFromTestCase__TestSuite_subclass(self):
149 class NotATestCase(unittest.TestSuite):
150 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000151
Georg Brandl15c5ce92007-03-07 09:09:40 +0000152 loader = unittest.TestLoader()
153 try:
154 loader.loadTestsFromTestCase(NotATestCase)
155 except TypeError:
156 pass
157 else:
158 self.fail('Should raise TypeError')
Tim Petersea5962f2007-03-12 18:07:52 +0000159
Georg Brandl15c5ce92007-03-07 09:09:40 +0000160 # "Return a suite of all tests cases contained in the TestCase-derived
161 # class testCaseClass"
162 #
163 # Make sure loadTestsFromTestCase() picks up the default test method
164 # name (as specified by TestCase), even though the method name does
165 # not match the default TestLoader.testMethodPrefix string
166 def test_loadTestsFromTestCase__default_method_name(self):
167 class Foo(unittest.TestCase):
168 def runTest(self):
169 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000170
Georg Brandl15c5ce92007-03-07 09:09:40 +0000171 loader = unittest.TestLoader()
172 # This has to be false for the test to succeed
173 self.failIf('runTest'.startswith(loader.testMethodPrefix))
Tim Petersea5962f2007-03-12 18:07:52 +0000174
Georg Brandl15c5ce92007-03-07 09:09:40 +0000175 suite = loader.loadTestsFromTestCase(Foo)
176 self.failUnless(isinstance(suite, loader.suiteClass))
177 self.assertEqual(list(suite), [Foo('runTest')])
178
179 ################################################################
180 ### /Tests for TestLoader.loadTestsFromTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000181
Georg Brandl15c5ce92007-03-07 09:09:40 +0000182 ### Tests for TestLoader.loadTestsFromModule
183 ################################################################
184
185 # "This method searches `module` for classes derived from TestCase"
186 def test_loadTestsFromModule__TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000187 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000188 class MyTestCase(unittest.TestCase):
189 def test(self):
190 pass
191 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000192
Georg Brandl15c5ce92007-03-07 09:09:40 +0000193 loader = unittest.TestLoader()
194 suite = loader.loadTestsFromModule(m)
195 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000196
Georg Brandl15c5ce92007-03-07 09:09:40 +0000197 expected = [loader.suiteClass([MyTestCase('test')])]
198 self.assertEqual(list(suite), expected)
Tim Petersea5962f2007-03-12 18:07:52 +0000199
Georg Brandl15c5ce92007-03-07 09:09:40 +0000200 # "This method searches `module` for classes derived from TestCase"
Tim Petersea5962f2007-03-12 18:07:52 +0000201 #
Georg Brandl15c5ce92007-03-07 09:09:40 +0000202 # What happens if no tests are found (no TestCase instances)?
203 def test_loadTestsFromModule__no_TestCase_instances(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000204 m = types.ModuleType('m')
Tim Petersea5962f2007-03-12 18:07:52 +0000205
Georg Brandl15c5ce92007-03-07 09:09:40 +0000206 loader = unittest.TestLoader()
207 suite = loader.loadTestsFromModule(m)
208 self.failUnless(isinstance(suite, loader.suiteClass))
209 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000210
Georg Brandl15c5ce92007-03-07 09:09:40 +0000211 # "This method searches `module` for classes derived from TestCase"
212 #
Tim Petersea5962f2007-03-12 18:07:52 +0000213 # What happens if no tests are found (TestCases instances, but no tests)?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000214 def test_loadTestsFromModule__no_TestCase_tests(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000215 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000216 class MyTestCase(unittest.TestCase):
217 pass
218 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000219
Georg Brandl15c5ce92007-03-07 09:09:40 +0000220 loader = unittest.TestLoader()
221 suite = loader.loadTestsFromModule(m)
222 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000223
Georg Brandl15c5ce92007-03-07 09:09:40 +0000224 self.assertEqual(list(suite), [loader.suiteClass()])
Tim Petersea5962f2007-03-12 18:07:52 +0000225
Georg Brandl15c5ce92007-03-07 09:09:40 +0000226 # "This method searches `module` for classes derived from TestCase"s
227 #
228 # What happens if loadTestsFromModule() is given something other
229 # than a module?
230 #
231 # XXX Currently, it succeeds anyway. This flexibility
232 # should either be documented or loadTestsFromModule() should
233 # raise a TypeError
234 #
235 # XXX Certain people are using this behaviour. We'll add a test for it
236 def test_loadTestsFromModule__not_a_module(self):
237 class MyTestCase(unittest.TestCase):
238 def test(self):
239 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000240
Georg Brandl15c5ce92007-03-07 09:09:40 +0000241 class NotAModule(object):
242 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000243
Georg Brandl15c5ce92007-03-07 09:09:40 +0000244 loader = unittest.TestLoader()
245 suite = loader.loadTestsFromModule(NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000246
Georg Brandl15c5ce92007-03-07 09:09:40 +0000247 reference = [unittest.TestSuite([MyTestCase('test')])]
248 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000249
Georg Brandl15c5ce92007-03-07 09:09:40 +0000250 ################################################################
251 ### /Tests for TestLoader.loadTestsFromModule()
Tim Petersea5962f2007-03-12 18:07:52 +0000252
Georg Brandl15c5ce92007-03-07 09:09:40 +0000253 ### Tests for TestLoader.loadTestsFromName()
254 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000255
Georg Brandl15c5ce92007-03-07 09:09:40 +0000256 # "The specifier name is a ``dotted name'' that may resolve either to
257 # a module, a test case class, a TestSuite instance, a test method
258 # within a test case class, or a callable object which returns a
259 # TestCase or TestSuite instance."
260 #
261 # Is ValueError raised in response to an empty name?
262 def test_loadTestsFromName__empty_name(self):
263 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000264
Georg Brandl15c5ce92007-03-07 09:09:40 +0000265 try:
266 loader.loadTestsFromName('')
267 except ValueError, e:
268 self.assertEqual(str(e), "Empty module name")
269 else:
270 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000271
Georg Brandl15c5ce92007-03-07 09:09:40 +0000272 # "The specifier name is a ``dotted name'' that may resolve either to
273 # a module, a test case class, a TestSuite instance, a test method
274 # within a test case class, or a callable object which returns a
275 # TestCase or TestSuite instance."
276 #
Tim Petersea5962f2007-03-12 18:07:52 +0000277 # What happens when the name contains invalid characters?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000278 def test_loadTestsFromName__malformed_name(self):
279 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000280
Georg Brandl15c5ce92007-03-07 09:09:40 +0000281 # XXX Should this raise ValueError or ImportError?
282 try:
283 loader.loadTestsFromName('abc () //')
284 except ValueError:
285 pass
286 except ImportError:
287 pass
288 else:
289 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000290
Georg Brandl15c5ce92007-03-07 09:09:40 +0000291 # "The specifier name is a ``dotted name'' that may resolve ... to a
292 # module"
293 #
Tim Petersea5962f2007-03-12 18:07:52 +0000294 # What happens when a module by that name can't be found?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000295 def test_loadTestsFromName__unknown_module_name(self):
296 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000297
Georg Brandl15c5ce92007-03-07 09:09:40 +0000298 try:
299 loader.loadTestsFromName('sdasfasfasdf')
300 except ImportError, e:
301 self.assertEqual(str(e), "No module named sdasfasfasdf")
302 else:
303 self.fail("TestLoader.loadTestsFromName failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000304
Georg Brandl15c5ce92007-03-07 09:09:40 +0000305 # "The specifier name is a ``dotted name'' that may resolve either to
306 # a module, a test case class, a TestSuite instance, a test method
307 # within a test case class, or a callable object which returns a
308 # TestCase or TestSuite instance."
309 #
Tim Petersea5962f2007-03-12 18:07:52 +0000310 # What happens when the module is found, but the attribute can't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000311 def test_loadTestsFromName__unknown_attr_name(self):
312 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000313
Georg Brandl15c5ce92007-03-07 09:09:40 +0000314 try:
315 loader.loadTestsFromName('unittest.sdasfasfasdf')
316 except AttributeError, e:
317 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
318 else:
319 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000320
Georg Brandl15c5ce92007-03-07 09:09:40 +0000321 # "The specifier name is a ``dotted name'' that may resolve either to
322 # a module, a test case class, a TestSuite instance, a test method
323 # within a test case class, or a callable object which returns a
324 # TestCase or TestSuite instance."
325 #
326 # What happens when we provide the module, but the attribute can't be
327 # found?
328 def test_loadTestsFromName__relative_unknown_name(self):
329 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000330
Georg Brandl15c5ce92007-03-07 09:09:40 +0000331 try:
332 loader.loadTestsFromName('sdasfasfasdf', unittest)
333 except AttributeError, e:
334 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
335 else:
336 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000337
Georg Brandl15c5ce92007-03-07 09:09:40 +0000338 # "The specifier name is a ``dotted name'' that may resolve either to
339 # a module, a test case class, a TestSuite instance, a test method
340 # within a test case class, or a callable object which returns a
341 # TestCase or TestSuite instance."
342 # ...
343 # "The method optionally resolves name relative to the given module"
344 #
345 # Does loadTestsFromName raise ValueError when passed an empty
346 # name relative to a provided module?
347 #
348 # XXX Should probably raise a ValueError instead of an AttributeError
349 def test_loadTestsFromName__relative_empty_name(self):
350 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000351
Georg Brandl15c5ce92007-03-07 09:09:40 +0000352 try:
353 loader.loadTestsFromName('', unittest)
354 except AttributeError, e:
355 pass
356 else:
357 self.fail("Failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000358
Georg Brandl15c5ce92007-03-07 09:09:40 +0000359 # "The specifier name is a ``dotted name'' that may resolve either to
360 # a module, a test case class, a TestSuite instance, a test method
361 # within a test case class, or a callable object which returns a
362 # TestCase or TestSuite instance."
363 # ...
364 # "The method optionally resolves name relative to the given module"
365 #
366 # What happens when an impossible name is given, relative to the provided
367 # `module`?
368 def test_loadTestsFromName__relative_malformed_name(self):
369 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000370
Georg Brandl15c5ce92007-03-07 09:09:40 +0000371 # XXX Should this raise AttributeError or ValueError?
372 try:
373 loader.loadTestsFromName('abc () //', unittest)
374 except ValueError:
375 pass
376 except AttributeError:
377 pass
378 else:
379 self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
380
381 # "The method optionally resolves name relative to the given module"
382 #
383 # Does loadTestsFromName raise TypeError when the `module` argument
384 # isn't a module object?
385 #
386 # XXX Accepts the not-a-module object, ignorning the object's type
387 # This should raise an exception or the method name should be changed
388 #
389 # XXX Some people are relying on this, so keep it for now
390 def test_loadTestsFromName__relative_not_a_module(self):
391 class MyTestCase(unittest.TestCase):
392 def test(self):
393 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000394
Georg Brandl15c5ce92007-03-07 09:09:40 +0000395 class NotAModule(object):
396 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000397
Georg Brandl15c5ce92007-03-07 09:09:40 +0000398 loader = unittest.TestLoader()
399 suite = loader.loadTestsFromName('test_2', NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000400
Georg Brandl15c5ce92007-03-07 09:09:40 +0000401 reference = [MyTestCase('test')]
402 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000403
Georg Brandl15c5ce92007-03-07 09:09:40 +0000404 # "The specifier name is a ``dotted name'' that may resolve either to
405 # a module, a test case class, a TestSuite instance, a test method
406 # within a test case class, or a callable object which returns a
407 # TestCase or TestSuite instance."
408 #
409 # Does it raise an exception if the name resolves to an invalid
410 # object?
411 def test_loadTestsFromName__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000412 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000413 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000414
Georg Brandl15c5ce92007-03-07 09:09:40 +0000415 loader = unittest.TestLoader()
416 try:
417 loader.loadTestsFromName('testcase_1', m)
418 except TypeError:
419 pass
420 else:
421 self.fail("Should have raised TypeError")
422
423 # "The specifier name is a ``dotted name'' that may
424 # resolve either to ... a test case class"
425 def test_loadTestsFromName__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000426 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000427 class MyTestCase(unittest.TestCase):
428 def test(self):
429 pass
430 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000431
Georg Brandl15c5ce92007-03-07 09:09:40 +0000432 loader = unittest.TestLoader()
433 suite = loader.loadTestsFromName('testcase_1', m)
434 self.failUnless(isinstance(suite, loader.suiteClass))
435 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000436
Georg Brandl15c5ce92007-03-07 09:09:40 +0000437 # "The specifier name is a ``dotted name'' that may resolve either to
438 # a module, a test case class, a TestSuite instance, a test method
439 # within a test case class, or a callable object which returns a
440 # TestCase or TestSuite instance."
441 def test_loadTestsFromName__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000442 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000443 class MyTestCase(unittest.TestCase):
444 def test(self):
445 pass
446 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000447
Georg Brandl15c5ce92007-03-07 09:09:40 +0000448 loader = unittest.TestLoader()
449 suite = loader.loadTestsFromName('testsuite', m)
450 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000451
Georg Brandl15c5ce92007-03-07 09:09:40 +0000452 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000453
Georg Brandl15c5ce92007-03-07 09:09:40 +0000454 # "The specifier name is a ``dotted name'' that may resolve ... to
455 # ... a test method within a test case class"
456 def test_loadTestsFromName__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000457 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000458 class MyTestCase(unittest.TestCase):
459 def test(self):
460 pass
461 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000462
Georg Brandl15c5ce92007-03-07 09:09:40 +0000463 loader = unittest.TestLoader()
464 suite = loader.loadTestsFromName('testcase_1.test', m)
465 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000466
Georg Brandl15c5ce92007-03-07 09:09:40 +0000467 self.assertEqual(list(suite), [MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000468
Georg Brandl15c5ce92007-03-07 09:09:40 +0000469 # "The specifier name is a ``dotted name'' that may resolve either to
470 # a module, a test case class, a TestSuite instance, a test method
471 # within a test case class, or a callable object which returns a
472 # TestCase or TestSuite instance."
473 #
474 # Does loadTestsFromName() raise the proper exception when trying to
475 # resolve "a test method within a test case class" that doesn't exist
476 # for the given name (relative to a provided module)?
477 def test_loadTestsFromName__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000478 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000479 class MyTestCase(unittest.TestCase):
480 def test(self):
481 pass
482 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000483
Georg Brandl15c5ce92007-03-07 09:09:40 +0000484 loader = unittest.TestLoader()
485 try:
486 loader.loadTestsFromName('testcase_1.testfoo', m)
487 except AttributeError, e:
488 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
489 else:
490 self.fail("Failed to raise AttributeError")
491
492 # "The specifier name is a ``dotted name'' that may resolve ... to
493 # ... a callable object which returns a ... TestSuite instance"
494 def test_loadTestsFromName__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000495 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000496 testcase_1 = unittest.FunctionTestCase(lambda: None)
497 testcase_2 = unittest.FunctionTestCase(lambda: None)
498 def return_TestSuite():
499 return unittest.TestSuite([testcase_1, testcase_2])
500 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000501
Georg Brandl15c5ce92007-03-07 09:09:40 +0000502 loader = unittest.TestLoader()
503 suite = loader.loadTestsFromName('return_TestSuite', m)
504 self.failUnless(isinstance(suite, loader.suiteClass))
505 self.assertEqual(list(suite), [testcase_1, testcase_2])
Tim Petersea5962f2007-03-12 18:07:52 +0000506
Georg Brandl15c5ce92007-03-07 09:09:40 +0000507 # "The specifier name is a ``dotted name'' that may resolve ... to
508 # ... a callable object which returns a TestCase ... instance"
509 def test_loadTestsFromName__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000510 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000511 testcase_1 = unittest.FunctionTestCase(lambda: None)
512 def return_TestCase():
513 return testcase_1
514 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000515
Georg Brandl15c5ce92007-03-07 09:09:40 +0000516 loader = unittest.TestLoader()
517 suite = loader.loadTestsFromName('return_TestCase', m)
518 self.failUnless(isinstance(suite, loader.suiteClass))
519 self.assertEqual(list(suite), [testcase_1])
Tim Petersea5962f2007-03-12 18:07:52 +0000520
Georg Brandl15c5ce92007-03-07 09:09:40 +0000521 # "The specifier name is a ``dotted name'' that may resolve ... to
522 # ... a callable object which returns a TestCase or TestSuite instance"
523 #
524 # What happens if the callable returns something else?
525 def test_loadTestsFromName__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000526 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000527 def return_wrong():
528 return 6
529 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000530
Georg Brandl15c5ce92007-03-07 09:09:40 +0000531 loader = unittest.TestLoader()
532 try:
533 suite = loader.loadTestsFromName('return_wrong', m)
534 except TypeError:
535 pass
536 else:
537 self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000538
Georg Brandl15c5ce92007-03-07 09:09:40 +0000539 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +0000540 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +0000541 def test_loadTestsFromName__module_not_loaded(self):
542 # We're going to try to load this module as a side-effect, so it
543 # better not be loaded before we try.
544 #
545 # Why pick audioop? Google shows it isn't used very often, so there's
546 # a good chance that it won't be imported when this test is run
547 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +0000548
Georg Brandl15c5ce92007-03-07 09:09:40 +0000549 import sys
550 if module_name in sys.modules:
551 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000552
Georg Brandl15c5ce92007-03-07 09:09:40 +0000553 loader = unittest.TestLoader()
554 try:
555 suite = loader.loadTestsFromName(module_name)
556
557 self.failUnless(isinstance(suite, loader.suiteClass))
558 self.assertEqual(list(suite), [])
559
560 # audioop should now be loaded, thanks to loadTestsFromName()
561 self.failUnless(module_name in sys.modules)
562 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000563 if module_name in sys.modules:
564 del sys.modules[module_name]
Georg Brandl15c5ce92007-03-07 09:09:40 +0000565
566 ################################################################
567 ### Tests for TestLoader.loadTestsFromName()
568
569 ### Tests for TestLoader.loadTestsFromNames()
570 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000571
Georg Brandl15c5ce92007-03-07 09:09:40 +0000572 # "Similar to loadTestsFromName(), but takes a sequence of names rather
573 # than a single name."
574 #
575 # What happens if that sequence of names is empty?
576 def test_loadTestsFromNames__empty_name_list(self):
577 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000578
Georg Brandl15c5ce92007-03-07 09:09:40 +0000579 suite = loader.loadTestsFromNames([])
580 self.failUnless(isinstance(suite, loader.suiteClass))
581 self.assertEqual(list(suite), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000582
Georg Brandl15c5ce92007-03-07 09:09:40 +0000583 # "Similar to loadTestsFromName(), but takes a sequence of names rather
584 # than a single name."
585 # ...
586 # "The method optionally resolves name relative to the given module"
587 #
588 # What happens if that sequence of names is empty?
589 #
590 # XXX Should this raise a ValueError or just return an empty TestSuite?
591 def test_loadTestsFromNames__relative_empty_name_list(self):
592 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000593
Georg Brandl15c5ce92007-03-07 09:09:40 +0000594 suite = loader.loadTestsFromNames([], unittest)
595 self.failUnless(isinstance(suite, loader.suiteClass))
596 self.assertEqual(list(suite), [])
597
598 # "The specifier name is a ``dotted name'' that may resolve either to
599 # a module, a test case class, a TestSuite instance, a test method
600 # within a test case class, or a callable object which returns a
601 # TestCase or TestSuite instance."
602 #
603 # Is ValueError raised in response to an empty name?
604 def test_loadTestsFromNames__empty_name(self):
605 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000606
Georg Brandl15c5ce92007-03-07 09:09:40 +0000607 try:
608 loader.loadTestsFromNames([''])
609 except ValueError, e:
610 self.assertEqual(str(e), "Empty module name")
611 else:
612 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000613
Georg Brandl15c5ce92007-03-07 09:09:40 +0000614 # "The specifier name is a ``dotted name'' that may resolve either to
615 # a module, a test case class, a TestSuite instance, a test method
616 # within a test case class, or a callable object which returns a
617 # TestCase or TestSuite instance."
618 #
Tim Petersea5962f2007-03-12 18:07:52 +0000619 # What happens when presented with an impossible module name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000620 def test_loadTestsFromNames__malformed_name(self):
621 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000622
Georg Brandl15c5ce92007-03-07 09:09:40 +0000623 # XXX Should this raise ValueError or ImportError?
624 try:
625 loader.loadTestsFromNames(['abc () //'])
626 except ValueError:
627 pass
628 except ImportError:
629 pass
630 else:
631 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000632
Georg Brandl15c5ce92007-03-07 09:09:40 +0000633 # "The specifier name is a ``dotted name'' that may resolve either to
634 # a module, a test case class, a TestSuite instance, a test method
635 # within a test case class, or a callable object which returns a
636 # TestCase or TestSuite instance."
637 #
Tim Petersea5962f2007-03-12 18:07:52 +0000638 # What happens when no module can be found for the given name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000639 def test_loadTestsFromNames__unknown_module_name(self):
640 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000641
Georg Brandl15c5ce92007-03-07 09:09:40 +0000642 try:
643 loader.loadTestsFromNames(['sdasfasfasdf'])
644 except ImportError, e:
645 self.assertEqual(str(e), "No module named sdasfasfasdf")
646 else:
647 self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
Tim Petersea5962f2007-03-12 18:07:52 +0000648
Georg Brandl15c5ce92007-03-07 09:09:40 +0000649 # "The specifier name is a ``dotted name'' that may resolve either to
650 # a module, a test case class, a TestSuite instance, a test method
651 # within a test case class, or a callable object which returns a
652 # TestCase or TestSuite instance."
653 #
Tim Petersea5962f2007-03-12 18:07:52 +0000654 # What happens when the module can be found, but not the attribute?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000655 def test_loadTestsFromNames__unknown_attr_name(self):
656 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000657
Georg Brandl15c5ce92007-03-07 09:09:40 +0000658 try:
659 loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
660 except AttributeError, e:
661 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
662 else:
663 self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000664
Georg Brandl15c5ce92007-03-07 09:09:40 +0000665 # "The specifier name is a ``dotted name'' that may resolve either to
666 # a module, a test case class, a TestSuite instance, a test method
667 # within a test case class, or a callable object which returns a
668 # TestCase or TestSuite instance."
669 # ...
670 # "The method optionally resolves name relative to the given module"
671 #
672 # What happens when given an unknown attribute on a specified `module`
673 # argument?
674 def test_loadTestsFromNames__unknown_name_relative_1(self):
675 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000676
Georg Brandl15c5ce92007-03-07 09:09:40 +0000677 try:
678 loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
679 except AttributeError, e:
680 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
681 else:
682 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000683
Georg Brandl15c5ce92007-03-07 09:09:40 +0000684 # "The specifier name is a ``dotted name'' that may resolve either to
685 # a module, a test case class, a TestSuite instance, a test method
686 # within a test case class, or a callable object which returns a
687 # TestCase or TestSuite instance."
688 # ...
689 # "The method optionally resolves name relative to the given module"
690 #
691 # Do unknown attributes (relative to a provided module) still raise an
Tim Petersea5962f2007-03-12 18:07:52 +0000692 # exception even in the presence of valid attribute names?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000693 def test_loadTestsFromNames__unknown_name_relative_2(self):
694 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000695
Georg Brandl15c5ce92007-03-07 09:09:40 +0000696 try:
697 loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
698 except AttributeError, e:
699 self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
700 else:
701 self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
702
703 # "The specifier name is a ``dotted name'' that may resolve either to
704 # a module, a test case class, a TestSuite instance, a test method
705 # within a test case class, or a callable object which returns a
706 # TestCase or TestSuite instance."
707 # ...
708 # "The method optionally resolves name relative to the given module"
709 #
710 # What happens when faced with the empty string?
711 #
712 # XXX This currently raises AttributeError, though ValueError is probably
713 # more appropriate
714 def test_loadTestsFromNames__relative_empty_name(self):
715 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000716
Georg Brandl15c5ce92007-03-07 09:09:40 +0000717 try:
718 loader.loadTestsFromNames([''], unittest)
719 except AttributeError:
720 pass
721 else:
722 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +0000723
Georg Brandl15c5ce92007-03-07 09:09:40 +0000724 # "The specifier name is a ``dotted name'' that may resolve either to
725 # a module, a test case class, a TestSuite instance, a test method
726 # within a test case class, or a callable object which returns a
727 # TestCase or TestSuite instance."
728 # ...
729 # "The method optionally resolves name relative to the given module"
730 #
Tim Petersea5962f2007-03-12 18:07:52 +0000731 # What happens when presented with an impossible attribute name?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000732 def test_loadTestsFromNames__relative_malformed_name(self):
733 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000734
Georg Brandl15c5ce92007-03-07 09:09:40 +0000735 # XXX Should this raise AttributeError or ValueError?
736 try:
737 loader.loadTestsFromNames(['abc () //'], unittest)
738 except AttributeError:
739 pass
740 except ValueError:
741 pass
742 else:
743 self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
744
745 # "The method optionally resolves name relative to the given module"
746 #
747 # Does loadTestsFromNames() make sure the provided `module` is in fact
748 # a module?
749 #
750 # XXX This validation is currently not done. This flexibility should
751 # either be documented or a TypeError should be raised.
752 def test_loadTestsFromNames__relative_not_a_module(self):
753 class MyTestCase(unittest.TestCase):
754 def test(self):
755 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000756
Georg Brandl15c5ce92007-03-07 09:09:40 +0000757 class NotAModule(object):
758 test_2 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000759
Georg Brandl15c5ce92007-03-07 09:09:40 +0000760 loader = unittest.TestLoader()
761 suite = loader.loadTestsFromNames(['test_2'], NotAModule)
Tim Petersea5962f2007-03-12 18:07:52 +0000762
Georg Brandl15c5ce92007-03-07 09:09:40 +0000763 reference = [unittest.TestSuite([MyTestCase('test')])]
764 self.assertEqual(list(suite), reference)
Tim Petersea5962f2007-03-12 18:07:52 +0000765
Georg Brandl15c5ce92007-03-07 09:09:40 +0000766 # "The specifier name is a ``dotted name'' that may resolve either to
767 # a module, a test case class, a TestSuite instance, a test method
768 # within a test case class, or a callable object which returns a
769 # TestCase or TestSuite instance."
770 #
771 # Does it raise an exception if the name resolves to an invalid
772 # object?
773 def test_loadTestsFromNames__relative_bad_object(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000774 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000775 m.testcase_1 = object()
Tim Petersea5962f2007-03-12 18:07:52 +0000776
Georg Brandl15c5ce92007-03-07 09:09:40 +0000777 loader = unittest.TestLoader()
778 try:
779 loader.loadTestsFromNames(['testcase_1'], m)
780 except TypeError:
781 pass
782 else:
783 self.fail("Should have raised TypeError")
784
785 # "The specifier name is a ``dotted name'' that may resolve ... to
786 # ... a test case class"
787 def test_loadTestsFromNames__relative_TestCase_subclass(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000788 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000789 class MyTestCase(unittest.TestCase):
790 def test(self):
791 pass
792 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000793
Georg Brandl15c5ce92007-03-07 09:09:40 +0000794 loader = unittest.TestLoader()
795 suite = loader.loadTestsFromNames(['testcase_1'], m)
796 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000797
Georg Brandl15c5ce92007-03-07 09:09:40 +0000798 expected = loader.suiteClass([MyTestCase('test')])
799 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000800
Georg Brandl15c5ce92007-03-07 09:09:40 +0000801 # "The specifier name is a ``dotted name'' that may resolve ... to
802 # ... a TestSuite instance"
803 def test_loadTestsFromNames__relative_TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000804 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000805 class MyTestCase(unittest.TestCase):
806 def test(self):
807 pass
808 m.testsuite = unittest.TestSuite([MyTestCase('test')])
Tim Petersea5962f2007-03-12 18:07:52 +0000809
Georg Brandl15c5ce92007-03-07 09:09:40 +0000810 loader = unittest.TestLoader()
811 suite = loader.loadTestsFromNames(['testsuite'], m)
812 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000813
Georg Brandl15c5ce92007-03-07 09:09:40 +0000814 self.assertEqual(list(suite), [m.testsuite])
Tim Petersea5962f2007-03-12 18:07:52 +0000815
Georg Brandl15c5ce92007-03-07 09:09:40 +0000816 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
817 # test method within a test case class"
818 def test_loadTestsFromNames__relative_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000819 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000820 class MyTestCase(unittest.TestCase):
821 def test(self):
822 pass
823 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000824
Georg Brandl15c5ce92007-03-07 09:09:40 +0000825 loader = unittest.TestLoader()
826 suite = loader.loadTestsFromNames(['testcase_1.test'], m)
827 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000828
Georg Brandl15c5ce92007-03-07 09:09:40 +0000829 ref_suite = unittest.TestSuite([MyTestCase('test')])
830 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000831
Georg Brandl15c5ce92007-03-07 09:09:40 +0000832 # "The specifier name is a ``dotted name'' that may resolve ... to ... a
833 # test method within a test case class"
834 #
835 # Does the method gracefully handle names that initially look like they
Tim Petersea5962f2007-03-12 18:07:52 +0000836 # resolve to "a test method within a test case class" but don't?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000837 def test_loadTestsFromNames__relative_invalid_testmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000838 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000839 class MyTestCase(unittest.TestCase):
840 def test(self):
841 pass
842 m.testcase_1 = MyTestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000843
Georg Brandl15c5ce92007-03-07 09:09:40 +0000844 loader = unittest.TestLoader()
845 try:
846 loader.loadTestsFromNames(['testcase_1.testfoo'], m)
847 except AttributeError, e:
848 self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
849 else:
850 self.fail("Failed to raise AttributeError")
851
852 # "The specifier name is a ``dotted name'' that may resolve ... to
853 # ... a callable object which returns a ... TestSuite instance"
854 def test_loadTestsFromNames__callable__TestSuite(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000855 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000856 testcase_1 = unittest.FunctionTestCase(lambda: None)
857 testcase_2 = unittest.FunctionTestCase(lambda: None)
858 def return_TestSuite():
859 return unittest.TestSuite([testcase_1, testcase_2])
860 m.return_TestSuite = return_TestSuite
Tim Petersea5962f2007-03-12 18:07:52 +0000861
Georg Brandl15c5ce92007-03-07 09:09:40 +0000862 loader = unittest.TestLoader()
863 suite = loader.loadTestsFromNames(['return_TestSuite'], m)
864 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000865
Georg Brandl15c5ce92007-03-07 09:09:40 +0000866 expected = unittest.TestSuite([testcase_1, testcase_2])
867 self.assertEqual(list(suite), [expected])
Tim Petersea5962f2007-03-12 18:07:52 +0000868
Georg Brandl15c5ce92007-03-07 09:09:40 +0000869 # "The specifier name is a ``dotted name'' that may resolve ... to
870 # ... a callable object which returns a TestCase ... instance"
871 def test_loadTestsFromNames__callable__TestCase_instance(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000872 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000873 testcase_1 = unittest.FunctionTestCase(lambda: None)
874 def return_TestCase():
875 return testcase_1
876 m.return_TestCase = return_TestCase
Tim Petersea5962f2007-03-12 18:07:52 +0000877
Georg Brandl15c5ce92007-03-07 09:09:40 +0000878 loader = unittest.TestLoader()
879 suite = loader.loadTestsFromNames(['return_TestCase'], m)
880 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000881
Georg Brandl15c5ce92007-03-07 09:09:40 +0000882 ref_suite = unittest.TestSuite([testcase_1])
883 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000884
Georg Brandl15c5ce92007-03-07 09:09:40 +0000885 # "The specifier name is a ``dotted name'' that may resolve ... to
886 # ... a callable object which returns a TestCase or TestSuite instance"
887 #
Tim Petersea5962f2007-03-12 18:07:52 +0000888 # Are staticmethods handled correctly?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000889 def test_loadTestsFromNames__callable__call_staticmethod(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000890 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000891 class Test1(unittest.TestCase):
892 def test(self):
893 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000894
Georg Brandl15c5ce92007-03-07 09:09:40 +0000895 testcase_1 = Test1('test')
896 class Foo(unittest.TestCase):
897 @staticmethod
898 def foo():
899 return testcase_1
900 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +0000901
Georg Brandl15c5ce92007-03-07 09:09:40 +0000902 loader = unittest.TestLoader()
903 suite = loader.loadTestsFromNames(['Foo.foo'], m)
904 self.failUnless(isinstance(suite, loader.suiteClass))
Tim Petersea5962f2007-03-12 18:07:52 +0000905
Georg Brandl15c5ce92007-03-07 09:09:40 +0000906 ref_suite = unittest.TestSuite([testcase_1])
907 self.assertEqual(list(suite), [ref_suite])
Tim Petersea5962f2007-03-12 18:07:52 +0000908
Georg Brandl15c5ce92007-03-07 09:09:40 +0000909 # "The specifier name is a ``dotted name'' that may resolve ... to
910 # ... a callable object which returns a TestCase or TestSuite instance"
911 #
912 # What happens when the callable returns something else?
913 def test_loadTestsFromNames__callable__wrong_type(self):
Christian Heimesc756d002007-11-27 21:34:01 +0000914 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +0000915 def return_wrong():
916 return 6
917 m.return_wrong = return_wrong
Tim Petersea5962f2007-03-12 18:07:52 +0000918
Georg Brandl15c5ce92007-03-07 09:09:40 +0000919 loader = unittest.TestLoader()
920 try:
921 suite = loader.loadTestsFromNames(['return_wrong'], m)
922 except TypeError:
923 pass
924 else:
925 self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +0000926
Georg Brandl15c5ce92007-03-07 09:09:40 +0000927 # "The specifier can refer to modules and packages which have not been
Tim Petersea5962f2007-03-12 18:07:52 +0000928 # imported; they will be imported as a side-effect"
Georg Brandl15c5ce92007-03-07 09:09:40 +0000929 def test_loadTestsFromNames__module_not_loaded(self):
930 # We're going to try to load this module as a side-effect, so it
931 # better not be loaded before we try.
932 #
933 # Why pick audioop? Google shows it isn't used very often, so there's
934 # a good chance that it won't be imported when this test is run
935 module_name = 'audioop'
Tim Petersea5962f2007-03-12 18:07:52 +0000936
Georg Brandl15c5ce92007-03-07 09:09:40 +0000937 import sys
938 if module_name in sys.modules:
939 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000940
Georg Brandl15c5ce92007-03-07 09:09:40 +0000941 loader = unittest.TestLoader()
942 try:
943 suite = loader.loadTestsFromNames([module_name])
944
945 self.failUnless(isinstance(suite, loader.suiteClass))
946 self.assertEqual(list(suite), [unittest.TestSuite()])
947
948 # audioop should now be loaded, thanks to loadTestsFromName()
949 self.failUnless(module_name in sys.modules)
950 finally:
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000951 if module_name in sys.modules:
952 del sys.modules[module_name]
Tim Petersea5962f2007-03-12 18:07:52 +0000953
Georg Brandl15c5ce92007-03-07 09:09:40 +0000954 ################################################################
955 ### /Tests for TestLoader.loadTestsFromNames()
956
957 ### Tests for TestLoader.getTestCaseNames()
958 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +0000959
Georg Brandl15c5ce92007-03-07 09:09:40 +0000960 # "Return a sorted sequence of method names found within testCaseClass"
961 #
962 # Test.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +0000963 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +0000964 def test_getTestCaseNames(self):
965 class Test(unittest.TestCase):
966 def test_1(self): pass
967 def test_2(self): pass
968 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000969
Georg Brandl15c5ce92007-03-07 09:09:40 +0000970 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000971
Georg Brandl15c5ce92007-03-07 09:09:40 +0000972 self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])
Tim Petersea5962f2007-03-12 18:07:52 +0000973
Georg Brandl15c5ce92007-03-07 09:09:40 +0000974 # "Return a sorted sequence of method names found within testCaseClass"
975 #
Tim Petersea5962f2007-03-12 18:07:52 +0000976 # Does getTestCaseNames() behave appropriately if no tests are found?
Georg Brandl15c5ce92007-03-07 09:09:40 +0000977 def test_getTestCaseNames__no_tests(self):
978 class Test(unittest.TestCase):
979 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +0000980
Georg Brandl15c5ce92007-03-07 09:09:40 +0000981 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +0000982
Georg Brandl15c5ce92007-03-07 09:09:40 +0000983 self.assertEqual(loader.getTestCaseNames(Test), [])
Tim Petersea5962f2007-03-12 18:07:52 +0000984
Georg Brandl15c5ce92007-03-07 09:09:40 +0000985 # "Return a sorted sequence of method names found within testCaseClass"
986 #
987 # Are not-TestCases handled gracefully?
988 #
989 # XXX This should raise a TypeError, not return a list
990 #
991 # XXX It's too late in the 2.5 release cycle to fix this, but it should
992 # probably be revisited for 2.6
993 def test_getTestCaseNames__not_a_TestCase(self):
994 class BadCase(int):
995 def test_foo(self):
996 pass
Tim Petersea5962f2007-03-12 18:07:52 +0000997
Georg Brandl15c5ce92007-03-07 09:09:40 +0000998 loader = unittest.TestLoader()
999 names = loader.getTestCaseNames(BadCase)
Tim Petersea5962f2007-03-12 18:07:52 +00001000
Georg Brandl15c5ce92007-03-07 09:09:40 +00001001 self.assertEqual(names, ['test_foo'])
Tim Petersea5962f2007-03-12 18:07:52 +00001002
Georg Brandl15c5ce92007-03-07 09:09:40 +00001003 # "Return a sorted sequence of method names found within testCaseClass"
1004 #
1005 # Make sure inherited names are handled.
1006 #
1007 # TestP.foobar is defined to make sure getTestCaseNames() respects
Tim Petersea5962f2007-03-12 18:07:52 +00001008 # loader.testMethodPrefix
Georg Brandl15c5ce92007-03-07 09:09:40 +00001009 def test_getTestCaseNames__inheritance(self):
1010 class TestP(unittest.TestCase):
1011 def test_1(self): pass
1012 def test_2(self): pass
1013 def foobar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001014
Georg Brandl15c5ce92007-03-07 09:09:40 +00001015 class TestC(TestP):
1016 def test_1(self): pass
1017 def test_3(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001018
Georg Brandl15c5ce92007-03-07 09:09:40 +00001019 loader = unittest.TestLoader()
Tim Petersea5962f2007-03-12 18:07:52 +00001020
Georg Brandl15c5ce92007-03-07 09:09:40 +00001021 names = ['test_1', 'test_2', 'test_3']
1022 self.assertEqual(loader.getTestCaseNames(TestC), names)
Tim Petersea5962f2007-03-12 18:07:52 +00001023
1024 ################################################################
Georg Brandl15c5ce92007-03-07 09:09:40 +00001025 ### /Tests for TestLoader.getTestCaseNames()
1026
1027 ### Tests for TestLoader.testMethodPrefix
1028 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001029
Georg Brandl15c5ce92007-03-07 09:09:40 +00001030 # "String giving the prefix of method names which will be interpreted as
1031 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001032 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001033 # Implicit in the documentation is that testMethodPrefix is respected by
1034 # all loadTestsFrom* methods.
1035 def test_testMethodPrefix__loadTestsFromTestCase(self):
1036 class Foo(unittest.TestCase):
1037 def test_1(self): pass
1038 def test_2(self): pass
1039 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001040
Georg Brandl15c5ce92007-03-07 09:09:40 +00001041 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1042 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001043
Georg Brandl15c5ce92007-03-07 09:09:40 +00001044 loader = unittest.TestLoader()
1045 loader.testMethodPrefix = 'foo'
1046 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
1047
1048 loader.testMethodPrefix = 'test'
1049 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001050
Georg Brandl15c5ce92007-03-07 09:09:40 +00001051 # "String giving the prefix of method names which will be interpreted as
1052 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001053 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001054 # Implicit in the documentation is that testMethodPrefix is respected by
1055 # all loadTestsFrom* methods.
1056 def test_testMethodPrefix__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001057 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001058 class Foo(unittest.TestCase):
1059 def test_1(self): pass
1060 def test_2(self): pass
1061 def foo_bar(self): pass
1062 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001063
Georg Brandl15c5ce92007-03-07 09:09:40 +00001064 tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
1065 tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]
Tim Petersea5962f2007-03-12 18:07:52 +00001066
Georg Brandl15c5ce92007-03-07 09:09:40 +00001067 loader = unittest.TestLoader()
1068 loader.testMethodPrefix = 'foo'
1069 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
1070
1071 loader.testMethodPrefix = 'test'
1072 self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001073
Georg Brandl15c5ce92007-03-07 09:09:40 +00001074 # "String giving the prefix of method names which will be interpreted as
1075 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001076 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001077 # Implicit in the documentation is that testMethodPrefix is respected by
1078 # all loadTestsFrom* methods.
1079 def test_testMethodPrefix__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001080 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001081 class Foo(unittest.TestCase):
1082 def test_1(self): pass
1083 def test_2(self): pass
1084 def foo_bar(self): pass
1085 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001086
Georg Brandl15c5ce92007-03-07 09:09:40 +00001087 tests_1 = unittest.TestSuite([Foo('foo_bar')])
1088 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
Tim Petersea5962f2007-03-12 18:07:52 +00001089
Georg Brandl15c5ce92007-03-07 09:09:40 +00001090 loader = unittest.TestLoader()
1091 loader.testMethodPrefix = 'foo'
1092 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
1093
1094 loader.testMethodPrefix = 'test'
1095 self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001096
Georg Brandl15c5ce92007-03-07 09:09:40 +00001097 # "String giving the prefix of method names which will be interpreted as
1098 # test methods"
Tim Petersea5962f2007-03-12 18:07:52 +00001099 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001100 # Implicit in the documentation is that testMethodPrefix is respected by
1101 # all loadTestsFrom* methods.
1102 def test_testMethodPrefix__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001103 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001104 class Foo(unittest.TestCase):
1105 def test_1(self): pass
1106 def test_2(self): pass
1107 def foo_bar(self): pass
1108 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001109
Georg Brandl15c5ce92007-03-07 09:09:40 +00001110 tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
1111 tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
1112 tests_2 = unittest.TestSuite([tests_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001113
Georg Brandl15c5ce92007-03-07 09:09:40 +00001114 loader = unittest.TestLoader()
1115 loader.testMethodPrefix = 'foo'
1116 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)
1117
1118 loader.testMethodPrefix = 'test'
1119 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001120
Georg Brandl15c5ce92007-03-07 09:09:40 +00001121 # "The default value is 'test'"
1122 def test_testMethodPrefix__default_value(self):
1123 loader = unittest.TestLoader()
1124 self.failUnless(loader.testMethodPrefix == 'test')
Tim Petersea5962f2007-03-12 18:07:52 +00001125
Georg Brandl15c5ce92007-03-07 09:09:40 +00001126 ################################################################
1127 ### /Tests for TestLoader.testMethodPrefix
1128
Tim Petersea5962f2007-03-12 18:07:52 +00001129 ### Tests for TestLoader.sortTestMethodsUsing
Georg Brandl15c5ce92007-03-07 09:09:40 +00001130 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001131
Georg Brandl15c5ce92007-03-07 09:09:40 +00001132 # "Function to be used to compare method names when sorting them in
1133 # getTestCaseNames() and all the loadTestsFromX() methods"
1134 def test_sortTestMethodsUsing__loadTestsFromTestCase(self):
1135 def reversed_cmp(x, y):
1136 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001137
Georg Brandl15c5ce92007-03-07 09:09:40 +00001138 class Foo(unittest.TestCase):
1139 def test_1(self): pass
1140 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001141
Georg Brandl15c5ce92007-03-07 09:09:40 +00001142 loader = unittest.TestLoader()
1143 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001144
Georg Brandl15c5ce92007-03-07 09:09:40 +00001145 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1146 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001147
Georg Brandl15c5ce92007-03-07 09:09:40 +00001148 # "Function to be used to compare method names when sorting them in
1149 # getTestCaseNames() and all the loadTestsFromX() methods"
1150 def test_sortTestMethodsUsing__loadTestsFromModule(self):
1151 def reversed_cmp(x, y):
1152 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001153
Christian Heimesc756d002007-11-27 21:34:01 +00001154 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001155 class Foo(unittest.TestCase):
1156 def test_1(self): pass
1157 def test_2(self): pass
1158 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001159
Georg Brandl15c5ce92007-03-07 09:09:40 +00001160 loader = unittest.TestLoader()
1161 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001162
Georg Brandl15c5ce92007-03-07 09:09:40 +00001163 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1164 self.assertEqual(list(loader.loadTestsFromModule(m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001165
Georg Brandl15c5ce92007-03-07 09:09:40 +00001166 # "Function to be used to compare method names when sorting them in
1167 # getTestCaseNames() and all the loadTestsFromX() methods"
1168 def test_sortTestMethodsUsing__loadTestsFromName(self):
1169 def reversed_cmp(x, y):
1170 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001171
Christian Heimesc756d002007-11-27 21:34:01 +00001172 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001173 class Foo(unittest.TestCase):
1174 def test_1(self): pass
1175 def test_2(self): pass
1176 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001177
Georg Brandl15c5ce92007-03-07 09:09:40 +00001178 loader = unittest.TestLoader()
1179 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001180
Georg Brandl15c5ce92007-03-07 09:09:40 +00001181 tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
1182 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001183
Georg Brandl15c5ce92007-03-07 09:09:40 +00001184 # "Function to be used to compare method names when sorting them in
1185 # getTestCaseNames() and all the loadTestsFromX() methods"
1186 def test_sortTestMethodsUsing__loadTestsFromNames(self):
1187 def reversed_cmp(x, y):
1188 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001189
Christian Heimesc756d002007-11-27 21:34:01 +00001190 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001191 class Foo(unittest.TestCase):
1192 def test_1(self): pass
1193 def test_2(self): pass
1194 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001195
Georg Brandl15c5ce92007-03-07 09:09:40 +00001196 loader = unittest.TestLoader()
1197 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001198
Georg Brandl15c5ce92007-03-07 09:09:40 +00001199 tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
1200 self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001201
Georg Brandl15c5ce92007-03-07 09:09:40 +00001202 # "Function to be used to compare method names when sorting them in
1203 # getTestCaseNames()"
1204 #
1205 # Does it actually affect getTestCaseNames()?
1206 def test_sortTestMethodsUsing__getTestCaseNames(self):
1207 def reversed_cmp(x, y):
1208 return -cmp(x, y)
Tim Petersea5962f2007-03-12 18:07:52 +00001209
Georg Brandl15c5ce92007-03-07 09:09:40 +00001210 class Foo(unittest.TestCase):
1211 def test_1(self): pass
1212 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001213
Georg Brandl15c5ce92007-03-07 09:09:40 +00001214 loader = unittest.TestLoader()
1215 loader.sortTestMethodsUsing = reversed_cmp
Tim Petersea5962f2007-03-12 18:07:52 +00001216
Georg Brandl15c5ce92007-03-07 09:09:40 +00001217 test_names = ['test_2', 'test_1']
1218 self.assertEqual(loader.getTestCaseNames(Foo), test_names)
Tim Petersea5962f2007-03-12 18:07:52 +00001219
Georg Brandl15c5ce92007-03-07 09:09:40 +00001220 # "The default value is the built-in cmp() function"
1221 def test_sortTestMethodsUsing__default_value(self):
1222 loader = unittest.TestLoader()
1223 self.failUnless(loader.sortTestMethodsUsing is cmp)
Tim Petersea5962f2007-03-12 18:07:52 +00001224
Georg Brandl15c5ce92007-03-07 09:09:40 +00001225 # "it can be set to None to disable the sort."
1226 #
1227 # XXX How is this different from reassigning cmp? Are the tests returned
1228 # in a random order or something? This behaviour should die
1229 def test_sortTestMethodsUsing__None(self):
1230 class Foo(unittest.TestCase):
1231 def test_1(self): pass
1232 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001233
Georg Brandl15c5ce92007-03-07 09:09:40 +00001234 loader = unittest.TestLoader()
1235 loader.sortTestMethodsUsing = None
Tim Petersea5962f2007-03-12 18:07:52 +00001236
Georg Brandl15c5ce92007-03-07 09:09:40 +00001237 test_names = ['test_2', 'test_1']
1238 self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))
Tim Petersea5962f2007-03-12 18:07:52 +00001239
Georg Brandl15c5ce92007-03-07 09:09:40 +00001240 ################################################################
1241 ### /Tests for TestLoader.sortTestMethodsUsing
Tim Petersea5962f2007-03-12 18:07:52 +00001242
Georg Brandl15c5ce92007-03-07 09:09:40 +00001243 ### Tests for TestLoader.suiteClass
1244 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001245
Georg Brandl15c5ce92007-03-07 09:09:40 +00001246 # "Callable object that constructs a test suite from a list of tests."
1247 def test_suiteClass__loadTestsFromTestCase(self):
1248 class Foo(unittest.TestCase):
1249 def test_1(self): pass
1250 def test_2(self): pass
1251 def foo_bar(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001252
Georg Brandl15c5ce92007-03-07 09:09:40 +00001253 tests = [Foo('test_1'), Foo('test_2')]
1254
1255 loader = unittest.TestLoader()
Benjamin Peterson692428e2009-03-23 21:50:21 +00001256 loader.classSuiteClass = MyClassSuite
Georg Brandl15c5ce92007-03-07 09:09:40 +00001257 self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001258
Georg Brandl15c5ce92007-03-07 09:09:40 +00001259 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001260 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001261 def test_suiteClass__loadTestsFromModule(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001262 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001263 class Foo(unittest.TestCase):
1264 def test_1(self): pass
1265 def test_2(self): pass
1266 def foo_bar(self): pass
1267 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001268
Benjamin Peterson692428e2009-03-23 21:50:21 +00001269 tests = [unittest.ClassTestSuite([Foo('test_1'), Foo('test_2')], Foo)]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001270
1271 loader = unittest.TestLoader()
1272 loader.suiteClass = list
1273 self.assertEqual(loader.loadTestsFromModule(m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001274
Georg Brandl15c5ce92007-03-07 09:09:40 +00001275 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001276 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001277 def test_suiteClass__loadTestsFromName(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001278 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001279 class Foo(unittest.TestCase):
1280 def test_1(self): pass
1281 def test_2(self): pass
1282 def foo_bar(self): pass
1283 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001284
Georg Brandl15c5ce92007-03-07 09:09:40 +00001285 tests = [Foo('test_1'), Foo('test_2')]
1286
1287 loader = unittest.TestLoader()
Benjamin Peterson692428e2009-03-23 21:50:21 +00001288 loader.classSuiteClass = MyClassSuite
Georg Brandl15c5ce92007-03-07 09:09:40 +00001289 self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001290
Georg Brandl15c5ce92007-03-07 09:09:40 +00001291 # It is implicit in the documentation for TestLoader.suiteClass that
Tim Petersea5962f2007-03-12 18:07:52 +00001292 # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
Georg Brandl15c5ce92007-03-07 09:09:40 +00001293 def test_suiteClass__loadTestsFromNames(self):
Christian Heimesc756d002007-11-27 21:34:01 +00001294 m = types.ModuleType('m')
Georg Brandl15c5ce92007-03-07 09:09:40 +00001295 class Foo(unittest.TestCase):
1296 def test_1(self): pass
1297 def test_2(self): pass
1298 def foo_bar(self): pass
1299 m.Foo = Foo
Tim Petersea5962f2007-03-12 18:07:52 +00001300
Benjamin Peterson692428e2009-03-23 21:50:21 +00001301 tests = [unittest.ClassTestSuite([Foo('test_1'), Foo('test_2')], Foo)]
Georg Brandl15c5ce92007-03-07 09:09:40 +00001302
1303 loader = unittest.TestLoader()
1304 loader.suiteClass = list
1305 self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)
Tim Petersea5962f2007-03-12 18:07:52 +00001306
Georg Brandl15c5ce92007-03-07 09:09:40 +00001307 # "The default value is the TestSuite class"
1308 def test_suiteClass__default_value(self):
1309 loader = unittest.TestLoader()
1310 self.failUnless(loader.suiteClass is unittest.TestSuite)
Tim Petersea5962f2007-03-12 18:07:52 +00001311
Georg Brandl15c5ce92007-03-07 09:09:40 +00001312 ################################################################
1313 ### /Tests for TestLoader.suiteClass
1314
1315### Support code for Test_TestSuite
1316################################################################
1317
1318class Foo(unittest.TestCase):
1319 def test_1(self): pass
1320 def test_2(self): pass
1321 def test_3(self): pass
1322 def runTest(self): pass
1323
1324def _mk_TestSuite(*names):
1325 return unittest.TestSuite(Foo(n) for n in names)
Tim Petersea5962f2007-03-12 18:07:52 +00001326
Georg Brandl15c5ce92007-03-07 09:09:40 +00001327################################################################
1328### /Support code for Test_TestSuite
1329
1330class Test_TestSuite(TestCase, TestEquality):
1331
1332 ### Set up attributes needed by inherited tests
1333 ################################################################
1334
1335 # Used by TestEquality.test_eq
1336 eq_pairs = [(unittest.TestSuite(), unittest.TestSuite())
1337 ,(unittest.TestSuite(), unittest.TestSuite([]))
1338 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001339
1340 # Used by TestEquality.test_ne
Georg Brandl15c5ce92007-03-07 09:09:40 +00001341 ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1'))
1342 ,(unittest.TestSuite([]), _mk_TestSuite('test_1'))
1343 ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3'))
1344 ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001345
Georg Brandl15c5ce92007-03-07 09:09:40 +00001346 ################################################################
1347 ### /Set up attributes needed by inherited tests
1348
1349 ### Tests for TestSuite.__init__
1350 ################################################################
1351
1352 # "class TestSuite([tests])"
1353 #
1354 # The tests iterable should be optional
1355 def test_init__tests_optional(self):
1356 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001357
Georg Brandl15c5ce92007-03-07 09:09:40 +00001358 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001359
Georg Brandl15c5ce92007-03-07 09:09:40 +00001360 # "class TestSuite([tests])"
1361 # ...
1362 # "If tests is given, it must be an iterable of individual test cases
1363 # or other test suites that will be used to build the suite initially"
1364 #
1365 # TestSuite should deal with empty tests iterables by allowing the
Tim Petersea5962f2007-03-12 18:07:52 +00001366 # creation of an empty suite
Georg Brandl15c5ce92007-03-07 09:09:40 +00001367 def test_init__empty_tests(self):
1368 suite = unittest.TestSuite([])
Tim Petersea5962f2007-03-12 18:07:52 +00001369
Georg Brandl15c5ce92007-03-07 09:09:40 +00001370 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001371
Georg Brandl15c5ce92007-03-07 09:09:40 +00001372 # "class TestSuite([tests])"
1373 # ...
1374 # "If tests is given, it must be an iterable of individual test cases
1375 # or other test suites that will be used to build the suite initially"
1376 #
Tim Petersea5962f2007-03-12 18:07:52 +00001377 # TestSuite should allow any iterable to provide tests
Georg Brandl15c5ce92007-03-07 09:09:40 +00001378 def test_init__tests_from_any_iterable(self):
1379 def tests():
1380 yield unittest.FunctionTestCase(lambda: None)
1381 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001382
Georg Brandl15c5ce92007-03-07 09:09:40 +00001383 suite_1 = unittest.TestSuite(tests())
1384 self.assertEqual(suite_1.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001385
Georg Brandl15c5ce92007-03-07 09:09:40 +00001386 suite_2 = unittest.TestSuite(suite_1)
1387 self.assertEqual(suite_2.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001388
Georg Brandl15c5ce92007-03-07 09:09:40 +00001389 suite_3 = unittest.TestSuite(set(suite_1))
1390 self.assertEqual(suite_3.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001391
Georg Brandl15c5ce92007-03-07 09:09:40 +00001392 # "class TestSuite([tests])"
1393 # ...
1394 # "If tests is given, it must be an iterable of individual test cases
1395 # or other test suites that will be used to build the suite initially"
1396 #
1397 # Does TestSuite() also allow other TestSuite() instances to be present
1398 # in the tests iterable?
1399 def test_init__TestSuite_instances_in_tests(self):
1400 def tests():
1401 ftc = unittest.FunctionTestCase(lambda: None)
1402 yield unittest.TestSuite([ftc])
1403 yield unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001404
Georg Brandl15c5ce92007-03-07 09:09:40 +00001405 suite = unittest.TestSuite(tests())
1406 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001407
Georg Brandl15c5ce92007-03-07 09:09:40 +00001408 ################################################################
1409 ### /Tests for TestSuite.__init__
1410
1411 # Container types should support the iter protocol
1412 def test_iter(self):
1413 test1 = unittest.FunctionTestCase(lambda: None)
1414 test2 = unittest.FunctionTestCase(lambda: None)
1415 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001416
Georg Brandl15c5ce92007-03-07 09:09:40 +00001417 self.assertEqual(list(suite), [test1, test2])
Tim Petersea5962f2007-03-12 18:07:52 +00001418
Georg Brandl15c5ce92007-03-07 09:09:40 +00001419 # "Return the number of tests represented by the this test object.
1420 # ...this method is also implemented by the TestSuite class, which can
1421 # return larger [greater than 1] values"
1422 #
Tim Petersea5962f2007-03-12 18:07:52 +00001423 # Presumably an empty TestSuite returns 0?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001424 def test_countTestCases_zero_simple(self):
1425 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001426
Georg Brandl15c5ce92007-03-07 09:09:40 +00001427 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001428
Georg Brandl15c5ce92007-03-07 09:09:40 +00001429 # "Return the number of tests represented by the this test object.
1430 # ...this method is also implemented by the TestSuite class, which can
1431 # return larger [greater than 1] values"
1432 #
1433 # Presumably an empty TestSuite (even if it contains other empty
1434 # TestSuite instances) returns 0?
1435 def test_countTestCases_zero_nested(self):
1436 class Test1(unittest.TestCase):
1437 def test(self):
1438 pass
1439
1440 suite = unittest.TestSuite([unittest.TestSuite()])
Tim Petersea5962f2007-03-12 18:07:52 +00001441
Georg Brandl15c5ce92007-03-07 09:09:40 +00001442 self.assertEqual(suite.countTestCases(), 0)
Tim Petersea5962f2007-03-12 18:07:52 +00001443
Georg Brandl15c5ce92007-03-07 09:09:40 +00001444 # "Return the number of tests represented by the this test object.
1445 # ...this method is also implemented by the TestSuite class, which can
1446 # return larger [greater than 1] values"
1447 def test_countTestCases_simple(self):
1448 test1 = unittest.FunctionTestCase(lambda: None)
1449 test2 = unittest.FunctionTestCase(lambda: None)
1450 suite = unittest.TestSuite((test1, test2))
Tim Petersea5962f2007-03-12 18:07:52 +00001451
Georg Brandl15c5ce92007-03-07 09:09:40 +00001452 self.assertEqual(suite.countTestCases(), 2)
Tim Petersea5962f2007-03-12 18:07:52 +00001453
Georg Brandl15c5ce92007-03-07 09:09:40 +00001454 # "Return the number of tests represented by the this test object.
1455 # ...this method is also implemented by the TestSuite class, which can
1456 # return larger [greater than 1] values"
1457 #
1458 # Make sure this holds for nested TestSuite instances, too
1459 def test_countTestCases_nested(self):
1460 class Test1(unittest.TestCase):
1461 def test1(self): pass
1462 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001463
Georg Brandl15c5ce92007-03-07 09:09:40 +00001464 test2 = unittest.FunctionTestCase(lambda: None)
1465 test3 = unittest.FunctionTestCase(lambda: None)
1466 child = unittest.TestSuite((Test1('test2'), test2))
1467 parent = unittest.TestSuite((test3, child, Test1('test1')))
Tim Petersea5962f2007-03-12 18:07:52 +00001468
Georg Brandl15c5ce92007-03-07 09:09:40 +00001469 self.assertEqual(parent.countTestCases(), 4)
Tim Petersea5962f2007-03-12 18:07:52 +00001470
Georg Brandl15c5ce92007-03-07 09:09:40 +00001471 # "Run the tests associated with this suite, collecting the result into
1472 # the test result object passed as result."
1473 #
1474 # And if there are no tests? What then?
1475 def test_run__empty_suite(self):
1476 events = []
1477 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001478
Georg Brandl15c5ce92007-03-07 09:09:40 +00001479 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001480
Georg Brandl15c5ce92007-03-07 09:09:40 +00001481 suite.run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001482
Georg Brandl15c5ce92007-03-07 09:09:40 +00001483 self.assertEqual(events, [])
Tim Petersea5962f2007-03-12 18:07:52 +00001484
Georg Brandl15c5ce92007-03-07 09:09:40 +00001485 # "Note that unlike TestCase.run(), TestSuite.run() requires the
1486 # "result object to be passed in."
1487 def test_run__requires_result(self):
1488 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001489
Georg Brandl15c5ce92007-03-07 09:09:40 +00001490 try:
1491 suite.run()
1492 except TypeError:
1493 pass
1494 else:
1495 self.fail("Failed to raise TypeError")
Tim Petersea5962f2007-03-12 18:07:52 +00001496
Georg Brandl15c5ce92007-03-07 09:09:40 +00001497 # "Run the tests associated with this suite, collecting the result into
Tim Petersea5962f2007-03-12 18:07:52 +00001498 # the test result object passed as result."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001499 def test_run(self):
1500 events = []
1501 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001502
Georg Brandl15c5ce92007-03-07 09:09:40 +00001503 class LoggingCase(unittest.TestCase):
1504 def run(self, result):
1505 events.append('run %s' % self._testMethodName)
Tim Petersea5962f2007-03-12 18:07:52 +00001506
Georg Brandl15c5ce92007-03-07 09:09:40 +00001507 def test1(self): pass
1508 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001509
1510 tests = [LoggingCase('test1'), LoggingCase('test2')]
1511
Georg Brandl15c5ce92007-03-07 09:09:40 +00001512 unittest.TestSuite(tests).run(result)
Tim Petersea5962f2007-03-12 18:07:52 +00001513
Georg Brandl15c5ce92007-03-07 09:09:40 +00001514 self.assertEqual(events, ['run test1', 'run test2'])
Tim Petersea5962f2007-03-12 18:07:52 +00001515
1516 # "Add a TestCase ... to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001517 def test_addTest__TestCase(self):
1518 class Foo(unittest.TestCase):
1519 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001520
Georg Brandl15c5ce92007-03-07 09:09:40 +00001521 test = Foo('test')
1522 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001523
Georg Brandl15c5ce92007-03-07 09:09:40 +00001524 suite.addTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001525
Georg Brandl15c5ce92007-03-07 09:09:40 +00001526 self.assertEqual(suite.countTestCases(), 1)
1527 self.assertEqual(list(suite), [test])
Tim Petersea5962f2007-03-12 18:07:52 +00001528
1529 # "Add a ... TestSuite to the suite"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001530 def test_addTest__TestSuite(self):
1531 class Foo(unittest.TestCase):
1532 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001533
Georg Brandl15c5ce92007-03-07 09:09:40 +00001534 suite_2 = unittest.TestSuite([Foo('test')])
Tim Petersea5962f2007-03-12 18:07:52 +00001535
Georg Brandl15c5ce92007-03-07 09:09:40 +00001536 suite = unittest.TestSuite()
1537 suite.addTest(suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001538
Georg Brandl15c5ce92007-03-07 09:09:40 +00001539 self.assertEqual(suite.countTestCases(), 1)
1540 self.assertEqual(list(suite), [suite_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001541
Georg Brandl15c5ce92007-03-07 09:09:40 +00001542 # "Add all the tests from an iterable of TestCase and TestSuite
1543 # instances to this test suite."
Tim Petersea5962f2007-03-12 18:07:52 +00001544 #
Georg Brandl15c5ce92007-03-07 09:09:40 +00001545 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001546 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001547 def test_addTests(self):
1548 class Foo(unittest.TestCase):
1549 def test_1(self): pass
1550 def test_2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001551
Georg Brandl15c5ce92007-03-07 09:09:40 +00001552 test_1 = Foo('test_1')
1553 test_2 = Foo('test_2')
1554 inner_suite = unittest.TestSuite([test_2])
Tim Petersea5962f2007-03-12 18:07:52 +00001555
Georg Brandl15c5ce92007-03-07 09:09:40 +00001556 def gen():
1557 yield test_1
1558 yield test_2
1559 yield inner_suite
Tim Petersea5962f2007-03-12 18:07:52 +00001560
Georg Brandl15c5ce92007-03-07 09:09:40 +00001561 suite_1 = unittest.TestSuite()
1562 suite_1.addTests(gen())
Tim Petersea5962f2007-03-12 18:07:52 +00001563
Georg Brandl15c5ce92007-03-07 09:09:40 +00001564 self.assertEqual(list(suite_1), list(gen()))
Tim Petersea5962f2007-03-12 18:07:52 +00001565
Georg Brandl15c5ce92007-03-07 09:09:40 +00001566 # "This is equivalent to iterating over tests, calling addTest() for
Tim Petersea5962f2007-03-12 18:07:52 +00001567 # each element"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001568 suite_2 = unittest.TestSuite()
1569 for t in gen():
1570 suite_2.addTest(t)
Tim Petersea5962f2007-03-12 18:07:52 +00001571
Georg Brandl15c5ce92007-03-07 09:09:40 +00001572 self.assertEqual(suite_1, suite_2)
Tim Petersea5962f2007-03-12 18:07:52 +00001573
Georg Brandl15c5ce92007-03-07 09:09:40 +00001574 # "Add all the tests from an iterable of TestCase and TestSuite
1575 # instances to this test suite."
1576 #
Tim Petersea5962f2007-03-12 18:07:52 +00001577 # What happens if it doesn't get an iterable?
Georg Brandl15c5ce92007-03-07 09:09:40 +00001578 def test_addTest__noniterable(self):
1579 suite = unittest.TestSuite()
Tim Petersea5962f2007-03-12 18:07:52 +00001580
Georg Brandl15c5ce92007-03-07 09:09:40 +00001581 try:
1582 suite.addTests(5)
1583 except TypeError:
1584 pass
1585 else:
1586 self.fail("Failed to raise TypeError")
Georg Brandld9e50262007-03-07 11:54:49 +00001587
1588 def test_addTest__noncallable(self):
1589 suite = unittest.TestSuite()
1590 self.assertRaises(TypeError, suite.addTest, 5)
1591
1592 def test_addTest__casesuiteclass(self):
1593 suite = unittest.TestSuite()
1594 self.assertRaises(TypeError, suite.addTest, Test_TestSuite)
1595 self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)
1596
1597 def test_addTests__string(self):
1598 suite = unittest.TestSuite()
1599 self.assertRaises(TypeError, suite.addTests, "foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001600
1601
Georg Brandl15c5ce92007-03-07 09:09:40 +00001602class Test_FunctionTestCase(TestCase):
Tim Petersea5962f2007-03-12 18:07:52 +00001603
Georg Brandl15c5ce92007-03-07 09:09:40 +00001604 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00001605 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00001606 def test_countTestCases(self):
1607 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001608
Georg Brandl15c5ce92007-03-07 09:09:40 +00001609 self.assertEqual(test.countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00001610
Georg Brandl15c5ce92007-03-07 09:09:40 +00001611 # "When a setUp() method is defined, the test runner will run that method
1612 # prior to each test. Likewise, if a tearDown() method is defined, the
1613 # test runner will invoke that method after each test. In the example,
1614 # setUp() was used to create a fresh sequence for each test."
1615 #
1616 # Make sure the proper call order is maintained, even if setUp() raises
1617 # an exception.
1618 def test_run_call_order__error_in_setUp(self):
1619 events = []
1620 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001621
Georg Brandl15c5ce92007-03-07 09:09:40 +00001622 def setUp():
1623 events.append('setUp')
1624 raise RuntimeError('raised by setUp')
1625
1626 def test():
1627 events.append('test')
1628
1629 def tearDown():
1630 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001631
1632 expected = ['startTest', 'setUp', 'addError', 'stopTest']
Georg Brandl15c5ce92007-03-07 09:09:40 +00001633 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1634 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001635
Georg Brandl15c5ce92007-03-07 09:09:40 +00001636 # "When a setUp() method is defined, the test runner will run that method
1637 # prior to each test. Likewise, if a tearDown() method is defined, the
1638 # test runner will invoke that method after each test. In the example,
1639 # setUp() was used to create a fresh sequence for each test."
1640 #
1641 # Make sure the proper call order is maintained, even if the test raises
1642 # an error (as opposed to a failure).
1643 def test_run_call_order__error_in_test(self):
1644 events = []
1645 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001646
Georg Brandl15c5ce92007-03-07 09:09:40 +00001647 def setUp():
1648 events.append('setUp')
1649
1650 def test():
1651 events.append('test')
1652 raise RuntimeError('raised by test')
1653
1654 def tearDown():
1655 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001656
Georg Brandl15c5ce92007-03-07 09:09:40 +00001657 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
1658 'stopTest']
1659 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1660 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001661
Georg Brandl15c5ce92007-03-07 09:09:40 +00001662 # "When a setUp() method is defined, the test runner will run that method
1663 # prior to each test. Likewise, if a tearDown() method is defined, the
1664 # test runner will invoke that method after each test. In the example,
1665 # setUp() was used to create a fresh sequence for each test."
1666 #
1667 # Make sure the proper call order is maintained, even if the test signals
1668 # a failure (as opposed to an error).
1669 def test_run_call_order__failure_in_test(self):
1670 events = []
1671 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001672
Georg Brandl15c5ce92007-03-07 09:09:40 +00001673 def setUp():
1674 events.append('setUp')
1675
1676 def test():
1677 events.append('test')
1678 self.fail('raised by test')
1679
1680 def tearDown():
1681 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001682
Georg Brandl15c5ce92007-03-07 09:09:40 +00001683 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
1684 'stopTest']
1685 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1686 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001687
Georg Brandl15c5ce92007-03-07 09:09:40 +00001688 # "When a setUp() method is defined, the test runner will run that method
1689 # prior to each test. Likewise, if a tearDown() method is defined, the
1690 # test runner will invoke that method after each test. In the example,
1691 # setUp() was used to create a fresh sequence for each test."
1692 #
1693 # Make sure the proper call order is maintained, even if tearDown() raises
1694 # an exception.
1695 def test_run_call_order__error_in_tearDown(self):
1696 events = []
1697 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00001698
Georg Brandl15c5ce92007-03-07 09:09:40 +00001699 def setUp():
1700 events.append('setUp')
1701
1702 def test():
1703 events.append('test')
1704
1705 def tearDown():
1706 events.append('tearDown')
1707 raise RuntimeError('raised by tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00001708
Georg Brandl15c5ce92007-03-07 09:09:40 +00001709 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
1710 'stopTest']
1711 unittest.FunctionTestCase(test, setUp, tearDown).run(result)
1712 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00001713
Georg Brandl15c5ce92007-03-07 09:09:40 +00001714 # "Return a string identifying the specific test case."
1715 #
1716 # Because of the vague nature of the docs, I'm not going to lock this
1717 # test down too much. Really all that can be asserted is that the id()
1718 # will be a string (either 8-byte or unicode -- again, because the docs
1719 # just say "string")
1720 def test_id(self):
1721 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001722
Georg Brandl15c5ce92007-03-07 09:09:40 +00001723 self.failUnless(isinstance(test.id(), basestring))
Tim Petersea5962f2007-03-12 18:07:52 +00001724
Georg Brandl15c5ce92007-03-07 09:09:40 +00001725 # "Returns a one-line description of the test, or None if no description
1726 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001727 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001728 def test_shortDescription__no_docstring(self):
1729 test = unittest.FunctionTestCase(lambda: None)
Tim Petersea5962f2007-03-12 18:07:52 +00001730
Georg Brandl15c5ce92007-03-07 09:09:40 +00001731 self.assertEqual(test.shortDescription(), None)
Tim Petersea5962f2007-03-12 18:07:52 +00001732
Georg Brandl15c5ce92007-03-07 09:09:40 +00001733 # "Returns a one-line description of the test, or None if no description
1734 # has been provided. The default implementation of this method returns
Tim Petersea5962f2007-03-12 18:07:52 +00001735 # the first line of the test method's docstring, if available, or None."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001736 def test_shortDescription__singleline_docstring(self):
1737 desc = "this tests foo"
1738 test = unittest.FunctionTestCase(lambda: None, description=desc)
Tim Petersea5962f2007-03-12 18:07:52 +00001739
Georg Brandl15c5ce92007-03-07 09:09:40 +00001740 self.assertEqual(test.shortDescription(), "this tests foo")
Tim Petersea5962f2007-03-12 18:07:52 +00001741
Georg Brandl15c5ce92007-03-07 09:09:40 +00001742class Test_TestResult(TestCase):
1743 # Note: there are not separate tests for TestResult.wasSuccessful(),
1744 # TestResult.errors, TestResult.failures, TestResult.testsRun or
1745 # TestResult.shouldStop because these only have meaning in terms of
1746 # other TestResult methods.
1747 #
1748 # Accordingly, tests for the aforenamed attributes are incorporated
1749 # in with the tests for the defining methods.
1750 ################################################################
Tim Petersea5962f2007-03-12 18:07:52 +00001751
Georg Brandl15c5ce92007-03-07 09:09:40 +00001752 def test_init(self):
1753 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001754
Georg Brandl15c5ce92007-03-07 09:09:40 +00001755 self.failUnless(result.wasSuccessful())
1756 self.assertEqual(len(result.errors), 0)
1757 self.assertEqual(len(result.failures), 0)
1758 self.assertEqual(result.testsRun, 0)
1759 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001760
Georg Brandl15c5ce92007-03-07 09:09:40 +00001761 # "This method can be called to signal that the set of tests being
1762 # run should be aborted by setting the TestResult's shouldStop
Tim Petersea5962f2007-03-12 18:07:52 +00001763 # attribute to True."
Georg Brandl15c5ce92007-03-07 09:09:40 +00001764 def test_stop(self):
1765 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001766
Georg Brandl15c5ce92007-03-07 09:09:40 +00001767 result.stop()
Tim Petersea5962f2007-03-12 18:07:52 +00001768
Georg Brandl15c5ce92007-03-07 09:09:40 +00001769 self.assertEqual(result.shouldStop, True)
Tim Petersea5962f2007-03-12 18:07:52 +00001770
Georg Brandl15c5ce92007-03-07 09:09:40 +00001771 # "Called when the test case test is about to be run. The default
1772 # implementation simply increments the instance's testsRun counter."
1773 def test_startTest(self):
1774 class Foo(unittest.TestCase):
1775 def test_1(self):
1776 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001777
Georg Brandl15c5ce92007-03-07 09:09:40 +00001778 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001779
Georg Brandl15c5ce92007-03-07 09:09:40 +00001780 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001781
Georg Brandl15c5ce92007-03-07 09:09:40 +00001782 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001783
Georg Brandl15c5ce92007-03-07 09:09:40 +00001784 self.failUnless(result.wasSuccessful())
1785 self.assertEqual(len(result.errors), 0)
1786 self.assertEqual(len(result.failures), 0)
1787 self.assertEqual(result.testsRun, 1)
1788 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001789
Georg Brandl15c5ce92007-03-07 09:09:40 +00001790 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001791
Georg Brandl15c5ce92007-03-07 09:09:40 +00001792 # "Called after the test case test has been executed, regardless of
1793 # the outcome. The default implementation does nothing."
1794 def test_stopTest(self):
1795 class Foo(unittest.TestCase):
1796 def test_1(self):
1797 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001798
Georg Brandl15c5ce92007-03-07 09:09:40 +00001799 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001800
Georg Brandl15c5ce92007-03-07 09:09:40 +00001801 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001802
Georg Brandl15c5ce92007-03-07 09:09:40 +00001803 result.startTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001804
Georg Brandl15c5ce92007-03-07 09:09:40 +00001805 self.failUnless(result.wasSuccessful())
1806 self.assertEqual(len(result.errors), 0)
1807 self.assertEqual(len(result.failures), 0)
1808 self.assertEqual(result.testsRun, 1)
1809 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001810
Georg Brandl15c5ce92007-03-07 09:09:40 +00001811 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001812
Georg Brandl15c5ce92007-03-07 09:09:40 +00001813 # Same tests as above; make sure nothing has changed
1814 self.failUnless(result.wasSuccessful())
1815 self.assertEqual(len(result.errors), 0)
1816 self.assertEqual(len(result.failures), 0)
1817 self.assertEqual(result.testsRun, 1)
1818 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001819
Georg Brandl15c5ce92007-03-07 09:09:40 +00001820 # "addSuccess(test)"
1821 # ...
1822 # "Called when the test case test succeeds"
1823 # ...
1824 # "wasSuccessful() - Returns True if all tests run so far have passed,
1825 # otherwise returns False"
1826 # ...
1827 # "testsRun - The total number of tests run so far."
1828 # ...
1829 # "errors - A list containing 2-tuples of TestCase instances and
1830 # formatted tracebacks. Each tuple represents a test which raised an
1831 # unexpected exception. Contains formatted
1832 # tracebacks instead of sys.exc_info() results."
1833 # ...
1834 # "failures - A list containing 2-tuples of TestCase instances and
1835 # formatted tracebacks. Each tuple represents a test where a failure was
1836 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1837 # methods. Contains formatted tracebacks instead
1838 # of sys.exc_info() results."
1839 def test_addSuccess(self):
1840 class Foo(unittest.TestCase):
1841 def test_1(self):
1842 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001843
Georg Brandl15c5ce92007-03-07 09:09:40 +00001844 test = Foo('test_1')
Tim Petersea5962f2007-03-12 18:07:52 +00001845
Georg Brandl15c5ce92007-03-07 09:09:40 +00001846 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001847
Georg Brandl15c5ce92007-03-07 09:09:40 +00001848 result.startTest(test)
1849 result.addSuccess(test)
1850 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001851
Georg Brandl15c5ce92007-03-07 09:09:40 +00001852 self.failUnless(result.wasSuccessful())
1853 self.assertEqual(len(result.errors), 0)
1854 self.assertEqual(len(result.failures), 0)
1855 self.assertEqual(result.testsRun, 1)
1856 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001857
Georg Brandl15c5ce92007-03-07 09:09:40 +00001858 # "addFailure(test, err)"
1859 # ...
1860 # "Called when the test case test signals a failure. err is a tuple of
1861 # the form returned by sys.exc_info(): (type, value, traceback)"
1862 # ...
1863 # "wasSuccessful() - Returns True if all tests run so far have passed,
1864 # otherwise returns False"
1865 # ...
1866 # "testsRun - The total number of tests run so far."
1867 # ...
1868 # "errors - A list containing 2-tuples of TestCase instances and
1869 # formatted tracebacks. Each tuple represents a test which raised an
1870 # unexpected exception. Contains formatted
1871 # tracebacks instead of sys.exc_info() results."
1872 # ...
1873 # "failures - A list containing 2-tuples of TestCase instances and
1874 # formatted tracebacks. Each tuple represents a test where a failure was
1875 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1876 # methods. Contains formatted tracebacks instead
1877 # of sys.exc_info() results."
1878 def test_addFailure(self):
1879 import sys
Tim Petersea5962f2007-03-12 18:07:52 +00001880
Georg Brandl15c5ce92007-03-07 09:09:40 +00001881 class Foo(unittest.TestCase):
1882 def test_1(self):
1883 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001884
Georg Brandl15c5ce92007-03-07 09:09:40 +00001885 test = Foo('test_1')
1886 try:
1887 test.fail("foo")
1888 except:
1889 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00001890
Georg Brandl15c5ce92007-03-07 09:09:40 +00001891 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001892
Georg Brandl15c5ce92007-03-07 09:09:40 +00001893 result.startTest(test)
1894 result.addFailure(test, exc_info_tuple)
1895 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001896
Georg Brandl15c5ce92007-03-07 09:09:40 +00001897 self.failIf(result.wasSuccessful())
1898 self.assertEqual(len(result.errors), 0)
1899 self.assertEqual(len(result.failures), 1)
1900 self.assertEqual(result.testsRun, 1)
1901 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001902
Georg Brandl15c5ce92007-03-07 09:09:40 +00001903 test_case, formatted_exc = result.failures[0]
1904 self.failUnless(test_case is test)
1905 self.failUnless(isinstance(formatted_exc, str))
Tim Petersea5962f2007-03-12 18:07:52 +00001906
Georg Brandl15c5ce92007-03-07 09:09:40 +00001907 # "addError(test, err)"
1908 # ...
1909 # "Called when the test case test raises an unexpected exception err
1910 # is a tuple of the form returned by sys.exc_info():
1911 # (type, value, traceback)"
1912 # ...
1913 # "wasSuccessful() - Returns True if all tests run so far have passed,
1914 # otherwise returns False"
1915 # ...
1916 # "testsRun - The total number of tests run so far."
1917 # ...
1918 # "errors - A list containing 2-tuples of TestCase instances and
1919 # formatted tracebacks. Each tuple represents a test which raised an
1920 # unexpected exception. Contains formatted
1921 # tracebacks instead of sys.exc_info() results."
1922 # ...
1923 # "failures - A list containing 2-tuples of TestCase instances and
1924 # formatted tracebacks. Each tuple represents a test where a failure was
1925 # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
1926 # methods. Contains formatted tracebacks instead
1927 # of sys.exc_info() results."
1928 def test_addError(self):
1929 import sys
Tim Petersea5962f2007-03-12 18:07:52 +00001930
Georg Brandl15c5ce92007-03-07 09:09:40 +00001931 class Foo(unittest.TestCase):
1932 def test_1(self):
1933 pass
Tim Petersea5962f2007-03-12 18:07:52 +00001934
Georg Brandl15c5ce92007-03-07 09:09:40 +00001935 test = Foo('test_1')
1936 try:
1937 raise TypeError()
1938 except:
1939 exc_info_tuple = sys.exc_info()
Tim Petersea5962f2007-03-12 18:07:52 +00001940
Georg Brandl15c5ce92007-03-07 09:09:40 +00001941 result = unittest.TestResult()
Tim Petersea5962f2007-03-12 18:07:52 +00001942
Georg Brandl15c5ce92007-03-07 09:09:40 +00001943 result.startTest(test)
1944 result.addError(test, exc_info_tuple)
1945 result.stopTest(test)
Tim Petersea5962f2007-03-12 18:07:52 +00001946
Georg Brandl15c5ce92007-03-07 09:09:40 +00001947 self.failIf(result.wasSuccessful())
1948 self.assertEqual(len(result.errors), 1)
1949 self.assertEqual(len(result.failures), 0)
1950 self.assertEqual(result.testsRun, 1)
1951 self.assertEqual(result.shouldStop, False)
Tim Petersea5962f2007-03-12 18:07:52 +00001952
Georg Brandl15c5ce92007-03-07 09:09:40 +00001953 test_case, formatted_exc = result.errors[0]
1954 self.failUnless(test_case is test)
1955 self.failUnless(isinstance(formatted_exc, str))
1956
1957### Support code for Test_TestCase
1958################################################################
1959
1960class Foo(unittest.TestCase):
1961 def runTest(self): pass
1962 def test1(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001963
Georg Brandl15c5ce92007-03-07 09:09:40 +00001964class Bar(Foo):
1965 def test2(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00001966
Georg Brandl15c5ce92007-03-07 09:09:40 +00001967################################################################
1968### /Support code for Test_TestCase
1969
1970class Test_TestCase(TestCase, TestEquality, TestHashing):
1971
1972 ### Set up attributes used by inherited tests
1973 ################################################################
1974
1975 # Used by TestHashing.test_hash and TestEquality.test_eq
1976 eq_pairs = [(Foo('test1'), Foo('test1'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001977
Georg Brandl15c5ce92007-03-07 09:09:40 +00001978 # Used by TestEquality.test_ne
1979 ne_pairs = [(Foo('test1'), Foo('runTest'))
1980 ,(Foo('test1'), Bar('test1'))
1981 ,(Foo('test1'), Bar('test2'))]
Tim Petersea5962f2007-03-12 18:07:52 +00001982
Georg Brandl15c5ce92007-03-07 09:09:40 +00001983 ################################################################
1984 ### /Set up attributes used by inherited tests
Tim Petersea5962f2007-03-12 18:07:52 +00001985
Georg Brandl15c5ce92007-03-07 09:09:40 +00001986
1987 # "class TestCase([methodName])"
1988 # ...
1989 # "Each instance of TestCase will run a single test method: the
1990 # method named methodName."
1991 # ...
1992 # "methodName defaults to "runTest"."
1993 #
1994 # Make sure it really is optional, and that it defaults to the proper
1995 # thing.
1996 def test_init__no_test_name(self):
1997 class Test(unittest.TestCase):
1998 def runTest(self): raise MyException()
1999 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002000
Georg Brandl15c5ce92007-03-07 09:09:40 +00002001 self.assertEqual(Test().id()[-13:], '.Test.runTest')
Tim Petersea5962f2007-03-12 18:07:52 +00002002
Georg Brandl15c5ce92007-03-07 09:09:40 +00002003 # "class TestCase([methodName])"
2004 # ...
2005 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002006 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002007 def test_init__test_name__valid(self):
2008 class Test(unittest.TestCase):
2009 def runTest(self): raise MyException()
2010 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002011
Georg Brandl15c5ce92007-03-07 09:09:40 +00002012 self.assertEqual(Test('test').id()[-10:], '.Test.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002013
Georg Brandl15c5ce92007-03-07 09:09:40 +00002014 # "class TestCase([methodName])"
2015 # ...
2016 # "Each instance of TestCase will run a single test method: the
Tim Petersea5962f2007-03-12 18:07:52 +00002017 # method named methodName."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002018 def test_init__test_name__invalid(self):
2019 class Test(unittest.TestCase):
2020 def runTest(self): raise MyException()
2021 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002022
Georg Brandl15c5ce92007-03-07 09:09:40 +00002023 try:
2024 Test('testfoo')
2025 except ValueError:
2026 pass
2027 else:
2028 self.fail("Failed to raise ValueError")
Tim Petersea5962f2007-03-12 18:07:52 +00002029
Georg Brandl15c5ce92007-03-07 09:09:40 +00002030 # "Return the number of tests represented by the this test object. For
Tim Petersea5962f2007-03-12 18:07:52 +00002031 # TestCase instances, this will always be 1"
Georg Brandl15c5ce92007-03-07 09:09:40 +00002032 def test_countTestCases(self):
2033 class Foo(unittest.TestCase):
2034 def test(self): pass
Tim Petersea5962f2007-03-12 18:07:52 +00002035
Georg Brandl15c5ce92007-03-07 09:09:40 +00002036 self.assertEqual(Foo('test').countTestCases(), 1)
Tim Petersea5962f2007-03-12 18:07:52 +00002037
Georg Brandl15c5ce92007-03-07 09:09:40 +00002038 # "Return the default type of test result object to be used to run this
2039 # test. For TestCase instances, this will always be
2040 # unittest.TestResult; subclasses of TestCase should
2041 # override this as necessary."
2042 def test_defaultTestResult(self):
2043 class Foo(unittest.TestCase):
2044 def runTest(self):
2045 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002046
Georg Brandl15c5ce92007-03-07 09:09:40 +00002047 result = Foo().defaultTestResult()
2048 self.assertEqual(type(result), unittest.TestResult)
2049
2050 # "When a setUp() method is defined, the test runner will run that method
2051 # prior to each test. Likewise, if a tearDown() method is defined, the
2052 # test runner will invoke that method after each test. In the example,
2053 # setUp() was used to create a fresh sequence for each test."
2054 #
2055 # Make sure the proper call order is maintained, even if setUp() raises
2056 # an exception.
2057 def test_run_call_order__error_in_setUp(self):
2058 events = []
2059 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002060
Georg Brandl15c5ce92007-03-07 09:09:40 +00002061 class Foo(unittest.TestCase):
2062 def setUp(self):
2063 events.append('setUp')
2064 raise RuntimeError('raised by Foo.setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002065
Georg Brandl15c5ce92007-03-07 09:09:40 +00002066 def test(self):
2067 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002068
Georg Brandl15c5ce92007-03-07 09:09:40 +00002069 def tearDown(self):
2070 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002071
Georg Brandl15c5ce92007-03-07 09:09:40 +00002072 Foo('test').run(result)
2073 expected = ['startTest', 'setUp', 'addError', 'stopTest']
2074 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002075
Georg Brandl15c5ce92007-03-07 09:09:40 +00002076 # "When a setUp() method is defined, the test runner will run that method
2077 # prior to each test. Likewise, if a tearDown() method is defined, the
2078 # test runner will invoke that method after each test. In the example,
2079 # setUp() was used to create a fresh sequence for each test."
2080 #
2081 # Make sure the proper call order is maintained, even if the test raises
2082 # an error (as opposed to a failure).
2083 def test_run_call_order__error_in_test(self):
2084 events = []
2085 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002086
Georg Brandl15c5ce92007-03-07 09:09:40 +00002087 class Foo(unittest.TestCase):
2088 def setUp(self):
2089 events.append('setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002090
Georg Brandl15c5ce92007-03-07 09:09:40 +00002091 def test(self):
2092 events.append('test')
2093 raise RuntimeError('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002094
Georg Brandl15c5ce92007-03-07 09:09:40 +00002095 def tearDown(self):
2096 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002097
Georg Brandl15c5ce92007-03-07 09:09:40 +00002098 expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
2099 'stopTest']
2100 Foo('test').run(result)
2101 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002102
Georg Brandl15c5ce92007-03-07 09:09:40 +00002103 # "When a setUp() method is defined, the test runner will run that method
2104 # prior to each test. Likewise, if a tearDown() method is defined, the
2105 # test runner will invoke that method after each test. In the example,
2106 # setUp() was used to create a fresh sequence for each test."
2107 #
2108 # Make sure the proper call order is maintained, even if the test signals
2109 # a failure (as opposed to an error).
2110 def test_run_call_order__failure_in_test(self):
2111 events = []
2112 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002113
Georg Brandl15c5ce92007-03-07 09:09:40 +00002114 class Foo(unittest.TestCase):
2115 def setUp(self):
2116 events.append('setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002117
Georg Brandl15c5ce92007-03-07 09:09:40 +00002118 def test(self):
2119 events.append('test')
2120 self.fail('raised by Foo.test')
Tim Petersea5962f2007-03-12 18:07:52 +00002121
Georg Brandl15c5ce92007-03-07 09:09:40 +00002122 def tearDown(self):
2123 events.append('tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002124
Georg Brandl15c5ce92007-03-07 09:09:40 +00002125 expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
2126 'stopTest']
2127 Foo('test').run(result)
2128 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002129
Georg Brandl15c5ce92007-03-07 09:09:40 +00002130 # "When a setUp() method is defined, the test runner will run that method
2131 # prior to each test. Likewise, if a tearDown() method is defined, the
2132 # test runner will invoke that method after each test. In the example,
2133 # setUp() was used to create a fresh sequence for each test."
2134 #
2135 # Make sure the proper call order is maintained, even if tearDown() raises
2136 # an exception.
2137 def test_run_call_order__error_in_tearDown(self):
2138 events = []
2139 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002140
Georg Brandl15c5ce92007-03-07 09:09:40 +00002141 class Foo(unittest.TestCase):
2142 def setUp(self):
2143 events.append('setUp')
Tim Petersea5962f2007-03-12 18:07:52 +00002144
Georg Brandl15c5ce92007-03-07 09:09:40 +00002145 def test(self):
2146 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002147
Georg Brandl15c5ce92007-03-07 09:09:40 +00002148 def tearDown(self):
2149 events.append('tearDown')
2150 raise RuntimeError('raised by Foo.tearDown')
Tim Petersea5962f2007-03-12 18:07:52 +00002151
Georg Brandl15c5ce92007-03-07 09:09:40 +00002152 Foo('test').run(result)
2153 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
2154 'stopTest']
2155 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002156
Georg Brandl15c5ce92007-03-07 09:09:40 +00002157 # "This class attribute gives the exception raised by the test() method.
2158 # If a test framework needs to use a specialized exception, possibly to
2159 # carry additional information, it must subclass this exception in
2160 # order to ``play fair'' with the framework. The initial value of this
2161 # attribute is AssertionError"
2162 def test_failureException__default(self):
2163 class Foo(unittest.TestCase):
2164 def test(self):
2165 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002166
Georg Brandl15c5ce92007-03-07 09:09:40 +00002167 self.failUnless(Foo('test').failureException is AssertionError)
Tim Petersea5962f2007-03-12 18:07:52 +00002168
Georg Brandl15c5ce92007-03-07 09:09:40 +00002169 # "This class attribute gives the exception raised by the test() method.
2170 # If a test framework needs to use a specialized exception, possibly to
2171 # carry additional information, it must subclass this exception in
2172 # order to ``play fair'' with the framework."
2173 #
2174 # Make sure TestCase.run() respects the designated failureException
2175 def test_failureException__subclassing__explicit_raise(self):
2176 events = []
2177 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002178
Georg Brandl15c5ce92007-03-07 09:09:40 +00002179 class Foo(unittest.TestCase):
2180 def test(self):
2181 raise RuntimeError()
Tim Petersea5962f2007-03-12 18:07:52 +00002182
Georg Brandl15c5ce92007-03-07 09:09:40 +00002183 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002184
Georg Brandl15c5ce92007-03-07 09:09:40 +00002185 self.failUnless(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002186
2187
Georg Brandl15c5ce92007-03-07 09:09:40 +00002188 Foo('test').run(result)
2189 expected = ['startTest', 'addFailure', 'stopTest']
2190 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002191
Georg Brandl15c5ce92007-03-07 09:09:40 +00002192 # "This class attribute gives the exception raised by the test() method.
2193 # If a test framework needs to use a specialized exception, possibly to
2194 # carry additional information, it must subclass this exception in
2195 # order to ``play fair'' with the framework."
2196 #
2197 # Make sure TestCase.run() respects the designated failureException
2198 def test_failureException__subclassing__implicit_raise(self):
2199 events = []
2200 result = LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002201
Georg Brandl15c5ce92007-03-07 09:09:40 +00002202 class Foo(unittest.TestCase):
2203 def test(self):
2204 self.fail("foo")
Tim Petersea5962f2007-03-12 18:07:52 +00002205
Georg Brandl15c5ce92007-03-07 09:09:40 +00002206 failureException = RuntimeError
Tim Petersea5962f2007-03-12 18:07:52 +00002207
Georg Brandl15c5ce92007-03-07 09:09:40 +00002208 self.failUnless(Foo('test').failureException is RuntimeError)
Tim Petersea5962f2007-03-12 18:07:52 +00002209
2210
Georg Brandl15c5ce92007-03-07 09:09:40 +00002211 Foo('test').run(result)
2212 expected = ['startTest', 'addFailure', 'stopTest']
2213 self.assertEqual(events, expected)
Tim Petersea5962f2007-03-12 18:07:52 +00002214
2215 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002216 def test_setUp(self):
2217 class Foo(unittest.TestCase):
2218 def runTest(self):
2219 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002220
Georg Brandl15c5ce92007-03-07 09:09:40 +00002221 # ... and nothing should happen
2222 Foo().setUp()
Tim Petersea5962f2007-03-12 18:07:52 +00002223
2224 # "The default implementation does nothing."
Georg Brandl15c5ce92007-03-07 09:09:40 +00002225 def test_tearDown(self):
2226 class Foo(unittest.TestCase):
2227 def runTest(self):
2228 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002229
Georg Brandl15c5ce92007-03-07 09:09:40 +00002230 # ... and nothing should happen
2231 Foo().tearDown()
Tim Petersea5962f2007-03-12 18:07:52 +00002232
Georg Brandl15c5ce92007-03-07 09:09:40 +00002233 # "Return a string identifying the specific test case."
2234 #
2235 # Because of the vague nature of the docs, I'm not going to lock this
2236 # test down too much. Really all that can be asserted is that the id()
2237 # will be a string (either 8-byte or unicode -- again, because the docs
2238 # just say "string")
2239 def test_id(self):
2240 class Foo(unittest.TestCase):
2241 def runTest(self):
2242 pass
Tim Petersea5962f2007-03-12 18:07:52 +00002243
Georg Brandl15c5ce92007-03-07 09:09:40 +00002244 self.failUnless(isinstance(Foo().id(), basestring))
Tim Petersea5962f2007-03-12 18:07:52 +00002245
Georg Brandl15c5ce92007-03-07 09:09:40 +00002246 # "If result is omitted or None, a temporary result object is created
Tim Petersea5962f2007-03-12 18:07:52 +00002247 # and used, but is not made available to the caller"
Georg Brandl15c5ce92007-03-07 09:09:40 +00002248 def test_run__uses_defaultTestResult(self):
2249 events = []
Tim Petersea5962f2007-03-12 18:07:52 +00002250
Georg Brandl15c5ce92007-03-07 09:09:40 +00002251 class Foo(unittest.TestCase):
2252 def test(self):
2253 events.append('test')
Tim Petersea5962f2007-03-12 18:07:52 +00002254
Georg Brandl15c5ce92007-03-07 09:09:40 +00002255 def defaultTestResult(self):
2256 return LoggingResult(events)
Tim Petersea5962f2007-03-12 18:07:52 +00002257
2258 # Make run() find a result object on its own
Georg Brandl15c5ce92007-03-07 09:09:40 +00002259 Foo('test').run()
Tim Petersea5962f2007-03-12 18:07:52 +00002260
Benjamin Peterson692428e2009-03-23 21:50:21 +00002261 expected = ['startTest', 'test', 'addSuccess', 'stopTest']
Georg Brandl15c5ce92007-03-07 09:09:40 +00002262 self.assertEqual(events, expected)
Jim Fultonfafd8742004-08-28 15:22:12 +00002263
Gregory P. Smith28399852009-03-31 16:54:10 +00002264 def testShortDescriptionWithoutDocstring(self):
2265 self.assertEqual(
2266 self.shortDescription(),
2267 'testShortDescriptionWithoutDocstring (' + __name__ +
2268 '.Test_TestCase)')
2269
2270 def testShortDescriptionWithOneLineDocstring(self):
2271 """Tests shortDescription() for a method with a docstring."""
2272 self.assertEqual(
2273 self.shortDescription(),
2274 ('testShortDescriptionWithOneLineDocstring '
2275 '(' + __name__ + '.Test_TestCase)\n'
2276 'Tests shortDescription() for a method with a docstring.'))
2277
2278 def testShortDescriptionWithMultiLineDocstring(self):
2279 """Tests shortDescription() for a method with a longer docstring.
2280
2281 This method ensures that only the first line of a docstring is
2282 returned used in the short description, no matter how long the
2283 whole thing is.
2284 """
2285 self.assertEqual(
2286 self.shortDescription(),
2287 ('testShortDescriptionWithMultiLineDocstring '
2288 '(' + __name__ + '.Test_TestCase)\n'
2289 'Tests shortDescription() for a method with a longer '
2290 'docstring.'))
2291
Gregory P. Smith28399852009-03-31 16:54:10 +00002292 def testAddTypeEqualityFunc(self):
2293 class SadSnake(object):
2294 """Dummy class for test_addTypeEqualityFunc."""
2295 s1, s2 = SadSnake(), SadSnake()
2296 self.assertFalse(s1 == s2)
2297 def AllSnakesCreatedEqual(a, b, msg=None):
2298 return type(a) == type(b) == SadSnake
2299 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
2300 self.assertEqual(s1, s2)
2301 # No this doesn't clean up and remove the SadSnake equality func
2302 # from this TestCase instance but since its a local nothing else
2303 # will ever notice that.
2304
Michael Foordf2dfef12009-04-05 19:19:28 +00002305 def testAssertIs(self):
2306 thing = object()
2307 self.assertIs(thing, thing)
2308 self.assertRaises(self.failureException, self.assertIs, thing, object())
2309
2310 def testAssertIsNot(self):
2311 thing = object()
2312 self.assertIsNot(thing, object())
2313 self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
2314
Gregory P. Smith28399852009-03-31 16:54:10 +00002315 def testAssertIn(self):
2316 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
2317
2318 self.assertIn('a', 'abc')
2319 self.assertIn(2, [1, 2, 3])
2320 self.assertIn('monkey', animals)
2321
2322 self.assertNotIn('d', 'abc')
2323 self.assertNotIn(0, [1, 2, 3])
2324 self.assertNotIn('otter', animals)
2325
2326 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
2327 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
2328 self.assertRaises(self.failureException, self.assertIn, 'elephant',
2329 animals)
2330
2331 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
2332 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
2333 self.assertRaises(self.failureException, self.assertNotIn, 'cow',
2334 animals)
2335
2336 def testAssertDictContainsSubset(self):
2337 self.assertDictContainsSubset({}, {})
2338 self.assertDictContainsSubset({}, {'a': 1})
2339 self.assertDictContainsSubset({'a': 1}, {'a': 1})
2340 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
2341 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
2342
2343 self.assertRaises(unittest.TestCase.failureException,
2344 self.assertDictContainsSubset, {'a': 2}, {'a': 1},
2345 '.*Mismatched values:.*')
2346
2347 self.assertRaises(unittest.TestCase.failureException,
2348 self.assertDictContainsSubset, {'c': 1}, {'a': 1},
2349 '.*Missing:.*')
2350
2351 self.assertRaises(unittest.TestCase.failureException,
2352 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2353 {'a': 1}, '.*Missing:.*')
2354
2355 self.assertRaises(unittest.TestCase.failureException,
2356 self.assertDictContainsSubset, {'a': 1, 'c': 1},
2357 {'a': 1}, '.*Missing:.*Mismatched values:.*')
2358
2359 def testAssertEqual(self):
2360 equal_pairs = [
2361 ((), ()),
2362 ({}, {}),
2363 ([], []),
2364 (set(), set()),
2365 (frozenset(), frozenset())]
2366 for a, b in equal_pairs:
2367 # This mess of try excepts is to test the assertEqual behavior
2368 # itself.
2369 try:
2370 self.assertEqual(a, b)
2371 except self.failureException:
2372 self.fail('assertEqual(%r, %r) failed' % (a, b))
2373 try:
2374 self.assertEqual(a, b, msg='foo')
2375 except self.failureException:
2376 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
2377 try:
2378 self.assertEqual(a, b, 'foo')
2379 except self.failureException:
2380 self.fail('assertEqual(%r, %r) with third parameter failed' %
2381 (a, b))
2382
2383 unequal_pairs = [
2384 ((), []),
2385 ({}, set()),
2386 (set([4,1]), frozenset([4,2])),
2387 (frozenset([4,5]), set([2,3])),
2388 (set([3,4]), set([5,4]))]
2389 for a, b in unequal_pairs:
2390 self.assertRaises(self.failureException, self.assertEqual, a, b)
2391 self.assertRaises(self.failureException, self.assertEqual, a, b,
2392 'foo')
2393 self.assertRaises(self.failureException, self.assertEqual, a, b,
2394 msg='foo')
2395
2396 def testEquality(self):
2397 self.assertListEqual([], [])
2398 self.assertTupleEqual((), ())
2399 self.assertSequenceEqual([], ())
2400
2401 a = [0, 'a', []]
2402 b = []
2403 self.assertRaises(unittest.TestCase.failureException,
2404 self.assertListEqual, a, b)
2405 self.assertRaises(unittest.TestCase.failureException,
2406 self.assertListEqual, tuple(a), tuple(b))
2407 self.assertRaises(unittest.TestCase.failureException,
2408 self.assertSequenceEqual, a, tuple(b))
2409
2410 b.extend(a)
2411 self.assertListEqual(a, b)
2412 self.assertTupleEqual(tuple(a), tuple(b))
2413 self.assertSequenceEqual(a, tuple(b))
2414 self.assertSequenceEqual(tuple(a), b)
2415
2416 self.assertRaises(self.failureException, self.assertListEqual,
2417 a, tuple(b))
2418 self.assertRaises(self.failureException, self.assertTupleEqual,
2419 tuple(a), b)
2420 self.assertRaises(self.failureException, self.assertListEqual, None, b)
2421 self.assertRaises(self.failureException, self.assertTupleEqual, None,
2422 tuple(b))
2423 self.assertRaises(self.failureException, self.assertSequenceEqual,
2424 None, tuple(b))
2425 self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
2426 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
2427 self.assertRaises(self.failureException, self.assertSequenceEqual,
2428 1, 1)
2429
2430 self.assertDictEqual({}, {})
2431
2432 c = { 'x': 1 }
2433 d = {}
2434 self.assertRaises(unittest.TestCase.failureException,
2435 self.assertDictEqual, c, d)
2436
2437 d.update(c)
2438 self.assertDictEqual(c, d)
2439
2440 d['x'] = 0
2441 self.assertRaises(unittest.TestCase.failureException,
2442 self.assertDictEqual, c, d, 'These are unequal')
2443
2444 self.assertRaises(self.failureException, self.assertDictEqual, None, d)
2445 self.assertRaises(self.failureException, self.assertDictEqual, [], d)
2446 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
2447
2448 self.assertSameElements([1, 2, 3], [3, 2, 1])
2449 self.assertSameElements([1, 2] + [3] * 100, [1] * 100 + [2, 3])
2450 self.assertSameElements(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
2451 self.assertRaises(self.failureException, self.assertSameElements,
2452 [10], [10, 11])
2453 self.assertRaises(self.failureException, self.assertSameElements,
2454 [10, 11], [10])
2455
2456 # Test that sequences of unhashable objects can be tested for sameness:
2457 self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]])
Michael Foordf2dfef12009-04-05 19:19:28 +00002458
Gregory P. Smith28399852009-03-31 16:54:10 +00002459 self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
2460 self.assertRaises(self.failureException, self.assertSameElements,
2461 [[1]], [[2]])
2462
2463 def testAssertSetEqual(self):
2464 set1 = set()
2465 set2 = set()
2466 self.assertSetEqual(set1, set2)
2467
2468 self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
2469 self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
2470 self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
2471 self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
2472
2473 set1 = set(['a'])
2474 set2 = set()
2475 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2476
2477 set1 = set(['a'])
2478 set2 = set(['a'])
2479 self.assertSetEqual(set1, set2)
2480
2481 set1 = set(['a'])
2482 set2 = set(['a', 'b'])
2483 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2484
2485 set1 = set(['a'])
2486 set2 = frozenset(['a', 'b'])
2487 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2488
2489 set1 = set(['a', 'b'])
2490 set2 = frozenset(['a', 'b'])
2491 self.assertSetEqual(set1, set2)
2492
2493 set1 = set()
2494 set2 = "foo"
2495 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2496 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
2497
2498 # make sure any string formatting is tuple-safe
2499 set1 = set([(0, 1), (2, 3)])
2500 set2 = set([(4, 5)])
2501 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
2502
2503 def testInequality(self):
2504 # Try ints
2505 self.assertGreater(2, 1)
2506 self.assertGreaterEqual(2, 1)
2507 self.assertGreaterEqual(1, 1)
2508 self.assertLess(1, 2)
2509 self.assertLessEqual(1, 2)
2510 self.assertLessEqual(1, 1)
2511 self.assertRaises(self.failureException, self.assertGreater, 1, 2)
2512 self.assertRaises(self.failureException, self.assertGreater, 1, 1)
2513 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
2514 self.assertRaises(self.failureException, self.assertLess, 2, 1)
2515 self.assertRaises(self.failureException, self.assertLess, 1, 1)
2516 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
2517
2518 # Try Floats
2519 self.assertGreater(1.1, 1.0)
2520 self.assertGreaterEqual(1.1, 1.0)
2521 self.assertGreaterEqual(1.0, 1.0)
2522 self.assertLess(1.0, 1.1)
2523 self.assertLessEqual(1.0, 1.1)
2524 self.assertLessEqual(1.0, 1.0)
2525 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
2526 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
2527 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
2528 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
2529 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
2530 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
2531
2532 # Try Strings
2533 self.assertGreater('bug', 'ant')
2534 self.assertGreaterEqual('bug', 'ant')
2535 self.assertGreaterEqual('ant', 'ant')
2536 self.assertLess('ant', 'bug')
2537 self.assertLessEqual('ant', 'bug')
2538 self.assertLessEqual('ant', 'ant')
2539 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
2540 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
2541 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
2542 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
2543 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
2544 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
2545
2546 # Try Unicode
2547 self.assertGreater(u'bug', u'ant')
2548 self.assertGreaterEqual(u'bug', u'ant')
2549 self.assertGreaterEqual(u'ant', u'ant')
2550 self.assertLess(u'ant', u'bug')
2551 self.assertLessEqual(u'ant', u'bug')
2552 self.assertLessEqual(u'ant', u'ant')
2553 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'bug')
2554 self.assertRaises(self.failureException, self.assertGreater, u'ant', u'ant')
2555 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2556 u'bug')
2557 self.assertRaises(self.failureException, self.assertLess, u'bug', u'ant')
2558 self.assertRaises(self.failureException, self.assertLess, u'ant', u'ant')
2559 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', u'ant')
2560
2561 # Try Mixed String/Unicode
2562 self.assertGreater('bug', u'ant')
2563 self.assertGreater(u'bug', 'ant')
2564 self.assertGreaterEqual('bug', u'ant')
2565 self.assertGreaterEqual(u'bug', 'ant')
2566 self.assertGreaterEqual('ant', u'ant')
2567 self.assertGreaterEqual(u'ant', 'ant')
2568 self.assertLess('ant', u'bug')
2569 self.assertLess(u'ant', 'bug')
2570 self.assertLessEqual('ant', u'bug')
2571 self.assertLessEqual(u'ant', 'bug')
2572 self.assertLessEqual('ant', u'ant')
2573 self.assertLessEqual(u'ant', 'ant')
2574 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'bug')
2575 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'bug')
2576 self.assertRaises(self.failureException, self.assertGreater, 'ant', u'ant')
2577 self.assertRaises(self.failureException, self.assertGreater, u'ant', 'ant')
2578 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant',
2579 u'bug')
2580 self.assertRaises(self.failureException, self.assertGreaterEqual, u'ant',
2581 'bug')
2582 self.assertRaises(self.failureException, self.assertLess, 'bug', u'ant')
2583 self.assertRaises(self.failureException, self.assertLess, u'bug', 'ant')
2584 self.assertRaises(self.failureException, self.assertLess, 'ant', u'ant')
2585 self.assertRaises(self.failureException, self.assertLess, u'ant', 'ant')
2586 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', u'ant')
2587 self.assertRaises(self.failureException, self.assertLessEqual, u'bug', 'ant')
2588
2589 def testAssertMultiLineEqual(self):
2590 sample_text = b"""\
2591http://www.python.org/doc/2.3/lib/module-unittest.html
2592test case
2593 A test case is the smallest unit of testing. [...]
2594"""
2595 revised_sample_text = b"""\
2596http://www.python.org/doc/2.4.1/lib/module-unittest.html
2597test case
2598 A test case is the smallest unit of testing. [...] You may provide your
2599 own implementation that does not subclass from TestCase, of course.
2600"""
2601 sample_text_error = b"""
2602- http://www.python.org/doc/2.3/lib/module-unittest.html
2603? ^
2604+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
2605? ^^^
2606 test case
2607- A test case is the smallest unit of testing. [...]
2608+ A test case is the smallest unit of testing. [...] You may provide your
2609? +++++++++++++++++++++
2610+ own implementation that does not subclass from TestCase, of course.
2611"""
2612
2613 for type_changer in (lambda x: x, lambda x: x.decode('utf8')):
2614 try:
2615 self.assertMultiLineEqual(type_changer(sample_text),
2616 type_changer(revised_sample_text))
2617 except self.failureException, e:
2618 # no fair testing ourself with ourself, use assertEqual..
2619 self.assertEqual(sample_text_error, str(e).encode('utf8'))
2620
2621 def testAssertIsNone(self):
2622 self.assertIsNone(None)
2623 self.assertRaises(self.failureException, self.assertIsNone, False)
2624 self.assertIsNotNone('DjZoPloGears on Rails')
2625 self.assertRaises(self.failureException, self.assertIsNotNone, None)
2626
2627 def testAssertRegexpMatches(self):
2628 self.assertRegexpMatches('asdfabasdf', r'ab+')
2629 self.assertRaises(self.failureException, self.assertRegexpMatches,
2630 'saaas', r'aaaa')
2631
2632 def testAssertRaisesRegexp(self):
2633 class ExceptionMock(Exception):
2634 pass
2635
2636 def Stub():
2637 raise ExceptionMock('We expect')
2638
2639 self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
2640 self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
2641 self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
2642
2643 def testAssertNotRaisesRegexp(self):
2644 self.assertRaisesRegexp(
2645 self.failureException, '^Exception not raised$',
2646 self.assertRaisesRegexp, Exception, re.compile('x'),
2647 lambda: None)
2648 self.assertRaisesRegexp(
2649 self.failureException, '^Exception not raised$',
2650 self.assertRaisesRegexp, Exception, 'x',
2651 lambda: None)
2652 self.assertRaisesRegexp(
2653 self.failureException, '^Exception not raised$',
2654 self.assertRaisesRegexp, Exception, u'x',
2655 lambda: None)
2656
2657 def testAssertRaisesRegexpMismatch(self):
2658 def Stub():
2659 raise Exception('Unexpected')
2660
2661 self.assertRaisesRegexp(
2662 self.failureException,
2663 r'"\^Expected\$" does not match "Unexpected"',
2664 self.assertRaisesRegexp, Exception, '^Expected$',
2665 Stub)
2666 self.assertRaisesRegexp(
2667 self.failureException,
2668 r'"\^Expected\$" does not match "Unexpected"',
2669 self.assertRaisesRegexp, Exception, u'^Expected$',
2670 Stub)
2671 self.assertRaisesRegexp(
2672 self.failureException,
2673 r'"\^Expected\$" does not match "Unexpected"',
2674 self.assertRaisesRegexp, Exception,
2675 re.compile('^Expected$'), Stub)
2676
Gregory P. Smith7558d572009-03-31 19:03:28 +00002677 def testSynonymAssertMethodNames(self):
2678 """Test undocumented method name synonyms.
2679
2680 Please do not use these methods names in your own code.
2681
2682 This test confirms their continued existence and functionality
2683 in order to avoid breaking existing code.
2684 """
2685 self.assertNotEquals(3, 5)
2686 self.assertEquals(3, 3)
2687 self.assertAlmostEquals(2.0, 2.0)
2688 self.assertNotAlmostEquals(3.0, 5.0)
2689 self.assert_(True)
2690
2691 def testPendingDeprecationMethodNames(self):
2692 """Test fail* methods pending deprecation, they will warn in 3.2.
2693
2694 Do not use these methods. They will go away in 3.3.
2695 """
2696 self.failIfEqual(3, 5)
2697 self.failUnlessEqual(3, 3)
2698 self.failUnlessAlmostEqual(2.0, 2.0)
2699 self.failIfAlmostEqual(3.0, 5.0)
2700 self.failUnless(True)
2701 self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam')
2702 self.failIf(False)
2703
Michael Foorde2942d02009-04-02 05:51:54 +00002704 def testDeepcopy(self):
2705 # Issue: 5660
2706 class TestableTest(TestCase):
2707 def testNothing(self):
2708 pass
2709
2710 test = TestableTest('testNothing')
2711
2712 # This shouldn't blow up
2713 deepcopy(test)
2714
Benjamin Peterson692428e2009-03-23 21:50:21 +00002715
2716class Test_TestSkipping(TestCase):
2717
2718 def test_skipping(self):
2719 class Foo(unittest.TestCase):
2720 def test_skip_me(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002721 self.skipTest("skip")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002722 events = []
2723 result = LoggingResult(events)
2724 test = Foo("test_skip_me")
2725 test.run(result)
2726 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2727 self.assertEqual(result.skipped, [(test, "skip")])
2728
2729 # Try letting setUp skip the test now.
2730 class Foo(unittest.TestCase):
2731 def setUp(self):
Benjamin Peterson47d97382009-03-26 20:05:50 +00002732 self.skipTest("testing")
Benjamin Peterson692428e2009-03-23 21:50:21 +00002733 def test_nothing(self): pass
2734 events = []
2735 result = LoggingResult(events)
2736 test = Foo("test_nothing")
2737 test.run(result)
2738 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
2739 self.assertEqual(result.skipped, [(test, "testing")])
2740 self.assertEqual(result.testsRun, 1)
2741
2742 def test_skipping_decorators(self):
2743 op_table = ((unittest.skipUnless, False, True),
2744 (unittest.skipIf, True, False))
2745 for deco, do_skip, dont_skip in op_table:
2746 class Foo(unittest.TestCase):
2747 @deco(do_skip, "testing")
2748 def test_skip(self): pass
2749
2750 @deco(dont_skip, "testing")
2751 def test_dont_skip(self): pass
2752 test_do_skip = Foo("test_skip")
2753 test_dont_skip = Foo("test_dont_skip")
2754 suite = unittest.ClassTestSuite([test_do_skip, test_dont_skip], Foo)
2755 events = []
2756 result = LoggingResult(events)
2757 suite.run(result)
2758 self.assertEqual(len(result.skipped), 1)
2759 expected = ['startTest', 'addSkip', 'stopTest',
2760 'startTest', 'addSuccess', 'stopTest']
2761 self.assertEqual(events, expected)
2762 self.assertEqual(result.testsRun, 2)
2763 self.assertEqual(result.skipped, [(test_do_skip, "testing")])
2764 self.assertTrue(result.wasSuccessful())
2765
2766 def test_skip_class(self):
2767 @unittest.skip("testing")
2768 class Foo(unittest.TestCase):
2769 def test_1(self):
2770 record.append(1)
2771 record = []
2772 result = unittest.TestResult()
2773 suite = unittest.ClassTestSuite([Foo("test_1")], Foo)
2774 suite.run(result)
2775 self.assertEqual(result.skipped, [(suite, "testing")])
2776 self.assertEqual(record, [])
2777
2778 def test_expected_failure(self):
2779 class Foo(unittest.TestCase):
2780 @unittest.expectedFailure
2781 def test_die(self):
2782 self.fail("help me!")
2783 events = []
2784 result = LoggingResult(events)
2785 test = Foo("test_die")
2786 test.run(result)
2787 self.assertEqual(events,
2788 ['startTest', 'addExpectedFailure', 'stopTest'])
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00002789 self.assertEqual(result.expectedFailures[0][0], test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00002790 self.assertTrue(result.wasSuccessful())
2791
2792 def test_unexpected_success(self):
2793 class Foo(unittest.TestCase):
2794 @unittest.expectedFailure
2795 def test_die(self):
2796 pass
2797 events = []
2798 result = LoggingResult(events)
2799 test = Foo("test_die")
2800 test.run(result)
2801 self.assertEqual(events,
2802 ['startTest', 'addUnexpectedSuccess', 'stopTest'])
2803 self.assertFalse(result.failures)
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00002804 self.assertEqual(result.unexpectedSuccesses, [test])
Benjamin Peterson692428e2009-03-23 21:50:21 +00002805 self.assertTrue(result.wasSuccessful())
2806
2807
2808
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002809class Test_Assertions(TestCase):
2810 def test_AlmostEqual(self):
2811 self.failUnlessAlmostEqual(1.00000001, 1.0)
2812 self.failIfAlmostEqual(1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00002813 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002814 self.failUnlessAlmostEqual, 1.0000001, 1.0)
Gregory P. Smith28399852009-03-31 16:54:10 +00002815 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002816 self.failIfAlmostEqual, 1.00000001, 1.0)
2817
2818 self.failUnlessAlmostEqual(1.1, 1.0, places=0)
Gregory P. Smith28399852009-03-31 16:54:10 +00002819 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002820 self.failUnlessAlmostEqual, 1.1, 1.0, places=1)
2821
2822 self.failUnlessAlmostEqual(0, .1+.1j, places=0)
2823 self.failIfAlmostEqual(0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00002824 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002825 self.failUnlessAlmostEqual, 0, .1+.1j, places=1)
Gregory P. Smith28399852009-03-31 16:54:10 +00002826 self.assertRaises(self.failureException,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002827 self.failIfAlmostEqual, 0, .1+.1j, places=0)
2828
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00002829 def test_assertRaises(self):
2830 def _raise(e):
2831 raise e
2832 self.assertRaises(KeyError, _raise, KeyError)
2833 self.assertRaises(KeyError, _raise, KeyError("key"))
2834 try:
2835 self.assertRaises(KeyError, lambda: None)
Gregory P. Smith28399852009-03-31 16:54:10 +00002836 except self.failureException as e:
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00002837 self.assert_("KeyError not raised" in e, str(e))
2838 else:
2839 self.fail("assertRaises() didn't fail")
2840 try:
2841 self.assertRaises(KeyError, _raise, ValueError)
2842 except ValueError:
2843 pass
2844 else:
2845 self.fail("assertRaises() didn't let exception pass through")
2846 with self.assertRaises(KeyError):
2847 raise KeyError
2848 with self.assertRaises(KeyError):
2849 raise KeyError("key")
2850 try:
2851 with self.assertRaises(KeyError):
2852 pass
Gregory P. Smith28399852009-03-31 16:54:10 +00002853 except self.failureException as e:
Antoine Pitrou697ca3d2008-12-28 14:09:36 +00002854 self.assert_("KeyError not raised" in e, str(e))
2855 else:
2856 self.fail("assertRaises() didn't fail")
2857 try:
2858 with self.assertRaises(KeyError):
2859 raise ValueError
2860 except ValueError:
2861 pass
2862 else:
2863 self.fail("assertRaises() didn't let exception pass through")
2864
2865
Michael Foord345b2fe2009-04-02 03:20:38 +00002866class TestLongMessage(TestCase):
2867 """Test that the individual asserts honour longMessage.
2868 This actually tests all the message behaviour for
2869 asserts that use longMessage."""
2870
2871 def setUp(self):
2872 class TestableTestFalse(TestCase):
2873 longMessage = False
2874 failureException = self.failureException
2875
2876 def testTest(self):
2877 pass
2878
2879 class TestableTestTrue(TestCase):
2880 longMessage = True
2881 failureException = self.failureException
2882
2883 def testTest(self):
2884 pass
2885
2886 self.testableTrue = TestableTestTrue('testTest')
2887 self.testableFalse = TestableTestFalse('testTest')
2888
2889 def testDefault(self):
2890 self.assertFalse(TestCase.longMessage)
2891
2892 def test_formatMsg(self):
2893 self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
2894 self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
2895
2896 self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
2897 self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
2898
2899 def assertMessages(self, methodName, args, errors):
2900 def getMethod(i):
2901 useTestableFalse = i < 2
2902 if useTestableFalse:
2903 test = self.testableFalse
2904 else:
2905 test = self.testableTrue
2906 return getattr(test, methodName)
2907
2908 for i, expected_regexp in enumerate(errors):
2909 testMethod = getMethod(i)
2910 kwargs = {}
2911 withMsg = i % 2
2912 if withMsg:
2913 kwargs = {"msg": "oops"}
2914
2915 with self.assertRaisesRegexp(self.failureException,
2916 expected_regexp=expected_regexp):
2917 testMethod(*args, **kwargs)
2918
2919 def testAssertTrue(self):
2920 self.assertMessages('assertTrue', (False,),
2921 ["^False is not True$", "^oops$", "^False is not True$",
2922 "^False is not True : oops$"])
2923
2924 def testAssertFalse(self):
2925 self.assertMessages('assertFalse', (True,),
2926 ["^True is not False$", "^oops$", "^True is not False$",
2927 "^True is not False : oops$"])
2928
2929 def testNotEqual(self):
2930 self.assertMessages('assertNotEqual', (1, 1),
2931 ["^1 == 1$", "^oops$", "^1 == 1$",
2932 "^1 == 1 : oops$"])
2933
2934 def testAlmostEqual(self):
2935 self.assertMessages('assertAlmostEqual', (1, 2),
2936 ["^1 != 2 within 7 places$", "^oops$",
2937 "^1 != 2 within 7 places$", "^1 != 2 within 7 places : oops$"])
2938
2939 def testNotAlmostEqual(self):
2940 self.assertMessages('assertNotAlmostEqual', (1, 1),
2941 ["^1 == 1 within 7 places$", "^oops$",
2942 "^1 == 1 within 7 places$", "^1 == 1 within 7 places : oops$"])
2943
2944 def test_baseAssertEqual(self):
2945 self.assertMessages('_baseAssertEqual', (1, 2),
2946 ["^1 != 2$", "^oops$", "^1 != 2$", "^1 != 2 : oops$"])
2947
2948 def testAssertSequenceEqual(self):
2949 # Error messages are multiline so not testing on full message
2950 # assertTupleEqual and assertListEqual delegate to this method
2951 self.assertMessages('assertSequenceEqual', ([], [None]),
2952 ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
2953 r"\+ \[None\] : oops$"])
2954
2955 def testAssertSetEqual(self):
2956 self.assertMessages('assertSetEqual', (set(), set([None])),
2957 ["None$", "^oops$", "None$",
2958 "None : oops$"])
2959
2960 def testAssertIn(self):
2961 self.assertMessages('assertIn', (None, []),
2962 ['^None not found in \[\]$', "^oops$",
2963 '^None not found in \[\]$',
2964 '^None not found in \[\] : oops$'])
2965
2966 def testAssertNotIn(self):
2967 self.assertMessages('assertNotIn', (None, [None]),
2968 ['^None unexpectedly found in \[None\]$', "^oops$",
2969 '^None unexpectedly found in \[None\]$',
2970 '^None unexpectedly found in \[None\] : oops$'])
2971
2972 def testAssertDictEqual(self):
2973 self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
2974 [r"\+ \{'key': 'value'\}$", "^oops$",
2975 "\+ \{'key': 'value'\}$",
2976 "\+ \{'key': 'value'\} : oops$"])
2977
2978 def testAssertDictContainsSubset(self):
2979 self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
2980 ["^Missing: 'key'$", "^oops$",
2981 "^Missing: 'key'$",
2982 "^Missing: 'key' : oops$"])
2983
2984 def testAssertSameElements(self):
2985 self.assertMessages('assertSameElements', ([], [None]),
2986 [r"\[None\]$", "^oops$",
2987 r"\[None\]$",
2988 r"\[None\] : oops$"])
2989
2990 def testAssertMultiLineEqual(self):
2991 self.assertMessages('assertMultiLineEqual', ("", "foo"),
2992 [r"\+ foo$", "^oops$",
2993 r"\+ foo$",
2994 r"\+ foo : oops$"])
2995
2996 def testAssertLess(self):
2997 self.assertMessages('assertLess', (2, 1),
2998 ["^2 not less than 1$", "^oops$",
2999 "^2 not less than 1$", "^2 not less than 1 : oops$"])
3000
3001 def testAssertLessEqual(self):
3002 self.assertMessages('assertLessEqual', (2, 1),
3003 ["^2 not less than or equal to 1$", "^oops$",
3004 "^2 not less than or equal to 1$",
3005 "^2 not less than or equal to 1 : oops$"])
3006
3007 def testAssertGreater(self):
3008 self.assertMessages('assertGreater', (1, 2),
3009 ["^1 not greater than 2$", "^oops$",
3010 "^1 not greater than 2$",
3011 "^1 not greater than 2 : oops$"])
3012
3013 def testAssertGreaterEqual(self):
3014 self.assertMessages('assertGreaterEqual', (1, 2),
3015 ["^1 not greater than or equal to 2$", "^oops$",
3016 "^1 not greater than or equal to 2$",
3017 "^1 not greater than or equal to 2 : oops$"])
3018
3019 def testAssertIsNone(self):
3020 self.assertMessages('assertIsNone', ('not None',),
3021 ["^'not None' is not None$", "^oops$",
3022 "^'not None' is not None$",
3023 "^'not None' is not None : oops$"])
3024
3025 def testAssertIsNotNone(self):
3026 self.assertMessages('assertIsNotNone', (None,),
3027 ["^unexpectedly None$", "^oops$",
3028 "^unexpectedly None$",
3029 "^unexpectedly None : oops$"])
3030
Michael Foordf2dfef12009-04-05 19:19:28 +00003031 def testAssertIs(self):
3032 self.assertMessages('assertIs', (None, 'foo'),
3033 ["^None is not 'foo'$", "^oops$",
3034 "^None is not 'foo'$",
3035 "^None is not 'foo' : oops$"])
3036
3037 def testAssertIsNot(self):
3038 self.assertMessages('assertIsNot', (None, None),
3039 ["^unexpectedly identical: None$", "^oops$",
3040 "^unexpectedly identical: None$",
3041 "^unexpectedly identical: None : oops$"])
3042
Michael Foord345b2fe2009-04-02 03:20:38 +00003043
Michael Foord829f6b82009-05-02 11:43:06 +00003044class Test_TestProgram(TestCase):
3045
3046 # Horrible white box test
3047 def testNoExit(self):
3048 result = object()
3049 test = object()
3050
3051 class FakeRunner(object):
3052 def run(self, test):
3053 self.test = test
3054 return result
3055
3056 runner = FakeRunner()
3057
3058 try:
3059 oldParseArgs = TestProgram.parseArgs
3060 TestProgram.parseArgs = lambda *args: None
3061 TestProgram.test = test
3062
3063 program = TestProgram(testRunner=runner, exit=False)
3064
3065 self.assertEqual(program.result, result)
3066 self.assertEqual(runner.test, test)
3067
3068 finally:
3069 TestProgram.parseArgs = oldParseArgs
3070 del TestProgram.test
3071
3072
3073 class FooBar(unittest.TestCase):
3074 def testPass(self):
3075 assert True
3076 def testFail(self):
3077 assert False
3078
3079 class FooBarLoader(unittest.TestLoader):
3080 """Test loader that returns a suite containing FooBar."""
3081 def loadTestsFromModule(self, module):
3082 return self.suiteClass(
3083 [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])
3084
3085
3086 def test_NonExit(self):
3087 program = unittest.main(exit=False,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003088 argv=["foobar"],
3089 testRunner=unittest.TextTestRunner(stream=StringIO()),
3090 testLoader=self.FooBarLoader())
Michael Foord829f6b82009-05-02 11:43:06 +00003091 self.assertTrue(hasattr(program, 'result'))
3092
3093
3094 def test_Exit(self):
3095 self.assertRaises(
3096 SystemExit,
3097 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003098 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003099 testRunner=unittest.TextTestRunner(stream=StringIO()),
3100 exit=True,
3101 testLoader=self.FooBarLoader())
3102
3103
3104 def test_ExitAsDefault(self):
3105 self.assertRaises(
3106 SystemExit,
3107 unittest.main,
Benjamin Petersond7e8e342009-05-02 16:24:37 +00003108 argv=["foobar"],
Michael Foord829f6b82009-05-02 11:43:06 +00003109 testRunner=unittest.TextTestRunner(stream=StringIO()),
3110 testLoader=self.FooBarLoader())
3111
3112
3113
Jim Fultonfafd8742004-08-28 15:22:12 +00003114######################################################################
3115## Main
3116######################################################################
3117
3118def test_main():
Georg Brandl15c5ce92007-03-07 09:09:40 +00003119 test_support.run_unittest(Test_TestCase, Test_TestLoader,
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003120 Test_TestSuite, Test_TestResult, Test_FunctionTestCase,
Michael Foord829f6b82009-05-02 11:43:06 +00003121 Test_TestSkipping, Test_Assertions, TestLongMessage,
3122 Test_TestProgram)
Jim Fultonfafd8742004-08-28 15:22:12 +00003123
Georg Brandl15c5ce92007-03-07 09:09:40 +00003124if __name__ == "__main__":
Tim Petersea5962f2007-03-12 18:07:52 +00003125 test_main()