summaryrefslogtreecommitdiff
path: root/pyflakes/test/harness.py
blob: 009923f9b860a4a8ab53a0dc3e11c3a3201886c7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72

import sys
import textwrap
import unittest

from pyflakes import checker

__all__ = ['TestCase', 'skip', 'skipIf']

if sys.version_info < (2, 7):
    skip = lambda why: (lambda func: 'skip')  # not callable
    skipIf = lambda cond, why: (skip(why) if cond else lambda func: func)
else:
    skip = unittest.skip
    skipIf = unittest.skipIf
PyCF_ONLY_AST = 1024


class TestCase(unittest.TestCase):

    withDoctest = False

    def flakes(self, input, *expectedOutputs, **kw):
        tree = compile(textwrap.dedent(input), "<test>", "exec", PyCF_ONLY_AST)
        w = checker.Checker(tree, withDoctest=self.withDoctest, **kw)
        outputs = [type(o) for o in w.messages]
        expectedOutputs = list(expectedOutputs)
        outputs.sort(key=lambda t: t.__name__)
        expectedOutputs.sort(key=lambda t: t.__name__)
        self.assertEqual(outputs, expectedOutputs, '''\
for input:
%s
expected outputs:
%r
but got:
%s''' % (input, expectedOutputs, '\n'.join([str(o) for o in w.messages])))
        return w

    if not hasattr(unittest.TestCase, 'assertIs'):

        def assertIs(self, expr1, expr2, msg=None):
            if expr1 is not expr2:
                self.fail(msg or '%r is not %r' % (expr1, expr2))

    if not hasattr(unittest.TestCase, 'assertIsInstance'):

        def assertIsInstance(self, obj, cls, msg=None):
            """Same as self.assertTrue(isinstance(obj, cls))."""
            if not isinstance(obj, cls):
                self.fail(msg or '%r is not an instance of %r' % (obj, cls))

    if not hasattr(unittest.TestCase, 'assertNotIsInstance'):

        def assertNotIsInstance(self, obj, cls, msg=None):
            """Same as self.assertFalse(isinstance(obj, cls))."""
            if isinstance(obj, cls):
                self.fail(msg or '%r is an instance of %r' % (obj, cls))

    if not hasattr(unittest.TestCase, 'assertIn'):

        def assertIn(self, member, container, msg=None):
            """Just like self.assertTrue(a in b)."""
            if member not in container:
                self.fail(msg or '%r not found in %r' % (member, container))

    if not hasattr(unittest.TestCase, 'assertNotIn'):

        def assertNotIn(self, member, container, msg=None):
            """Just like self.assertTrue(a not in b)."""
            if member in container:
                self.fail(msg or
                          '%r unexpectedly found in %r' % (member, container))