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