~justin-fathomdb/nova/justinsb-openstack-api-volumes

« back to all changes in this revision

Viewing changes to vendor/Twisted-10.0.0/twisted/trial/test/test_assertions.py

  • Committer: Jesse Andrews
  • Date: 2010-05-28 06:05:26 UTC
  • Revision ID: git-v1:bf6e6e718cdc7488e2da87b21e258ccc065fe499
initial commit

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (c) 2001-2010 Twisted Matrix Laboratories.
 
2
# See LICENSE for details
 
3
 
 
4
"""
 
5
Tests for assertions provided by L{twisted.trial.unittest.TestCase}.
 
6
"""
 
7
 
 
8
import warnings, StringIO
 
9
from pprint import pformat
 
10
 
 
11
from twisted.python import reflect, failure
 
12
from twisted.python.deprecate import deprecated, getVersionString
 
13
from twisted.python.versions import Version
 
14
from twisted.python.util import dsu
 
15
from twisted.internet import defer
 
16
from twisted.trial import unittest, runner, reporter
 
17
 
 
18
class MockEquality(object):
 
19
    def __init__(self, name):
 
20
        self.name = name
 
21
 
 
22
    def __repr__(self):
 
23
        return "MockEquality(%s)" % (self.name,)
 
24
 
 
25
    def __eq__(self, other):
 
26
        if not hasattr(other, 'name'):
 
27
            raise ValueError("%r not comparable to %r" % (other, self))
 
28
        return self.name[0] == other.name[0]
 
29
 
 
30
 
 
31
class TestAssertions(unittest.TestCase):
 
32
    """
 
33
    Tests for TestCase's assertion methods.  That is, failUnless*,
 
34
    failIf*, assert*.
 
35
 
 
36
    This is pretty paranoid.  Still, a certain paranoia is healthy if you
 
37
    are testing a unit testing framework.
 
38
    """
 
39
 
 
40
    class FailingTest(unittest.TestCase):
 
41
        def test_fails(self):
 
42
            raise self.failureException()
 
43
 
 
44
    def testFail(self):
 
45
        try:
 
46
            self.fail("failed")
 
47
        except self.failureException, e:
 
48
            if not str(e) == 'failed':
 
49
                raise self.failureException("Exception had msg %s instead of %s"
 
50
                                            % str(e), 'failed')
 
51
        else:
 
52
            raise self.failureException("Call to self.fail() didn't fail test")
 
53
 
 
54
    def test_failingException_fails(self):
 
55
        test = runner.TestLoader().loadClass(TestAssertions.FailingTest)
 
56
        io = StringIO.StringIO()
 
57
        result = reporter.TestResult()
 
58
        test.run(result)
 
59
        self.failIf(result.wasSuccessful())
 
60
        self.failUnlessEqual(result.errors, [])
 
61
        self.failUnlessEqual(len(result.failures), 1)
 
62
 
 
63
    def test_failIf(self):
 
64
        for notTrue in [0, 0.0, False, None, (), []]:
 
65
            self.failIf(notTrue, "failed on %r" % (notTrue,))
 
66
        for true in [1, True, 'cat', [1,2], (3,4)]:
 
67
            try:
 
68
                self.failIf(true, "failed on %r" % (true,))
 
69
            except self.failureException, e:
 
70
                self.failUnlessEqual(str(e), "failed on %r" % (true,))
 
71
            else:
 
72
                self.fail("Call to failIf(%r) didn't fail" % (true,))
 
73
 
 
74
    def test_failUnless(self):
 
75
        for notTrue in [0, 0.0, False, None, (), []]:
 
76
            try:
 
77
                self.failUnless(notTrue, "failed on %r" % (notTrue,))
 
78
            except self.failureException, e:
 
79
                self.failUnlessEqual(str(e), "failed on %r" % (notTrue,))
 
80
            else:
 
81
                self.fail("Call to failUnless(%r) didn't fail" % (notTrue,))
 
82
        for true in [1, True, 'cat', [1,2], (3,4)]:
 
83
            self.failUnless(true, "failed on %r" % (true,))
 
84
 
 
85
    def _testEqualPair(self, first, second):
 
86
        x = self.failUnlessEqual(first, second)
 
