Michael W. Hudson | 53d58bb | 2002-08-30 13:09:51 +0000 | [diff] [blame] | 1 | # Testing the line trace facility. |
| 2 | |
| 3 | from test import test_support |
| 4 | import unittest |
| 5 | import sys |
| 6 | import difflib |
| 7 | |
| 8 | # A very basic example. If this fails, we're in deep trouble. |
| 9 | def basic(): |
| 10 | return 1 |
| 11 | |
| 12 | basic.events = [(0, 'call'), |
| 13 | (1, 'line'), |
| 14 | (1, 'return')] |
| 15 | |
| 16 | # Armin Rigo's failing example: |
| 17 | def arigo_example(): |
| 18 | x = 1 |
| 19 | del x |
| 20 | while 0: |
| 21 | pass |
| 22 | x = 1 |
| 23 | |
| 24 | arigo_example.events = [(0, 'call'), |
| 25 | (1, 'line'), |
| 26 | (2, 'line'), |
| 27 | (3, 'line'), |
| 28 | (5, 'line'), |
| 29 | (5, 'return')] |
| 30 | |
| 31 | # check that lines consisting of just one instruction get traced: |
| 32 | def one_instr_line(): |
| 33 | x = 1 |
| 34 | del x |
| 35 | x = 1 |
| 36 | |
| 37 | one_instr_line.events = [(0, 'call'), |
| 38 | (1, 'line'), |
| 39 | (2, 'line'), |
| 40 | (3, 'line'), |
| 41 | (3, 'return')] |
| 42 | |
| 43 | def no_pop_tops(): # 0 |
| 44 | x = 1 # 1 |
| 45 | for a in range(2): # 2 |
| 46 | if a: # 3 |
| 47 | x = 1 # 4 |
| 48 | else: # 5 |
| 49 | x = 1 # 6 |
| 50 | |
| 51 | no_pop_tops.events = [(0, 'call'), |
| 52 | (1, 'line'), |
| 53 | (2, 'line'), |
| 54 | (3, 'line'), |
| 55 | (6, 'line'), |
| 56 | (2, 'line'), |
| 57 | (3, 'line'), |
| 58 | (4, 'line'), |
| 59 | (2, 'line'), |
| 60 | (6, 'return')] |
| 61 | |
| 62 | def no_pop_blocks(): |
| 63 | while 0: |
| 64 | bla |
| 65 | x = 1 |
| 66 | |
| 67 | no_pop_blocks.events = [(0, 'call'), |
| 68 | (1, 'line'), |
| 69 | (3, 'line'), |
| 70 | (3, 'return')] |
| 71 | |
| 72 | class Tracer: |
| 73 | def __init__(self): |
| 74 | self.events = [] |
| 75 | def trace(self, frame, event, arg): |
| 76 | self.events.append((frame.f_lineno, event)) |
| 77 | return self.trace |
| 78 | |
| 79 | class TraceTestCase(unittest.TestCase): |
| 80 | def run_test(self, func): |
| 81 | tracer = Tracer() |
| 82 | sys.settrace(tracer.trace) |
| 83 | func() |
| 84 | sys.settrace(None) |
| 85 | fl = func.func_code.co_firstlineno |
| 86 | events = [(l - fl, e) for (l, e) in tracer.events] |
| 87 | if events != func.events: |
| 88 | self.fail( |
| 89 | "events did not match expectation:\n" + |
| 90 | "\n".join(difflib.ndiff(map(str, func.events), |
| 91 | map(str, events)))) |
| 92 | |
| 93 | def test_1_basic(self): |
| 94 | self.run_test(basic) |
| 95 | def test_2_arigo(self): |
| 96 | self.run_test(arigo_example) |
| 97 | def test_3_one_instr(self): |
| 98 | self.run_test(one_instr_line) |
| 99 | def test_4_no_pop_blocks(self): |
| 100 | self.run_test(no_pop_blocks) |
| 101 | def test_5_no_pop_tops(self): |
| 102 | self.run_test(no_pop_tops) |
| 103 | |
| 104 | |
| 105 | |
| 106 | def test_main(): |
| 107 | test_support.run_unittest(TraceTestCase) |
| 108 | |
| 109 | if __name__ == "__main__": |
| 110 | test_main() |