~divmod-dev/divmod.org/trunk

« back to all changes in this revision

Viewing changes to Epsilon/epsilon/hotfixes/trial_assertwarns.py

  • Committer: Jean-Paul Calderone
  • Date: 2014-06-29 20:33:04 UTC
  • mfrom: (2749.1.1 remove-epsilon-1325289)
  • Revision ID: exarkun@twistedmatrix.com-20140629203304-gdkmbwl1suei4m97
mergeĀ lp:~exarkun/divmod.org/remove-epsilon-1325289

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
 
2
 
"""
3
 
failUnlessWarns assertion from twisted.trial in Twisted 8.0.
4
 
"""
5
 
 
6
 
import warnings
7
 
 
8
 
def failUnlessWarns(self, category, message, filename, f,
9
 
                   *args, **kwargs):
10
 
    """
11
 
    Fail if the given function doesn't generate the specified warning when
12
 
    called. It calls the function, checks the warning, and forwards the
13
 
    result of the function if everything is fine.
14
 
 
15
 
    @param category: the category of the warning to check.
16
 
    @param message: the output message of the warning to check.
17
 
    @param filename: the filename where the warning should come from.
18
 
    @param f: the function which is supposed to generate the warning.
19
 
    @type f: any callable.
20
 
    @param args: the arguments to C{f}.
21
 
    @param kwargs: the keywords arguments to C{f}.
22
 
 
23
 
    @return: the result of the original function C{f}.
24
 
    """
25
 
    warningsShown = []
26
 
    def warnExplicit(*args):
27
 
        warningsShown.append(args)
28
 
 
29
 
    origExplicit = warnings.warn_explicit
30
 
    try:
31
 
        warnings.warn_explicit = warnExplicit
32
 
        result = f(*args, **kwargs)
33
 
    finally:
34
 
        warnings.warn_explicit = origExplicit
35
 
 
36
 
    if not warningsShown:
37
 
        self.fail("No warnings emitted")
38
 
    first = warningsShown[0]
39
 
    for other in warningsShown[1:]:
40
 
        if other[:2] != first[:2]:
41
 
            self.fail("Can't handle different warnings")
42
 
    gotMessage, gotCategory, gotFilename, lineno = first[:4]
43
 
    self.assertEqual(gotMessage, message)
44
 
    self.assertIdentical(gotCategory, category)
45
 
 
46
 
    # Use starts with because of .pyc/.pyo issues.
47
 
    self.failUnless(
48
 
        filename.startswith(gotFilename),
49
 
        'Warning in %r, expected %r' % (gotFilename, filename))
50
 
 
51
 
    # It would be nice to be able to check the line number as well, but
52
 
    # different configurations actually end up reporting different line
53
 
    # numbers (generally the variation is only 1 line, but that's enough
54
 
    # to fail the test erroneously...).
55
 
    # self.assertEqual(lineno, xxx)
56
 
 
57
 
    return result
58
 
 
59
 
def install():
60
 
    from twisted.trial.unittest import TestCase
61
 
    TestCase.failUnlessWarns = TestCase.assertWarns = failUnlessWarns