87
        if x != first:
 
88
            self.fail("failUnlessEqual should return first parameter")
 
89
 
 
90
    def _testUnequalPair(self, first, second):
 
91
        try:
 
92
            self.failUnlessEqual(first, second)
 
93
        except self.failureException, e:
 
94
            expected = 'not equal:\na = %s\nb = %s\n' % (
 
95
                pformat(first), pformat(second))
 
96
            if str(e) != expected:
 
97
                self.fail("Expected: %r; Got: %s" % (expected, str(e)))
 
98
        else:
 
99
            self.fail("Call to failUnlessEqual(%r, %r) didn't fail"
 
100
                      % (first, second))
 
101
 
 
102
    def test_failUnlessEqual_basic(self):
 
103
        self._testEqualPair('cat', 'cat')
 
104
        self._testUnequalPair('cat', 'dog')
 
105
        self._testEqualPair([1], [1])
 
106
        self._testUnequalPair([1], 'orange')
 
107
 
 
108
    def test_failUnlessEqual_custom(self):
 
109
        x = MockEquality('first')
 
110
        y = MockEquality('second')
 
111
        z = MockEquality('fecund')
 
112
        self._testEqualPair(x, x)
 
113
        self._testEqualPair(x, z)
 
114
        self._testUnequalPair(x, y)
 
115
        self._testUnequalPair(y, z)
 
116
 
 
117
    def test_failUnlessEqualMessage(self):
 
118
        """
 
119
        When a message is passed to L{assertEqual}, it is included in the
 
120
        error message.
 
121
        """
 
122
        exception = self.assertRaises(
 
123
            self.failureException, self.assertEqual,
 
124
            'foo', 'bar', 'message')
 
125
        self.assertEqual(
 
126
            str(exception),
 
127
            "message\nnot equal:\na = 'foo'\nb = 'bar'\n")
 
128
 
 
129
 
 
130
    def test_failUnlessEqualNoneMessage(self):
 
131
        """
 
132
        If a message is specified as C{None}, it is not included in the error
 
133
        message of L{assertEqual}.
 
134
        """
 
135
        exception = self.assertRaises(
 
136
            self.failureException, self.assertEqual, 'foo', 'bar', None)
 
137
        self.assertEqual(str(exception), "not equal:\na = 'foo'\nb = 'bar'\n")
 
138
 
 
139
 
 
140
    def test_failUnlessEqual_incomparable(self):
 
141
        apple = MockEquality('apple')
 
142
        orange = ['orange']
 
143
        try:
 
144
            self.failUnlessEqual(apple, orange)
 
145
        except self.failureException:
 
146
            self.fail("Fail raised when ValueError ought to have been raised.")
 
147
        except ValueError:
 
148
            # good. error not swallowed
 
149
            pass
 
150
        else:
 
151
            self.fail("Comparing %r and %r should have raised an exception"
 
152
                      % (apple, orange))
 
153
 
 
154
    def _raiseError(self, error):
 
155
        raise error
 
156
 
 
157
    def test_failUnlessRaises_expected(self):
 
158
        x = self.failUnlessRaises(ValueError, self._raiseError, ValueError)
 
159
        self.failUnless(isinstance(x, ValueError),
 
160
                        "Expect failUnlessRaises to return instance of raised "
 
161
                        "exception.")
 
162
 
 
163
    def test_failUnlessRaises_unexpected(self):
 
164
        try:
 
165
            self.failUnlessRaises(ValueError, self._raiseError, TypeError)
 
166
        except TypeError:
 
167
            self.fail("failUnlessRaises shouldn't re-raise unexpected "
 
168
                      "exceptions")
 
169
        except self.failureException, e:
 
170
            # what we expect
 
171
            pass
 
172
        else:
 
173
            self.fail("Expected exception wasn't raised. Should have failed")
 
174
 
 
175
    def test_failUnlessRaises_noException(self):
 
176
        try:
 
177
            self.failUnlessRaises(ValueError, lambda : None)
 
178
        except self.failureException, e:
 
179
            self.failUnlessEqual(str(e),
 
180
                                 'ValueError not raised (None returned)')
 
181
        else:
 
