Debian Codegraph @

Lib/test/test_bdb.py

raw
1 """ Test the bdb module.
2
3 A test defines a list of tuples that may be seen as paired tuples, each
4 pair being defined by 'expect_tuple, set_tuple' as follows:
5
6 ([event, [lineno[, co_name[, eargs]]]]), (set_type, [sargs])
7
8 * 'expect_tuple' describes the expected current state of the Bdb instance.
9 It may be the empty tuple and no check is done in that case.
10 * 'set_tuple' defines the set_*() method to be invoked when the Bdb
11 instance reaches this state.
12
13 Example of an 'expect_tuple, set_tuple' pair:
14
15 ('line', 2, 'tfunc_main'), ('step', )
16
17 Definitions of the members of the 'expect_tuple':
18 event:
19 Name of the trace event. The set methods that do not give back
20 control to the tracer [1] do not trigger a tracer event and in
21 that case the next 'event' may be 'None' by convention, its value
22 is not checked.
23 [1] Methods that trigger a trace event are set_step(), set_next(),
24 set_return(), set_until() and set_continue().
25 lineno:
26 Line number. Line numbers are relative to the start of the
27 function when tracing a function in the test_bdb module (i.e. this
28 module).
29 co_name:
30 Name of the function being currently traced.
31 eargs:
32 A tuple:
33 * On an 'exception' event the tuple holds a class object, the
34 current exception must be an instance of this class.
35 * On a 'line' event, the tuple holds a dictionary and a list. The
36 dictionary maps each breakpoint number that has been hit on this
37 line to its hits count. The list holds the list of breakpoint
38 number temporaries that are being deleted.
39
40 Definitions of the members of the 'set_tuple':
41 set_type:
42 The type of the set method to be invoked. This may
43 be the type of one of the Bdb set methods: 'step', 'next',
44 'until', 'return', 'continue', 'break', 'quit', or the type of one
45 of the set methods added by test_bdb.Bdb: 'ignore', 'enable',
46 'disable', 'clear', 'up', 'down'.
47 sargs:
48 The arguments of the set method if any, packed in a tuple.
49 """
50
51 import bdb as _bdb
52 import sys
53 import os
54 import unittest
55 import textwrap
56 import importlib
57 import linecache
58 from contextlib import contextmanager
59 from itertools import islice, repeat
60 from test.support import import_helper
61 from test.support import os_helper
62 from test.support import patch_list
63
64
65 class BdbException(Exception): pass
66 class BdbError(BdbException): """Error raised by the Bdb instance."""
67 class BdbSyntaxError(BdbException): """Syntax error in the test case."""
68 class BdbNotExpectedError(BdbException): """Unexpected result."""
69
70 # When 'dry_run' is set to true, expect tuples are ignored and the actual
71 # state of the tracer is printed after running each set_*() method of the test
72 # case. The full list of breakpoints and their attributes is also printed
73 # after each 'line' event where a breakpoint has been hit.
74 dry_run = 0
75
76 def reset_Breakpoint():
77 _bdb.Breakpoint.clearBreakpoints()
78
79 def info_breakpoints():
80 bp_list = [bp for bp in _bdb.Breakpoint.bpbynumber if bp]
81 if not bp_list:
82 return ''
83
84 header_added = False
85 for bp in bp_list:
86 if not header_added:
87 info = 'BpNum Temp Enb Hits Ignore Where\n'
88 header_added = True
89
90 disp = 'yes ' if bp.temporary else 'no '
91 enab = 'yes' if bp.enabled else 'no '
92 info += ('%-5d %s %s %-4d %-6d at %s:%d' %
93 (bp.number, disp, enab, bp.hits, bp.ignore,
94 os.path.basename(bp.file), bp.line))
95 if bp.cond:
96 info += '\n\tstop only if %s' % (bp.cond,)
97 info += '\n'
98 return info
99
100 class Bdb(_bdb.Bdb):
101 """Extend Bdb to enhance test coverage."""
102
103 def trace_dispatch(self, frame, event, arg):
104 self.currentbp = None
105 return super().trace_dispatch(frame, event, arg)
106
107 def set_break(self, filename, lineno, temporary=False, cond=None,
108 funcname=None):
109 if isinstance(funcname, str):
110 if filename == __file__:
111 globals_ = globals()
112 else:
113 module = importlib.import_module(filename[:-3])
114 globals_ = module.__dict__
115 func = eval(funcname, globals_)
116 code = func.__code__
117 filename = code.co_filename
118 lineno = code.co_firstlineno
119 funcname = code.co_name
120
121 res = super().set_break(filename, lineno, temporary=temporary,
122 cond=cond, funcname=funcname)
123 if isinstance(res, str):
124 raise BdbError(res)
125 return res
126
127 def get_stack(self, f, t):
128 self.stack, self.index = super().get_stack(f, t)
129 self.frame = self.stack[self.index][0]
130 return self.stack, self.index
131
132 def set_ignore(self, bpnum):
133 """Increment the ignore count of Breakpoint number 'bpnum'."""
134 bp = self.get_bpbynumber(bpnum)
135 bp.ignore += 1
136
137 def set_enable(self, bpnum):
138 bp = self.get_bpbynumber(bpnum)
139 bp.enabled = True
140
141 def set_disable(self, bpnum):
142 bp = self.get_bpbynumber(bpnum)
143 bp.enabled = False
144
145 def set_clear(self, fname, lineno):
146 err = self.clear_break(fname, lineno)
147 if err:
148 raise BdbError(err)
149
150 def set_up(self):
151 """Move up in the frame stack."""
152 if not self.index:
153 raise BdbError('Oldest frame')
154 self.index -= 1
155 self.frame = self.stack[self.index][0]
156
157 def set_down(self):
158 """Move down in the frame stack."""
159 if self.index + 1 == len(self.stack):
160 raise BdbError('Newest frame')
161 self.index += 1
162 self.frame = self.stack[self.index][0]
163
164 class Tracer(Bdb):
165 """A tracer for testing the bdb module."""
166
167 def __init__(self, expect_set, skip=None, dry_run=False, test_case=None):
168 super().__init__(skip=skip)
169 self.expect_set = expect_set
170 self.dry_run = dry_run
171 self.header = ('Dry-run results for %s:' % test_case if
172 test_case is not None else None)
173 self.init_test()
174
175 def init_test(self):
176 self.cur_except = None
177 self.expect_set_no = 0
178 self.breakpoint_hits = None
179 self.expected_list = list(islice(self.expect_set, 0, None, 2))
180 self.set_list = list(islice(self.expect_set, 1, None, 2))
181
182 def trace_dispatch(self, frame, event, arg):
183 # On an 'exception' event, call_exc_trace() in Python/ceval.c discards
184 # a BdbException raised by the Tracer instance, so we raise it on the
185 # next trace_dispatch() call that occurs unless the set_quit() or
186 # set_continue() method has been invoked on the 'exception' event.
187 if self.cur_except is not None:
188 raise self.cur_except
189
190 if event == 'exception':
191 try:
192 res = super().trace_dispatch(frame, event, arg)
193 return res
194 except BdbException as e:
195 self.cur_except = e
196 return self.trace_dispatch
197 else:
198 return super().trace_dispatch(frame, event, arg)
199
200 def user_call(self, frame, argument_list):
201 # Adopt the same behavior as pdb and, as a side effect, skip also the
202 # first 'call' event when the Tracer is started with Tracer.runcall()
203 # which may be possibly considered as a bug.
204 if not self.stop_here(frame):
205 return
206 self.process_event('call', frame, argument_list)
207 self.next_set_method()
208
209 def user_line(self, frame):
210 self.process_event('line', frame)
211
212 if self.dry_run and self.breakpoint_hits:
213 info = info_breakpoints().strip('\n')
214 # Indent each line.
215 for line in info.split('\n'):
216 print(' ' + line)
217 self.delete_temporaries()
218 self.breakpoint_hits = None
219
220 self.next_set_method()
221
222 def user_return(self, frame, return_value):
223 self.process_event('return', frame, return_value)
224 self.next_set_method()
225
226 def user_exception(self, frame, exc_info):
227 self.exc_info = exc_info
228 self.process_event('exception', frame)
229 self.next_set_method()
230
231 def user_opcode(self, frame):
232 self.process_event('opcode', frame)
233 self.next_set_method()
234
235 def do_clear(self, arg):
236 # The temporary breakpoints are deleted in user_line().
237 bp_list = [self.currentbp]
238 self.breakpoint_hits = (bp_list, bp_list)
239
240 def delete_temporaries(self):
241 if self.breakpoint_hits:
242 for n in self.breakpoint_hits[1]:
243 self.clear_bpbynumber(n)
244
245 def pop_next(self):
246 self.expect_set_no += 1
247 try:
248 self.expect = self.expected_list.pop(0)
249 except IndexError:
250 raise BdbNotExpectedError(
251 'expect_set list exhausted, cannot pop item %d' %
252 self.expect_set_no)
253 self.set_tuple = self.set_list.pop(0)
254
255 def process_event(self, event, frame, *args):
256 # Call get_stack() to enable walking the stack with set_up() and
257 # set_down().
258 tb = None
259 if event == 'exception':
260 tb = self.exc_info[2]
261 self.get_stack(frame, tb)
262
263 # A breakpoint has been hit and it is not a temporary.
264 if self.currentbp is not None and not self.breakpoint_hits:
265 bp_list = [self.currentbp]
266 self.breakpoint_hits = (bp_list, [])
267
268 # Pop next event.
269 self.event= event
270 self.pop_next()
271 if self.dry_run:
272 self.print_state(self.header)
273 return
274
275 # Validate the expected results.
276 if self.expect:
277 self.check_equal(self.expect[0], event, 'Wrong event type')
278 self.check_lno_name()
279
280 if event in ('call', 'return'):
281 self.check_expect_max_size(3)
282 elif len(self.expect) > 3:
283 if event == 'line':
284 bps, temporaries = self.expect[3]
285 bpnums = sorted(bps.keys())
286 if not self.breakpoint_hits:
287 self.raise_not_expected(
288 'No breakpoints hit at expect_set item %d' %
289 self.expect_set_no)
290 self.check_equal(bpnums, self.breakpoint_hits[0],
291 'Breakpoint numbers do not match')
292 self.check_equal([bps[n] for n in bpnums],
293 [self.get_bpbynumber(n).hits for
294 n in self.breakpoint_hits[0]],
295 'Wrong breakpoint hit count')
296 self.check_equal(sorted(temporaries), self.breakpoint_hits[1],
297 'Wrong temporary breakpoints')
298
299 elif event == 'exception':
300 if not isinstance(self.exc_info[1], self.expect[3]):
301 self.raise_not_expected(
302 "Wrong exception at expect_set item %d, got '%s'" %
303 (self.expect_set_no, self.exc_info))
304
305 def check_equal(self, expected, result, msg):
306 if expected == result:
307 return
308 self.raise_not_expected("%s at expect_set item %d, got '%s'" %
309 (msg, self.expect_set_no, result))
310
311 def check_lno_name(self):
312 """Check the line number and function co_name."""
313 s = len(self.expect)
314 if s > 1:
315 lineno = self.lno_abs2rel()
316 self.check_equal(self.expect[1], lineno, 'Wrong line number')
317 if s > 2:
318 self.check_equal(self.expect[2], self.frame.f_code.co_name,
319 'Wrong function name')
320
321 def check_expect_max_size(self, size):
322 if len(self.expect) > size:
323 raise BdbSyntaxError('Invalid size of the %s expect tuple: %s' %
324 (self.event, self.expect))
325
326 def lno_abs2rel(self):
327 fname = self.canonic(self.frame.f_code.co_filename)
328 lineno = self.frame.f_lineno
329 return ((lineno - self.frame.f_code.co_firstlineno + 1)
330 if fname == self.canonic(__file__) else lineno)
331
332 def lno_rel2abs(self, fname, lineno):
333 return (self.frame.f_code.co_firstlineno + lineno - 1
334 if (lineno and self.canonic(fname) == self.canonic(__file__))
335 else lineno)
336
337 def get_state(self):
338 lineno = self.lno_abs2rel()
339 co_name = self.frame.f_code.co_name
340 state = "('%s', %d, '%s'" % (self.event, lineno, co_name)
341 if self.breakpoint_hits:
342 bps = '{'
343 for n in self.breakpoint_hits[0]:
344 if bps != '{':
345 bps += ', '
346 bps += '%s: %s' % (n, self.get_bpbynumber(n).hits)
347 bps += '}'
348 bps = '(' + bps + ', ' + str(self.breakpoint_hits[1]) + ')'
349 state += ', ' + bps
350 elif self.event == 'exception':
351 state += ', ' + self.exc_info[0].__name__
352 state += '), '
353 return state.ljust(32) + str(self.set_tuple) + ','
354
355 def print_state(self, header=None):
356 if header is not None and self.expect_set_no == 1:
357 print()
358 print(header)
359 print('%d: %s' % (self.expect_set_no, self.get_state()))
360
361 def raise_not_expected(self, msg):
362 msg += '\n'
363 msg += ' Expected: %s\n' % str(self.expect)
364 msg += ' Got: ' + self.get_state()
365 raise BdbNotExpectedError(msg)
366
367 def next_set_method(self):
368 set_type = self.set_tuple[0]
369 args = self.set_tuple[1] if len(self.set_tuple) == 2 else None
370 set_method = getattr(self, 'set_' + set_type)
371
372 # The following set methods give back control to the tracer.
373 if set_type in ('step', 'stepinstr', 'continue', 'quit'):
374 set_method()
375 return
376 elif set_type in ('next', 'return'):
377 set_method(self.frame)
378 return
379 elif set_type == 'until':
380 lineno = None
381 if args:
382 lineno = self.lno_rel2abs(self.frame.f_code.co_filename,
383 args[0])
384 set_method(self.frame, lineno)
385 return
386
387 # The following set methods do not give back control to the tracer and
388 # next_set_method() is called recursively.
389 if (args and set_type in ('break', 'clear', 'ignore', 'enable',
390 'disable')) or set_type in ('up', 'down'):
391 if set_type in ('break', 'clear'):
392 fname, lineno, *remain = args
393 lineno = self.lno_rel2abs(fname, lineno)
394 args = [fname, lineno]
395 args.extend(remain)
396 set_method(*args)
397 elif set_type in ('ignore', 'enable', 'disable'):
398 set_method(*args)
399 elif set_type in ('up', 'down'):
400 set_method()
401
402 # Process the next expect_set item.
403 # It is not expected that a test may reach the recursion limit.
404 self.event= None
405 self.pop_next()
406 if self.dry_run:
407 self.print_state()
408 else:
409 if self.expect:
410 self.check_lno_name()
411 self.check_expect_max_size(3)
412 self.next_set_method()
413 else:
414 raise BdbSyntaxError('"%s" is an invalid set_tuple' %
415 self.set_tuple)
416
417 class TracerRun():
418 """Provide a context for running a Tracer instance with a test case."""
419
420 def __init__(self, test_case, skip=None):
421 self.test_case = test_case
422 self.dry_run = test_case.dry_run
423 self.tracer = Tracer(test_case.expect_set, skip=skip,
424 dry_run=self.dry_run, test_case=test_case.id())
425 self._original_tracer = None
426
427 def __enter__(self):
428 # test_pdb does not reset Breakpoint class attributes on exit :-(
429 reset_Breakpoint()
430 self._original_tracer = sys.gettrace()
431 return self.tracer
432
433 def __exit__(self, type_=None, value=None, traceback=None):
434 reset_Breakpoint()
435 sys.settrace(self._original_tracer)
436
437 not_empty = ''
438 if self.tracer.set_list:
439 not_empty += 'All paired tuples have not been processed, '
440 not_empty += ('the last one was number %d\n' %
441 self.tracer.expect_set_no)
442 not_empty += repr(self.tracer.set_list)
443
444 # Make a BdbNotExpectedError a unittest failure.
445 if type_ is not None and issubclass(BdbNotExpectedError, type_):
446 if isinstance(value, BaseException) and value.args:
447 err_msg = value.args[0]
448 if not_empty:
449 err_msg += '\n' + not_empty
450 if self.dry_run:
451 print(err_msg)
452 return True
453 else:
454 self.test_case.fail(err_msg)
455 else:
456 assert False, 'BdbNotExpectedError with empty args'
457
458 if not_empty:
459 if self.dry_run:
460 print(not_empty)
461 else:
462 self.test_case.fail(not_empty)
463
464 def run_test(modules, set_list, skip=None):
465 """Run a test and print the dry-run results.
466
467 'modules': A dictionary mapping module names to their source code as a
468 string. The dictionary MUST include one module named
469 'test_module' with a main() function.
470 'set_list': A list of set_type tuples to be run on the module.
471
472 For example, running the following script outputs the following results:
473
474 ***************************** SCRIPT ********************************
475
476 from test.test_bdb import run_test, break_in_func
477
478 code = '''
479 def func():
480 lno = 3
481
482 def main():
483 func()
484 lno = 7
485 '''
486
487 set_list = [
488 break_in_func('func', 'test_module.py'),
489 ('continue', ),
490 ('step', ),
491 ('step', ),
492 ('step', ),
493 ('quit', ),
494 ]
495
496 modules = { 'test_module': code }
497 run_test(modules, set_list)
498
499 **************************** results ********************************
500
501 1: ('line', 2, 'tfunc_import'), ('next',),
502 2: ('line', 3, 'tfunc_import'), ('step',),
503 3: ('call', 5, 'main'), ('break', ('test_module.py', None, False, None, 'func')),
504 4: ('None', 5, 'main'), ('continue',),
505 5: ('line', 3, 'func', ({1: 1}, [])), ('step',),
506 BpNum Temp Enb Hits Ignore Where
507 1 no yes 1 0 at test_module.py:2
508 6: ('return', 3, 'func'), ('step',),
509 7: ('line', 7, 'main'), ('step',),
510 8: ('return', 7, 'main'), ('quit',),
511
512 *************************************************************************
513
514 """
515 def gen(a, b):
516 try:
517 while 1:
518 x = next(a)
519 y = next(b)
520 yield x
521 yield y
522 except StopIteration:
523 return
524
525 # Step over the import statement in tfunc_import using 'next' and step
526 # into main() in test_module.
527 sl = [('next', ), ('step', )]
528 sl.extend(set_list)
529
530 test = BaseTestCase()
531 test.dry_run = True
532 test.id = lambda : None
533 test.expect_set = list(gen(repeat(()), iter(sl)))
534 with create_modules(modules):
535 with TracerRun(test, skip=skip) as tracer:
536 tracer.runcall(tfunc_import)
537
538 @contextmanager
539 def create_modules(modules):
540 with os_helper.temp_cwd():
541 sys.path.append(os.getcwd())
542 try:
543 for m in modules:
544 fname = m + '.py'
545 with open(fname, 'w', encoding="utf-8") as f:
546 f.write(textwrap.dedent(modules[m]))
547 linecache.checkcache(fname)
548 importlib.invalidate_caches()
549 yield
550 finally:
551 for m in modules:
552 import_helper.forget(m)
553 sys.path.pop()
554
555 def break_in_func(funcname, fname=__file__, temporary=False, cond=None):
556 return 'break', (fname, None, temporary, cond, funcname)
557
558 TEST_MODULE = 'test_module_for_bdb'
559 TEST_MODULE_FNAME = TEST_MODULE + '.py'
560 def tfunc_import():
561 import test_module_for_bdb
562 test_module_for_bdb.main()
563
564 def tfunc_main():
565 lno = 2
566 tfunc_first()
567 tfunc_second()
568 lno = 5
569 lno = 6
570 lno = 7
571
572 def tfunc_first():
573 lno = 2
574 lno = 3
575 lno = 4
576
577 def tfunc_second():
578 lno = 2
579
580 class BaseTestCase(unittest.TestCase):
581 """Base class for all tests."""
582
583 dry_run = dry_run
584
585 def fail(self, msg=None):
586 # Override fail() to use 'raise from None' to avoid repetition of the
587 # error message and traceback.
588 raise self.failureException(msg) from None
589
590 class StateTestCase(BaseTestCase):
591 """Test the step, next, return, until and quit 'set_' methods."""
592
593 def test_step(self):
594 self.expect_set = [
595 ('line', 2, 'tfunc_main'), ('step', ),
596 ('line', 3, 'tfunc_main'), ('step', ),
597 ('call', 1, 'tfunc_first'), ('step', ),
598 ('line', 2, 'tfunc_first'), ('quit', ),
599 ]
600 with TracerRun(self) as tracer:
601 tracer.runcall(tfunc_main)
602
603 def test_step_next_on_last_statement(self):
604 for set_type in ('step', 'next'):
605 with self.subTest(set_type=set_type):
606 self.expect_set = [
607 ('line', 2, 'tfunc_main'), ('step', ),
608 ('line', 3, 'tfunc_main'), ('step', ),
609 ('call', 1, 'tfunc_first'), ('break', (__file__, 3)),
610 ('None', 1, 'tfunc_first'), ('continue', ),
611 ('line', 3, 'tfunc_first', ({1:1}, [])), (set_type, ),
612 ('line', 4, 'tfunc_first'), ('quit', ),
613 ]
614 with TracerRun(self) as tracer:
615 tracer.runcall(tfunc_main)
616
617 def test_stepinstr(self):
618 self.expect_set = [
619 ('line', 2, 'tfunc_main'), ('stepinstr', ),
620 ('opcode', 2, 'tfunc_main'), ('next', ),
621 ('line', 3, 'tfunc_main'), ('quit', ),
622 ]
623 with TracerRun(self) as tracer:
624 tracer.runcall(tfunc_main)
625
626 def test_next(self):
627 self.expect_set = [
628 ('line', 2, 'tfunc_main'), ('step', ),
629 ('line', 3, 'tfunc_main'), ('next', ),
630 ('line', 4, 'tfunc_main'), ('step', ),
631 ('call', 1, 'tfunc_second'), ('step', ),
632 ('line', 2, 'tfunc_second'), ('quit', ),
633 ]
634 with TracerRun(self) as tracer:
635 tracer.runcall(tfunc_main)
636
637 def test_next_over_import(self):
638 code = """
639 def main():
640 lno = 3
641 """
642 modules = { TEST_MODULE: code }
643 with create_modules(modules):
644 self.expect_set = [
645 ('line', 2, 'tfunc_import'), ('next', ),
646 ('line', 3, 'tfunc_import'), ('quit', ),
647 ]
648 with TracerRun(self) as tracer:
649 tracer.runcall(tfunc_import)
650
651 def test_next_on_plain_statement(self):
652 # Check that set_next() is equivalent to set_step() on a plain
653 # statement.
654 self.expect_set = [
655 ('line', 2, 'tfunc_main'), ('step', ),
656 ('line', 3, 'tfunc_main'), ('step', ),
657 ('call', 1, 'tfunc_first'), ('next', ),
658 ('line', 2, 'tfunc_first'), ('quit', ),
659 ]
660 with TracerRun(self) as tracer:
661 tracer.runcall(tfunc_main)
662
663 def test_next_in_caller_frame(self):
664 # Check that set_next() in the caller frame causes the tracer
665 # to stop next in the caller frame.
666 self.expect_set = [
667 ('line', 2, 'tfunc_main'), ('step', ),
668 ('line', 3, 'tfunc_main'), ('step', ),
669 ('call', 1, 'tfunc_first'), ('up', ),
670 ('None', 3, 'tfunc_main'), ('next', ),
671 ('line', 4, 'tfunc_main'), ('quit', ),
672 ]
673 with TracerRun(self) as tracer:
674 tracer.runcall(tfunc_main)
675
676 def test_return(self):
677 self.expect_set = [
678 ('line', 2, 'tfunc_main'), ('step', ),
679 ('line', 3, 'tfunc_main'), ('step', ),
680 ('call', 1, 'tfunc_first'), ('step', ),
681 ('line', 2, 'tfunc_first'), ('return', ),
682 ('return', 4, 'tfunc_first'), ('step', ),
683 ('line', 4, 'tfunc_main'), ('quit', ),
684 ]
685 with TracerRun(self) as tracer:
686 tracer.runcall(tfunc_main)
687
688 def test_return_in_caller_frame(self):
689 self.expect_set = [
690 ('line', 2, 'tfunc_main'), ('step', ),
691 ('line', 3, 'tfunc_main'), ('step', ),
692 ('call', 1, 'tfunc_first'), ('up', ),
693 ('None', 3, 'tfunc_main'), ('return', ),
694 ('return', 7, 'tfunc_main'), ('quit', ),
695 ]
696 with TracerRun(self) as tracer:
697 tracer.runcall(tfunc_main)
698
699 def test_until(self):
700 self.expect_set = [
701 ('line', 2, 'tfunc_main'), ('step', ),
702 ('line', 3, 'tfunc_main'), ('step', ),
703 ('call', 1, 'tfunc_first'), ('step', ),
704 ('line', 2, 'tfunc_first'), ('until', (4, )),
705 ('line', 4, 'tfunc_first'), ('quit', ),
706 ]
707 with TracerRun(self) as tracer:
708 tracer.runcall(tfunc_main)
709
710 def test_until_with_too_large_count(self):
711 self.expect_set = [
712 ('line', 2, 'tfunc_main'), break_in_func('tfunc_first'),
713 ('None', 2, 'tfunc_main'), ('continue', ),
714 ('line', 2, 'tfunc_first', ({1:1}, [])), ('until', (9999, )),
715 ('return', 4, 'tfunc_first'), ('quit', ),
716 ]
717 with TracerRun(self) as tracer:
718 tracer.runcall(tfunc_main)
719
720 def test_until_in_caller_frame(self):
721 self.expect_set = [
722 ('line', 2, 'tfunc_main'), ('step', ),
723 ('line', 3, 'tfunc_main'), ('step', ),
724 ('call', 1, 'tfunc_first'), ('up', ),
725 ('None', 3, 'tfunc_main'), ('until', (6, )),
726 ('line', 6, 'tfunc_main'), ('quit', ),
727 ]
728 with TracerRun(self) as tracer:
729 tracer.runcall(tfunc_main)
730
731 @patch_list(sys.meta_path)
732 def test_skip(self):
733 # Check that tracing is skipped over the import statement in
734 # 'tfunc_import()'.
735
736 # Remove all but the standard importers.
737 sys.meta_path[:] = (
738 item
739 for item in sys.meta_path
740 if item.__module__.startswith('_frozen_importlib')
741 )
742
743 code = """
744 def main():
745 lno = 3
746 """
747 modules = { TEST_MODULE: code }
748 with create_modules(modules):
749 self.expect_set = [
750 ('line', 2, 'tfunc_import'), ('step', ),
751 ('line', 3, 'tfunc_import'), ('quit', ),
752 ]
753 skip = ('importlib*', 'zipimport', 'encodings.*', TEST_MODULE)
754 with TracerRun(self, skip=skip) as tracer:
755 tracer.runcall(tfunc_import)
756
757 def test_skip_with_no_name_module(self):
758 # some frames have `globals` with no `__name__`
759 # for instance the second frame in this traceback
760 # exec(compile('raise ValueError()', '', 'exec'), {})
761 bdb = Bdb(skip=['anything*'])
762 self.assertIs(bdb.is_skipped_module(None), False)
763
764 def test_down(self):
765 # Check that set_down() raises BdbError at the newest frame.
766 self.expect_set = [
767 ('line', 2, 'tfunc_main'), ('down', ),
768 ]
769 with TracerRun(self) as tracer:
770 self.assertRaises(BdbError, tracer.runcall, tfunc_main)
771
772 def test_up(self):
773 self.expect_set = [
774 ('line', 2, 'tfunc_main'), ('step', ),
775 ('line', 3, 'tfunc_main'), ('step', ),
776 ('call', 1, 'tfunc_first'), ('up', ),
777 ('None', 3, 'tfunc_main'), ('quit', ),
778 ]
779 with TracerRun(self) as tracer:
780 tracer.runcall(tfunc_main)
781
782 class BreakpointTestCase(BaseTestCase):
783 """Test the breakpoint set method."""
784
785 def test_bp_on_non_existent_module(self):
786 self.expect_set = [
787 ('line', 2, 'tfunc_import'), ('break', ('/non/existent/module.py', 1))
788 ]
789 with TracerRun(self) as tracer:
790 self.assertRaises(BdbError, tracer.runcall, tfunc_import)
791
792 def test_bp_after_last_statement(self):
793 code = """
794 def main():
795 lno = 3
796 """
797 modules = { TEST_MODULE: code }
798 with create_modules(modules):
799 self.expect_set = [
800 ('line', 2, 'tfunc_import'), ('break', (TEST_MODULE_FNAME, 4))
801 ]
802 with TracerRun(self) as tracer:
803 self.assertRaises(BdbError, tracer.runcall, tfunc_import)
804
805 def test_temporary_bp(self):
806 code = """
807 def func():
808 lno = 3
809
810 def main():
811 for i in range(2):
812 func()
813 """
814 modules = { TEST_MODULE: code }
815 with create_modules(modules):
816 self.expect_set = [
817 ('line', 2, 'tfunc_import'),
818 break_in_func('func', TEST_MODULE_FNAME, True),
819 ('None', 2, 'tfunc_import'),
820 break_in_func('func', TEST_MODULE_FNAME, True),
821 ('None', 2, 'tfunc_import'), ('continue', ),
822 ('line', 3, 'func', ({1:1}, [1])), ('continue', ),
823 ('line', 3, 'func', ({2:1}, [2])), ('quit', ),
824 ]
825 with TracerRun(self) as tracer:
826 tracer.runcall(tfunc_import)
827
828 def test_disabled_temporary_bp(self):
829 code = """
830 def func():
831 lno = 3
832
833 def main():
834 for i in range(3):
835 func()
836 """
837 modules = { TEST_MODULE: code }
838 with create_modules(modules):
839 self.expect_set = [
840 ('line', 2, 'tfunc_import'),
841 break_in_func('func', TEST_MODULE_FNAME),
842 ('None', 2, 'tfunc_import'),
843 break_in_func('func', TEST_MODULE_FNAME, True),
844 ('None', 2, 'tfunc_import'), ('disable', (2, )),
845 ('None', 2, 'tfunc_import'), ('continue', ),
846 ('line', 3, 'func', ({1:1}, [])), ('enable', (2, )),
847 ('None', 3, 'func'), ('disable', (1, )),
848 ('None', 3, 'func'), ('continue', ),
849 ('line', 3, 'func', ({2:1}, [2])), ('enable', (1, )),
850 ('None', 3, 'func'), ('continue', ),
851 ('line', 3, 'func', ({1:2}, [])), ('quit', ),
852 ]
853 with TracerRun(self) as tracer:
854 tracer.runcall(tfunc_import)
855
856 def test_bp_condition(self):
857 code = """
858 def func(a):
859 lno = 3
860
861 def main():
862 for i in range(3):
863 func(i)
864 """
865 modules = { TEST_MODULE: code }
866 with create_modules(modules):
867 self.expect_set = [
868 ('line', 2, 'tfunc_import'),
869 break_in_func('func', TEST_MODULE_FNAME, False, 'a == 2'),
870 ('None', 2, 'tfunc_import'), ('continue', ),
871 ('line', 3, 'func', ({1:3}, [])), ('quit', ),
872 ]
873 with TracerRun(self) as tracer:
874 tracer.runcall(tfunc_import)
875
876 def test_bp_exception_on_condition_evaluation(self):
877 code = """
878 def func(a):
879 lno = 3
880
881 def main():
882 func(0)
883 """
884 modules = { TEST_MODULE: code }
885 with create_modules(modules):
886 self.expect_set = [
887 ('line', 2, 'tfunc_import'),
888 break_in_func('func', TEST_MODULE_FNAME, False, '1 / 0'),
889 ('None', 2, 'tfunc_import'), ('continue', ),
890 ('line', 3, 'func', ({1:1}, [])), ('quit', ),
891 ]
892 with TracerRun(self) as tracer:
893 tracer.runcall(tfunc_import)
894
895 def test_bp_ignore_count(self):
896 code = """
897 def func():
898 lno = 3
899
900 def main():
901 for i in range(2):
902 func()
903 """
904 modules = { TEST_MODULE: code }
905 with create_modules(modules):
906 self.expect_set = [
907 ('line', 2, 'tfunc_import'),
908 break_in_func('func', TEST_MODULE_FNAME),
909 ('None', 2, 'tfunc_import'), ('ignore', (1, )),
910 ('None', 2, 'tfunc_import'), ('continue', ),
911 ('line', 3, 'func', ({1:2}, [])), ('quit', ),
912 ]
913 with TracerRun(self) as tracer:
914 tracer.runcall(tfunc_import)
915
916 def test_ignore_count_on_disabled_bp(self):
917 code = """
918 def func():
919 lno = 3
920
921 def main():
922 for i in range(3):
923 func()
924 """
925 modules = { TEST_MODULE: code }
926 with create_modules(modules):
927 self.expect_set = [
928 ('line', 2, 'tfunc_import'),
929 break_in_func('func', TEST_MODULE_FNAME),
930 ('None', 2, 'tfunc_import'),
931 break_in_func('func', TEST_MODULE_FNAME),
932 ('None', 2, 'tfunc_import'), ('ignore', (1, )),
933 ('None', 2, 'tfunc_import'), ('disable', (1, )),
934 ('None', 2, 'tfunc_import'), ('continue', ),
935 ('line', 3, 'func', ({2:1}, [])), ('enable', (1, )),
936 ('None', 3, 'func'), ('continue', ),
937 ('line', 3, 'func', ({2:2}, [])), ('continue', ),
938 ('line', 3, 'func', ({1:2}, [])), ('quit', ),
939 ]
940 with TracerRun(self) as tracer:
941 tracer.runcall(tfunc_import)
942
943 def test_clear_two_bp_on_same_line(self):
944 code = """
945 def func():
946 lno = 3
947 lno = 4
948
949 def main():
950 for i in range(3):
951 func()
952 """
953 modules = { TEST_MODULE: code }
954 with create_modules(modules):
955 self.expect_set = [
956 ('line', 2, 'tfunc_import'), ('break', (TEST_MODULE_FNAME, 3)),
957 ('None', 2, 'tfunc_import'), ('break', (TEST_MODULE_FNAME, 3)),
958 ('None', 2, 'tfunc_import'), ('break', (TEST_MODULE_FNAME, 4)),
959 ('None', 2, 'tfunc_import'), ('continue', ),
960 ('line', 3, 'func', ({1:1}, [])), ('continue', ),
961 ('line', 4, 'func', ({3:1}, [])), ('clear', (TEST_MODULE_FNAME, 3)),
962 ('None', 4, 'func'), ('continue', ),
963 ('line', 4, 'func', ({3:2}, [])), ('quit', ),
964 ]
965 with TracerRun(self) as tracer:
966 tracer.runcall(tfunc_import)
967
968 def test_clear_at_no_bp(self):
969 self.expect_set = [
970 ('line', 2, 'tfunc_import'), ('clear', (__file__, 1))
971 ]
972 with TracerRun(self) as tracer:
973 self.assertRaises(BdbError, tracer.runcall, tfunc_import)
974
975 def test_load_bps_from_previous_Bdb_instance(self):
976 reset_Breakpoint()
977 db1 = Bdb()
978 fname = db1.canonic(__file__)
979 db1.set_break(__file__, 1)
980 self.assertEqual(db1.get_all_breaks(), {fname: [1]})
981
982 db2 = Bdb()
983 db2.set_break(__file__, 2)
984 db2.set_break(__file__, 3)
985 db2.set_break(__file__, 4)
986 self.assertEqual(db1.get_all_breaks(), {fname: [1]})
987 self.assertEqual(db2.get_all_breaks(), {fname: [1, 2, 3, 4]})
988 db2.clear_break(__file__, 1)
989 self.assertEqual(db1.get_all_breaks(), {fname: [1]})
990 self.assertEqual(db2.get_all_breaks(), {fname: [2, 3, 4]})
991
992 db3 = Bdb()
993 self.assertEqual(db1.get_all_breaks(), {fname: [1]})
994 self.assertEqual(db2.get_all_breaks(), {fname: [2, 3, 4]})
995 self.assertEqual(db3.get_all_breaks(), {fname: [2, 3, 4]})
996 db2.clear_break(__file__, 2)
997 self.assertEqual(db1.get_all_breaks(), {fname: [1]})
998 self.assertEqual(db2.get_all_breaks(), {fname: [3, 4]})
999 self.assertEqual(db3.get_all_breaks(), {fname: [2, 3, 4]})
1000
1001 db4 = Bdb()
1002 db4.set_break(__file__, 5)
1003 self.assertEqual(db1.get_all_breaks(), {fname: [1]})
1004 self.assertEqual(db2.get_all_breaks(), {fname: [3, 4]})
1005 self.assertEqual(db3.get_all_breaks(), {fname: [2, 3, 4]})
1006 self.assertEqual(db4.get_all_breaks(), {fname: [3, 4, 5]})
1007 reset_Breakpoint()
1008
1009 db5 = Bdb()
1010 db5.set_break(__file__, 6)
1011 self.assertEqual(db1.get_all_breaks(), {fname: [1]})
1012 self.assertEqual(db2.get_all_breaks(), {fname: [3, 4]})
1013 self.assertEqual(db3.get_all_breaks(), {fname: [2, 3, 4]})
1014 self.assertEqual(db4.get_all_breaks(), {fname: [3, 4, 5]})
1015 self.assertEqual(db5.get_all_breaks(), {fname: [6]})
1016
1017
1018 class RunTestCase(BaseTestCase):
1019 """Test run, runeval and set_trace."""
1020
1021 def test_run_step(self):
1022 # Check that the bdb 'run' method stops at the first line event.
1023 code = """
1024 lno = 2
1025 """
1026 self.expect_set = [
1027 ('line', 2, '<module>'), ('step', ),
1028 ('return', 2, '<module>'), ('quit', ),
1029 ]
1030 with TracerRun(self) as tracer:
1031 tracer.run(compile(textwrap.dedent(code), '<string>', 'exec'))
1032
1033 def test_runeval_step(self):
1034 # Test bdb 'runeval'.
1035 code = """
1036 def main():
1037 lno = 3
1038 """
1039 modules = { TEST_MODULE: code }
1040 with create_modules(modules):
1041 self.expect_set = [
1042 ('line', 1, '<module>'), ('step', ),
1043 ('call', 2, 'main'), ('step', ),
1044 ('line', 3, 'main'), ('step', ),
1045 ('return', 3, 'main'), ('step', ),
1046 ('return', 1, '<module>'), ('quit', ),
1047 ]
1048 import test_module_for_bdb
1049 ns = {'test_module_for_bdb': test_module_for_bdb}
1050 with TracerRun(self) as tracer:
1051 tracer.runeval('test_module_for_bdb.main()', ns, ns)
1052
1053 class IssuesTestCase(BaseTestCase):
1054 """Test fixed bdb issues."""
1055
1056 def test_step_at_return_with_no_trace_in_caller(self):
1057 # Issue #13183.
1058 # Check that the tracer does step into the caller frame when the
1059 # trace function is not set in that frame.
1060 code_1 = """
1061 from test_module_for_bdb_2 import func
1062 def main():
1063 func()
1064 lno = 5
1065 """
1066 code_2 = """
1067 def func():
1068 lno = 3
1069 """
1070 modules = {
1071 TEST_MODULE: code_1,
1072 'test_module_for_bdb_2': code_2,
1073 }
1074 with create_modules(modules):
1075 self.expect_set = [
1076 ('line', 2, 'tfunc_import'),
1077 break_in_func('func', 'test_module_for_bdb_2.py'),
1078 ('None', 2, 'tfunc_import'), ('continue', ),
1079 ('line', 3, 'func', ({1:1}, [])), ('step', ),
1080 ('return', 3, 'func'), ('step', ),
1081 ('line', 5, 'main'), ('quit', ),
1082 ]
1083 with TracerRun(self) as tracer:
1084 tracer.runcall(tfunc_import)
1085
1086 def test_next_until_return_in_generator(self):
1087 # Issue #16596.
1088 # Check that set_next(), set_until() and set_return() do not treat the
1089 # `yield` and `yield from` statements as if they were returns and stop
1090 # instead in the current frame.
1091 code = """
1092 def test_gen():
1093 yield 0
1094 lno = 4
1095 return 123
1096
1097 def main():
1098 it = test_gen()
1099 next(it)
1100 next(it)
1101 lno = 11
1102 """
1103 modules = { TEST_MODULE: code }
1104 for set_type in ('next', 'until', 'return'):
1105 with self.subTest(set_type=set_type):
1106 with create_modules(modules):
1107 self.expect_set = [
1108 ('line', 2, 'tfunc_import'),
1109 break_in_func('test_gen', TEST_MODULE_FNAME),
1110 ('None', 2, 'tfunc_import'), ('continue', ),
1111 ('line', 3, 'test_gen', ({1:1}, [])), (set_type, ),
1112 ]
1113
1114 if set_type == 'return':
1115 self.expect_set.extend(
1116 [('exception', 10, 'main', StopIteration), ('step',),
1117 ('return', 10, 'main'), ('quit', ),
1118 ]
1119 )
1120 else:
1121 self.expect_set.extend(
1122 [('line', 4, 'test_gen'), ('quit', ),]
1123 )
1124 with TracerRun(self) as tracer:
1125 tracer.runcall(tfunc_import)
1126
1127 def test_next_command_in_generator_for_loop(self):
1128 # Issue #16596.
1129 code = """
1130 def test_gen():
1131 yield 0
1132 lno = 4
1133 yield 1
1134 return 123
1135
1136 def main():
1137 for i in test_gen():
1138 lno = 10
1139 lno = 11
1140 """
1141 modules = { TEST_MODULE: code }
1142 with create_modules(modules):
1143 self.expect_set = [
1144 ('line', 2, 'tfunc_import'),
1145 break_in_func('test_gen', TEST_MODULE_FNAME),
1146 ('None', 2, 'tfunc_import'), ('continue', ),
1147 ('line', 3, 'test_gen', ({1:1}, [])), ('next', ),
1148 ('line', 4, 'test_gen'), ('next', ),
1149 ('line', 5, 'test_gen'), ('next', ),
1150 ('line', 6, 'test_gen'), ('next', ),
1151 ('exception', 9, 'main', StopIteration), ('step', ),
1152 ('line', 11, 'main'), ('quit', ),
1153
1154 ]
1155 with TracerRun(self) as tracer:
1156 tracer.runcall(tfunc_import)
1157
1158 def test_next_command_in_generator_with_subiterator(self):
1159 # Issue #16596.
1160 code = """
1161 def test_subgen():
1162 yield 0
1163 return 123
1164
1165 def test_gen():
1166 x = yield from test_subgen()
1167 return 456
1168
1169 def main():
1170 for i in test_gen():
1171 lno = 12
1172 lno = 13
1173 """
1174 modules = { TEST_MODULE: code }
1175 with create_modules(modules):
1176 self.expect_set = [
1177 ('line', 2, 'tfunc_import'),
1178 break_in_func('test_gen', TEST_MODULE_FNAME),
1179 ('None', 2, 'tfunc_import'), ('continue', ),
1180 ('line', 7, 'test_gen', ({1:1}, [])), ('next', ),
1181 ('line', 8, 'test_gen'), ('next', ),
1182 ('exception', 11, 'main', StopIteration), ('step', ),
1183 ('line', 13, 'main'), ('quit', ),
1184
1185 ]
1186 with TracerRun(self) as tracer:
1187 tracer.runcall(tfunc_import)
1188
1189 def test_return_command_in_generator_with_subiterator(self):
1190 # Issue #16596.
1191 code = """
1192 def test_subgen():
1193 yield 0
1194 return 123
1195
1196 def test_gen():
1197 x = yield from test_subgen()
1198 return 456
1199
1200 def main():
1201 for i in test_gen():
1202 lno = 12
1203 lno = 13
1204 """
1205 modules = { TEST_MODULE: code }
1206 with create_modules(modules):
1207 self.expect_set = [
1208 ('line', 2, 'tfunc_import'),
1209 break_in_func('test_subgen', TEST_MODULE_FNAME),
1210 ('None', 2, 'tfunc_import'), ('continue', ),
1211 ('line', 3, 'test_subgen', ({1:1}, [])), ('return', ),
1212 ('exception', 7, 'test_gen', StopIteration), ('return', ),
1213 ('exception', 11, 'main', StopIteration), ('step', ),
1214 ('line', 13, 'main'), ('quit', ),
1215
1216 ]
1217 with TracerRun(self) as tracer:
1218 tracer.runcall(tfunc_import)
1219
1220 def test_next_to_botframe(self):
1221 # gh-125422
1222 # Check that next command won't go to the bottom frame.
1223 code = """
1224 lno = 2
1225 """
1226 self.expect_set = [
1227 ('line', 2, '<module>'), ('step', ),
1228 ('return', 2, '<module>'), ('next', ),
1229 ]
1230 with TracerRun(self) as tracer:
1231 tracer.run(compile(textwrap.dedent(code), '<string>', 'exec'))
1232
1233
1234 class TestRegressions(unittest.TestCase):
1235 def test_format_stack_entry_no_lineno(self):
1236 # See gh-101517
1237 self.assertIn('Warning: lineno is None',
1238 Bdb().format_stack_entry((sys._getframe(), None)))
1239
1240
1241 if __name__ == "__main__":
1242 unittest.main()