1import ast 2import textwrap 3import unittest 4 5from pyflakes import checker 6 7__all__ = ['TestCase', 'skip', 'skipIf'] 8 9skip = unittest.skip 10skipIf = unittest.skipIf 11 12 13class TestCase(unittest.TestCase): 14 15 withDoctest = False 16 17 def flakes(self, input, *expectedOutputs, **kw): 18 tree = ast.parse(textwrap.dedent(input)) 19 file_tokens = checker.make_tokens(textwrap.dedent(input)) 20 if kw.get('is_segment'): 21 tree = tree.body[0] 22 kw.pop('is_segment') 23 w = checker.Checker( 24 tree, file_tokens=file_tokens, withDoctest=self.withDoctest, **kw 25 ) 26 outputs = [type(o) for o in w.messages] 27 expectedOutputs = list(expectedOutputs) 28 outputs.sort(key=lambda t: t.__name__) 29 expectedOutputs.sort(key=lambda t: t.__name__) 30 self.assertEqual(outputs, expectedOutputs, '''\ 31for input: 32%s 33expected outputs: 34%r 35but got: 36%s''' % (input, expectedOutputs, '\n'.join([str(o) for o in w.messages]))) 37 return w 38 39 if not hasattr(unittest.TestCase, 'assertIs'): 40 41 def assertIs(self, expr1, expr2, msg=None): 42 if expr1 is not expr2: 43 self.fail(msg or '%r is not %r' % (expr1, expr2)) 44 45 if not hasattr(unittest.TestCase, 'assertIsInstance'): 46 47 def assertIsInstance(self, obj, cls, msg=None): 48 """Same as self.assertTrue(isinstance(obj, cls)).""" 49 if not isinstance(obj, cls): 50 self.fail(msg or '%r is not an instance of %r' % (obj, cls)) 51 52 if not hasattr(unittest.TestCase, 'assertNotIsInstance'): 53 54 def assertNotIsInstance(self, obj, cls, msg=None): 55 """Same as self.assertFalse(isinstance(obj, cls)).""" 56 if isinstance(obj, cls): 57 self.fail(msg or '%r is an instance of %r' % (obj, cls)) 58 59 if not hasattr(unittest.TestCase, 'assertIn'): 60 61 def assertIn(self, member, container, msg=None): 62 """Just like self.assertTrue(a in b).""" 63 if member not in container: 64 self.fail(msg or '%r not found in %r' % (member, container)) 65 66 if not hasattr(unittest.TestCase, 'assertNotIn'): 67 68 def assertNotIn(self, member, container, msg=None): 69 """Just like self.assertTrue(a not in b).""" 70 if member in container: 71 self.fail(msg or 72 '%r unexpectedly found in %r' % (member, container)) 73