182
            self.fail("Exception not raised. Should have failed")
 
183
 
 
184
    def test_failUnlessRaises_failureException(self):
 
185
        x = self.failUnlessRaises(self.failureException, self._raiseError,
 
186
                                  self.failureException)
 
187
        self.failUnless(isinstance(x, self.failureException),
 
188
                        "Expected %r instance to be returned"
 
189
                        % (self.failureException,))
 
190
        try:
 
191
            x = self.failUnlessRaises(self.failureException, self._raiseError,
 
192
                                      ValueError)
 
193
        except self.failureException, e:
 
194
            # what we expect
 
195
            pass
 
196
        else:
 
197
            self.fail("Should have raised exception")
 
198
 
 
199
    def test_failIfEqual_basic(self):
 
200
        x, y, z = [1], [2], [1]
 
201
        ret = self.failIfEqual(x, y)
 
202
        self.failUnlessEqual(ret, x,
 
203
                             "failIfEqual should return first parameter")
 
204
        self.failUnlessRaises(self.failureException,
 
205
                              self.failIfEqual, x, x)
 
206
        self.failUnlessRaises(self.failureException,
 
207
                              self.failIfEqual, x, z)
 
208
 
 
209
    def test_failIfEqual_customEq(self):
 
210
        x = MockEquality('first')
 
211
        y = MockEquality('second')
 
212
        z = MockEquality('fecund')
 
213
        ret = self.failIfEqual(x, y)
 
214
        self.failUnlessEqual(ret, x,
 
215
                             "failIfEqual should return first parameter")
 
216
        self.failUnlessRaises(self.failureException,
 
217
                              self.failIfEqual, x, x)
 
218
        # test when __ne__ is not defined
 
219
        self.failIfEqual(x, z, "__ne__ not defined, so not equal")
 
220
 
 
221
    def test_failUnlessIdentical(self):
 
222
        x, y, z = [1], [1], [2]
 
223
        ret = self.failUnlessIdentical(x, x)
 
224
        self.failUnlessEqual(ret, x,
 
225
                             'failUnlessIdentical should return first '
 
226
                             'parameter')
 
227
        self.failUnlessRaises(self.failureException,
 
228
                              self.failUnlessIdentical, x, y)
 
229
        self.failUnlessRaises(self.failureException,
 
230
                              self.failUnlessIdentical, x, z)
 
231
 
 
232
    def test_failUnlessApproximates(self):
 
233
        x, y, z = 1.0, 1.1, 1.2
 
234
        self.failUnlessApproximates(x, x, 0.2)
 
235
        ret = self.failUnlessApproximates(x, y, 0.2)
 
236
        self.failUnlessEqual(ret, x, "failUnlessApproximates should return "
 
237
                             "first parameter")
 
238
        self.failUnlessRaises(self.failureException,
 
239
                              self.failUnlessApproximates, x, z, 0.1)
 
240
        self.failUnlessRaises(self.failureException,
 
241
                              self.failUnlessApproximates, x, y, 0.1)
 
242
 
 
243
    def test_failUnlessAlmostEqual(self):
 
244
        precision = 5
 
245
        x = 8.000001
 
246
        y = 8.00001
 
247
        z = 8.000002
 
248
        self.failUnlessAlmostEqual(x, x, precision)
 
249
        ret = self.failUnlessAlmostEqual(x, z, precision)
 
250
        self.failUnlessEqual(ret, x, "failUnlessAlmostEqual should return "
 
251
                             "first parameter (%r, %r)" % (ret, x))
 
252
        self.failUnlessRaises(self.failureException,
 
253
                              self.failUnlessAlmostEqual, x, y, precision)
 
254
 
 
255
    def test_failIfAlmostEqual(self):
 
256
        precision = 5
 
257
        x = 8.000001
 
258
        y = 8.00001
 
259
        z = 8.000002
 
260
        ret = self.failIfAlmostEqual(x, y, precision)
 
261
        self.failUnlessEqual(ret, x, "failIfAlmostEqual should return "
 
262
                             "first parameter (%r, %r)" % (ret, x))
 
263
        self.failUnlessRaises(self.failureException,
 
264
                              self.failIfAlmostEqual, x, x, precision)
 
265
        self.failUnlessRaises(self.failureException,
 
266
                              self.failIfAlmostEqual, x, z, precision)
 
267
 
 
268
    def test_failUnlessSubstring(self):
 
269
        x = "cat"
 
270
        y = "the dog sat"
 
271
        z = "the cat sat"
 
272
        self.failUnlessSubstring(x, x)
 
273
        ret = self.failUnlessSubstring(x, z)
 
274
        self.failUnlessEqual(ret, x, 'should return first parameter')
 
275
        self.failUnlessRaises(self.failureException,
 
276
                              self.failUnlessSubstring, x, y)
 
277
        self.failUnlessRaises(self.failureException,
 
278
                              self.failUnlessSubstring, z, x)
 
279
 
 
280
    def test_failIfSubstring(self):
 
281
        x = "cat"
 
282
        y = "the dog sat"
 
283
        z = "the cat sat"
 
284
        self.failIfSubstring(z, x)
 
285
        ret = self.failIfSubstring(x, y)
 
286
        self.failUnlessEqual(ret, x, 'should return first parameter')
 
287
        self.failUnlessRaises(self.failureException,
 
288
                              self.failIfSubstring, x, x)
 
289
        self.failUnlessRaises(self.failureException,
 
290
                              self.failIfSubstring, x, z)
 
291
 
 
292
    def test_assertFailure(self):
 
293
        d = defer.maybeDeferred(lambda: 1/0)
 
294
        return self.assertFailure(d, ZeroDivisionError)
 
295
 
 
296
    def test_assertFailure_wrongException(self):
 
297
        d = defer.maybeDeferred(lambda: 1/0)
 
298
        self.assertFailure(d, OverflowError)
 
299
        d.addCallbacks(lambda x: self.fail('Should have failed'),
 
300
                       lambda x: x.trap(self.failureException))
 
301
        return d
 
302
 
 
303
    def test_assertFailure_noException(self):
 
304
        d = defer.succeed(None)
 
305
        self.assertFailure(d, ZeroDivisionError)
 
306
        d.addCallbacks(lambda x: self.fail('Should have failed'),
 
307
                       lambda x: x.trap(self.failureException))
 
308
        return d
 
309
 
 
310
    def test_assertFailure_moreInfo(self):
 
311
        """
 
312
        In the case of assertFailure failing, check that we get lots of
 
313
        information about the exception that was raised.
 
314
        """
 
315
        try:
 
316
            1/0
 
317
        except ZeroDivisionError:
 
318
            f = failure.Failure()
 
319
            d = defer.fail(f)
 
320
        d = self.assertFailure(d, RuntimeError)
 
321
        d.addErrback(self._checkInfo, f)
 
322
        return d
 
323
 
 
324
    def _checkInfo(self, assertionFailure, f):
 
325
        assert assertionFailure.check(self.failureException)
 
326
        output = assertionFailure.getErrorMessage()
 
327
        self.assertIn(f.getErrorMessage(), output)
 
328
        self.assertIn(f.getBriefTraceback(), output)
 
329
 
 
330
    def test_assertFailure_masked(self):
 
331
        """
 
332
        A single wrong assertFailure should fail the whole test.
 
333
        """
 
334
        class ExampleFailure(Exception):
 
335
            pass
 
336
 
 
337
        class TC(unittest.TestCase):
 
338
            failureException = ExampleFailure
 
339
            def test_assertFailure(self):
 
340
                d = defer.maybeDeferred(lambda: 1/0)
 
341
                self.assertFailure(d, OverflowError)
 
342
                self.assertFailure(d, ZeroDivisionError)
 
343
                return d
 
344
 
 
345
        test = TC('test_assertFailure')
 
346
        result = reporter.TestResult()
 
347
        test.run(result)
 
348
        self.assertEqual(1, len(result.failures))
 
349
 
 
350
 
 
351
    def test_assertWarns(self):
 
352
        """
 
353
        Test basic assertWarns report.
 
354
        """
 
355
        def deprecated(a):
 
356
            warnings.warn("Woo deprecated", category=DeprecationWarning)
 
357
            return a
 
358
        r = self.assertWarns(DeprecationWarning, "Woo deprecated", __file__,
 
359
            deprecated, 123)
 
360
        self.assertEquals(r, 123)
 
361
 
 
362
 
 
363
    def test_assertWarnsRegistryClean(self):
 
364
        """
 
365
        Test that assertWarns cleans the warning registry, so the warning is
 
366
        not swallowed the second time.
 
367
        """
 
368
        def deprecated(a):
 
369
            warnings.warn("Woo deprecated", category=DeprecationWarning)
 
370
            return a
 
371
        r1 = self.assertWarns(DeprecationWarning, "Woo deprecated", __file__,
 
372
            deprecated, 123)
 
373
        self.assertEquals(r1, 123)
 
374
        # The warning should be raised again
 
375
        r2 = self.assertWarns(DeprecationWarning, "Woo deprecated", __file__,
 
376
            deprecated, 321)
 
377
        self.assertEquals(r2, 321)
 
378
 
 
379
 
 
380
    def test_assertWarnsError(self):
 
381
        """
 
382
        Test assertWarns failure when no warning is generated.
 
383
        """
 
384
        def normal(a):
 
385
            return a
 
386
        self.assertRaises(self.failureException,
 
387
            self.assertWarns, DeprecationWarning, "Woo deprecated", __file__,
 
388
            normal, 123)
 
389
 
 
390
 
 
391
    def test_assertWarnsWrongCategory(self):
 
392
        """
 
393
        Test assertWarns failure when the category is wrong.
 
394
        """
 
395
        def deprecated(a):
 
396
            warnings.warn("Foo deprecated", category=DeprecationWarning)
 
397
            return a
 
398
        self.assertRaises(self.failureException,
 
399
            self.assertWarns, UserWarning, "Foo deprecated", __file__,
 
400
            deprecated, 123)
 
401
 
 
402
 
 
403
    def test_assertWarnsWrongMessage(self):
 
404
        """
 
405
        Test assertWarns failure when the message is wrong.
 
406
        """
 
407
        def deprecated(a):
 
408
            warnings.warn("Foo deprecated", category=DeprecationWarning)
 
409
            return a
 
410
        self.assertRaises(self.failureException,
 
411
            self.assertWarns, DeprecationWarning, "Bar deprecated", __file__,
 
412
            deprecated, 123)
 
413
 
 
414
 
 
415
    def test_assertWarnsWrongFile(self):
 
416
        """
 
417
        If the warning emitted by a function refers to a different file than is
 
418
        passed to C{assertWarns}, C{failureException} is raised.
 
419
        """
 
420
        def deprecated(a):
 
421
            # stacklevel=2 points at the direct caller of the function.  The
 
422
            # way assertRaises is invoked below, the direct caller will be
 
423
            # something somewhere in trial, not something in this file.  In
 
424
            # Python 2.5 and earlier, stacklevel of 0 resulted in a warning
 
425
            # pointing to the warnings module itself.  Starting in Python 2.6,
 
426
            # stacklevel of 0 and 1 both result in a warning pointing to *this*
 
427
            # file, presumably due to the fact that the warn function is
 
428
            # implemented in C and has no convenient Python
 
429
            # filename/linenumber.
 
430
            warnings.warn(
 
431
                "Foo deprecated", category=DeprecationWarning, stacklevel=2)
 
432
        self.assertRaises(
 
433
            self.failureException,
 
434
            # Since the direct caller isn't in this file, try to assert that
 
435
            # the warning *does* point to this file, so that assertWarns raises
 
436
            # an exception.
 
437
            self.assertWarns, DeprecationWarning, "Foo deprecated", __file__,
 
438
            deprecated, 123)
 
439
 
 
440
    def test_assertWarnsOnClass(self):
 
441
        """
 
442
        Test assertWarns works when creating a class instance.
 
443
        """
 
444
        class Warn:
 
445
            def __init__(self):
 
446
                warnings.warn("Do not call me", category=RuntimeWarning)
 
447
        r = self.assertWarns(RuntimeWarning, "Do not call me", __file__,
 
448
            Warn)
 
449
        self.assertTrue(isinstance(r, Warn))
 
450
        r = self.assertWarns(RuntimeWarning, "Do not call me", __file__,
 
451
            Warn)
 
452
        self.assertTrue(isinstance(r, Warn))
 
453
 
 
454
 
 
455
    def test_assertWarnsOnMethod(self):
 
456
        """
 
457
        Test assertWarns works when used on an instance method.
 
458
        """
 
459
        class Warn:
 
460
            def deprecated(self, a):
 
461
                warnings.warn("Bar deprecated", category=DeprecationWarning)
 
462
                return a
 
463
        w = Warn()
 
464
        r = self.assertWarns(DeprecationWarning, "Bar deprecated", __file__,
 
465
            w.deprecated, 321)
 
466
        self.assertEquals(r, 321)
 
467
        r = self.assertWarns(DeprecationWarning, "Bar deprecated", __file__,
 
468
            w.deprecated, 321)
 
469
        self.assertEquals(r, 321)
 
470
 
 
471
 
 
472
    def test_assertWarnsOnCall(self):
 
473
        """
 
474
        Test assertWarns works on instance with C{__call__} method.
 
475
        """
 
476
        class Warn:
 
477
            def __call__(self, a):
 
478
                warnings.warn("Egg deprecated", category=DeprecationWarning)
 
479
                return a
 
480
        w = Warn()
 
481
        r = self.assertWarns(DeprecationWarning, "Egg deprecated", __file__,
 
482
            w, 321)
 
483
        self.assertEquals(r, 321)
 
484
        r = self.assertWarns(DeprecationWarning, "Egg deprecated", __file__,
 
485
            w, 321)
 
486
        self.assertEquals(r, 321)
 
487
 
 
488
 
 
489
    def test_assertWarnsFilter(self):
 
490
        """
 
491
        Test assertWarns on a warning filterd by default.
 
492
        """
 
493
        def deprecated(a):
 
494
            warnings.warn("Woo deprecated", category=PendingDeprecationWarning)
 
495
            return a
 
496
        r = self.assertWarns(PendingDeprecationWarning, "Woo deprecated",
 
497
            __file__, deprecated, 123)
 
498
        self.assertEquals(r, 123)
 
499
 
 
500
 
 
501
    def test_assertWarnsMultipleWarnings(self):
 
502
        """
 
503
        C{assertWarns} does not raise an exception if the function it is passed
 
504
        triggers the same warning more than once.
 
505
        """
 
506
        def deprecated():
 
507
            warnings.warn("Woo deprecated", category=PendingDeprecationWarning)
 
508
        def f():
 
509
            deprecated()
 
510
            deprecated()
 
511
        self.assertWarns(
 
512
            PendingDeprecationWarning, "Woo deprecated", __file__, f)
 
513
 
 
514
 
 
515
    def test_assertWarnsDifferentWarnings(self):
 
516
        """
 
517
        For now, assertWarns is unable to handle multiple different warnings,
 
518
        so it should raise an exception if it's the case.
 
519
        """
 
520
        def deprecated(a):
 
521
            warnings.warn("Woo deprecated", category=DeprecationWarning)
 
522
            warnings.warn("Another one", category=PendingDeprecationWarning)
 
523
        e = self.assertRaises(self.failureException,
 
524
                self.assertWarns, DeprecationWarning, "Woo deprecated",
 
525
                __file__, deprecated, 123)
 
526
        self.assertEquals(str(e), "Can't handle different warnings")
 
527
 
 
528
 
 
529
    def test_assertWarnsAfterUnassertedWarning(self):
 
530
        """
 
531
        Warnings emitted before L{TestCase.assertWarns} is called do not get
 
532
        flushed and do not alter the behavior of L{TestCase.assertWarns}.
 
533
        """
 
534
        class TheWarning(Warning):
 
535
            pass
 
536
 
 
537
        def f(message):
 
538
            warnings.warn(message, category=TheWarning)
 
539
        f("foo")
 
540
        self.assertWarns(TheWarning, "bar", __file__, f, "bar")
 
541
        [warning] = self.flushWarnings([f])
 
542
        self.assertEqual(warning['message'], "foo")
 
543
 
 
544
 
 
545
    def test_assertIsInstance(self):
 
546
        """
 
547
        Test a true condition of assertIsInstance.
 
548
        """
 
549
        A = type('A', (object,), {})
 
550
        a = A()
 
551
        self.assertIsInstance(a, A)
 
552
 
 
553
    def test_assertIsInstanceMultipleClasses(self):
 
554
        """
 
555
        Test a true condition of assertIsInstance with multiple classes.
 
556
        """
 
557
        A = type('A', (object,), {})
 
558
        B = type('B', (object,), {})
 
559
        a = A()
 
560
        self.assertIsInstance(a, (A, B))
 
561
 
 
562
    def test_assertIsInstanceError(self):
 
563
        """
 
564
        Test an error with assertIsInstance.
 
565
        """
 
566
        A = type('A', (object,), {})
 
567
        B = type('B', (object,), {})
 
568
        a = A()
 
569
        self.assertRaises(self.failureException, self.assertIsInstance, a, B)
 
570
 
 
571
    def test_assertIsInstanceErrorMultipleClasses(self):
 
572
        """
 
573
        Test an error with assertIsInstance and multiple classes.
 
574
        """
 
575
        A = type('A', (object,), {})
 
576
        B = type('B', (object,), {})
 
577
        C = type('C', (object,), {})
 
578
        a = A()
 
579
        self.assertRaises(self.failureException, self.assertIsInstance, a, (B, C))
 
580
 
 
581
    def test_assertNotIsInstance(self):
 
582
        """
 
583
        Test a true condition of assertNotIsInstance.
 
584
        """
 
585
        A = type('A', (object,), {})
 
586
        B = type('B', (object,), {})
 
587
        a = A()
 
588
        self.assertNotIsInstance(a, B)
 
589
 
 
590
    def test_assertNotIsInstanceMultipleClasses(self):
 
591
        """
 
592
        Test a true condition of assertNotIsInstance and multiple classes.
 
593
        """
 
594
        A = type('A', (object,), {})
 
595
        B = type('B', (object,), {})
 
596
        C = type('C', (object,), {})
 
597
        a = A()
 
598
        self.assertNotIsInstance(a, (B, C))
 
599
 
 
600
    def test_assertNotIsInstanceError(self):
 
601
        """
 
602
        Test an error with assertNotIsInstance.
 
603
        """
 
604
        A = type('A', (object,), {})
 
605
        a = A()
 
606
        error = self.assertRaises(self.failureException,
 
607
                                  self.assertNotIsInstance, a, A)
 
608
        self.assertEquals(str(error), "%r is an instance of %s" % (a, A))
 
609
 
 
610
    def test_assertNotIsInstanceErrorMultipleClasses(self):
 
611
        """
 
612
        Test an error with assertNotIsInstance and multiple classes.
 
613
        """
 
614
        A = type('A', (object,), {})
 
615
        B = type('B', (object,), {})
 
616
        a = A()
 
617
        self.assertRaises(self.failureException, self.assertNotIsInstance, a, (A, B))
 
618
 
 
619
 
 
620
 
 
621
class TestAssertionNames(unittest.TestCase):
 
622
    """
 
623
    Tests for consistency of naming within TestCase assertion methods
 
624
    """
 
625
    def _getAsserts(self):
 
626
        dct = {}
 
627
        reflect.accumulateMethods(self, dct, 'assert')
 
628
        return [ dct[k] for k in dct if not k.startswith('Not') and k != '_' ]
 
629
 
 
630
    def _name(self, x):
 
631
        return x.__name__
 
632
 
 
633
    def test_failUnless_matches_assert(self):
 
634
        asserts = self._getAsserts()
 
635
        failUnlesses = reflect.prefixedMethods(self, 'failUnless')
 
636
        self.failUnlessEqual(dsu(asserts, self._name),
 
637
                             dsu(failUnlesses, self._name))
 
638
 
 
639
    def test_failIf_matches_assertNot(self):
 
640
        asserts = reflect.prefixedMethods(unittest.TestCase, 'assertNot')
 
641
        failIfs = reflect.prefixedMethods(unittest.TestCase, 'failIf')
 
642
        self.failUnlessEqual(dsu(asserts, self._name),
 
643
                             dsu(failIfs, self._name))
 
644
 
 
645
    def test_equalSpelling(self):
 
646
        for name, value in vars(self).items():
 
647
            if not callable(value):
 
648
                continue
 
649
            if name.endswith('Equal'):
 
650
                self.failUnless(hasattr(self, name+'s'),
 
651
                                "%s but no %ss" % (name, name))
 
652
                self.failUnlessEqual(value, getattr(self, name+'s'))
 
653
            if name.endswith('Equals'):
 
654
                self.failUnless(hasattr(self, name[:-1]),
 
655
                                "%s but no %s" % (name, name[:-1]))
 
656
                self.failUnlessEqual(value, getattr(self, name[:-1]))
 
657
 
 
658
 
 
659
class TestCallDeprecated(unittest.TestCase):
 
660
    """
 
661
    Test use of the L{TestCase.callDeprecated} method with version objects.
 
662
    """
 
663
 
 
664
    version = Version('Twisted', 8, 0, 0)
 
665
 
 
666
    def oldMethod(self, x):
 
667
        """
 
668
        Deprecated method for testing.
 
669
        """
 
670
        return x
 
671
 
 
672
 
 
673
    def test_callDeprecatedSuppressesWarning(self):
 
674
        """
 
675
        callDeprecated calls a deprecated callable, suppressing the
 
676
        deprecation warning.
 
677
        """
 
678
        self.callDeprecated(self.version, self.oldMethod, 'foo')
 
679
        self.assertEqual(
 
680
            self.flushWarnings(), [], "No warnings should be shown")
 
681
 
 
682
 
 
683
    def test_callDeprecatedCallsFunction(self):
 
684
        """
 
685
        L{callDeprecated} actually calls the callable passed to it.
 
686
        """
 
687
        result = self.callDeprecated(self.version, self.oldMethod, 'foo')
 
688
        self.assertEqual('foo', result)
 
689
 
 
690
 
 
691
    def test_failsWithoutDeprecation(self):
 
692
        """
 
693
        callDeprecated raises a test failure if the callable is not
 
694
        deprecated.
 
695
        """
 
696
        def notDeprecated():
 
697
            pass
 
698
        exception = self.assertRaises(
 
699
            self.failureException,
 
700
            self.callDeprecated, self.version, notDeprecated)
 
701
        self.assertEqual(
 
702
            "%r is not deprecated." % notDeprecated, str(exception))
 
703
 
 
704
 
 
705
    def test_failsWithIncorrectDeprecation(self):
 
706
        """
 
707
        callDeprecated raises a test failure if the callable was deprecated
 
708
        at a different version to the one expected.
 
709
        """
 
710
        differentVersion = Version('Foo', 1, 2, 3)
 
711
        exception = self.assertRaises(
 
712
            self.failureException,
 
713
            self.callDeprecated,
 
714
            differentVersion, self.oldMethod, 'foo')
 
715
        self.assertIn(getVersionString(self.version), str(exception))
 
716
        self.assertIn(getVersionString(differentVersion), str(exception))
 
717
 
 
718
 
 
719
    def test_nestedDeprecation(self):
 
720
        """
 
721
        L{callDeprecated} ignores all deprecations apart from the first.
 
722
 
 
723
        Multiple warnings are generated when a deprecated function calls
 
724
        another deprecated function. The first warning is the one generated by
 
725
        the explicitly called function. That's the warning that we care about.
 
726
        """
 
727
        differentVersion = Version('Foo', 1, 2, 3)
 
728
 
 
729
        def nestedDeprecation(*args):
 
730
            return self.oldMethod(*args)
 
731
        nestedDeprecation = deprecated(differentVersion)(nestedDeprecation)
 
732
 
 
733
        self.callDeprecated(differentVersion, nestedDeprecation, 24)
 
734
 
 
735
        # The oldMethod deprecation should have been emitted too, not captured
 
736
        # by callDeprecated.  Flush it now to make sure it did happen and to
 
737
        # prevent it from showing up on stdout.
 
738
        warningsShown = self.flushWarnings()
 
739
        self.assertEqual(len(warningsShown), 1)
 
740
 
 
741
TestCallDeprecated.oldMethod = deprecated(TestCallDeprecated.version)(
 
742
    TestCallDeprecated.oldMethod)