Best Python code snippet using Contexts
test_pdb.py
Source:test_pdb.py
...100 frame = sys._getframe().f_back101 if cleanup:102 pdbpp.cleanup()103 class PdbForFrame(Pdb):104 def set_trace(self, _frame, *args, **kwargs):105 super(PdbForFrame, self).set_trace(frame, *args, **kwargs)106 newglobals = pdbpp.set_trace.__globals__.copy()107 newglobals['Pdb'] = PdbForFrame108 new_set_trace = pdbpp.rebind_globals(pdbpp.set_trace, newglobals)109 new_set_trace(**kwds)110def set_trace(frame=None, cleanup=True, Pdb=PdbTest, **kwds):111 """set_trace helper for tests, going through Pdb.set_trace directly."""112 if frame is None:113 frame = sys._getframe().f_back114 if cleanup:115 pdbpp.cleanup()116 Pdb(**kwds).set_trace(frame)117def xpm():118 pdbpp.xpm(PdbTest)119def runpdb(func, input, terminal_size=None):120 oldstdin = sys.stdin121 oldstdout = sys.stdout122 oldstderr = sys.stderr123 # Use __dict__ to avoid class descriptor (staticmethod).124 old_get_terminal_size = pdbpp.Pdb.__dict__["get_terminal_size"]125 if sys.version_info < (3, ):126 text_type = unicode # noqa: F821127 else:128 text_type = str129 class MyBytesIO(BytesIO):130 """write accepts unicode or bytes"""131 encoding = 'ascii'132 def __init__(self, encoding='utf-8'):133 self.encoding = encoding134 def write(self, msg):135 if isinstance(msg, text_type):136 msg = msg.encode(self.encoding)137 super(MyBytesIO, self).write(msg)138 def get_unicode_value(self):139 return self.getvalue().decode(self.encoding).replace(140 pdbpp.CLEARSCREEN, "<CLEARSCREEN>\n"141 ).replace(chr(27), "^[")142 # Use a predictable terminal size.143 if terminal_size is None:144 terminal_size = (80, 24)145 pdbpp.Pdb.get_terminal_size = staticmethod(lambda: terminal_size)146 try:147 sys.stdin = FakeStdin(input)148 sys.stdout = stdout = MyBytesIO()149 sys.stderr = stderr = MyBytesIO()150 func()151 except InnerTestException:152 pass153 except bdb.BdbQuit:154 print("!! Received unexpected bdb.BdbQuit !!")155 except Exception:156 # Make it available for pytests output capturing.157 print(stdout.get_unicode_value(), file=oldstdout)158 raise159 finally:160 sys.stdin = oldstdin161 sys.stdout = oldstdout162 sys.stderr = oldstderr163 pdbpp.Pdb.get_terminal_size = old_get_terminal_size164 stderr = stderr.get_unicode_value()165 if stderr:166 # Make it available for pytests output capturing.167 print(stdout.get_unicode_value())168 raise AssertionError("Unexpected output on stderr: %s" % stderr)169 return stdout.get_unicode_value().splitlines()170def is_prompt(line):171 prompts = {'# ', '(#) ', '((#)) ', '(((#))) ', '(Pdb) ', '(Pdb++) ', '(com++) '}172 for prompt in prompts:173 if line.startswith(prompt):174 return len(prompt)175 return False176def extract_commands(lines):177 cmds = []178 for line in lines:179 prompt_len = is_prompt(line)180 if prompt_len:181 cmds.append(line[prompt_len:])182 return cmds183shortcuts = [184 ('[', '\\['),185 (']', '\\]'),186 ('(', '\\('),187 (')', '\\)'),188 ('^', '\\^'),189 (r'\(Pdb++\) ', r'\(Pdb\+\+\) '),190 (r'\(com++\) ', r'\(com\+\+\) '),191 ('<COLORCURLINE>', r'\^\[\[44m\^\[\[36;01;44m *[0-9]+\^\[\[00;44m'),192 ('<COLORNUM>', r'\^\[\[36;01m *[0-9]+\^\[\[00m'),193 ('<COLORFNAME>', r'\^\[\[33;01m'),194 ('<COLORLNUM>', r'\^\[\[36;01m'),195 ('<COLORRESET>', r'\^\[\[00m'),196 ('<PYGMENTSRESET>', r'\^\[\[39[^m]*m'),197 ('NUM', ' *[0-9]+'),198 # Optional message with Python 2.7 (e.g. "--Return--"), not using Pdb.message.199 ('<PY27_MSG>', '\n.*' if sys.version_info < (3,) else ''),200]201def cook_regexp(s):202 for key, value in shortcuts:203 s = s.replace(key, value)204 return s205def run_func(func, expected, terminal_size=None):206 """Runs given function and returns its output along with expected patterns.207 It does not make any assertions. To compare func's output with expected208 lines, use `check` function.209 """210 expected = textwrap.dedent(expected).strip().splitlines()211 # Remove comments.212 expected = [re.split(r'\s+###', line)[0] for line in expected]213 commands = extract_commands(expected)214 expected = list(map(cook_regexp, expected))215 # Explode newlines from pattern replacements (PY27_MSG).216 flattened = []217 for line in expected:218 if line == "":219 flattened.append("")220 else:221 flattened.extend(line.splitlines())222 expected = flattened223 return expected, runpdb(func, commands, terminal_size)224def count_frames():225 f = sys._getframe()226 i = 0227 while f is not None:228 i += 1229 f = f.f_back230 return i231class InnerTestException(Exception):232 """Ignored by check()."""233 pass234trans_trn_dict = {"\n": r"\n", "\r": r"\r", "\t": r"\t"}235if sys.version_info >= (3,):236 trans_trn_table = str.maketrans(trans_trn_dict)237 def trans_trn(string):238 return string.translate(trans_trn_table)239else:240 def trans_trn(string):241 for k, v in trans_trn_dict.items():242 string = string.replace(k, v)243 return string244def check(func, expected, terminal_size=None):245 expected, lines = run_func(func, expected, terminal_size)246 if expected:247 maxlen = max(map(len, expected))248 if sys.version_info < (3,):249 # Ensure same type for comparison.250 expected = [251 x.decode("utf8") if isinstance(x, bytes) else x for x in expected252 ]253 else:254 maxlen = 0255 all_ok = True256 print()257 for pattern, string in zip_longest(expected, lines):258 if pattern is not None and string is not None:259 if is_prompt(pattern) and is_prompt(string):260 ok = True261 else:262 try:263 ok = re.match(pattern, string)264 except re.error as exc:265 raise ValueError("re.match failed for {!r}: {!r}".format(266 pattern, exc))267 else:268 ok = False269 if pattern is None:270 pattern = '<None>'271 if string is None:272 string = '<None>'273 # Use "$" to mark end of line with trailing space274 if re.search(r'\s+$', string):275 string += '$'276 if re.search(r'\s+$', pattern):277 pattern += '$'278 pattern = trans_trn(pattern)279 string = trans_trn(string)280 print(pattern.ljust(maxlen+1), '| ', string, end='')281 if ok:282 print()283 else:284 print(pdbpp.Color.set(pdbpp.Color.red, ' <<<<<'))285 all_ok = False286 assert all_ok287def test_prompt_setter():288 p = pdbpp.Pdb()289 assert p.prompt == "(Pdb++) "290 p.prompt = "(Pdb)"291 assert p.prompt == "(Pdb++)"292 p.prompt = "ipdb> "293 assert p.prompt == "ipdb++> "294 p.prompt = "custom"295 assert p.prompt == "custom++"296 p.prompt = "custom "297 assert p.prompt == "custom++ "298 p.prompt = "custom :"299 assert p.prompt == "custom++ :"300 p.prompt = "custom "301 assert p.prompt == "custom++ "302 p.prompt = ""303 assert p.prompt == ""304 # Not changed (also used in tests).305 p.prompt = "# "306 assert p.prompt == "# "307 # Can be forced.308 p._prompt = "custom"309 assert p.prompt == "custom"310def test_config_pygments(monkeypatch):311 import pygments.formatters312 assert not hasattr(DefaultConfig, "use_terminal256formatter")313 p = Pdb(Config=DefaultConfig)314 monkeypatch.delenv("TERM", raising=False)315 assert isinstance(316 p._get_pygments_formatter(), pygments.formatters.TerminalFormatter317 )318 monkeypatch.setenv("TERM", "xterm-256color")319 assert isinstance(320 p._get_pygments_formatter(), pygments.formatters.Terminal256Formatter321 )322 monkeypatch.setenv("TERM", "xterm-kitty")323 assert isinstance(324 p._get_pygments_formatter(), pygments.formatters.TerminalTrueColorFormatter325 )326 class Config(DefaultConfig):327 formatter = object()328 assert Pdb(Config=Config)._get_pygments_formatter() is Config.formatter329 class Config(DefaultConfig):330 pygments_formatter_class = "pygments.formatters.TerminalTrueColorFormatter"331 assert isinstance(332 Pdb(Config=Config)._get_pygments_formatter(),333 pygments.formatters.TerminalTrueColorFormatter334 )335 source = Pdb(Config=Config).format_source("print(42)")336 assert source.startswith("\x1b[38;2;0;128;")337 assert "print\x1b[39" in source338 assert source.endswith("m42\x1b[39m)\n")339@pytest.mark.parametrize("use_pygments", (None, True, False))340def test_config_missing_pygments(use_pygments, monkeypatch_importerror):341 class Config(DefaultConfig):342 pass343 Config.use_pygments = use_pygments344 class PdbForMessage(Pdb):345 messages = []346 def message(self, msg):347 self.messages.append(msg)348 pdb_ = PdbForMessage(Config=Config)349 with monkeypatch_importerror(('pygments', 'pygments.formatters')):350 with pytest.raises(ImportError):351 pdb_._get_pygments_formatter()352 assert pdb_._get_source_highlight_function() is False353 assert pdb_.format_source("print(42)") == "print(42)"354 if use_pygments is True:355 assert pdb_.messages == ['Could not import pygments, disabling.']356 else:357 assert pdb_.messages == []358 # Cover branch for cached _highlight property.359 assert pdb_.format_source("print(42)") == "print(42)"360def test_config_pygments_deprecated_use_terminal256formatter(monkeypatch):361 import pygments.formatters362 monkeypatch.setenv("TERM", "xterm-256color")363 class Config(DefaultConfig):364 use_terminal256formatter = False365 assert isinstance(366 Pdb(Config=Config)._get_pygments_formatter(),367 pygments.formatters.TerminalFormatter368 )369 class Config(DefaultConfig):370 use_terminal256formatter = True371 assert isinstance(372 Pdb(Config=Config)._get_pygments_formatter(),373 pygments.formatters.Terminal256Formatter374 )375def test_runpdb():376 def fn():377 set_trace()378 a = 1379 b = 2380 c = 3381 return a+b+c382 check(fn, """383[NUM] > .*fn()384-> a = 1385 5 frames hidden .*386# n387[NUM] > .*fn()388-> b = 2389 5 frames hidden .*390# n391[NUM] > .*fn()392-> c = 3393 5 frames hidden .*394# c395""")396def test_set_trace_remembers_previous_state():397 def fn():398 a = 1399 set_trace()400 a = 2401 set_trace(cleanup=False)402 a = 3403 set_trace(cleanup=False)404 a = 4405 return a406 check(fn, """407[NUM] > .*fn()408-> a = 2409 5 frames hidden .*410# display a411# c412[NUM] > .*fn()413-> a = 3414 5 frames hidden .*415a: 1 --> 2416# c417[NUM] > .*fn()418-> a = 4419 5 frames hidden .*420a: 2 --> 3421# c422""")423def test_set_trace_remembers_previous_state_via_module():424 def fn():425 a = 1426 set_trace_via_module()427 a = 2428 set_trace_via_module(cleanup=False)429 a = 3430 set_trace_via_module(cleanup=False)431 a = 4432 return a433 check(fn, """434[NUM] > .*fn()435-> a = 2436 5 frames hidden .*437# display a438# c439[NUM] > .*fn()440-> a = 3441 5 frames hidden .*442a: 1 --> 2443# c444[NUM] > .*fn()445-> a = 4446 5 frames hidden .*447a: 2 --> 3448# c449""")450class TestPdbMeta:451 def test_called_for_set_trace_false(self):452 assert pdbpp.PdbMeta.called_for_set_trace(sys._getframe()) is False453 def test_called_for_set_trace_staticmethod(self):454 class Foo:455 @staticmethod456 def set_trace():457 frame = sys._getframe()458 assert pdbpp.PdbMeta.called_for_set_trace(frame) is frame459 return True460 assert Foo.set_trace() is True461 def test_called_for_set_trace_method(self):462 class Foo:463 def set_trace(self):464 frame = sys._getframe()465 assert pdbpp.PdbMeta.called_for_set_trace(frame) is frame466 return True467 assert Foo().set_trace() is True468 def test_called_for_set_trace_via_func(self):469 def set_trace():470 frame = sys._getframe()471 assert pdbpp.PdbMeta.called_for_set_trace(frame) is frame472 return True473 assert set_trace() is True474 def test_called_for_set_trace_via_other_func(self):475 def somefunc():476 def meta():477 frame = sys._getframe()478 assert pdbpp.PdbMeta.called_for_set_trace(frame) is False479 meta()480 return True481 assert somefunc() is True482def test_forget_with_new_pdb():483 """Regression test for having used local.GLOBAL_PDB in forget.484 This caused "AttributeError: 'NewPdb' object has no attribute 'lineno'",485 e.g. when pdbpp was used before pytest's debugging plugin was setup, which486 then later uses a custom Pdb wrapper.487 """488 def fn():489 set_trace()490 class NewPdb(PdbTest, pdbpp.Pdb):491 def set_trace(self, *args):492 print("new_set_trace")493 return super(NewPdb, self).set_trace(*args)494 new_pdb = NewPdb()495 new_pdb.set_trace()496 check(fn, """497[NUM] > .*fn()498-> class NewPdb(PdbTest, pdbpp.Pdb):499 5 frames hidden .*500# c501new_set_trace502--Return--503[NUM] .*set_trace()->None504-> return super(NewPdb, self).set_trace(\\*args)505 5 frames hidden .*506# l507NUM .*508NUM .*509NUM .*510NUM .*511NUM .*512NUM .*513NUM .*514NUM .*515NUM .*516NUM .*517NUM .*518# c519""")520def test_global_pdb_with_classmethod():521 def fn():522 set_trace()523 assert isinstance(pdbpp.local.GLOBAL_PDB, PdbTest)524 class NewPdb(PdbTest, pdbpp.Pdb):525 def set_trace(self, *args):526 print("new_set_trace")527 assert pdbpp.local.GLOBAL_PDB is self528 ret = super(NewPdb, self).set_trace(*args)529 assert pdbpp.local.GLOBAL_PDB is self530 return ret531 new_pdb = NewPdb()532 new_pdb.set_trace()533 check(fn, """534[NUM] > .*fn()535-> assert isinstance(pdbpp.local.GLOBAL_PDB, PdbTest)536 5 frames hidden .*537# c538new_set_trace539[NUM] .*set_trace()540-> assert pdbpp.local.GLOBAL_PDB is self541 5 frames hidden .*542# c543""")544def test_global_pdb_via_new_class_in_init_method():545 def fn():546 set_trace()547 first = pdbpp.local.GLOBAL_PDB548 assert isinstance(pdbpp.local.GLOBAL_PDB, PdbTest)549 class PdbLikePytest(object):550 @classmethod551 def init_pdb(cls):552 class NewPdb(PdbTest, pdbpp.Pdb):553 def set_trace(self, frame):554 print("new_set_trace")555 super(NewPdb, self).set_trace(frame)556 return NewPdb()557 @classmethod558 def set_trace(cls, *args, **kwargs):559 frame = sys._getframe().f_back560 pdb_ = cls.init_pdb(*args, **kwargs)561 return pdb_.set_trace(frame)562 PdbLikePytest.set_trace()563 second = pdbpp.local.GLOBAL_PDB564 assert first != second565 PdbLikePytest.set_trace()566 third = pdbpp.local.GLOBAL_PDB567 assert third == second568 check(fn, """569[NUM] > .*fn()570-> first = pdbpp.local.GLOBAL_PDB571 5 frames hidden .*572# c573new_set_trace574[NUM] > .*fn()575-> second = pdbpp.local.GLOBAL_PDB576 5 frames hidden .*577# c578new_set_trace579[NUM] > .*fn()580-> third = pdbpp.local.GLOBAL_PDB581 5 frames hidden .*582# c583""")584def test_global_pdb_via_existing_class_in_init_method():585 def fn():586 set_trace()587 first = pdbpp.local.GLOBAL_PDB588 assert isinstance(pdbpp.local.GLOBAL_PDB, PdbTest)589 class NewPdb(PdbTest, pdbpp.Pdb):590 def set_trace(self, frame):591 print("new_set_trace")592 super(NewPdb, self).set_trace(frame)593 class PdbViaClassmethod(object):594 @classmethod595 def init_pdb(cls):596 return NewPdb()597 @classmethod598 def set_trace(cls, *args, **kwargs):599 frame = sys._getframe().f_back600 pdb_ = cls.init_pdb(*args, **kwargs)601 return pdb_.set_trace(frame)602 PdbViaClassmethod.set_trace()603 second = pdbpp.local.GLOBAL_PDB604 assert first != second605 PdbViaClassmethod.set_trace()606 third = pdbpp.local.GLOBAL_PDB607 assert third == second608 check(fn, """609[NUM] > .*fn()610-> first = pdbpp.local.GLOBAL_PDB611 5 frames hidden .*612# c613new_set_trace614[NUM] > .*fn()615-> second = pdbpp.local.GLOBAL_PDB616 5 frames hidden .*617# c618new_set_trace619[NUM] > .*fn()620-> third = pdbpp.local.GLOBAL_PDB621 5 frames hidden .*622# c623""")624def test_global_pdb_can_be_skipped():625 def fn():626 set_trace()627 first = pdbpp.local.GLOBAL_PDB628 assert isinstance(first, PdbTest)629 class NewPdb(PdbTest, pdbpp.Pdb):630 def set_trace(self, *args):631 print("new_set_trace")632 assert pdbpp.local.GLOBAL_PDB is not self633 ret = super(NewPdb, self).set_trace(*args)634 assert pdbpp.local.GLOBAL_PDB is not self635 return ret636 new_pdb = NewPdb(use_global_pdb=False)637 new_pdb.set_trace()638 assert pdbpp.local.GLOBAL_PDB is not new_pdb639 set_trace(cleanup=False)640 assert pdbpp.local.GLOBAL_PDB is not new_pdb641 check(fn, """642[NUM] > .*fn()643-> first = pdbpp.local.GLOBAL_PDB644 5 frames hidden .*645# c646new_set_trace647[NUM] .*set_trace()648-> assert pdbpp.local.GLOBAL_PDB is not self649 5 frames hidden .*650# readline_ = pdbpp.local.GLOBAL_PDB.fancycompleter.config.readline651# assert readline_.get_completer() != pdbpp.local.GLOBAL_PDB.complete652# c653[NUM] > .*fn()654-> assert pdbpp.local.GLOBAL_PDB is not new_pdb655 5 frames hidden .*656# c657""")658def test_global_pdb_can_be_skipped_unit(monkeypatch_pdb_methods):659 """Same as test_global_pdb_can_be_skipped, but with mocked Pdb methods."""660 def fn():661 set_trace()662 first = pdbpp.local.GLOBAL_PDB663 assert isinstance(first, PdbTest)664 class NewPdb(PdbTest, pdbpp.Pdb):665 def set_trace(self, *args):666 print("new_set_trace")667 assert pdbpp.local.GLOBAL_PDB is not self668 ret = super(NewPdb, self).set_trace(*args)669 assert pdbpp.local.GLOBAL_PDB is not self670 return ret671 new_pdb = NewPdb(use_global_pdb=False)672 new_pdb.set_trace()673 assert pdbpp.local.GLOBAL_PDB is not new_pdb674 set_trace(cleanup=False)675 assert pdbpp.local.GLOBAL_PDB is not new_pdb676 check(fn, """677=== set_trace678new_set_trace679=== set_trace680=== set_trace681""")682def test_global_pdb_can_be_skipped_but_set():683 def fn():684 set_trace()685 first = pdbpp.local.GLOBAL_PDB686 assert isinstance(first, PdbTest)687 class NewPdb(PdbTest, pdbpp.Pdb):688 def set_trace(self, *args):689 print("new_set_trace")690 assert pdbpp.local.GLOBAL_PDB is self691 ret = super(NewPdb, self).set_trace(*args)692 assert pdbpp.local.GLOBAL_PDB is self693 return ret694 new_pdb = NewPdb(use_global_pdb=False, set_global_pdb=True)695 new_pdb.set_trace()696 assert pdbpp.local.GLOBAL_PDB is new_pdb697 set_trace(cleanup=False)698 assert pdbpp.local.GLOBAL_PDB is new_pdb699 check(fn, """700[NUM] > .*fn()701-> first = pdbpp.local.GLOBAL_PDB702 5 frames hidden .*703# c704new_set_trace705[NUM] .*set_trace()706-> assert pdbpp.local.GLOBAL_PDB is self707 5 frames hidden .*708# readline_ = pdbpp.local.GLOBAL_PDB.fancycompleter.config.readline709# assert readline_.get_completer() == pdbpp.local.GLOBAL_PDB.complete710# c711new_set_trace712[NUM] > .*fn()713-> assert pdbpp.local.GLOBAL_PDB is new_pdb714 5 frames hidden .*715# c716""")717def test_global_pdb_can_be_skipped_but_set_unit(monkeypatch_pdb_methods):718 def fn():719 set_trace()720 first = pdbpp.local.GLOBAL_PDB721 assert isinstance(first, PdbTest)722 class NewPdb(PdbTest, pdbpp.Pdb):723 def set_trace(self, *args):724 print("new_set_trace")725 assert pdbpp.local.GLOBAL_PDB is self726 ret = super(NewPdb, self).set_trace(*args)727 assert pdbpp.local.GLOBAL_PDB is self728 return ret729 new_pdb = NewPdb(use_global_pdb=False, set_global_pdb=True)730 new_pdb.set_trace()731 assert pdbpp.local.GLOBAL_PDB is new_pdb732 set_trace(cleanup=False)733 assert pdbpp.local.GLOBAL_PDB is new_pdb734 check(fn, """735=== set_trace736new_set_trace737=== set_trace738new_set_trace739=== set_trace740""")741def test_global_pdb_only_reused_for_same_class(monkeypatch_pdb_methods):742 def fn():743 class NewPdb(PdbTest, pdbpp.Pdb):744 def set_trace(self, *args):745 print("new_set_trace")746 ret = super(NewPdb, self).set_trace(*args)747 return ret748 new_pdb = NewPdb()749 new_pdb.set_trace()750 assert pdbpp.local.GLOBAL_PDB is new_pdb751 set_trace(cleanup=False)752 assert pdbpp.local.GLOBAL_PDB is not new_pdb753 # What "debug" does, for coverage.754 new_pdb = NewPdb()755 new_pdb.set_trace()756 assert pdbpp.local.GLOBAL_PDB is new_pdb757 pdbpp.local.GLOBAL_PDB._use_global_pdb_for_class = PdbTest758 set_trace(cleanup=False)759 assert pdbpp.local.GLOBAL_PDB is new_pdb760 # Explicit kwarg for coverage.761 new_pdb = NewPdb(set_global_pdb=False)762 new_pdb.set_trace()763 assert pdbpp.local.GLOBAL_PDB is not new_pdb764 check(fn, """765new_set_trace766=== set_trace767=== set_trace768new_set_trace769=== set_trace770new_set_trace771=== set_trace772new_set_trace773=== set_trace774""")775def test_global_pdb_not_reused_with_different_home(776 monkeypatch_pdb_methods, monkeypatch777):778 def fn():779 set_trace()780 first = pdbpp.local.GLOBAL_PDB781 set_trace(cleanup=False)782 assert first is pdbpp.local.GLOBAL_PDB783 monkeypatch.setenv("HOME", "something else")784 set_trace(cleanup=False)785 assert first is not pdbpp.local.GLOBAL_PDB786 check(fn, """787=== set_trace788=== set_trace789=== set_trace790""")791def test_single_question_mark():792 def fn():793 def nodoc():794 pass795 def f2(x, y):796 """Return product of x and y"""797 return x * y798 set_trace()799 a = 1800 b = 2801 c = 3802 return a+b+c803 check(fn, r"""804[NUM] > .*fn()805-> a = 1806 5 frames hidden .*807# f2808<function .*f2 at .*>809# f2?810.*Type:.*function811.*String Form:.*<function .*f2 at .*>812^[[31;01mFile:^[[00m {filename}:{lnum_f2}813.*Definition:.*f2(x, y)814.*Docstring:.*Return product of x and y815# nodoc?816.*Type:.*function817.*String Form:.*<function .*nodoc at .*>818^[[31;01mFile:^[[00m {filename}:{lnum_nodoc}819^[[31;01mDefinition:^[[00m nodoc()820# doesnotexist?821\*\*\* NameError.*822# c823 """.format(824 filename=RE_THIS_FILE_CANONICAL,825 lnum_nodoc=fn.__code__.co_firstlineno + 1,826 lnum_f2=fn.__code__.co_firstlineno + 4,827 ))828def test_double_question_mark():829 """Test do_inspect_with_source."""830 def fn():831 def f2(x, y):832 """Return product of x and y"""833 return x * y834 set_trace()835 a = 1836 b = 2837 c = 3838 return a+b+c839 check(fn, r"""840[NUM] > .*fn()841-> a = 1842 5 frames hidden .*843# f2844<function .*f2 at .*>845# f2??846.*Type:.*function847.*String Form:.*<function .*f2 at .*>848^[[31;01mFile:^[[00m {filename}849.*Definition:.*f2(x, y)850.*Docstring:.*Return product of x and y851.*Source:.*852.* def f2(x, y):853.* \"\"\"Return product of x and y\"\"\"854.* return x \* y855# doesnotexist??856\*\*\* NameError.*857# c858 """.format(859 filename=RE_THIS_FILE_CANONICAL,860 ))861def test_question_mark_unit(capsys, LineMatcher):862 _pdb = PdbTest()863 _pdb.reset()864 foo = {12: 34} # noqa: F841865 _pdb.setup(sys._getframe(), None)866 _pdb.do_inspect("foo")867 out, err = capsys.readouterr()868 LineMatcher(out.splitlines()).fnmatch_lines([869 "\x1b[31;01mString Form:\x1b[00m {12: 34}"870 ])871 _pdb.do_inspect("doesnotexist")872 out, err = capsys.readouterr()873 LineMatcher(out.splitlines()).re_match_lines([874 r"^\*\*\* NameError:",875 ])876 # Source for function, indented docstring.877 def foo():878 """doc_for_foo879 3rd line."""880 raise NotImplementedError()881 _pdb.setup(sys._getframe(), None)882 _pdb.do_inspect_with_source("foo")883 out, err = capsys.readouterr()884 LineMatcher(out.splitlines()).re_match_lines([885 r"\x1b\[31;01mDocstring:\x1b\[00m doc_for_foo",886 r"",887 r" 3rd line\.",888 r"\x1b\[31;01mSource:\x1b\[00m ",889 r" ?\d+ def foo\(\):",890 r" ?\d+ raise NotImplementedError\(\)",891 ])892 # Missing source893 _pdb.do_inspect_with_source("str.strip")894 out, err = capsys.readouterr()895 LineMatcher(out.splitlines()).fnmatch_lines([896 "\x1b[31;01mSource:\x1b[00m -",897 ])898def test_single_question_mark_with_existing_command(monkeypatch):899 def mocked_inspect(self, arg):900 print("mocked_inspect: %r" % arg)901 monkeypatch.setattr(PdbTest, "do_inspect", mocked_inspect)902 def fn():903 mp = monkeypatch # noqa: F841904 class MyClass:905 pass906 a = MyClass() # noqa: F841907 set_trace()908 check(fn, """909--Return--910[NUM] > .*fn()->None911-> set_trace()912 5 frames hidden .*913# a?914mocked_inspect: 'a'915# a.__class__?916mocked_inspect: 'a.__class__'917# !!a?918# !a?919do_shell_called: a?920\\*\\*\\* SyntaxError:921# mp.delattr(pdbpp.local.GLOBAL_PDB.__class__, "do_shell")922# !a?923\\*\\*\\* SyntaxError:924# help a925a(rgs)926.*927# c928""")929def test_up_local_vars():930 def nested():931 set_trace()932 return933 def fn():934 xx = 42 # noqa: F841935 nested()936 check(fn, """937[NUM] > .*nested()938-> return939 5 frames hidden .*940# up941[NUM] > .*fn()942-> nested()943# xx94442945# c946""")947def test_frame():948 def a():949 b()950 def b():951 c()952 def c():953 set_trace()954 return955 check(a, """956[NUM] > .*c()957-> return958 5 frames hidden .*959# f {frame_num_a}960[NUM] > .*a()961-> b()962# f963[{frame_num_a}] > .*a()964-> b()965# f 0966[ 0] > .*()967-> .*968# f -1969[{stack_len}] > .*c()970-> return971# c972 """.format(973 frame_num_a=count_frames() + 2 - 5,974 stack_len=len(traceback.extract_stack())975 ))976@pytest.mark.skipif(sys.version_info < (3, 6),977 reason="only with f-strings")978def test_fstrings(monkeypatch):979 def mocked_inspect(self, arg):980 print("mocked_inspect: %r" % arg)981 monkeypatch.setattr(PdbTest, "do_inspect", mocked_inspect)982 def f():983 set_trace()984 check(f, """985--Return--986[NUM] > .*987-> set_trace()988 5 frames hidden .*989# f"fstring"990'fstring'991# f"foo"?992mocked_inspect: 'f"foo"'993# c994""")995def test_prefixed_strings(monkeypatch):996 def mocked_inspect(self, arg):997 print("mocked_inspect: %r" % arg)998 monkeypatch.setattr(PdbTest, "do_inspect", mocked_inspect)999 def f():1000 set_trace()1001 check(1002 f,1003 """1004--Return--1005[NUM] > .*1006-> set_trace()1007 5 frames hidden .*1008# b"string"1009{bytestring!r}1010# u"string"1011{unicodestring!r}1012# r"string"1013'string'1014# b"foo"?1015mocked_inspect: 'b"foo"'1016# r"foo"?1017mocked_inspect: 'r"foo"'1018# u"foo"?1019mocked_inspect: 'u"foo"'1020# c1021""".format(bytestring=b"string", unicodestring=u"string"))1022def test_up_down_arg():1023 def a():1024 b()1025 def b():1026 c()1027 def c():1028 set_trace()1029 return1030 check(a, """1031[NUM] > .*c()1032-> return1033 5 frames hidden .*1034# up 31035[NUM] > .*runpdb()1036-> func()1037# down 11038[NUM] > .*a()1039-> b()1040# c1041""")1042def test_up_down_sticky():1043 def a():1044 b()1045 def b():1046 set_trace()1047 return1048 check(a, """1049[NUM] > .*b()1050-> return1051 5 frames hidden .*1052# sticky1053<CLEARSCREEN>1054[NUM] > .*b(), 5 frames hidden1055NUM def b():1056NUM set_trace()1057NUM -> return1058# up1059<CLEARSCREEN>1060[NUM] > .*a(), 5 frames hidden1061NUM def a()1062NUM -> b()1063# c1064""")1065def test_top_bottom():1066 def a():1067 b()1068 def b():1069 c()1070 def c():1071 set_trace()1072 return1073 check(1074 a, """1075[NUM] > .*c()1076-> return1077 5 frames hidden .*1078# top1079[ 0] > .*()1080-> .*1081# bottom1082[{stack_len}] > .*c()1083-> return1084# c1085""".format(stack_len=len(traceback.extract_stack())))1086def test_top_bottom_frame_post_mortem():1087 def fn():1088 def throws():1089 0 / 01090 def f():1091 throws()1092 try:1093 f()1094 except:1095 pdbpp.post_mortem(Pdb=PdbTest)1096 check(fn, r"""1097[2] > .*throws()1098-> 0 / 01099# top1100[0] > .*fn()1101-> f()1102# top1103\*\*\* Oldest frame1104# bottom1105[2] > .*throws()1106-> 0 / 01107# bottom1108\*\*\* Newest frame1109# frame -1 ### Same as bottom, no error.1110[2] > .*throws()1111-> 0 / 01112# frame -21113[1] > .*f()1114-> throws()1115# frame -31116\*\*\* Out of range1117# c1118""")1119def test_parseline():1120 def fn():1121 c = 421122 set_trace()1123 return c1124 check(fn, """1125[NUM] > .*fn()1126-> return c1127 5 frames hidden .*1128# c1129421130# !c1131do_shell_called: 'c'1132421133# r = 51134# r113551136# r = 61137# r113861139# !!c1140""")1141def test_parseline_with_rc_commands(tmpdir):1142 """Test that parseline handles execution of rc lines during setup."""1143 with tmpdir.as_cwd():1144 with open(".pdbrc", "w") as f:1145 f.writelines([1146 "p 'readrc'\n",1147 "alias myalias print(%1)\n",1148 ])1149 def fn():1150 alias = "trigger" # noqa: F8411151 set_trace(readrc=True)1152 check(fn, """1153--Return--1154'readrc'1155[NUM] > .*fn()->None1156-> set_trace(readrc=True)1157 5 frames hidden .*1158# alias myalias1159myalias = print(%1)1160# !!alias myalias1161myalias = print(%1)1162# myalias 421163421164# c1165""")1166def test_parseline_with_existing_command():1167 def fn():1168 c = 421169 debug = True # noqa: F8411170 class r:1171 text = "r.text"1172 set_trace()1173 return c1174 check(fn, """1175[NUM] > .*fn()1176-> return c1177 5 frames hidden .*1178# print(pdbpp.local.GLOBAL_PDB.parseline("foo = "))1179('foo', '=', 'foo =')1180# print(pdbpp.local.GLOBAL_PDB.parseline("c = "))1181(None, None, 'c = ')1182# print(pdbpp.local.GLOBAL_PDB.parseline("a = "))1183(None, None, 'a = ')1184# print(pdbpp.local.GLOBAL_PDB.parseline("list()"))1185(None, None, 'list()')1186# print(pdbpp.local.GLOBAL_PDB.parseline("next(my_iter)"))1187(None, None, 'next(my_iter)')1188# c1189421190# debug print(1)1191ENTERING RECURSIVE DEBUGGER1192[1] > <string>(1)<module>()1193(#) cont119411195LEAVING RECURSIVE DEBUGGER1196# debug1197True1198# r.text1199'r.text'1200# cont1201""")1202def test_parseline_remembers_smart_command_escape():1203 def fn():1204 n = 421205 set_trace()1206 n = 431207 n = 441208 return n1209 check(fn, """1210[NUM] > .*fn()1211-> n = 431212 5 frames hidden .*1213# n1214421215# !!n1216[NUM] > .*fn()1217-> n = 441218 5 frames hidden .*1219# 1220[NUM] > .*fn()1221-> return n1222 5 frames hidden .*1223# n1224441225# c1226""") # noqa: W2911227def test_args_name():1228 def fn():1229 args = 421230 set_trace()1231 return args1232 check(fn, """1233[NUM] > .*fn()1234-> return args1235 5 frames hidden .*1236# args1237421238# c1239""")1240def lineno():1241 """Returns the current line number in our program."""1242 return inspect.currentframe().f_back.f_lineno1243def test_help():1244 instance = PdbTest()1245 instance.stdout = StringIO()1246 help_params = [1247 ("", r"Documented commands \(type help <topic>\):"),1248 ("EOF", "Handles the receipt of EOF as a command."),1249 ("a", "Print the argument"),1250 ("alias", "an alias"),1251 ("args", "Print the argument"),1252 ("b", "set a break"),1253 ("break", "set a break"),1254 ("bt", "Print a stack trace"),1255 ("c", "Continue execution, only stop when a breakpoint"),1256 ("cl", "clear all breaks"),1257 ("clear", "clear all breaks"),1258 ("commands", "Specify a list of commands for breakpoint"),1259 ("condition", "must evaluate to true"),1260 ("cont", "Continue execution, only stop when a breakpoint"),1261 ("continue", "Continue execution, only stop when a breakpoint"),1262 ("d", "Move the current frame .* down"),1263 ("debug", "Enter a recursive debugger"),1264 ("disable", "Disables the breakpoints"),1265 ("display", "Add expression to the display list"),1266 ("down", "Move the current frame .* down"),1267 ("ed", "Open an editor"),1268 ("edit", "Open an editor"),1269 ("enable", "Enables the breakpoints"),1270 ("exit", "Quit from the debugger."),1271 ("h", "h(elp)"),1272 ("help", "h(elp)"),1273 ("hf_hide", "hide hidden frames"),1274 ("hf_unhide", "unhide hidden frames"),1275 ("ignore", "ignore count for the given breakpoint"),1276 ("interact", "Start an interactive interpreter"),1277 ("j", "Set the next line that will be executed."),1278 ("jump", "Set the next line that will be executed."),1279 ("l", "List source code for the current file."),1280 ("list", "List source code for the current file."),1281 ("ll", "List source code for the current function."),1282 ("longlist", "List source code for the current function."),1283 ("n", "Continue execution until the next line"),1284 ("next", "Continue execution until the next line"),1285 ("p", "Print the value of the expression"),1286 ("pp", "Pretty-print the value of the expression."),1287 ("q", "Quit from the debugger."),1288 ("quit", "Quit from the debugger."),1289 ("r", "Continue execution until the current function returns."),1290 ("restart", "Restart the debugged python program."),1291 ("return", "Continue execution until the current function returns."),1292 ("run", "Restart the debugged python program"),1293 ("s", "Execute the current line, stop at the first possible occasion"),1294 ("step", "Execute the current line, stop at the first possible occasion"),1295 ("sticky", "Toggle sticky mode"),1296 ("tbreak", "arguments as break"),1297 ("track", "track expression"),1298 ("u", "Move the current frame .* up"),1299 ("unalias", "specified alias."),1300 ("undisplay", "Remove expression from the display list"),1301 ("unt", "until the line"),1302 ("until", "until the line"),1303 ("up", "Move the current frame .* up"),1304 ("w", "Print a stack trace"),1305 ("whatis", "Prints? the type of the argument."),1306 ("where", "Print a stack trace"),1307 ("hidden_frames", 'Some frames might be marked as "hidden"'),1308 ("exec", r"Execute the \(one-line\) statement"),1309 ("hf_list", r"\*\*\* No help"),1310 ("paste", r"\*\*\* No help"),1311 ("put", r"\*\*\* No help"),1312 ("retval", r"\*\*\* No help|return value"),1313 ("rv", r"\*\*\* No help|return value"),1314 ("source", r"\*\*\* No help"),1315 ("unknown_command", r"\*\*\* No help"),1316 ("help", "print the list of available commands."),1317 ]1318 # Redirect sys.stdout because Python 2 pdb.py has `print >>self.stdout` for1319 # some functions and plain ol' `print` for others.1320 oldstdout = sys.stdout1321 sys.stdout = instance.stdout1322 errors = []1323 try:1324 for command, expected_regex in help_params:1325 instance.do_help(command)1326 output = instance.stdout.getvalue()1327 if not re.search(expected_regex, output):1328 errors.append(command)1329 finally:1330 sys.stdout = oldstdout1331 if errors:1332 pytest.fail("unexpected help for: {}".format(", ".join(errors)))1333def test_shortlist():1334 def fn():1335 a = 11336 set_trace(Config=ConfigTest)1337 return a1338 check(fn, """1339[NUM] > .*fn()1340-> return a1341 5 frames hidden .*1342# l {line_num}, 31343NUM +\t def fn():1344NUM +\t a = 11345NUM +\t set_trace(Config=ConfigTest)1346NUM +-> return a1347# c1348""".format(line_num=fn.__code__.co_firstlineno))1349def test_shortlist_with_pygments_and_EOF():1350 def fn():1351 a = 11352 set_trace(Config=ConfigWithPygments)1353 return a1354 check(fn, """1355[NUM] > .*fn()1356-> ^[[38;5;28;01mreturn^[[39;00m a1357 5 frames hidden .*1358# l {line_num}, 31359[EOF]1360# c1361""".format(line_num=100000))1362def test_shortlist_with_highlight_and_EOF():1363 def fn():1364 a = 11365 set_trace(Config=ConfigWithHighlight)1366 return a1367 check(fn, """1368[NUM] > .*fn()1369-> return a1370 5 frames hidden .*1371# l {line_num}, 31372[EOF]1373# c1374""".format(line_num=100000))1375@pytest.mark.parametrize('config', [ConfigWithPygments, ConfigWithPygmentsNone])1376def test_shortlist_with_pygments(config, monkeypatch):1377 def fn():1378 a = 11379 set_trace(Config=config)1380 return a1381 calls = []1382 orig_get_func = pdbpp.Pdb._get_source_highlight_function1383 def check_calls(self):1384 orig_highlight = orig_get_func(self)1385 calls.append(["get", self])1386 def new_highlight(src):1387 calls.append(["highlight", src])1388 return orig_highlight(src)1389 return new_highlight1390 monkeypatch.setattr(pdbpp.Pdb, "_get_source_highlight_function", check_calls)1391 check(fn, """1392[NUM] > .*fn()1393-> ^[[38;5;28;01mreturn^[[39;00m a1394 5 frames hidden .*1395# l {line_num}, 51396NUM +\t$1397NUM +\t ^[[38;5;28;01mdef^[[39;00m ^[[38;5;21mfn^[[39m():1398NUM +\t a ^[[38;5;241m=^[[39m ^[[38;5;241m1^[[39m1399NUM +\t set_trace(Config^[[38;5;241m=^[[39mconfig)1400NUM +\t$1401NUM +->\t ^[[38;5;28;01mreturn^[[39;00m a1402# c1403""".format(line_num=fn.__code__.co_firstlineno - 1))1404 assert len(calls) == 3, calls1405def test_shortlist_with_partial_code():1406 """Highlights the whole file, to handle partial docstring etc."""1407 def fn():1408 """1409 11410 21411 31412 """1413 a = 11414 set_trace(Config=ConfigWithPygments)1415 return a1416 check(fn, """1417[NUM] > .*fn()1418-> ^[[38;5;28;01mreturn^[[39;00m a1419 5 frames hidden .*1420# l1421NUM \t^[[38;5;124.*m 2^[[39.*m1422NUM \t^[[38;5;124.*m 3^[[39.*m1423NUM \t^[[38;5;124.*m \"\"\"^[[39.*m1424NUM \t a ^[[38;5;241m=^[[39m ^[[38;5;241m1^[[39m1425NUM \t set_trace(Config^[[38;5;241m=^[[39mConfigWithPygments)1426NUM ->\t ^[[38;5;28;01mreturn^[[39;00m a1427NUM \t$1428NUM \t check(fn, ^[[38;5;124m\"\"\"^[[39m1429NUM \t^[[38;5;124m.* > .*fn()^[[39m1430NUM \t^[[38;5;124m-> ^[[38;5;28;01mreturn^[[39;00m a^[[39m1431NUM \t^[[38;5;124m 5 frames hidden .*^[[39m1432# c1433""")1434def test_truncated_source_with_pygments():1435 def fn():1436 """some docstring longer than maxlength for truncate_long_lines, which is 80"""1437 a = 11438 set_trace(Config=ConfigWithPygments)1439 return a1440 check(fn, """1441[NUM] > .*fn()1442-> ^[[38;5;28;01mreturn^[[39;00m a1443 5 frames hidden .*1444# l {line_num}, 51445NUM +\t$1446NUM +\t ^[[38;5;28;01mdef^[[39;00m ^[[38;5;21mfn^[[39m():1447NUM +\t ^[[38;5;124.*m\"\"\"some docstring longer than maxlength for truncate_long_lines, which is 80\"\"\"^[[39.*m1448NUM +\t a ^[[38;5;241m=^[[39m ^[[38;5;241m1^[[39m1449NUM +\t set_trace(Config^[[38;5;241m=^[[39mConfigWithPygments)1450NUM +\t$1451# sticky1452<CLEARSCREEN>1453[NUM] > .*fn(), 5 frames hidden1454NUM + ^[[38;5;28;01mdef^[[39;00m ^[[38;5;21mfn^[[39m():1455NUM + ^[[38;5;124.*m\"\"\"some docstring longer than maxlength for truncate_long_lines^[[39.*m1456NUM + a ^[[38;5;241m=^[[39m ^[[38;5;241m1^[[39m1457NUM + set_trace(Config^[[38;5;241m=^[[39mConfigWithPygments)1458NUM +$1459NUM +-> ^[[38;5;28;01mreturn^[[39;00m a1460# c1461""".format(line_num=fn.__code__.co_firstlineno - 1)) # noqa: E5011462def test_truncated_source_with_pygments_and_highlight():1463 def fn():1464 """some docstring longer than maxlength for truncate_long_lines, which is 80"""1465 a = 11466 set_trace(Config=ConfigWithPygmentsAndHighlight)1467 return a1468 check(fn, """1469[NUM] > .*fn()1470-> ^[[38;5;28;01mreturn^[[39;00m a1471 5 frames hidden .*1472# l {line_num}, 51473<COLORNUM> +\t$1474<COLORNUM> +\t ^[[38;5;28;01mdef^[[39;00m ^[[38;5;21mfn^[[39m():1475<COLORNUM> +\t ^[[38;5;124.*m\"\"\"some docstring longer than maxlength for truncate_long_lines, which is 80\"\"\"^[[39.*m1476<COLORNUM> +\t a ^[[38;5;241m=^[[39m ^[[38;5;241m1^[[39m1477<COLORNUM> +\t set_trace(Config^[[38;5;241m=^[[39mConfigWithPygmentsAndHighlight)1478<COLORNUM> +\t$1479# sticky1480<CLEARSCREEN>1481[NUM] > .*fn(), 5 frames hidden1482<COLORNUM> + ^[[38;5;28;01mdef^[[39;00m ^[[38;5;21mfn^[[39m():1483<COLORNUM> + ^[[38;5;124.*m\"\"\"some docstring longer than maxlength for truncate_long_lines<PYGMENTSRESET>1484<COLORNUM> + a ^[[38;5;241m=^[[39m ^[[38;5;241m1^[[39m1485<COLORNUM> + set_trace(Config^[[38;5;241m=^[[39mConfigWithPygmentsAndHighlight)1486<COLORNUM> +$1487<COLORCURLINE> +-> ^[[38;5;28;01;44mreturn<PYGMENTSRESET> a ^[[00m1488# c1489""".format(line_num=fn.__code__.co_firstlineno - 1)) # noqa: E5011490def test_shortlist_with_highlight():1491 def fn():1492 a = 11493 set_trace(Config=ConfigWithHighlight)1494 return a1495 check(fn, """1496[NUM] > .*fn()1497-> return a1498 5 frames hidden .*1499# l {line_num}, 41500<COLORNUM> +\t def fn():1501<COLORNUM> +\t a = 11502<COLORNUM> +\t set_trace(Config=ConfigWithHighlight)1503<COLORNUM> +\t$1504<COLORNUM> +->\t return a1505# c1506""".format(line_num=fn.__code__.co_firstlineno))1507def test_shortlist_without_arg():1508 """Ensure that forget was called for lineno."""1509 def fn():1510 a = 11511 set_trace(Config=ConfigTest)1512 return a1513 check(fn, """1514[NUM] > .*fn()1515-> return a1516 5 frames hidden .*1517# l1518NUM \tdef test_shortlist_without_arg():1519NUM \t \"""Ensure that forget was called for lineno.\"""1520.*1521.*1522.*1523.*1524.*1525.*1526.*1527NUM \t-> return a1528NUM \t 5 frames hidden .*1529# c1530""")1531def test_shortlist_heuristic():1532 def fn():1533 a = 11534 set_trace(Config=ConfigTest)1535 return a1536 check(fn, """1537[NUM] > .*fn()1538-> return a1539 5 frames hidden .*1540# list {line_num}, 31541NUM \t def fn():1542NUM \t a = 11543NUM \t set_trace(Config=ConfigTest)1544NUM -> return a1545# list(range(4))1546[0, 1, 2, 3]1547# c1548""".format(line_num=fn.__code__.co_firstlineno))1549def test_shortlist_with_second_set_trace_resets_lineno():1550 def fn():1551 def f1():1552 set_trace(cleanup=False)1553 set_trace()1554 f1()1555 check(fn, r"""1556[NUM] > .*fn()1557-> f1()1558 5 frames hidden .*1559# l {line_num}, 21560NUM \t def fn():1561NUM \t def f1():1562NUM \t set_trace(cleanup=False)1563# import pdb; pdbpp.local.GLOBAL_PDB.lineno1564{set_lineno}1565# c1566--Return--1567[NUM] > .*f1()->None1568-> set_trace(cleanup=False)1569 5 frames hidden .*1570# import pdb; pdbpp.local.GLOBAL_PDB.lineno1571# c1572 """.format(1573 line_num=fn.__code__.co_firstlineno,1574 set_lineno=fn.__code__.co_firstlineno + 2,1575 ))1576def test_longlist():1577 def fn():1578 a = 11579 set_trace()1580 return a1581 check(fn, """1582[NUM] > .*fn()1583-> return a1584 5 frames hidden .*1585# ll1586NUM def fn():1587NUM a = 11588NUM set_trace()1589NUM -> return a1590# c1591""")1592def test_longlist_displays_whole_function():1593 """`ll` displays the whole function (no cutoff)."""1594 def fn():1595 set_trace()1596 a = 11597 a = 11598 a = 11599 a = 11600 a = 11601 a = 11602 a = 11603 a = 11604 a = 11605 return a1606 check(fn, """1607[NUM] > .*fn()1608-> a = 11609 5 frames hidden (try 'help hidden_frames')1610# ll1611NUM def fn():1612NUM set_trace()1613NUM -> a = 11614NUM a = 11615NUM a = 11616NUM a = 11617NUM a = 11618NUM a = 11619NUM a = 11620NUM a = 11621NUM a = 11622NUM return a1623# c1624""", terminal_size=(len(__file__) + 50, 10))1625class TestListWithChangedSource:1626 """Uses the cached (current) code."""1627 @pytest.fixture(autouse=True)1628 def setup_myfile(self, testdir):1629 testdir.makepyfile(1630 myfile="""1631 from pdbpp import set_trace1632 def rewrite_file():1633 with open(__file__, "w") as f:1634 f.write("something completely different")1635 def after_settrace():1636 import linecache1637 linecache.checkcache()1638 def fn():1639 set_trace()1640 after_settrace()1641 set_trace()1642 a = 31643 """)1644 testdir.monkeypatch.setenv("PDBPP_COLORS", "0")1645 testdir.syspathinsert()1646 def test_list_with_changed_source(self):1647 from myfile import fn1648 check(fn, r"""1649 [NUM] > .*fn()1650 -> after_settrace()1651 5 frames hidden (try 'help hidden_frames')1652 (Pdb++) l1653 NUM \t import linecache$1654 NUM \t linecache.checkcache()$1655 NUM \t$1656 NUM \tdef fn():1657 NUM \t set_trace()1658 NUM ->\t after_settrace()1659 NUM \t set_trace()1660 NUM \t a = 31661 [EOF]1662 (Pdb++) rewrite_file()1663 (Pdb++) c1664 [NUM] > .*fn()1665 -> a = 31666 5 frames hidden (try 'help hidden_frames')1667 (Pdb++) l1668 NUM \t1669 NUM \tdef fn():1670 NUM \t set_trace()1671 NUM \t after_settrace()1672 NUM \t set_trace()1673 NUM ->\t a = 31674 [EOF]1675 (Pdb++) c1676 """)1677 def test_longlist_with_changed_source(self):1678 from myfile import fn1679 check(fn, r"""1680 [NUM] > .*fn()1681 -> after_settrace()1682 5 frames hidden (try 'help hidden_frames')1683 (Pdb++) ll1684 NUM def fn():1685 NUM set_trace()1686 NUM -> after_settrace()1687 NUM set_trace()1688 NUM a = 31689 (Pdb++) rewrite_file()1690 (Pdb++) c1691 [NUM] > .*fn()1692 -> a = 31693 5 frames hidden (try 'help hidden_frames')1694 (Pdb++) ll1695 NUM def fn():1696 NUM set_trace()1697 NUM after_settrace()1698 NUM set_trace()1699 NUM -> a = 31700 (Pdb++) c1701 """)1702def test_longlist_with_highlight():1703 def fn():1704 a = 11705 set_trace(Config=ConfigWithHighlight)1706 return a1707 check(fn, r"""1708[NUM] > .*fn()1709-> return a1710 5 frames hidden .*1711# ll1712<COLORNUM> def fn():1713<COLORNUM> a = 11714<COLORNUM> set_trace(Config=ConfigWithHighlight)1715<COLORCURLINE> +-> return a ^[[00m$1716# c1717""") # noqa: E5011718def test_display():1719 def fn():1720 a = 11721 set_trace()1722 b = 1 # noqa: F8411723 a = 21724 a = 31725 return a1726 check(fn, """1727[NUM] > .*fn()1728-> b = 11729 5 frames hidden .*1730# display a1731# n1732[NUM] > .*fn()1733-> a = 21734 5 frames hidden .*1735# n1736[NUM] > .*fn()1737-> a = 31738 5 frames hidden .*1739a: 1 --> 21740# undisplay a1741# n1742[NUM] > .*fn()1743-> return a1744 5 frames hidden .*1745# c1746""")1747def test_display_undefined():1748 def fn():1749 set_trace()1750 b = 421751 return b1752 check(fn, """1753[NUM] > .*fn()1754-> b = 421755 5 frames hidden .*1756# display b1757# n1758[NUM] > .*fn()1759-> return b1760 5 frames hidden .*1761b: <undefined> --> 421762# c1763""")1764def test_sticky():1765 def fn():1766 set_trace()1767 a = 11768 b = 2 # noqa: F8411769 c = 3 # noqa: F8411770 return a1771 check(fn, """1772[NUM] > .*fn()1773-> a = 11774 5 frames hidden .*1775# sticky1776<CLEARSCREEN>1777[NUM] > .*fn(), 5 frames hidden1778NUM def fn():1779NUM set_trace()1780NUM -> a = 11781NUM b = 21782NUM c = 31783NUM return a1784# n1785<CLEARSCREEN>1786[NUM] > .*fn(), 5 frames hidden1787NUM def fn():1788NUM set_trace()1789NUM a = 11790NUM -> b = 21791NUM c = 31792NUM return a1793# sticky1794# n1795[NUM] > .*fn()1796-> c = 31797 5 frames hidden .*1798# c1799""")1800def test_sticky_resets_cls():1801 def fn():1802 set_trace()1803 a = 11804 print(a)1805 set_trace(cleanup=False)1806 return a1807 check(fn, """1808[NUM] > .*fn()1809-> a = 11810 5 frames hidden .*1811# sticky1812<CLEARSCREEN>1813[NUM] > .*fn(), 5 frames hidden1814NUM def fn():1815NUM set_trace()1816NUM -> a = 11817NUM print(a)1818NUM set_trace(cleanup=False)1819NUM return a1820# c182111822[NUM] > .*fn(), 5 frames hidden1823NUM def fn():1824NUM set_trace()1825NUM a = 11826NUM print(a)1827NUM set_trace(cleanup=False)1828NUM -> return a1829# n1830<CLEARSCREEN><PY27_MSG>1831[NUM] > .*fn()->1, 5 frames hidden1832NUM def fn():1833NUM set_trace()1834NUM a = 11835NUM print(a)1836NUM set_trace(cleanup=False)1837NUM -> return a1838 return 11839# c1840""")1841def test_sticky_with_same_frame():1842 def fn():1843 def inner(cleanup):1844 set_trace(cleanup=cleanup)1845 print(cleanup)1846 for cleanup in (True, False):1847 inner(cleanup)1848 check(fn, """1849[NUM] > .*inner()1850-> print(cleanup)1851 5 frames hidden (try 'help hidden_frames')1852# sticky1853<CLEARSCREEN>1854[NUM] > .*inner(), 5 frames hidden1855NUM def inner(cleanup):1856NUM set_trace(cleanup=cleanup)1857NUM -> print(cleanup)1858# n1859<CLEARSCREEN>1860True<PY27_MSG>1861[NUM] > .*inner()->None, 5 frames hidden1862NUM def inner(cleanup):1863NUM set_trace(cleanup=cleanup)1864NUM -> print(cleanup)1865 return None1866# c1867[NUM] > .*inner(), 5 frames hidden1868NUM def inner(cleanup):1869NUM set_trace(cleanup=cleanup)1870NUM -> print(cleanup)1871# n1872<CLEARSCREEN>1873False<PY27_MSG>1874[NUM] > .*inner()->None, 5 frames hidden1875NUM def inner(cleanup):1876NUM set_trace(cleanup=cleanup)1877NUM -> print(cleanup)1878 return None1879# c1880""")1881def test_sticky_range():1882 def fn():1883 set_trace()1884 a = 11885 b = 2 # noqa: F8411886 c = 3 # noqa: F8411887 return a1888 _, lineno = inspect.getsourcelines(fn)1889 start = lineno + 11890 end = lineno + 31891 check(fn, """1892[NUM] > .*fn()1893-> a = 11894 5 frames hidden .*1895# sticky %d %d1896<CLEARSCREEN>1897[NUM] > .*fn(), 5 frames hidden1898%d \\s+ set_trace()1899NUM -> a = 11900NUM b = 21901# c1902""" % (start, end, start))1903def test_sticky_by_default():1904 class MyConfig(ConfigTest):1905 sticky_by_default = True1906 def fn():1907 set_trace(Config=MyConfig)1908 a = 11909 b = 2 # noqa: F8411910 c = 3 # noqa: F8411911 return a1912 check(fn, """1913[NUM] > .*fn(), 5 frames hidden1914NUM def fn():1915NUM set_trace(Config=MyConfig)1916NUM -> a = 11917NUM b = 21918NUM c = 31919NUM return a1920# n1921<CLEARSCREEN>1922[NUM] > .*fn(), 5 frames hidden1923NUM def fn():1924NUM set_trace(Config=MyConfig)1925NUM a = 11926NUM -> b = 21927NUM c = 31928NUM return a1929# c1930""")1931def test_sticky_by_default_with_use_pygments_auto():1932 class MyConfig(ConfigTest):1933 sticky_by_default = True1934 use_pygments = None1935 def fn():1936 set_trace(Config=MyConfig)1937 a = 11938 return a1939 check(fn, """1940[NUM] > .*fn(), 5 frames hidden1941NUM ^[[38;5;28;01mdef^[[39;00m ^[[38;5;21mfn^[[39m():1942NUM set_trace(Config^[[38;5;241m=^[[39mMyConfig)1943NUM -> a ^[[38;5;241m=^[[39m ^[[38;5;241m1^[[39m1944NUM ^[[38;5;28;01mreturn^[[39;00m a1945# c1946""")1947def test_sticky_dunder_exception():1948 """Test __exception__ being displayed in sticky mode."""1949 def fn():1950 def raises():1951 raise InnerTestException()1952 set_trace()1953 raises()1954 check(fn, """1955[NUM] > .*fn()1956-> raises()1957 5 frames hidden (try 'help hidden_frames')1958# n1959.*InnerTestException.* ### via pdbpp.Pdb.user_exception (differs on py3/py27)1960[NUM] > .*fn()1961-> raises()1962 5 frames hidden .*1963# sticky1964<CLEARSCREEN>1965[NUM] > {filename}(NUM)fn(), 5 frames hidden1966NUM def fn():1967NUM def raises():1968NUM raise InnerTestException()1969NUM1970NUM set_trace(.*)1971NUM -> raises()1972InnerTestException:1973# c1974 """.format(1975 filename=RE_THIS_FILE_CANONICAL,1976 ))1977def test_sticky_dunder_exception_with_highlight():1978 """Test __exception__ being displayed in sticky mode."""1979 def fn():1980 def raises():1981 raise InnerTestException()1982 set_trace(Config=ConfigWithHighlight)1983 raises()1984 check(fn, """1985[NUM] > .*fn()1986-> raises()1987 5 frames hidden (try 'help hidden_frames')1988# n1989.*InnerTestException.* ### via pdbpp.Pdb.user_exception (differs on py3/py27)1990[NUM] > .*fn()1991-> raises()1992 5 frames hidden .*1993# sticky1994<CLEARSCREEN>1995[NUM] > <COLORFNAME>{filename}<COLORRESET>(<COLORNUM>)fn(), 5 frames hidden1996<COLORNUM> def fn():1997<COLORNUM> def raises():1998<COLORNUM> raise InnerTestException()1999<COLORNUM>2000<COLORNUM> set_trace(.*)2001<COLORCURLINE> -> raises().*2002<COLORLNUM>InnerTestException: <COLORRESET>2003# c2004 """.format(2005 filename=RE_THIS_FILE_CANONICAL,2006 ))2007def test_format_exc_for_sticky():2008 _pdb = PdbTest()2009 f = _pdb._format_exc_for_sticky2010 assert f((Exception, Exception())) == "Exception: "2011 exc_from_str = Exception("exc_from_str")2012 class UnprintableExc:2013 def __str__(self):2014 raise exc_from_str2015 assert f((UnprintableExc, UnprintableExc())) == (2016 "UnprintableExc: (unprintable exception: %r)" % exc_from_str2017 )2018 class UnprintableExc:2019 def __str__(self):2020 class RaisesInRepr(Exception):2021 def __repr__(self):2022 raise Exception()2023 raise RaisesInRepr()2024 assert f((UnprintableExc, UnprintableExc())) == (2025 "UnprintableExc: (unprintable exception)"2026 )2027 assert f((1, 3, 3)) == 'pdbpp: got unexpected __exception__: (1, 3, 3)'2028def test_sticky_dunder_return():2029 """Test __return__ being displayed in sticky mode."""2030 def fn():2031 def returns():2032 return 40 + 22033 set_trace()2034 returns()2035 check(fn, """2036[NUM] > .*fn()2037-> returns()2038 5 frames hidden (try 'help hidden_frames')2039# s2040--Call--2041[NUM] > .*returns()2042-> def returns()2043 5 frames hidden .*2044# sticky2045<CLEARSCREEN>2046[NUM] > .*(NUM)returns(), 5 frames hidden2047NUM -> def returns():2048NUM return 40 \\+ 22049# retval2050\\*\\*\\* Not yet returned!2051# r2052<CLEARSCREEN><PY27_MSG>2053[NUM] > {filename}(NUM)returns()->42, 5 frames hidden2054NUM def returns():2055NUM -> return 40 \\+ 22056 return 422057# retval2058422059# c2060 """.format(2061 filename=RE_THIS_FILE_CANONICAL,2062 ))2063def test_sticky_with_user_exception():2064 def fn():2065 def throws():2066 raise InnerTestException()2067 set_trace()2068 throws()2069 check(fn, """2070[NUM] > .*fn()2071-> throws()2072 5 frames hidden (try 'help hidden_frames')2073# s2074--Call--2075[NUM] > .*throws()2076-> def throws():2077 5 frames hidden .*2078# sticky2079<CLEARSCREEN>2080[NUM] > .*throws(), 5 frames hidden2081NUM -> def throws():2082NUM raise InnerTestException()2083# n2084<CLEARSCREEN>2085[NUM] > .*throws(), 5 frames hidden2086NUM def throws():2087NUM -> raise InnerTestException()2088# n2089<CLEARSCREEN><PY27_MSG>2090[NUM] > .*throws(), 5 frames hidden2091NUM def throws():2092NUM -> raise InnerTestException()2093InnerTestException:2094# c2095""")2096def test_sticky_last_value():2097 """sys.last_value is displayed in sticky mode."""2098 def outer():2099 try:2100 raise ValueError("very long excmsg\n" * 10)2101 except ValueError:2102 sys.last_value, sys.last_traceback = sys.exc_info()[1:]2103 def fn():2104 outer()2105 set_trace()2106 __exception__ = "foo" # noqa: F8412107 set_trace(cleanup=False)2108 expected = r"""2109[NUM] > .*fn()2110-> __exception__ = "foo"2111 5 frames hidden (try 'help hidden_frames')2112# sticky2113<CLEARSCREEN>2114[NUM] > .*fn(), 5 frames hidden2115NUM def fn():2116NUM outer()2117NUM set_trace()2118NUM2119NUM -> __exception__ = "foo" # noqa: F8412120NUM set_trace(cleanup=False)2121ValueError: very long excmsg\\nvery long excmsg\\nvery long eâ¦2122# c2123<PY27_MSG>[NUM] > .*fn()->None, 5 frames hidden2124NUM def fn():2125NUM outer()2126NUM set_trace()2127NUM2128NUM __exception__ = "foo" # noqa: F8412129NUM -> set_trace(cleanup=False)2130pdbpp: got unexpected __exception__: 'foo'2131# c2132"""2133 saved = sys.exc_info()[1:]2134 try:2135 check(fn, expected, terminal_size=(60, 20))2136 finally:2137 sys.last_value, sys.last_traceback = saved2138def test_sticky_dunder_return_with_highlight():2139 class Config(ConfigWithHighlight, ConfigWithPygments):2140 pass2141 def fn():2142 def returns():2143 return 40 + 22144 set_trace(Config=Config)2145 returns()2146 expected, lines = run_func(fn, '# s\n# sticky\n# r\n# retval\n# c')2147 assert lines[-4:] == [2148 '^[[36;01m return 42^[[00m',2149 '# retval',2150 '42',2151 '# c',2152 ]2153 colored_cur_lines = [2154 x for x in lines2155 if x.startswith('^[[44m^[[36;01;44m') and '->' in x2156 ]2157 assert len(colored_cur_lines) == 22158def test_sticky_cutoff_with_tail():2159 class MyConfig(ConfigTest):2160 sticky_by_default = True2161 def fn():2162 set_trace(Config=MyConfig)2163 print(1)2164 # 12165 # 22166 # 32167 return2168 check(fn, """2169[NUM] > .*fn(), 5 frames hidden2170NUM def fn():2171NUM set_trace(Config=MyConfig)2172NUM -> print(1)2173NUM # 12174NUM # 22175...2176# c217712178""", terminal_size=(len(__file__) + 50, 10))2179def test_sticky_cutoff_with_head():2180 class MyConfig(ConfigTest):2181 sticky_by_default = True2182 def fn():2183 # 12184 # 22185 # 32186 # 42187 # 52188 set_trace(Config=MyConfig)2189 print(1)2190 return2191 check(fn, """2192[NUM] > .*fn(), 5 frames hidden2193...2194NUM # 42195NUM # 52196NUM set_trace(Config=MyConfig)2197NUM -> print(1)2198NUM return2199# c220012201""", terminal_size=(len(__file__) + 50, 10))2202def test_sticky_cutoff_with_head_and_tail():2203 class MyConfig(ConfigTest):2204 sticky_by_default = True2205 def fn():2206 # 12207 # 22208 # 32209 set_trace(Config=MyConfig)2210 print(1)2211 # 12212 # 22213 # 32214 return2215 check(fn, """2216[NUM] > .*fn(), 5 frames hidden2217...2218NUM set_trace(Config=MyConfig)2219NUM -> print(1)2220NUM # 12221NUM # 22222...2223# c222412225""", terminal_size=(len(__file__) + 50, 10))2226def test_sticky_cutoff_with_long_head_and_tail():2227 class MyConfig(ConfigTest):2228 sticky_by_default = True2229 def fn():2230 # 12231 # 22232 # 32233 # 42234 # 52235 # 62236 # 72237 # 82238 # 92239 # 102240 set_trace(Config=MyConfig)2241 print(1)2242 # 12243 # 22244 # 32245 # 42246 # 52247 # 62248 # 72249 # 82250 # 92251 # 102252 # 112253 # 122254 # 132255 # 142256 # 152257 return2258 check(fn, """2259[NUM] > .*fn(), 5 frames hidden2260...2261NUM # 82262NUM # 92263NUM # 102264NUM set_trace(Config=MyConfig)2265NUM -> print(1)2266NUM # 12267NUM # 22268NUM # 32269NUM # 42270...2271# c227212273""", terminal_size=(len(__file__) + 50, 15))2274def test_sticky_cutoff_with_decorator():2275 class MyConfig(ConfigTest):2276 sticky_by_default = True2277 def deco(f):2278 return f2279 @deco2280 def fn():2281 # 12282 # 22283 # 32284 # 42285 # 52286 set_trace(Config=MyConfig)2287 print(1)2288 return2289 check(fn, """2290[NUM] > .*fn(), 5 frames hidden2291NUM @deco2292...2293NUM # 52294NUM set_trace(Config=MyConfig)2295NUM -> print(1)2296NUM return2297# c229812299""", terminal_size=(len(__file__) + 50, 10))2300def test_sticky_cutoff_with_many_decorators():2301 class MyConfig(ConfigTest):2302 sticky_by_default = True2303 def deco(f):2304 return f2305 @deco2306 @deco2307 @deco2308 @deco2309 @deco2310 @deco2311 @deco2312 @deco2313 def fn():2314 # 12315 # 22316 # 32317 # 42318 # 52319 set_trace(Config=MyConfig)2320 print(1)2321 return2322 check(fn, """2323[NUM] > .*fn(), 5 frames hidden2324NUM @deco2325...2326NUM @deco2327...2328NUM -> print(1)2329NUM return2330# c233112332""", terminal_size=(len(__file__) + 50, 10))2333def test_sticky_cutoff_with_decorator_colored():2334 class MyConfig(ConfigWithPygmentsAndHighlight):2335 sticky_by_default = True2336 def deco(f):2337 return f2338 @deco2339 @deco2340 def fn():2341 # 12342 # 22343 # 32344 # 42345 # 52346 set_trace(Config=MyConfig)2347 print(1)2348 return2349 check(fn, """2350[NUM] > .*fn(), 5 frames hidden2351<COLORNUM> ^[[38;5;129m@deco^[[39m2352<COLORNUM> ^[[38;5;129m@deco^[[39m2353...2354<COLORNUM> set_trace.*2355<COLORCURLINE> -> ^[[38;5;28.*;44mprint.*2356<COLORNUM> ^[[38;5;28;01mreturn^[[39;00m2357# c235812359""", terminal_size=(len(__file__) + 50, 10))2360def test_sticky_cutoff_with_minimal_lines():2361 class MyConfig(ConfigTest):2362 sticky_by_default = True2363 def deco(f):2364 return f2365 @deco2366 def fn():2367 set_trace(Config=MyConfig)2368 print(1)2369 # 12370 # 22371 # 32372 return2373 check(fn, """2374[NUM] > .*fn(), 5 frames hidden2375NUM @deco2376...2377NUM -> print(1)2378NUM # 12379NUM # 22380...2381# c238212383""", terminal_size=(len(__file__) + 50, 3))2384def test_exception_lineno():2385 def bar():2386 assert False2387 def fn():2388 try:2389 a = 1 # noqa: F8412390 bar()2391 b = 2 # noqa: F8412392 except AssertionError:2393 xpm()2394 check(fn, """2395Traceback (most recent call last):2396 File "{filename}", line NUM, in fn2397 bar()2398 File "{filename}", line NUM, in bar2399 assert False2400AssertionError.*2401[NUM] > .*bar()2402-> assert False2403# u2404[NUM] > .*fn()2405-> bar()2406# ll2407NUM def fn():2408NUM try:2409NUM a = 12410NUM >> bar()2411NUM b = 22412NUM except AssertionError:2413NUM -> xpm()2414# c2415 """.format(2416 filename=RE_THIS_FILE,2417 ))2418def test_postmortem_noargs():2419 def fn():2420 try:2421 a = 1 # noqa: F8412422 1/02423 except ZeroDivisionError:2424 pdbpp.post_mortem(Pdb=PdbTest)2425 check(fn, """2426[NUM] > .*fn()2427-> 1/02428# c2429""")2430def test_postmortem_needs_exceptioncontext():2431 pytest.raises(ValueError, pdbpp.post_mortem)2432def test_exception_through_generator():2433 def gen():2434 yield 52435 assert False2436 def fn():2437 try:2438 for i in gen():2439 pass2440 except AssertionError:2441 xpm()2442 check(fn, """2443Traceback (most recent call last):2444 File "{filename}", line NUM, in fn2445 for i in gen():2446 File "{filename}", line NUM, in gen2447 assert False2448AssertionError.*2449[NUM] > .*gen()2450-> assert False2451# u2452[NUM] > .*fn()2453-> for i in gen():2454# c2455 """.format(2456 filename=RE_THIS_FILE,2457 ))2458def test_py_code_source(): # noqa: F8212459 src = py.code.Source("""2460 def fn():2461 x = 422462 set_trace()2463 return x2464 """)2465 exec(src.compile(), globals())2466 check(fn, # noqa: F8212467 """2468[NUM] > .*fn()2469-> return x2470 5 frames hidden .*2471# ll2472NUM def fn():2473NUM x = 422474NUM set_trace()2475NUM -> return x2476# c2477""")2478def test_source():2479 def bar():2480 return 422481 def fn():2482 set_trace()2483 return bar()2484 check(fn, """2485[NUM] > .*fn()2486-> return bar()2487 5 frames hidden .*2488# source bar2489NUM def bar():2490NUM return 422491# c2492""")2493def test_source_with_pygments():2494 def bar():2495 return 422496 def fn():2497 set_trace(Config=ConfigWithPygments)2498 return bar()2499 check(fn, """2500[NUM] > .*fn()2501-> ^[[38;5;28;01mreturn^[[39;00m bar()2502 5 frames hidden .*2503# source bar2504NUM ^[[38;5;28;01mdef^[[39;00m ^[[38;5;21mbar^[[39m():2505NUM2506NUM ^[[38;5;28;01mreturn^[[39;00m ^[[38;5;241m42^[[39m2507# c2508""")2509def test_source_with_highlight():2510 def bar():2511 return 422512 def fn():2513 set_trace(Config=ConfigWithHighlight)2514 return bar()2515 check(fn, """2516[NUM] > .*fn()2517-> return bar()2518 5 frames hidden .*2519# source bar2520<COLORNUM> def bar():2521<COLORNUM>2522<COLORNUM> return 422523# c2524""")2525def test_source_with_pygments_and_highlight():2526 def bar():2527 return 422528 def fn():2529 set_trace(Config=ConfigWithPygmentsAndHighlight)2530 return bar()2531 check(fn, """2532[NUM] > .*fn()2533-> ^[[38;5;28;01mreturn^[[39;00m bar()2534 5 frames hidden .*2535# source bar2536<COLORNUM> ^[[38;5;28;01mdef^[[39;00m ^[[38;5;21mbar^[[39m():2537<COLORNUM>2538<COLORNUM> ^[[38;5;28;01mreturn^[[39;00m ^[[38;5;241m42^[[39m2539# c2540""")2541def test_bad_source():2542 def fn():2543 set_trace()2544 return 422545 check(fn, r"""2546[NUM] > .*fn()2547-> return 422548 5 frames hidden .*2549# source 422550\*\*\* could not get obj: .*module, class, method, .*, or code object.*2551# c2552""")2553def test_edit():2554 def fn():2555 set_trace()2556 return 422557 def bar():2558 fn()2559 return 1002560 _, lineno = inspect.getsourcelines(fn)2561 return42_lineno = lineno + 22562 call_fn_lineno = lineno + 52563 check(fn, r"""2564[NUM] > .*fn()2565-> return 422566 5 frames hidden .*2567# edit2568RUN emacs \+%d %s2569# c2570""" % (return42_lineno, RE_THIS_FILE_QUOTED))2571 check(bar, r"""2572[NUM] > .*fn()2573-> return 422574 5 frames hidden .*2575# up2576[NUM] > .*bar()2577-> fn()2578# edit2579RUN emacs \+%d %s2580# c2581""" % (call_fn_lineno, RE_THIS_FILE_QUOTED))2582def test_edit_obj():2583 def fn():2584 bar()2585 set_trace()2586 return 422587 def bar():2588 pass2589 _, bar_lineno = inspect.getsourcelines(bar)2590 check(fn, r"""2591[NUM] > .*fn()2592-> return 422593 5 frames hidden .*2594# edit bar2595RUN emacs \+%d %s2596# c2597""" % (bar_lineno, RE_THIS_FILE_CANONICAL_QUOTED))2598def test_edit_fname_lineno():2599 def fn():2600 set_trace()2601 check(fn, r"""2602--Return--2603[NUM] > .*fn()->None2604-> set_trace()2605 5 frames hidden .*2606# edit {fname}2607RUN emacs \+1 {fname_edit}2608# edit {fname}:52609RUN emacs \+5 {fname_edit}2610# edit {fname}:meh2611\*\*\* could not parse filename/lineno2612# edit {fname}:-12613\*\*\* could not parse filename/lineno2614# edit {fname} meh:-12615\*\*\* could not parse filename/lineno2616# edit os.py2617RUN emacs \+1 {os_fname}2618# edit doesnotexist.py2619\*\*\* could not parse filename/lineno2620# c2621""".format(fname=__file__,2622 fname_edit=RE_THIS_FILE_QUOTED,2623 os_fname=re.escape(quote(os.__file__.rstrip("c")))))2624def test_edit_py_code_source():2625 src = py.code.Source("""2626 def bar():2627 set_trace()2628 return 422629 """)2630 _, base_lineno = inspect.getsourcelines(test_edit_py_code_source)2631 dic = {'set_trace': set_trace}2632 exec(src.compile(), dic) # 8th line from the beginning of the function2633 bar = dic['bar']2634 src_compile_lineno = base_lineno + 82635 check(bar, r"""2636[NUM] > .*bar()2637-> return 422638 5 frames hidden .*2639# edit bar2640RUN emacs \+%d %s2641# c2642""" % (src_compile_lineno, RE_THIS_FILE_CANONICAL_QUOTED))2643def test_put():2644 def fn():2645 set_trace()2646 return 422647 _, lineno = inspect.getsourcelines(fn)2648 start_lineno = lineno + 12649 check(fn, r"""2650[NUM] > .*fn()2651-> return 422652 5 frames hidden .*2653# x = 102654# y = 122655# put2656RUN epaste \+%d2657' x = 10\\n y = 12\\n'2658# c2659""" % start_lineno)2660def test_paste():2661 def g():2662 print('hello world')2663 def fn():2664 set_trace()2665 if 4 != 5:2666 g()2667 return 422668 _, lineno = inspect.getsourcelines(fn)2669 start_lineno = lineno + 12670 check(fn, r"""2671[NUM] > .*fn()2672-> if 4 != 5:2673 5 frames hidden .*2674# g()2675hello world2676# paste g()2677hello world2678RUN epaste \+%d2679'hello world\\n'2680# c2681hello world2682""" % start_lineno)2683def test_put_if():2684 def fn():2685 x = 02686 if x < 10:2687 set_trace()2688 return x2689 _, lineno = inspect.getsourcelines(fn)2690 start_lineno = lineno + 32691 check(fn, r"""2692[NUM] > .*fn()2693-> return x2694 5 frames hidden .*2695# x = 102696# y = 122697# put2698RUN epaste \+%d2699.*x = 10\\n y = 12\\n.2700# c2701""" % start_lineno)2702def test_side_effects_free():2703 r = pdbpp.side_effects_free2704 assert r.match(' x')2705 assert r.match('x.y[12]')2706 assert not r.match('x(10)')2707 assert not r.match(' x = 10')2708 assert not r.match('x = 10')2709def test_put_side_effects_free():2710 def fn():2711 x = 10 # noqa: F8412712 set_trace()2713 return 422714 _, lineno = inspect.getsourcelines(fn)2715 start_lineno = lineno + 22716 check(fn, r"""2717[NUM] > .*fn()2718-> return 422719 5 frames hidden .*2720# x2721102722# x.__add__2723.*2724# y = 122725# put2726RUN epaste \+%d2727' y = 12\\n'2728# c2729""" % start_lineno)2730def test_enable_disable_via_module():2731 def fn():2732 x = 12733 pdbpp.disable()2734 set_trace_via_module()2735 x = 22736 pdbpp.enable()2737 set_trace_via_module()2738 return x2739 check(fn, """2740[NUM] > .*fn()2741-> return x2742 5 frames hidden .*2743# x274422745# c2746""")2747def test_enable_disable_from_prompt_via_class():2748 def fn():2749 pdb_ = PdbTest()2750 pdb_.set_trace()2751 x = 12752 pdb_.set_trace()2753 x = 22754 pdbpp.enable()2755 pdb_.set_trace()2756 return x2757 check(fn, """2758[NUM] > .*fn()2759-> x = 12760 5 frames hidden .*2761# pdbpp.disable()2762# c2763[NUM] > .*fn()2764-> return x2765 5 frames hidden .*2766# x276722768# c2769""")2770def test_hideframe():2771 @pdbpp.hideframe2772 def g():2773 pass2774 assert g.__code__.co_consts[-1] is pdbpp._HIDE_FRAME2775def test_hide_hidden_frames():2776 @pdbpp.hideframe2777 def g():2778 set_trace()2779 return 'foo'2780 def fn():2781 g()2782 return 12783 check(fn, """2784[NUM] > .*fn()2785-> g()2786 6 frames hidden .*2787# down2788... Newest frame2789# hf_unhide2790# down2791[NUM] > .*g()2792-> return 'foo'2793# up2794[NUM] > .*fn()2795-> g()2796# hf_hide ### hide the frame again2797# down2798... Newest frame2799# c2800""")2801def test_hide_current_frame():2802 @pdbpp.hideframe2803 def g():2804 set_trace()2805 return 'foo'2806 def fn():2807 g()2808 return 12809 check(fn, """2810[NUM] > .*fn()2811-> g()2812 6 frames hidden .*2813# hf_unhide2814# down ### now the frame is no longer hidden2815[NUM] > .*g()2816-> return 'foo'2817# hf_hide ### hide the current frame, go to the top of the stack2818[NUM] > .*fn()2819-> g()2820# c2821""")2822def test_hide_frame_for_set_trace_on_class():2823 def g():2824 # Simulate set_trace, with frame=None.2825 pdbpp.cleanup()2826 _pdb = PdbTest()2827 _pdb.set_trace()2828 return 'foo'2829 def fn():2830 g()2831 return 12832 check(fn, """2833[NUM] > .*g()2834-> return 'foo'2835 5 frames hidden .*2836# hf_unhide2837# down2838\\*\\*\\* Newest frame2839# c2840""")2841def test_list_hidden_frames():2842 @pdbpp.hideframe2843 def g():2844 set_trace()2845 return 'foo'2846 @pdbpp.hideframe2847 def k():2848 return g()2849 def fn():2850 k()2851 return 12852 check(fn, r"""2853[NUM] > .*fn()2854-> k()2855 7 frames hidden .*2856# hf_list2857.*_multicall()2858-> res = hook_impl.function(\*args)2859.*_multicall()2860-> res = hook_impl.function(\*args)2861.*_multicall()2862-> res = hook_impl.function(\*args)2863.*_multicall()2864-> res = hook_impl.function(\*args)2865.*_multicall()2866-> res = hook_impl.function(\*args)2867.*k()2868-> return g()2869.*g()2870-> return 'foo'2871# c2872""")2873def test_hidden_pytest_frames():2874 def s():2875 __tracebackhide__ = True # Ignored for set_trace in here.2876 set_trace()2877 return 'foo'2878 def g(s=s):2879 __tracebackhide__ = True2880 return s()2881 def k(g=g):2882 return g()2883 k = pdbpp.rebind_globals(k, {'__tracebackhide__': True})2884 def fn():2885 k()2886 return 12887 check(fn, r"""2888[NUM] > .*s()2889-> return 'foo'2890 7 frames hidden .*2891# hf_list2892.*_multicall()2893-> res = hook_impl.function(\*args)2894.*_multicall()2895-> res = hook_impl.function(\*args)2896.*_multicall()2897-> res = hook_impl.function(\*args)2898.*_multicall()2899-> res = hook_impl.function(\*args)2900.*_multicall()2901-> res = hook_impl.function(\*args)2902.*k()2903-> return g()2904.*g()2905-> return s()2906# c2907 """)2908def test_hidden_pytest_frames_f_local_nondict():2909 class M:2910 values = []2911 def __getitem__(self, name):2912 if name == 0:2913 # Handle 'if "__tracebackhide__" in frame.f_locals'.2914 raise IndexError()2915 return globals()[name]2916 def __setitem__(self, name, value):2917 # pdb assigns to f_locals itself.2918 self.values.append((name, value))2919 def fn():2920 m = M()2921 set_trace()2922 exec("print(1)", {}, m)2923 assert m.values == [('__return__', None)]2924 check(fn, r"""2925[NUM] > .*fn()2926-> exec("print(1)", {}, m)2927 5 frames hidden (try 'help hidden_frames')2928# s2929--Call--2930[NUM] > <string>(1)<module>()2931 5 frames hidden (try 'help hidden_frames')2932# n2933[NUM] > <string>(1)<module>()2934 5 frames hidden (try 'help hidden_frames')2935# n293612937--Return--2938[NUM] > <string>(1)<module>()2939 5 frames hidden (try 'help hidden_frames')2940# c2941 """)2942def test_hidden_unittest_frames():2943 def s(set_trace=set_trace):2944 set_trace()2945 return 'foo'2946 def g(s=s):2947 return s()2948 g = pdbpp.rebind_globals(g, {'__unittest': True})2949 def fn():2950 return g()2951 check(fn, r"""2952[NUM] > .*s()2953-> return 'foo'2954 6 frames hidden .*2955# hf_list2956.*_multicall()2957-> res = hook_impl.function(\*args)2958.*_multicall()2959-> res = hook_impl.function(\*args)2960.*_multicall()2961-> res = hook_impl.function(\*args)2962.*_multicall()2963-> res = hook_impl.function(\*args)2964.*_multicall()2965-> res = hook_impl.function(\*args)2966.*g()2967-> return s()2968# c2969 """)2970def test_dont_show_hidden_frames_count():2971 class MyConfig(ConfigTest):2972 show_hidden_frames_count = False2973 @pdbpp.hideframe2974 def g():2975 set_trace(Config=MyConfig)2976 return 'foo'2977 def fn():2978 g()2979 return 12980 check(fn, """2981[NUM] > .*fn()2982-> g()2983# c ### note that the hidden frame count is not displayed2984""")2985def test_disable_hidden_frames():2986 class MyConfig(ConfigTest):2987 enable_hidden_frames = False2988 @pdbpp.hideframe2989 def g():2990 set_trace(Config=MyConfig)2991 return 'foo'2992 def fn():2993 g()2994 return 12995 check(fn, """2996[NUM] > .*g()2997-> return 'foo'2998# c ### note that we were inside g()2999""")3000def test_break_on_setattr():3001 # we don't use a class decorator to keep 2.5 compatibility3002 class Foo(object):3003 pass3004 Foo = pdbpp.break_on_setattr('x', Pdb=PdbTest)(Foo)3005 def fn():3006 obj = Foo()3007 obj.x = 03008 return obj.x3009 check(fn, """3010[NUM] > .*fn()3011-> obj.x = 03012 5 frames hidden .*3013# hasattr(obj, 'x')3014False3015# n3016[NUM] > .*fn()3017-> return obj.x3018 5 frames hidden .*3019# p obj.x3020# c3021""")3022def test_break_on_setattr_without_hidden_frames():3023 class PdbWithConfig(PdbTest):3024 def __init__(self, *args, **kwargs):3025 class Config(ConfigTest):3026 enable_hidden_frames = False3027 super(PdbWithConfig, self).__init__(*args, Config=Config, **kwargs)3028 class Foo(object):3029 pass3030 Foo = pdbpp.break_on_setattr('x', Pdb=PdbWithConfig)(Foo)3031 def fn():3032 obj = Foo()3033 obj.x = 03034 return obj.x3035 check(fn, """3036[NUM] > .*fn()3037-> obj.x = 03038# hasattr(obj, 'x')3039False3040# n3041[NUM] > .*fn()3042-> return obj.x3043# p obj.x3044# c3045""")3046def test_break_on_setattr_condition():3047 def mycond(obj, value):3048 return value == 423049 class Foo(object):3050 pass3051 # we don't use a class decorator to keep 2.5 compatibility3052 Foo = pdbpp.break_on_setattr('x', condition=mycond, Pdb=PdbTest)(Foo)3053 def fn():3054 obj = Foo()3055 obj.x = 03056 obj.x = 423057 return obj.x3058 check(fn, """3059[NUM] > .*fn()3060-> obj.x = 423061 5 frames hidden .*3062# obj.x3063# n3064[NUM] > .*fn()3065-> return obj.x3066 5 frames hidden .*3067# obj.x3068423069# c3070""")3071def test_break_on_setattr_non_decorator():3072 class Foo(object):3073 pass3074 def fn():3075 a = Foo()3076 b = Foo()3077 def break_if_a(obj, value):3078 return obj is a3079 pdbpp.break_on_setattr("bar", condition=break_if_a, Pdb=PdbTest)(Foo)3080 b.bar = 103081 a.bar = 423082 check(fn, """3083[NUM] > .*fn()3084-> a.bar = 423085 5 frames hidden .*3086# c3087""")3088def test_break_on_setattr_overridden():3089 # we don't use a class decorator to keep 2.5 compatibility3090 class Foo(object):3091 def __setattr__(self, attr, value):3092 object.__setattr__(self, attr, value+1)3093 Foo = pdbpp.break_on_setattr('x', Pdb=PdbTest)(Foo)3094 def fn():3095 obj = Foo()3096 obj.y = 413097 obj.x = 03098 return obj.x3099 check(fn, """3100[NUM] > .*fn()3101-> obj.x = 03102 5 frames hidden .*3103# obj.y3104423105# hasattr(obj, 'x')3106False3107# n3108[NUM] > .*fn()3109-> return obj.x3110 5 frames hidden .*3111# p obj.x311213113# c3114""")3115def test_track_with_no_args():3116 pytest.importorskip('rpython.translator.tool.reftracker')3117 def fn():3118 set_trace()3119 return 423120 check(fn, """3121[NUM] > .*fn()3122-> return 423123# track3124... SyntaxError:3125# c3126""")3127def test_utf8():3128 def fn():3129 # ÑеÑÑ3130 a = 13131 set_trace(Config=ConfigWithHighlight)3132 return a3133 # we cannot easily use "check" because the output is full of ANSI escape3134 # sequences3135 expected, lines = run_func(fn, '# ll\n# c')3136 assert u'ÑеÑÑ' in lines[5]3137def test_debug_normal():3138 def g():3139 a = 13140 return a3141 def fn():3142 g()3143 set_trace()3144 return 13145 check(fn, """3146[NUM] > .*fn()3147-> return 13148 5 frames hidden .*3149# debug g()3150ENTERING RECURSIVE DEBUGGER3151[NUM] > .*3152(#) s3153--Call--3154[NUM] > .*g()3155-> def g():3156(#) ll3157NUM -> def g():3158NUM a = 13159NUM return a3160(#) c3161LEAVING RECURSIVE DEBUGGER3162# c3163""")3164def test_debug_thrice():3165 def fn():3166 set_trace()3167 check(fn, """3168--Return--3169[NUM] > .*fn()3170-> set_trace()3171 5 frames hidden .*3172# debug 13173ENTERING RECURSIVE DEBUGGER3174[NUM] > .*3175(#) debug 23176ENTERING RECURSIVE DEBUGGER3177[NUM] > .*3178((#)) debug 343179ENTERING RECURSIVE DEBUGGER3180[NUM] > .*3181(((#))) p 423182423183(((#))) c3184LEAVING RECURSIVE DEBUGGER3185((#)) c3186LEAVING RECURSIVE DEBUGGER3187(#) c3188LEAVING RECURSIVE DEBUGGER3189# c3190""")3191def test_syntaxerror_in_command():3192 def f():3193 set_trace()3194 check(f, """3195--Return--3196[NUM] > .*f()3197-> set_trace3198 5 frames hidden .*3199# print(3200\\*\\*\\* SyntaxError: .*3201# debug print(3202ENTERING RECURSIVE DEBUGGER3203\\*\\*\\* SyntaxError: .*3204LEAVING RECURSIVE DEBUGGER3205# c3206""")3207def test_debug_with_overridden_continue():3208 class CustomPdb(PdbTest, object):3209 """CustomPdb that overrides do_continue like with pytest's wrapper."""3210 def do_continue(self, arg):3211 global count_continue3212 count_continue += 13213 print("do_continue_%d" % count_continue)3214 return super(CustomPdb, self).do_continue(arg)3215 do_c = do_cont = do_continue3216 def g():3217 a = 13218 return a3219 def fn():3220 global count_continue3221 count_continue = 03222 g()3223 set_trace(Pdb=CustomPdb)3224 set_trace(Pdb=CustomPdb)3225 assert count_continue == 33226 return 13227 check(fn, """3228[NUM] > .*fn()3229-> set_trace(Pdb=CustomPdb)3230 5 frames hidden .*3231# c3232do_continue_13233[NUM] > .*fn()3234-> assert count_continue == 33235 5 frames hidden .*3236# debug g()3237ENTERING RECURSIVE DEBUGGER3238[NUM] > .*3239(#) s3240--Call--3241[NUM] > .*g()3242-> def g():3243(#) ll3244NUM -> def g():3245NUM a = 13246NUM return a3247(#) c3248do_continue_23249LEAVING RECURSIVE DEBUGGER3250# c3251do_continue_33252""")3253def test_before_interaction_hook():3254 class MyConfig(ConfigTest):3255 def before_interaction_hook(self, pdb):3256 pdb.stdout.write('HOOK!\n')3257 def fn():3258 set_trace(Config=MyConfig)3259 return 13260 check(fn, """3261[NUM] > .*fn()3262-> return 13263 5 frames hidden .*3264HOOK!3265# c3266""")3267def test_unicode_bug():3268 def fn():3269 set_trace()3270 x = "this is plain ascii" # noqa: F8413271 y = "this contains a unicode: à " # noqa: F8413272 return3273 check_output = """3274[NUM] > .*fn()3275-> x = "this is plain ascii"3276 5 frames hidden .*3277# n3278[NUM] > .*fn()3279-> y = "this contains a unicode: à "3280 5 frames hidden .*3281# c3282"""3283 if sys.version_info < (3, ):3284 check_output = check_output.decode('utf-8')3285 check(fn, check_output)3286def test_continue_arg():3287 def fn():3288 set_trace()3289 x = 13290 y = 23291 z = 33292 return x+y+z3293 _, lineno = inspect.getsourcelines(fn)3294 line_z = lineno+43295 check(fn, """3296[NUM] > .*fn()3297-> x = 13298 5 frames hidden .*3299# c {break_lnum}3300Breakpoint NUM at {filename}:{break_lnum}3301Deleted breakpoint NUM3302[NUM] > .*fn()3303-> z = 33304 5 frames hidden .*3305# c3306 """.format(3307 break_lnum=line_z,3308 filename=RE_THIS_FILE_CANONICAL,3309 ))3310# On Windows, it seems like this file is handled as cp1252-encoded instead3311# of utf8 (even though the "# -*- coding: utf-8 -*-" line exists) and the3312# core pdb code does not support that. Or something to that effect, I don't3313# actually know.3314# UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position3315# 6998: character maps to <undefined>.3316# So we XFail this test on Windows.3317@pytest.mark.xfail(3318 (3319 sys.platform == "win32" and (3320 # bpo-41894: fixed in 3.10, backported to 3.9.1 and 3.8.7.3321 sys.version_info < (3, 8, 7) or3322 (sys.version_info[:2] == (3, 9) and sys.version_info < (3, 9, 1))3323 )3324 ),3325 raises=UnicodeDecodeError,3326 strict=True,3327 reason=(3328 "Windows encoding issue. See comments and"3329 " https://github.com/pdbpp/pdbpp/issues/341"3330 ),3331)3332@pytest.mark.skipif(not hasattr(pdbpp.pdb.Pdb, "error"),3333 reason="no error method")3334def test_continue_arg_with_error():3335 def fn():3336 set_trace()3337 x = 13338 y = 23339 z = 33340 return x+y+z3341 _, lineno = inspect.getsourcelines(fn)3342 line_z = lineno + 43343 check(fn, r"""3344[NUM] > .*fn()3345-> x = 13346 5 frames hidden .*3347# c.foo3348\*\*\* The specified object '.foo' is not a function or was not found along sys.path.3349# c {break_lnum}3350Breakpoint NUM at {filename}:{break_lnum}3351Deleted breakpoint NUM3352[NUM] > .*fn()3353-> z = 33354 5 frames hidden .*3355# c3356 """.format(3357 break_lnum=line_z,3358 filename=RE_THIS_FILE_CANONICAL,3359 ))3360@pytest.mark.skipif(sys.version_info < (3, 7), reason="header kwarg is 3.7+")3361def test_set_trace_header():3362 """Handler header kwarg added with Python 3.7 in pdb.set_trace."""3363 def fn():3364 set_trace_via_module(header="my_header")3365 check(fn, """3366my_header3367--Return--3368[NUM] > .*fn()3369-> set_trace.*3370 5 frames hidden .*3371# c3372""")3373def test_stdout_encoding_None():3374 instance = PdbTest()3375 instance.stdout = BytesIO()3376 instance.stdout.encoding = None3377 instance.ensure_file_can_write_unicode(instance.stdout)3378 try:3379 import cStringIO3380 except ImportError:3381 pass3382 else:3383 instance.stdout = cStringIO.StringIO()3384 instance.ensure_file_can_write_unicode(instance.stdout)3385def test_frame_cmd_changes_locals():3386 def a():3387 x = 42 # noqa: F8413388 b()3389 def b():3390 fn()3391 def fn():3392 set_trace()3393 return3394 check(a, """3395[NUM] > .*fn()3396-> return3397 5 frames hidden .*3398# f {frame_num_a}3399[NUM] > .*a()3400-> b()3401# p list(sorted(locals().keys()))3402['b', 'x']3403# c3404""".format(frame_num_a=count_frames() + 2 - 5))3405@pytest.mark.skipif(not hasattr(pdbpp.pdb.Pdb, "_cmdloop"),3406 reason="_cmdloop is not available")3407def test_sigint_in_interaction_with_new_cmdloop():3408 def fn():3409 def inner():3410 raise KeyboardInterrupt()3411 set_trace()3412 check(fn, """3413--Return--3414[NUM] > .*fn()3415-> set_trace()3416 5 frames hidden .*3417# debug inner()3418ENTERING RECURSIVE DEBUGGER3419[NUM] > .*3420(#) c3421--KeyboardInterrupt--3422# c3423""")3424@pytest.mark.skipif(hasattr(pdbpp.pdb.Pdb, "_cmdloop"),3425 reason="_cmdloop is available")3426def test_sigint_in_interaction_without_new_cmdloop():3427 def fn():3428 def inner():3429 raise KeyboardInterrupt()3430 set_trace()3431 with pytest.raises(KeyboardInterrupt):3432 check(fn, """3433--Return--3434[NUM] > .*fn()3435-> set_trace()3436 5 frames hidden .*3437# debug inner()3438ENTERING RECURSIVE DEBUGGER3439[NUM] > .*3440(#) c3441""")3442 # Reset pdb, which did not clean up correctly.3443 # Needed for PyPy (Python 2.7.13[pypy-7.1.0-final]) with coverage and3444 # restoring trace function.3445 pdbpp.local.GLOBAL_PDB.reset()3446@pytest.mark.skipif(not hasattr(pdbpp.pdb.Pdb, "_previous_sigint_handler"),3447 reason="_previous_sigint_handler is not available")3448def test_interaction_restores_previous_sigint_handler():3449 """Test is based on cpython's test_pdb_issue_20766."""3450 def fn():3451 i = 13452 while i <= 2:3453 sess = PdbTest(nosigint=False)3454 sess.set_trace(sys._getframe())3455 print('pdb %d: %s' % (i, sess._previous_sigint_handler))3456 i += 13457 check(fn, """3458[NUM] > .*fn()3459-> print('pdb %d: %s' % (i, sess._previous_sigint_handler))3460 5 frames hidden .*3461# c3462pdb 1: <built-in function default_int_handler>3463[NUM] > .*fn()3464-> .*3465 5 frames hidden .*3466# c3467pdb 2: <built-in function default_int_handler>3468""")3469def test_recursive_set_trace():3470 def fn():3471 global inner3472 global count3473 count = 03474 def inner():3475 global count3476 count += 13477 if count == 1:3478 set_trace()3479 else:3480 set_trace(cleanup=False)3481 inner()3482 check(fn, """3483--Return--3484[NUM] > .*inner()3485-> set_trace()3486 5 frames hidden .*3487# inner()3488# c3489""")3490def test_steps_over_set_trace():3491 def fn():3492 set_trace()3493 print(1)3494 set_trace(cleanup=False)3495 print(2)3496 check(fn, """3497[NUM] > .*fn()3498-> print(1)3499 5 frames hidden .*3500# n350113502[NUM] > .*fn()3503-> set_trace(cleanup=False)3504 5 frames hidden .*3505# n3506[NUM] > .*fn()3507-> print(2)3508 5 frames hidden .*3509# c351023511""")3512def test_break_after_set_trace():3513 def fn():3514 set_trace()3515 print(1)3516 print(2)3517 _, lineno = inspect.getsourcelines(fn)3518 check(fn, """3519[NUM] > .*fn()3520-> print(1)3521 5 frames hidden .*3522# break {lineno}3523Breakpoint . at .*:{lineno}3524# c352513526[NUM] > .*fn()3527-> print(2)3528 5 frames hidden .*3529# import pdb; pdbpp.local.GLOBAL_PDB.clear_all_breaks()3530# c353123532""".format(lineno=lineno + 3))3533def test_break_with_inner_set_trace():3534 def fn():3535 def inner():3536 set_trace(cleanup=False)3537 set_trace()3538 inner()3539 print(1)3540 _, lineno = inspect.getsourcelines(fn)3541 check(fn, """3542[NUM] > .*fn()3543-> inner()3544 5 frames hidden .*3545# break {lineno}3546Breakpoint . at .*:{lineno}3547# c3548--Return--3549[NUM] > .*inner()->None3550-> set_trace(cleanup=False)3551 5 frames hidden .*3552# import pdb; pdbpp.local.GLOBAL_PDB.clear_all_breaks()3553# c355413555""".format(lineno=lineno + 8))3556@pytest.mark.skipif(3557 sys.version_info < (3,), reason="no support for exit from interaction with pdbrc"3558)3559def test_pdbrc_continue(tmpdirhome):3560 """Test that interaction is skipped with continue in pdbrc."""3561 assert os.getcwd() == str(tmpdirhome)3562 with open(".pdbrc", "w") as f:3563 f.writelines([3564 "p 'from_pdbrc'\n",3565 "continue\n",3566 ])3567 def fn():3568 set_trace(readrc=True)3569 print("after_set_trace")3570 check(fn, """3571'from_pdbrc'3572after_set_trace3573""")3574def test_python_m_pdb_usage():3575 p = subprocess.Popen(3576 [sys.executable, "-m", "pdb"],3577 stdout=subprocess.PIPE, stderr=subprocess.PIPE3578 )3579 stdout, stderr = p.communicate()3580 out = stdout.decode("utf8")3581 err = stderr.decode("utf8")3582 assert err == ""3583 assert "usage: pdb.py" in out3584@pytest.mark.parametrize('PDBPP_HIJACK_PDB', (1, 0))3585def test_python_m_pdb_uses_pdbpp_and_env(PDBPP_HIJACK_PDB, monkeypatch, tmpdir):3586 if PDBPP_HIJACK_PDB:3587 skip_with_missing_pth_file()3588 monkeypatch.setenv("PDBPP_HIJACK_PDB", str(PDBPP_HIJACK_PDB))3589 f = tmpdir.ensure("test.py")3590 f.write(textwrap.dedent("""3591 import inspect3592 import os3593 import pdb3594 fname = os.path.basename(inspect.getfile(pdb.Pdb))3595 if {PDBPP_HIJACK_PDB}:3596 assert fname == 'pdbpp.py', (fname, pdb, pdb.Pdb)3597 else:3598 assert fname in ('pdb.py', 'pdb.pyc'), (fname, pdb, pdb.Pdb)3599 pdb.set_trace()3600 """.format(PDBPP_HIJACK_PDB=PDBPP_HIJACK_PDB)))3601 p = subprocess.Popen(3602 [sys.executable, "-m", "pdb", str(f)],3603 stdout=subprocess.PIPE, stderr=subprocess.PIPE,3604 stdin=subprocess.PIPE3605 )3606 stdout, stderr = p.communicate(b"c\n")3607 out = stdout.decode("utf8")3608 err = stderr.decode("utf8")3609 print(out)3610 print(err, file=sys.stderr)3611 assert err == ""3612 if PDBPP_HIJACK_PDB:3613 assert "(Pdb)" not in out3614 assert "(Pdb++)" in out3615 if sys.platform == "win32" and (3616 sys.version_info < (3,) or sys.version_info >= (3, 5)3617 ):3618 assert out.endswith("\n(Pdb++) " + os.linesep)3619 else:3620 assert out.endswith("\n(Pdb++) \n")3621 else:3622 assert "(Pdb)" in out3623 assert "(Pdb++)" not in out3624 assert out.endswith("\n(Pdb) " + os.linesep)3625def get_completions(text):3626 """Get completions from the installed completer."""3627 readline_ = pdbpp.local.GLOBAL_PDB.fancycompleter.config.readline3628 complete = readline_.get_completer()3629 comps = []3630 assert complete.__self__ is pdbpp.local.GLOBAL_PDB3631 while True:3632 val = complete(text, len(comps))3633 if val is None:3634 break3635 comps += [val]3636 return comps3637def test_set_trace_in_completion(monkeypatch_readline):3638 def fn():3639 class CompleteMe(object):3640 attr_called = 03641 @property3642 def set_trace_in_attrib(self):3643 self.attr_called += 13644 set_trace(cleanup=False)3645 print("inner_set_trace_was_ignored")3646 obj = CompleteMe()3647 def check_completions():3648 monkeypatch_readline("obj.", 0, 4)3649 comps = get_completions("obj.")3650 assert obj.attr_called == 1, "attr was called"3651 # Colorization only works with pyrepl, via pyrepl.readline._setup.3652 assert any("set_trace_in_attrib" in comp for comp in comps), comps3653 return True3654 set_trace()3655 check(fn, """3656--Return--3657[NUM] > .*fn()3658.*3659 5 frames hidden .*3660# check_completions()3661inner_set_trace_was_ignored3662True3663# c3664""")3665def test_completes_from_pdb(monkeypatch_readline):3666 """Test that pdb's original completion is used."""3667 def fn():3668 where = 1 # noqa: F8413669 set_trace()3670 def check_completions():3671 # Patch readline to return expected results for "wher".3672 monkeypatch_readline("wher", 0, 4)3673 assert get_completions("wher") == ["where"]3674 if sys.version_info > (3, ):3675 # Patch readline to return expected results for "disable ".3676 monkeypatch_readline("disable", 8, 8)3677 # NOTE: number depends on bpb.Breakpoint class state, just ensure that3678 # is a number.3679 completion = pdbpp.local.GLOBAL_PDB.complete("", 0)3680 assert int(completion) > 03681 # Patch readline to return expected results for "p ".3682 monkeypatch_readline("p ", 2, 2)3683 comps = get_completions("")3684 assert "where" in comps3685 # Dunder members get completed only on second invocation.3686 assert "__name__" not in comps3687 comps = get_completions("")3688 assert "__name__" in comps3689 # Patch readline to return expected results for "help ".3690 monkeypatch_readline("help ", 5, 5)3691 comps = get_completions("")3692 assert "help" in comps3693 return True3694 set_trace()3695 _, lineno = inspect.getsourcelines(fn)3696 if sys.version_info >= (3, 10, 0, "a", 7): # bpo-241603697 pre_py310_output = ""3698 else:3699 pre_py310_output = "\n'There are no breakpoints'"3700 check(fn, """3701[NUM] > .*fn()3702.*3703 5 frames hidden .*3704# break {lineno}3705Breakpoint NUM at .*3706# c3707--Return--3708[NUM] > .*fn()3709.*3710 5 frames hidden .*3711# check_completions()3712True3713# import pdb; pdbpp.local.GLOBAL_PDB.clear_all_breaks(){pre_py310_output}3714# c3715""".format(lineno=lineno, pre_py310_output=pre_py310_output))3716def test_completion_uses_tab_from_fancycompleter(monkeypatch_readline):3717 """Test that pdb's original completion is used."""3718 def fn():3719 def check_completions():3720 # Patch readline to return expected results for "C.f()".3721 monkeypatch_readline("C.f()", 5, 5)3722 assert get_completions("") == ["\t"]3723 return True3724 set_trace()3725 _, lineno = inspect.getsourcelines(fn)3726 check(fn, """3727--Return--3728[NUM] > .*fn()->None3729.*3730 5 frames hidden .*3731# check_completions()3732True3733# c3734""")3735def test_complete_removes_duplicates_with_coloring(3736 monkeypatch_readline, readline_param3737):3738 def fn():3739 helpvar = 42 # noqa: F8413740 class obj:3741 foo = 13742 foobar = 23743 def check_completions():3744 # Patch readline to return expected results for "help".3745 monkeypatch_readline("help", 0, 4)3746 if readline_param == "pyrepl":3747 assert pdbpp.local.GLOBAL_PDB.fancycompleter.config.use_colors is True3748 assert get_completions("help") == [3749 "\x1b[000;00m\x1b[00mhelp\x1b[00m",3750 "\x1b[001;00m\x1b[33;01mhelpvar\x1b[00m",3751 " ",3752 ]3753 else:3754 assert pdbpp.local.GLOBAL_PDB.fancycompleter.config.use_colors is False3755 assert get_completions("help") == ["help", "helpvar"]3756 # Patch readline to return expected results for "p helpvar.".3757 monkeypatch_readline("p helpvar.", 2, 10)3758 if readline_param == "pyrepl":3759 assert pdbpp.local.GLOBAL_PDB.fancycompleter.config.use_colors is True3760 comps = get_completions("helpvar.")3761 assert type(helpvar.denominator) == int3762 assert any(3763 re.match(r"\x1b\[\d\d\d;00m\x1b\[33;01mdenominator\x1b\[00m", x)3764 for x in comps3765 )3766 assert " " in comps3767 else:3768 assert pdbpp.local.GLOBAL_PDB.fancycompleter.config.use_colors is False3769 comps = get_completions("helpvar.")3770 assert "denominator" in comps3771 assert " " not in comps3772 monkeypatch_readline("p obj.f", 2, 7)3773 comps = get_completions("obj.f")3774 assert comps == ['obj.foo']3775 monkeypatch_readline("p obj.foo", 2, 9)3776 comps = get_completions("obj.foo")3777 if readline_param == "pyrepl":3778 assert comps == [3779 '\x1b[000;00m\x1b[33;01mfoo\x1b[00m',3780 '\x1b[001;00m\x1b[33;01mfoobar\x1b[00m',3781 ' ']3782 else:3783 assert comps == ['foo', 'foobar', ' ']3784 monkeypatch_readline("disp", 0, 4)3785 comps = get_completions("disp")3786 assert comps == ['display']3787 return True3788 set_trace()3789 _, lineno = inspect.getsourcelines(fn)3790 check(fn, """3791--Return--3792[NUM] > .*fn()->None3793.*3794 5 frames hidden .*3795# check_completions()3796True3797# c3798""")3799class TestCompleteUnit:3800 def test_fancy_prefix_with_same_in_pdb(self, patched_completions):3801 assert patched_completions(3802 "p foo.b",3803 ["foo.bar"],3804 ["foo.bar", "foo.barbaz"]3805 ) == ["foo.bar"]3806 assert patched_completions(3807 "p foo.b",3808 ["foo.bar"],3809 ["foo.bar", "foo.barbaz", "foo.barbaz2"]3810 ) == ["foo.bar"]3811 def test_fancy_prefix_with_more_pdb(self, patched_completions):3812 assert patched_completions(3813 "p foo.b", ["foo.bar"], ["foo.bar", "foo.barbaz", "something else"]3814 ) == ["foo.bar", "foo.barbaz", "something else"]3815 def test_fancy_with_no_pdb(self, patched_completions,3816 fancycompleter_color_param):3817 if fancycompleter_color_param == "color":3818 fancy = [3819 "\x1b[000;00m\x1b[33;01mfoo\x1b[00m",3820 "\x1b[001;00m\x1b[33;01mfoobar\x1b[00m",3821 " ",3822 ]3823 else:3824 fancy = [3825 "foo",3826 "foobar",3827 " ",3828 ]3829 assert patched_completions("foo", fancy, []) == fancy3830 def test_fancy_with_prefixed_pdb(self, patched_completions):3831 assert patched_completions("sys.version", [3832 "version",3833 "version_info",3834 " ",3835 ], [3836 "sys.version",3837 "sys.version_info",3838 ]) == ["version", "version_info", " "]3839 def test_fancy_with_prefixed_pdb_other_text(self, patched_completions):3840 fancy = ["version", "version_info"]3841 pdb = ["sys.version", "sys.version_info"]3842 assert patched_completions("xxx", fancy, pdb) == fancy + pdb3843 def test_fancy_tab_without_pdb(self, patched_completions):3844 assert patched_completions("", ["\t"], []) == ["\t"]3845 def test_fancy_tab_with_pdb(self, patched_completions):3846 assert patched_completions("", ["\t"], ["help"]) == ["help"]3847def test_complete_uses_attributes_only_from_orig_pdb(3848 monkeypatch_readline, readline_param3849):3850 def fn():3851 def check_completions():3852 # Patch readline to return expected results for "p sys.version".3853 monkeypatch_readline("p sys.version", 2, 13)3854 if readline_param == "pyrepl":3855 assert pdbpp.local.GLOBAL_PDB.fancycompleter.config.use_colors is True3856 assert get_completions("sys.version") == [3857 "\x1b[000;00m\x1b[32;01mversion\x1b[00m",3858 "\x1b[001;00m\x1b[00mversion_info\x1b[00m",3859 " ",3860 ]3861 else:3862 assert pdbpp.local.GLOBAL_PDB.fancycompleter.config.use_colors is False3863 assert get_completions("sys.version") == [3864 "version",3865 "version_info",3866 " ",3867 ]3868 return True3869 set_trace()3870 _, lineno = inspect.getsourcelines(fn)3871 check(fn, """3872--Return--3873[NUM] > .*fn()->None3874.*3875 5 frames hidden .*3876# import sys3877# check_completions()3878True3879# c3880""")3881@pytest.mark.skipif(sys.version_info < (3, ), reason="py2: no completion for break")3882def test_completion_removes_tab_from_fancycompleter(monkeypatch_readline):3883 def fn():3884 def check_completions():3885 # Patch readline to return expected results for "b ".3886 monkeypatch_readline("b ", 2, 2)3887 comps = get_completions("")3888 assert "\t" not in comps3889 assert "inspect" in comps3890 return True3891 set_trace()3892 _, lineno = inspect.getsourcelines(fn)3893 check(fn, """3894--Return--3895[NUM] > .*fn()3896.*3897 5 frames hidden .*3898# check_completions()3899True3900# c3901""")3902def test_complete_with_bang(monkeypatch_readline):3903 """Test that completion works after "!".3904 This requires parseline to return "" for the command (bpo-35270).3905 """3906 def fn():3907 a_var = 1 # noqa: F8413908 def check_completions():3909 # Patch readline to return expected results for "!a_va".3910 monkeypatch_readline("!a_va", 0, 5)3911 assert pdbpp.local.GLOBAL_PDB.complete("a_va", 0) == "a_var"3912 # Patch readline to return expected results for "list(a_va".3913 monkeypatch_readline("list(a_va", 5, 9)3914 assert pdbpp.local.GLOBAL_PDB.complete("a_va", 0) == "a_var"3915 return True3916 set_trace()3917 check(fn, """3918--Return--3919[NUM] > .*fn()3920.*3921 5 frames hidden .*3922# check_completions()3923True3924# c3925""")3926def test_completer_after_debug(monkeypatch_readline):3927 def fn():3928 myvar = 1 # noqa: F8413929 def inner():3930 myinnervar = 1 # noqa: F8413931 def check_completions_inner():3932 # Patch readline to return expected results for "myin".3933 monkeypatch_readline("myin", 0, 4)3934 assert "myinnervar" in get_completions("myin")3935 return True3936 print("inner_end")3937 def check_completions():3938 # Patch readline to return expected results for "myva".3939 monkeypatch_readline("myva", 0, 4)3940 assert "myvar" in get_completions("myva")3941 return True3942 set_trace()3943 print("ok_end")3944 check(fn, """3945[NUM] > .*fn()3946.*3947 5 frames hidden .*3948# pdbpp.local.GLOBAL_PDB.curframe.f_code.co_name3949'fn'3950# debug inner()3951ENTERING RECURSIVE DEBUGGER3952[1] > <string>(1)<module>()3953(#) pdbpp.local.GLOBAL_PDB.curframe.f_code.co_name3954'<module>'3955(#) s3956--Call--3957[NUM] > .*inner()3958-> def inner():3959(#) pdbpp.local.GLOBAL_PDB.curframe.f_code.co_name3960'inner'3961(#) r3962inner_end3963--Return--3964[NUM] > .*inner()->None3965-> print("inner_end")3966(#) check_completions_inner()3967True3968(#) q3969LEAVING RECURSIVE DEBUGGER3970# check_completions()3971True3972# c3973ok_end3974""")3975def test_nested_completer(testdir):3976 p1 = testdir.makepyfile(3977 """3978 import sys3979 frames = []3980 def inner():3981 completeme_inner = 13982 frames.append(sys._getframe())3983 inner()3984 def outer():3985 completeme_outer = 23986 __import__('pdbpp').set_trace()3987 outer()3988 """3989 )3990 with open(".fancycompleterrc.py", "w") as f:3991 f.write(textwrap.dedent("""3992 from fancycompleter import DefaultConfig3993 class Config(DefaultConfig):3994 use_colors = False3995 prefer_pyrepl = False3996 """))3997 testdir.monkeypatch.setenv("PDBPP_COLORS", "0")3998 child = testdir.spawn("{} {}".format(quote(sys.executable), str(p1)))3999 child.send("completeme\t")4000 child.expect_exact("\r\n(Pdb++) completeme_outer")4001 child.send("\nimport pdbpp; _p = pdbpp.Pdb(); _p.reset()")4002 child.send("\n_p.interaction(frames[0], None)\n")4003 child.expect_exact("\r\n-> frames.append(sys._getframe())\r\n(Pdb++) ")4004 child.send("completeme\t")4005 child.expect_exact("completeme_inner")4006 child.send("\nq\n")4007 child.send("completeme\t")4008 child.expect_exact("completeme_outer")4009 child.send("\n")4010 child.sendeof()4011def test_ensure_file_can_write_unicode():4012 out = io.BytesIO(b"")4013 stdout = io.TextIOWrapper(out, encoding="latin1")4014 p = Pdb(Config=DefaultConfig, stdout=stdout)4015 assert p.stdout.stream is out4016 p.stdout.write(u"test äöüÃ")4017 out.seek(0)4018 assert out.read().decode("utf-8") == u"test äöüÃ"4019@pytest.mark.skipif(sys.version_info >= (3, 0),4020 reason="test is python2 specific")4021def test_py2_ensure_file_can_write_unicode():4022 import StringIO4023 stdout = StringIO.StringIO()4024 stdout.encoding = 'ascii'4025 p = Pdb(Config=DefaultConfig, stdout=stdout)4026 assert p.stdout.stream is stdout4027 p.stdout.write(u"test äöüÃ")4028 stdout.seek(0)4029 assert stdout.read().decode('utf-8') == u"test äöüÃ"4030def test_signal_in_nonmain_thread_with_interaction():4031 def fn():4032 import threading4033 evt = threading.Event()4034 def start_thread():4035 evt.wait()4036 set_trace(nosigint=False)4037 t = threading.Thread(target=start_thread)4038 t.start()4039 set_trace(nosigint=False)4040 evt.set()4041 t.join()4042 check(fn, """4043[NUM] > .*fn()4044-> evt.set()4045 5 frames hidden .*4046# c4047--Return--4048[NUM] > .*start_thread()->None4049-> set_trace(nosigint=False)4050# c4051""")4052def test_signal_in_nonmain_thread_with_continue():4053 """Test for cpython issue 13120 (test_issue13120).4054 Without the try/execept for ValueError in its do_continue it would4055 display the exception, but work otherwise.4056 """4057 def fn():4058 import threading4059 def start_thread():4060 a = 42 # noqa F8414061 set_trace(nosigint=False)4062 t = threading.Thread(target=start_thread)4063 t.start()4064 # set_trace(nosigint=False)4065 t.join()4066 check(fn, """4067--Return--4068[NUM] > .*start_thread()->None4069-> set_trace(nosigint=False)4070# p a4071424072# c4073""")4074def test_next_at_end_of_stack_after_unhide():4075 """Test that compute_stack returns correct length with show_hidden_frames."""4076 class MyConfig(ConfigTest):4077 def before_interaction_hook(self, pdb):4078 pdb.stdout.write('before_interaction_hook\n')4079 pdb.do_hf_unhide(arg=None)4080 def fn():4081 set_trace(Config=MyConfig)4082 return 14083 check(fn, """4084[NUM] > .*fn()4085-> return 14086 5 frames hidden .*4087before_interaction_hook4088# n4089--Return--4090[NUM] > .*fn()->14091-> return 14092 5 frames hidden .*4093before_interaction_hook4094# c4095""")4096def test_compute_stack_keeps_frame():4097 """With only hidden frames the last one is kept."""4098 def fn():4099 def raises():4100 raise Exception("foo")4101 try:4102 raises()4103 except Exception:4104 tb = sys.exc_info()[2]4105 tb_ = tb4106 while tb_:4107 tb_.tb_frame.f_locals["__tracebackhide__"] = True4108 tb_ = tb_.tb_next4109 pdbpp.post_mortem(tb, Pdb=PdbTest)4110 return 14111 check(fn, """4112[0] > .*raises()4113-> raise Exception("foo")4114 1 frame hidden (try 'help hidden_frames')4115# bt4116> [0] .*raises()4117 raise Exception("foo")4118# hf_unhide4119# bt4120 [0] .*fn()4121 raises()4122> [1] .*raises()4123 raise Exception("foo")4124# q4125""")4126def test_compute_stack_without_stack():4127 pdb_ = PdbTest()4128 assert pdb_.compute_stack([], idx=None) == ([], 0)4129 assert pdb_.compute_stack([], idx=0) == ([], 0)4130 assert pdb_.compute_stack([], idx=10) == ([], 10)4131def test_rawinput_with_debug():4132 """Test backport of fix for bpo-31078."""4133 def fn():4134 set_trace()4135 check(fn, """4136--Return--4137[NUM] > .*fn()4138-> set_trace()4139 5 frames hidden .*4140# debug 14141ENTERING RECURSIVE DEBUGGER4142[NUM] > <string>(1)<module>()->None4143(#) import pdb; print(pdbpp.local.GLOBAL_PDB.use_rawinput)414414145(#) p sys._getframe().f_back.f_locals['self'].use_rawinput414614147(#) c4148LEAVING RECURSIVE DEBUGGER4149# c4150""")4151def test_error_with_traceback():4152 def fn():4153 def error():4154 raise ValueError("error")4155 set_trace()4156 check(fn, """4157--Return--4158[NUM] > .*fn()4159-> set_trace()4160 5 frames hidden .*4161# error()4162\\*\\*\\* ValueError: error4163Traceback (most recent call last):4164 File .*, in error4165 raise ValueError("error")4166# c4167""")4168def test_chained_syntaxerror_with_traceback():4169 def fn():4170 def compile_error():4171 compile("invalid(", "<stdin>", "single")4172 def error():4173 try:4174 compile_error()4175 except Exception:4176 raise AttributeError4177 set_trace()4178 if sys.version_info > (3,):4179 if sys.version_info >= (3, 10, 0, "final") and sys.version_info <= (3, 10, 1):4180 # changed after rc2 (bpo-45249), fixed in 3.10.1.4181 caret_line = " $"4182 else:4183 caret_line = " .*^"4184 check(fn, """4185--Return--4186[NUM] > .*fn()4187-> set_trace()4188 5 frames hidden .*4189# error()4190\\*\\*\\* AttributeError.*4191Traceback (most recent call last):4192 File .*, in error4193 compile_error()4194 File .*, in compile_error4195 compile.*4196 File "<stdin>", line 14197 invalid(4198""" + caret_line + """4199SyntaxError: .*4200During handling of the above exception, another exception occurred:4201Traceback (most recent call last):4202 File .*, in error4203 raise AttributeError4204# c4205""")4206 else:4207 check(fn, """4208--Return--4209[NUM] > .*fn()4210-> set_trace()4211 5 frames hidden .*4212# error()4213\\*\\*\\* AttributeError.*4214Traceback (most recent call last):4215 File .*, in error4216 raise AttributeError4217# c4218""")4219def test_error_with_traceback_disabled():4220 class ConfigWithoutTraceback(ConfigTest):4221 show_traceback_on_error = False4222 def fn():4223 def error():4224 raise ValueError("error")4225 set_trace(Config=ConfigWithoutTraceback)4226 check(fn, """4227--Return--4228[NUM] > .*fn()4229-> set_trace(Config=ConfigWithoutTraceback)4230 5 frames hidden .*4231# error()4232\\*\\*\\* ValueError: error4233# c4234""")4235def test_error_with_traceback_limit():4236 class ConfigWithLimit(ConfigTest):4237 show_traceback_on_error_limit = 24238 def fn():4239 def f(i):4240 i -= 14241 if i <= 0:4242 raise ValueError("the_end")4243 f(i)4244 def error():4245 f(10)4246 set_trace(Config=ConfigWithLimit)4247 check(fn, """4248--Return--4249[NUM] > .*fn()4250-> set_trace(Config=ConfigWithLimit)4251 5 frames hidden .*4252# error()4253\\*\\*\\* ValueError: the_end4254Traceback (most recent call last):4255 File .*, in error4256 f(10)4257 File .*, in f4258 f(i)4259# c4260""")4261@pytest.mark.parametrize("show", (True, False))4262def test_complete_displays_errors(show, monkeypatch, LineMatcher):4263 class Config(ConfigTest):4264 show_traceback_on_error = show4265 def raises(*args):4266 raise ValueError("err_complete")4267 monkeypatch.setattr("pdbpp.Pdb._get_all_completions", raises)4268 def fn():4269 set_trace(Config=Config)4270 out = runpdb(fn, ["get_completions('test')", "c"])4271 lm = LineMatcher(out)4272 if show:4273 lm.fnmatch_lines([4274 "--Return--",4275 "[[]*[]] > *fn()->None",4276 "-> set_trace(Config=Config)",4277 " 5 frames hidden (try 'help hidden_frames')",4278 "# get_completions('test')",4279 "*** error during completion: err_complete",4280 "ValueError: err_complete",4281 "[[][]]",4282 "# c",4283 ])4284 else:4285 lm.fnmatch_lines([4286 "[[]*[]] > *fn()->None",4287 "-> set_trace(Config=Config)",4288 " 5 frames hidden (try 'help hidden_frames')",4289 "# get_completions('test')",4290 "*** error during completion: err_complete",4291 "??",4292 "# c",4293 ])4294def test_next_with_exception_in_call():4295 """Ensure that "next" works correctly with exception (in try/except).4296 Previously it would display the frame where the exception occurred, and4297 then "next" would continue, instead of stopping at the next statement.4298 """4299 def fn():4300 def keyerror():4301 raise KeyError4302 set_trace()4303 try:4304 keyerror()4305 except KeyError:4306 print("got_keyerror")4307 check(fn, """4308[NUM] > .*fn()4309-> try:4310 5 frames hidden .*4311# n4312[NUM] > .*fn()4313-> keyerror()4314 5 frames hidden .*4315# n4316KeyError4317[NUM] > .*fn()4318-> keyerror()4319 5 frames hidden .*4320# n4321[NUM] > .*fn()4322-> except KeyError:4323 5 frames hidden .*4324# c4325got_keyerror4326""")4327def test_locals():4328 def fn():4329 def f():4330 set_trace()4331 print("foo=%s" % foo) # noqa: F8214332 foo = 2 # noqa: F8414333 f()4334 check(fn, """4335[NUM] > .*f()4336-> print("foo=%s" % foo)4337 5 frames hidden .*4338# foo = 424339# foo4340424341# pp foo4342424343# p foo4344424345# c4346foo=424347""")4348def test_locals_with_list_comprehension():4349 def fn():4350 mylocal = 1 # noqa: F8414351 set_trace()4352 print(mylocal)4353 check(fn, """4354[NUM] > .*fn()4355-> print(mylocal)4356 5 frames hidden .*4357# mylocal435814359# [x for x in str(mylocal)]4360['1']4361# [mylocal for x in range(1)]4362[1]4363# mylocal = 424364# [x for x in str(mylocal)]4365['4', '2']4366# [mylocal for x in range(1)]4367[42]4368# c4369424370""")4371def test_get_editor_cmd(monkeypatch):4372 _pdb = PdbTest()4373 _pdb.config.editor = None4374 monkeypatch.setenv("EDITOR", "nvim")4375 assert _pdb._get_editor_cmd("fname", 42) == "nvim +42 fname"4376 monkeypatch.setenv("EDITOR", "")4377 with pytest.raises(RuntimeError, match=(4378 r"Could not detect editor. Configure it or set \$EDITOR."4379 )):4380 _pdb._get_editor_cmd("fname", 42)4381 monkeypatch.delenv("EDITOR")4382 try:4383 which = "shutil.which"4384 monkeypatch.setattr(which, lambda x: None)4385 except AttributeError:4386 which = "distutils.spawn.find_executable"4387 monkeypatch.setattr(which, lambda x: None)4388 with pytest.raises(RuntimeError, match=(4389 r"Could not detect editor. Configure it or set \$EDITOR."4390 )):4391 _pdb._get_editor_cmd("fname", 42)4392 monkeypatch.setattr(which, lambda x: "vim")4393 assert _pdb._get_editor_cmd("fname", 42) == "vim +42 fname"4394 monkeypatch.setattr(which, lambda x: "vi")4395 assert _pdb._get_editor_cmd("fname", 42) == "vi +42 fname"4396 _format = _pdb._format_editcmd4397 assert _format("subl {filename}:{lineno}", "with space", 12) == (4398 "subl 'with space':12")4399 assert _format("edit", "with space", 12) == (4400 "edit +12 'with space'")4401 assert _format("edit +%%%d %%%s%% %d", "with space", 12) == (4402 "edit +%12 %'with space'% 12")4403def test_edit_error(monkeypatch):4404 class MyConfig(ConfigTest):4405 editor = None4406 monkeypatch.setenv("EDITOR", "")4407 def fn():4408 set_trace(Config=MyConfig)4409 check(fn, r"""4410--Return--4411[NUM] > .*fn()4412-> set_trace(Config=MyConfig)4413 5 frames hidden .*4414# edit4415\*\*\* Could not detect editor. Configure it or set \$EDITOR.4416# c4417""")4418def test_global_pdb_per_thread_with_input_lock():4419 def fn():4420 import threading4421 evt1 = threading.Event()4422 evt2 = threading.Event()4423 def __t1__(evt1, evt2):4424 set_trace(cleanup=False)4425 def __t2__(evt2):4426 evt2.set()4427 set_trace(cleanup=False)4428 t1 = threading.Thread(name="__t1__", target=__t1__, args=(evt1, evt2))4429 t1.start()4430 assert evt1.wait(1.0) is True4431 t2 = threading.Thread(name="__t2__", target=__t2__, args=(evt2,))4432 t2.start()4433 t1.join()4434 t2.join()4435 check(fn, r"""4436--Return--4437[NUM] > .*__t1__()4438-> set_trace(cleanup=False)4439# evt1.set()4440# import threading; threading.current_thread().name4441'__t1__'4442# assert evt2.wait(1.0) is True; import time; time.sleep(0.1)4443--Return--4444[NUM] > .*__t2__()->None4445-> set_trace(cleanup=False)4446# import threading; threading.current_thread().name4447'__t2__'4448# c4449# import threading; threading.current_thread().name4450'__t1__'4451# c4452""")4453def test_usage_error_with_commands():4454 def fn():4455 set_trace()4456 check(fn, r"""4457--Return--4458[NUM] > .*fn()->None4459-> set_trace()4460 5 frames hidden .*4461# commands invalid4462.*Usage.*: commands [bnum]4463 ...4464 end4465# c4466""")4467@pytest.mark.skipif(sys.version_info < (3,),4468 reason="py2 has no support for kwonly")4469def test_rebind_globals_kwonly():4470 exec("def func(*args, header=None): pass", globals())4471 func = globals()["func"]4472 sig = str(inspect.signature(func))4473 assert sig == "(*args, header=None)"4474 new = pdbpp.rebind_globals(func, globals())4475 assert str(inspect.signature(new)) == sig4476@pytest.mark.skipif(sys.version_info < (3,),4477 reason="py2 has no support for annotations")4478def test_rebind_globals_annotations():4479 exec("def func(ann: str = None): pass", globals())4480 func = globals()["func"]4481 sig = str(inspect.signature(func))4482 if sys.version_info < (3, 5):4483 assert sig == "(ann:str=None)"4484 else:4485 assert sig in (4486 "(ann: str = None)",4487 "(ann:str=None)",4488 )4489 new = pdbpp.rebind_globals(func, globals())4490 assert str(inspect.signature(new)) == sig4491def test_rebind_globals_with_partial():4492 import functools4493 global test_global4494 test_global = 04495 def func(a, b):4496 global test_global4497 return a + b + test_global4498 pfunc = functools.partial(func)4499 assert pfunc(0, 0) == 04500 newglobals = globals().copy()4501 newglobals['test_global'] = 14502 new = pdbpp.rebind_globals(pfunc, newglobals)4503 assert new(1, 40) == 424504def test_debug_with_set_trace():4505 def fn():4506 def inner():4507 def inner_inner():4508 pass4509 set_trace(cleanup=False)4510 set_trace()4511 check(fn, """4512--Return--4513[NUM] > .*fn()4514.*4515 5 frames hidden .*4516# debug inner()4517ENTERING RECURSIVE DEBUGGER4518[NUM] > <string>(1)<module>()->None4519(#) r4520--Return--4521[NUM] > .*inner()->None4522-> set_trace(cleanup=False)4523 5 frames hidden .*4524(#) pdbpp.local.GLOBAL_PDB.curframe.f_code.co_name4525'inner'4526(#) debug inner_inner()4527ENTERING RECURSIVE DEBUGGER4528[NUM] > <string>(1)<module>()->None4529((#)) c4530LEAVING RECURSIVE DEBUGGER4531(#) c4532LEAVING RECURSIVE DEBUGGER4533# c4534""")4535def test_set_trace_with_incomplete_pdb():4536 def fn():4537 existing_pdb = PdbTest()4538 assert not hasattr(existing_pdb, "botframe")4539 set_trace(cleanup=False)4540 assert hasattr(existing_pdb, "botframe")4541 assert pdbpp.local.GLOBAL_PDB is existing_pdb4542 check(fn, """4543[NUM] > .*fn()4544.*4545 5 frames hidden .*4546# c4547""")4548def test_config_gets_start_filename():4549 def fn():4550 setup_lineno = set_trace.__code__.co_firstlineno + 84551 set_trace_lineno = sys._getframe().f_lineno + 84552 class MyConfig(ConfigTest):4553 def setup(self, pdb):4554 print("config_setup")4555 assert pdb.start_filename.lower() == THIS_FILE_CANONICAL.lower()4556 assert pdb.start_lineno == setup_lineno4557 set_trace(Config=MyConfig)4558 assert pdbpp.local.GLOBAL_PDB.start_lineno == set_trace_lineno4559 check(fn, r"""4560config_setup4561[NUM] > .*fn()4562-> assert pdbpp.local.GLOBAL_PDB.start_lineno == set_trace_lineno4563 5 frames hidden .*4564# c4565""")4566def test_do_bt():4567 def fn():4568 set_trace()4569 expected_bt = []4570 for i, entry in enumerate(traceback.extract_stack()[:-3]):4571 expected_bt.append(" [%2d] .*" % i)4572 expected_bt.append(" .*")4573 check(fn, r"""4574--Return--4575[NUM] > .*fn()->None4576-> set_trace()4577 5 frames hidden .*4578# bt4579{expected}4580 [NUM] .*(NUM)runpdb()4581 func()4582> [NUM] .*(NUM)fn()->None4583 set_trace()4584# c4585""".format(expected="\n".join(expected_bt)))4586def test_do_bt_highlight():4587 def fn():4588 set_trace(Config=ConfigWithHighlight)4589 expected_bt = []4590 for i, entry in enumerate(traceback.extract_stack()[:-3]):4591 expected_bt.append(" [%2d] .*" % i)4592 expected_bt.append(" .*")4593 check(fn, r"""4594--Return--4595[NUM] > .*fn()->None4596-> set_trace(Config=ConfigWithHighlight)4597 5 frames hidden .*4598# bt4599{expected}4600 [NUM] ^[[33;01m.*\.py^[[00m(^[[36;01mNUM^[[00m)runpdb()4601 func()4602> [NUM] ^[[33;01m.*\.py^[[00m(^[[36;01mNUM^[[00m)fn()->None4603 set_trace(Config=ConfigWithHighlight)4604# c4605""".format(expected="\n".join(expected_bt)))4606def test_do_bt_pygments():4607 def fn():4608 set_trace(Config=ConfigWithPygments)4609 expected_bt = []4610 for i, entry in enumerate(traceback.extract_stack()[:-3]):4611 expected_bt.append(" [%2d] .*" % i)4612 expected_bt.append(" .*")4613 check(fn, r"""4614--Return--4615[NUM] > .*fn()->None4616-> set_trace(Config^[[38;5;241m=^[[39mConfigWithPygments)4617 5 frames hidden .*4618# bt4619{expected}4620 [NUM] .*(NUM)runpdb()4621 func()4622> [NUM] .*\.py(NUM)fn()->None4623 set_trace(Config^[[38;5;241m=^[[39mConfigWithPygments)4624# c4625""".format(expected="\n".join(expected_bt)))4626def test_debug_with_pygments():4627 def fn():4628 set_trace(Config=ConfigWithPygments)4629 check(fn, r"""4630--Return--4631[NUM] > .*fn()->None4632-> set_trace(Config^[[38;5;241m=^[[39mConfigWithPygments)4633 5 frames hidden .*4634# debug 14635ENTERING RECURSIVE DEBUGGER4636[1] > <string>(1)<module>()->None4637(#) c4638LEAVING RECURSIVE DEBUGGER4639# c4640""")4641def test_debug_with_pygments_and_highlight():4642 def fn():4643 set_trace(Config=ConfigWithPygmentsAndHighlight)4644 check(fn, r"""4645--Return--4646[NUM] > .*fn()->None4647-> set_trace(Config^[[38;5;241m=^[[39mConfigWithPygmentsAndHighlight)4648 5 frames hidden .*4649# debug 14650ENTERING RECURSIVE DEBUGGER4651[1] > ^[[33;01m<string>^[[00m(^[[36;01m1^[[00m)<module>()->None4652(#) c4653LEAVING RECURSIVE DEBUGGER4654# c4655""")4656def test_set_trace_in_default_code():4657 """set_trace while not tracing and should not (re)set the global pdb."""4658 def fn():4659 def f():4660 before = pdbpp.local.GLOBAL_PDB4661 set_trace(cleanup=False)4662 assert before is pdbpp.local.GLOBAL_PDB4663 set_trace()4664 check(fn, r"""4665--Return--4666[NUM] > .*fn()->None4667-> set_trace()4668 5 frames hidden .*4669# f()4670# import pdbpp; pdbpp.local.GLOBAL_PDB.curframe is not None4671True4672# l {line_num}, 24673NUM \t def fn():4674NUM \t def f():4675NUM \t before = pdbpp.local.GLOBAL_PDB4676# c4677 """.format(4678 line_num=fn.__code__.co_firstlineno,4679 ))4680def test_error_with_pp():4681 def fn():4682 class BadRepr:4683 def __repr__(self):4684 raise Exception('repr_exc')4685 obj = BadRepr() # noqa: F8414686 set_trace()4687 check(fn, r"""4688--Return--4689[NUM] > .*fn()->None4690-> set_trace()4691 5 frames hidden .*4692# p obj4693\*\*\* Exception: repr_exc4694# pp obj4695\*\*\* Exception: repr_exc4696# pp BadRepr.__repr__()4697\*\*\* TypeError: .*__repr__.*4698# c4699""")4700def test_count_with_pp():4701 def fn():4702 set_trace()4703 check(fn, r"""4704--Return--4705[NUM] > .*fn()->None4706-> set_trace()4707 5 frames hidden .*4708# pp [1, 2, 3]4709[1, 2, 3]4710# 2pp [1, 2, 3]4711[1,4712 2,4713 3]4714# 80pp [1, 2, 3]4715[1, 2, 3]4716# c4717""")4718def test_ArgWithCount():4719 from pdbpp import ArgWithCount4720 obj = ArgWithCount("", None)4721 assert obj == ""4722 assert repr(obj) == "<ArgWithCount cmd_count=None value=''>"4723 assert isinstance(obj, str)4724 obj = ArgWithCount("foo", 42)4725 assert obj == "foo"4726 assert repr(obj) == "<ArgWithCount cmd_count=42 value='foo'>"4727def test_do_source():4728 def fn():4729 set_trace()4730 check(fn, r"""4731--Return--4732[NUM] > .*fn()->None4733-> set_trace()4734 5 frames hidden .*4735# source ConfigWithPygmentsAndHighlight4736\d\d class ConfigWithPygmentsAndHighlight(ConfigWithPygments, ConfigWithHigh$4737\d\d pass4738# c4739""")4740def test_do_source_with_pygments():4741 def fn():4742 set_trace(Config=ConfigWithPygments)4743 check(fn, r"""4744--Return--4745[NUM] > .*fn()->None4746-> set_trace(Config^[[38;5;241m=^[[39mConfigWithPygments)4747 5 frames hidden .*4748# source ConfigWithPygmentsAndHighlight4749\d\d ^[[38;5;28;01mclass^[[39;00m ^[[38;5;21;01mConfigWithPygmentsAndHighlight^[[39;00m(ConfigWithPygments, ConfigWithHigh$4750\d\d ^[[38;5;28;01mpass^[[39;00m4751# c4752""") # noqa: E5014753def test_do_source_with_highlight():4754 def fn():4755 set_trace(Config=ConfigWithHighlight)4756 check(fn, r"""4757--Return--4758[NUM] > .*fn()->None4759-> set_trace(Config=ConfigWithHighlight)4760 5 frames hidden .*4761# source ConfigWithPygmentsAndHighlight4762^[[36;01m\d\d^[[00m class ConfigWithPygmentsAndHighlight(ConfigWithPygments, ConfigWithHigh$4763^[[36;01m\d\d^[[00m pass4764# c4765""") # noqa: E5014766def test_do_source_with_pygments_and_highlight():4767 def fn():4768 set_trace(Config=ConfigWithPygmentsAndHighlight)4769 check(fn, r"""4770--Return--4771[NUM] > .*fn()->None4772-> set_trace(Config^[[38;5;241m=^[[39mConfigWithPygmentsAndHighlight)4773 5 frames hidden .*4774# source ConfigWithPygmentsAndHighlight4775^[[36;01m\d\d^[[00m ^[[38;5;28;01mclass^[[39;00m ^[[38;5;21;01mConfigWithPygmentsAndHighlight^[[39;00m(ConfigWithPygments, ConfigWithHigh$4776^[[36;01m\d\d^[[00m ^[[38;5;28;01mpass^[[39;00m4777# c4778""") # noqa: E5014779def test_do_source_without_truncating():4780 def fn():4781 class Config(ConfigTest):4782 truncate_long_lines = False4783 set_trace(Config=Config)4784 check(fn, r"""4785--Return--4786[NUM] > .*fn()->None4787-> set_trace(Config=Config)4788 5 frames hidden .*4789# source ConfigWithPygmentsAndHighlight4790\d\d class ConfigWithPygmentsAndHighlight(ConfigWithPygments, ConfigWithHighlight):$4791\d\d pass4792# c4793""")4794def test_handles_set_trace_in_config(tmpdir):4795 """Should not cause a RecursionError."""4796 def fn():4797 class Config(ConfigTest):4798 def __init__(self, *args, **kwargs):4799 print("Config.__init__")4800 # Becomes a no-op.4801 set_trace(Config=Config)4802 print("after_set_trace")4803 set_trace(Config=Config)4804 check(fn, r"""4805Config.__init__4806pdb\+\+: using pdb.Pdb for recursive set_trace.4807> .*__init__()4808-> print("after_set_trace")4809(Pdb) c4810after_set_trace4811--Return--4812[NUM] > .*fn()->None4813-> set_trace(Config=Config)4814 5 frames hidden .*4815# c4816""")4817def test_only_question_mark(monkeypatch):4818 def fn():4819 set_trace()4820 a = 14821 return a4822 monkeypatch.setattr(PdbTest, "do_help", lambda self, arg: print("do_help"))4823 check(fn, """4824[NUM] > .*fn()4825-> a = 14826 5 frames hidden .*4827# ?4828do_help4829# c4830""")4831@pytest.mark.parametrize('s,maxlength,expected', [4832 pytest.param('foo', 3, 'foo', id='id1'),4833 pytest.param('foo', 1, 'f', id='id2'),4834 # Keeps trailing escape sequences (for reset at least).4835 pytest.param("\x1b[39m1\x1b[39m23", 1, "\x1b[39m1\x1b[39m", id="id3"),4836 pytest.param("\x1b[39m1\x1b[39m23", 2, "\x1b[39m1\x1b[39m2", id="id4"),4837 pytest.param("\x1b[39m1\x1b[39m23", 3, "\x1b[39m1\x1b[39m23", id="id5"),4838 pytest.param("\x1b[39m1\x1b[39m23", 100, "\x1b[39m1\x1b[39m23", id="id5"),4839 pytest.param("\x1b[39m1\x1b[39m", 100, "\x1b[39m1\x1b[39m", id="id5"),4840])4841def test_truncate_to_visible_length(s, maxlength, expected):4842 assert pdbpp.Pdb._truncate_to_visible_length(s, maxlength) == expected4843def test_keeps_reset_escape_sequence_with_source_highlight():4844 class MyConfig(ConfigWithPygmentsAndHighlight):4845 sticky_by_default = True4846 def fn():4847 set_trace(Config=MyConfig)4848 a = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaX" # noqa: E5014849 b = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbX" # noqa: E5014850 return a, b4851 check(fn, """4852[NUM] > .*fn()4853<COLORNUM> ^[[38;5;28;01mdef^[[39;00m ^[[38;5;21mfn^[[39m():4854<COLORNUM> set_trace(Config^[[38;5;241m=^[[39mMyConfig)4855<COLORNUM> $4856<COLORCURLINE> -> a ^[[38;5;241;44m=^[[39;44m ^[[38;5;124;44m"^[[39;44m^[[38;5;124;44maaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa^[[39;44m^[[38;5;124;44m<PYGMENTSRESET><COLORRESET>4857<COLORNUM> b ^[[38;5;241m=^[[39m ^[[38;5;124m"^[[39m^[[38;5;124mbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb^[[39m^[[38;5;124m<PYGMENTSRESET>4858<COLORNUM> ^[[38;5;28;01mreturn^[[39;00m a, b4859# c4860""") # noqa: E5014861@pytest.mark.parametrize("pass_stdout", (True, False))4862def test_stdout_reconfigured(pass_stdout, monkeypatch):4863 """Check that self.stdout is re-configured with global pdb."""4864 def fn():4865 import sys4866 if sys.version_info > (3,):4867 from io import StringIO4868 else:4869 from StringIO import StringIO4870 patched_stdout = StringIO()4871 with monkeypatch.context() as mp:4872 mp.setattr(sys, "stdout", patched_stdout)4873 class _PdbTestKeepRawInput(PdbTest):4874 def __init__(4875 self, completekey="tab", stdin=None, stdout=None, *args, **kwargs4876 ):4877 if pass_stdout:4878 stdout = sys.stdout4879 else:4880 stdout = None4881 super(_PdbTestKeepRawInput, self).__init__(4882 completekey, stdin, stdout, *args, **kwargs4883 )4884 # Keep this, which gets set to 0 with stdin being passed in.4885 self.use_rawinput = True4886 set_trace(Pdb=_PdbTestKeepRawInput)4887 assert pdbpp.local.GLOBAL_PDB.stdout is patched_stdout4888 print(patched_stdout.getvalue())4889 patched_stdout.close()4890 set_trace(Pdb=_PdbTestKeepRawInput, cleanup=False)4891 assert pdbpp.local.GLOBAL_PDB.stdout is sys.stdout4892 print('# c') # Hack to reflect output in test.4893 return4894 check(fn, """4895[NUM] > .*fn()4896-> assert pdbpp.local.GLOBAL_PDB.stdout is sys.stdout4897 5 frames hidden .*4898# c4899# c4900""")4901def test_position_of_obj_unwraps():4902 import contextlib4903 @contextlib.contextmanager4904 def cm():4905 raise NotImplementedError()4906 pdb_ = PdbTest()4907 pos = pdb_._get_position_of_obj(cm)4908 if hasattr(inspect, "unwrap"):4909 assert pos[0] == THIS_FILE_CANONICAL4910 assert pos[2] == [4911 " @contextlib.contextmanager\n",4912 " def cm():\n",4913 " raise NotImplementedError()\n",4914 ]4915 else:4916 contextlib_file = contextlib.__file__4917 if sys.platform == 'win32':4918 contextlib_file = contextlib_file.lower()4919 assert pos[0] == contextlib_file.rstrip("c")4920def test_set_trace_in_skipped_module(testdir):4921 def fn():4922 class SkippingPdbTest(PdbTest):4923 def __init__(self, *args, **kwargs):4924 kwargs["skip"] = ["testing.test_pdb"]4925 super(SkippingPdbTest, self).__init__(*args, **kwargs)4926 self.calls = []4927 def is_skipped_module(self, module_name):4928 self.calls.append(module_name)4929 if len(self.calls) == 1:4930 print("is_skipped_module?", module_name)4931 ret = super(SkippingPdbTest, self).is_skipped_module(module_name)4932 assert module_name == "testing.test_pdb"4933 assert ret is True4934 return True4935 return False4936 set_trace(Pdb=SkippingPdbTest) # 14937 set_trace(Pdb=SkippingPdbTest, cleanup=False) # 24938 set_trace(Pdb=SkippingPdbTest, cleanup=False) # 34939 check(fn, r"""4940[NUM] > .*fn()4941-> set_trace(Pdb=SkippingPdbTest, cleanup=False) # 24942 5 frames hidden (try 'help hidden_frames')4943# n4944is_skipped_module\? testing.test_pdb4945[NUM] > .*fn()4946-> set_trace(Pdb=SkippingPdbTest, cleanup=False) # 34947 5 frames hidden (try 'help hidden_frames')4948# c4949--Return--4950[NUM] > .*fn()4951-> set_trace(Pdb=SkippingPdbTest, cleanup=False) # 34952 5 frames hidden (try 'help hidden_frames')4953# c4954""")4955def test_exception_info_main(testdir):4956 """Test that interaction adds __exception__ similar to user_exception."""4957 p1 = testdir.makepyfile(4958 """4959 def f():4960 raise ValueError("foo")4961 f()4962 """4963 )4964 testdir.monkeypatch.setenv("PDBPP_COLORS", "0")4965 result = testdir.run(4966 sys.executable, "-m", "pdbpp", str(p1),4967 stdin=b"p 'sticky'\nsticky\np 'cont'\ncont\np 'quit'\nq\n",4968 )4969 result.stdout.lines = [4970 ln.replace(pdbpp.CLEARSCREEN, "<CLEARSCREEN>") for ln in result.stdout.lines4971 ]4972 assert result.stdout.str().count("<CLEARSCREEN>") == 24973 if (3,) <= sys.version_info <= (3, 5):4974 # NOTE: skipping explicit check for slighty different output with py34.4975 return4976 result.stdout.fnmatch_lines(4977 [4978 "(Pdb++) 'sticky'",4979 "(Pdb++) <CLEARSCREEN>[[]2[]] > */test_exception_info_main.py(1)<module>()",4980 "(Pdb++) 'cont'",4981 "(Pdb++) Uncaught exception. Entering post mortem debugging",4982 # NOTE: this explicitly checks for a missing CLEARSCREEN in front.4983 "[[]5[]] > *test_exception_info_main.py(2)f()",4984 "",4985 "1 def f():",4986 '2 -> raise ValueError("foo")',4987 "ValueError: foo",4988 "(Pdb++) 'quit'",4989 "(Pdb++) Post mortem debugger finished. *",4990 "<CLEARSCREEN>[[]2[]] > */test_exception_info_main.py(1)<module>()",4991 ]4992 )4993def test_interaction_no_exception():4994 """Check that it does not display `None`."""4995 def outer():4996 try:4997 raise ValueError()4998 except ValueError:4999 return sys.exc_info()[2]5000 def fn():5001 tb = outer()5002 pdb_ = PdbTest()5003 pdb_.reset()5004 pdb_.interaction(None, tb)5005 check(fn, """5006[NUM] > .*outer()5007-> raise ValueError()5008# sticky5009[0] > .*outer()5010NUM def outer():5011NUM try:5012NUM >> raise ValueError()5013NUM except ValueError:5014NUM -> return sys.exc_info()[2]5015# q5016""")5017def test_debug_in_post_mortem_does_not_trace_itself():5018 def fn():5019 try:5020 raise ValueError()5021 except:5022 pdbpp.post_mortem(Pdb=PdbTest)5023 a = 15024 return a5025 check(fn, """5026[0] > .*fn()5027-> raise ValueError()5028# debug "".strip()5029ENTERING RECURSIVE DEBUGGER5030[1] > <string>(1)<module>()5031(#) s5032--Return--5033[1] > <string>(1)<module>()->None5034(#) q5035LEAVING RECURSIVE DEBUGGER5036# q5037""")5038class TestCommands:5039 @staticmethod5040 def fn():5041 def f():5042 print(a)5043 a = 05044 set_trace()5045 for i in range(5):5046 a += i5047 f()5048 def test_commands_with_sticky(self):5049 check(5050 self.fn,5051 r"""5052 [NUM] > .*fn()5053 -> for i in range(5):5054 5 frames hidden .*5055 # sticky5056 <CLEARSCREEN>5057 [NUM] > .*(), 5 frames hidden5058 NUM @staticmethod5059 NUM def fn():5060 NUM def f():5061 NUM print(a)5062 NUM $5063 NUM a = 05064 NUM set_trace()5065 NUM $5066 NUM -> for i in range(5):5067 NUM a \+= i5068 NUM f()5069 # break f, a==65070 Breakpoint NUM at .*5071 # commands5072 (com++) print("stop", a)5073 (com++) end5074 # c5075 05076 15077 35078 stop 6...
Network.py
Source:Network.py
...12 # an affine operation: y = Wx + b13 self.layer2 = nn.Linear(912, 64) # from image dimension14 self.readout = nn.Linear(64, 1)15 def forward(self, x):16 # pdb.set_trace()17 # Max pooling over a (2, 2) window18 x = F.max_pool2d(F.relu(self.layer1(x)), (2, 2))19 # If the size is a square, you can specify with a single number20 # x = F.max_pool2d(F.relu(self.conv2(x)), 2)21 x = torch.flatten(x, 1)22 # pdb.set_trace()23 # flatten all dimensions except the batch dimension24 x = F.relu(self.layer2(x))25 x = self.readout(x)26 return x27class Net_fc(nn.Module):28 def __init__(self):29 # an affine operation: y = Wx + b30 super(Net_fc, self).__init__()31 self.layer1 = torch.nn.Conv2d(in_channels=1,32 out_channels=64,33 kernel_size=(1, 1))34 # 1 input image channel, 6 output channels, 5x5 square convolution35 # kernel36 self.layer2 = nn.Conv2d(64, 6, 3)37 # self.conv2 = nn.Conv2d(6, 16, 3)38 self.readout =nn.Linear(912, 1)39 def forward(self, x):40 # pdb.set_trace()41 # x = torch.flatten(x, 1) # flatten all dimensions except the batch dimension42 x = F.relu(self.layer1(x))43 # Max pooling over a (2, 2) window44 x = F.max_pool2d(F.relu(self.layer2(x)), (2, 2))45 # If the size is a square, you can specify with a single number46 # x = F.max_pool2d(F.relu(self.conv2(x)), 2)47 x = torch.flatten(x, 1)48 # pdb.set_trace()49 x = self.readout(x)50 return x51class Net_cc(nn.Module):52 def __init__(self):53 # an affine operation: y = Wx + b54 super(Net_cc, self).__init__()55 self.layer1 = torch.nn.Conv2d(1, 6, 3)56 # 1 input image channel, 6 output channels, 5x5 square convolution57 # kernel58 self.layer2 = nn.Conv2d(6, 10, 3)59 # self.conv2 = nn.Conv2d(16, 32, 3)60 self.readout = nn.Linear(240, 1)61 def forward(self, x):62 # pdb.set_trace()63 # x = torch.flatten(x, 1) # flatten all dimensions except the batch dimension64 x = F.max_pool2d(F.relu(self.layer1(x)), (2, 2))65 # Max pooling over a (2, 2) window66 x = F.max_pool2d(F.relu(self.layer2(x)), (2, 2))67 # If the size is a square, you can specify with a single number68 # x = F.max_pool2d(F.relu(self.conv2(x)), 2)69 x = torch.flatten(x, 1)70 # pdb.set_trace()71 x = self.readout(x)72 return x73class Net_ff(nn.Module):74 def __init__(self):75 super(Net_ff, self).__init__()76 # 1 input image channel, 6 output channels, 2 square convolution77 # kernel78 self.layer1 = nn.Linear(40*18,64)79 # self.conv2 = nn.Conv2d(6, 16, 3)80 # an affine operation: y = Wx + b81 self.layer2 = nn.Linear(64, 64) # from image dimension82 self.readout = nn.Linear(64, 1)83 def forward(self, x):84 # pdb.set_trace()85 x = torch.flatten(x, 1)86 x = F.relu(self.layer1(x))87 x = F.relu(self.layer2(x))88 x = self.readout(x)89 return x90class Net_fc5(nn.Module):91 def __init__(self):92 # an affine operation: y = Wx + b93 super(Net_fc5, self).__init__()94 self.layer1 = torch.nn.Conv2d(in_channels=1,95 out_channels=64,96 kernel_size=(1, 1))97 # 1 input image channel, 6 output channels, 5x5 square convolution98 # kernel99 self.layer2 = nn.Conv2d(64, 6, 5)100 # self.conv2 = nn.Conv2d(6, 16, 3)101 self.readout = nn.Linear(756, 1)102 def forward(self, x):103 # pdb.set_trace()104 # x = torch.flatten(x, 1) # flatten all dimensions except the batch dimension105 x = F.relu(self.layer1(x))106 # Max pooling over a (2, 2) window107 x = F.max_pool2d(F.relu(self.layer2(x)), (2, 2))108 # If the size is a square, you can specify with a single number109 # x = F.max_pool2d(F.relu(self.conv2(x)), 2)110 x = torch.flatten(x, 1)111 # pdb.set_trace()112 x = self.readout(x)113 return x114class Net_fc7(nn.Module):115 def __init__(self):116 # an affine operation: y = Wx + b117 super(Net_fc7, self).__init__()118 self.layer1 = torch.nn.Conv2d(in_channels=1,119 out_channels=64,120 kernel_size=(1, 1))121 # 1 input image channel, 6 output channels, 5x5 square convolution122 # kernel123 self.layer2 = nn.Conv2d(64, 6, 7)124 # self.conv2 = nn.Conv2d(6, 16, 3)125 self.readout = nn.Linear(612, 1)126 def forward(self, x):127 # pdb.set_trace()128 # x = torch.flatten(x, 1) # flatten all dimensions except the batch dimension129 x = F.relu(self.layer1(x))130 # Max pooling over a (2, 2) window131 x = F.max_pool2d(F.relu(self.layer2(x)), (2, 2))132 # If the size is a square, you can specify with a single number133 # x = F.max_pool2d(F.relu(self.conv2(x)), 2)134 x = torch.flatten(x, 1)135 # pdb.set_trace()136 x = self.readout(x)137 return x138class Net_cc5(nn.Module):139 def __init__(self):140 # an affine operation: y = Wx + b141 super(Net_cc5, self).__init__()142 self.layer1 = torch.nn.Conv2d(1, 6, 3)143 # 1 input image channel, 6 output channels, 5x5 square convolution144 # kernel145 self.layer2 = nn.Conv2d(6, 10, 5)146 # self.conv2 = nn.Conv2d(16, 32, 3)147 self.readout = nn.Linear(140, 1)148 def forward(self, x):149 # pdb.set_trace()150 # x = torch.flatten(x, 1) # flatten all dimensions except the batch dimension151 x = F.max_pool2d(F.relu(self.layer1(x)), (2, 2))152 # Max pooling over a (2, 2) window153 x = F.max_pool2d(F.relu(self.layer2(x)), (2, 2))154 # If the size is a square, you can specify with a single number155 # x = F.max_pool2d(F.relu(self.conv2(x)), 2)156 x = torch.flatten(x, 1)157 # pdb.set_trace()158 x = self.readout(x)159 return x160class Net_cc7(nn.Module):161 def __init__(self):162 # an affine operation: y = Wx + b163 super(Net_cc7, self).__init__()164 self.layer1 = torch.nn.Conv2d(1, 6, 3)165 # 1 input image channel, 6 output channels, 5x5 square convolution166 # kernel167 self.layer2 = nn.Conv2d(6, 10, 7)168 # self.conv2 = nn.Conv2d(16, 32, 3)169 self.readout = nn.Linear(60, 1)170 def forward(self, x):171 # pdb.set_trace()172 # x = torch.flatten(x, 1) # flatten all dimensions except the batch dimension173 x = F.max_pool2d(F.relu(self.layer1(x)), (2, 2))174 # Max pooling over a (2, 2) window175 x = F.max_pool2d(F.relu(self.layer2(x)), (2, 2))176 # If the size is a square, you can specify with a single number177 # x = F.max_pool2d(F.relu(self.conv2(x)), 2)178 x = torch.flatten(x, 1)179 # pdb.set_trace()180 x = self.readout(x)181 return x182class Net_smCC(nn.Module):183 def __init__(self):184 # an affine operation: y = Wx + b185 super(Net_smCC, self).__init__()186 self.layer1 = torch.nn.Conv2d(1, 6, 3)187 # 1 input image channel, 6 output channels, 5x5 square convolution188 # kernel189 self.layer2 = nn.Conv2d(6, 10, 3)190 # self.conv2 = nn.Conv2d(16, 32, 3)191 self.readout = nn.Conv2d(10, 1, 3)192 def forward(self, x):193 # pdb.set_trace()194 # x = torch.flatten(x, 1) # flatten all dimensions except the batch dimension195 x = F.max_pool2d(F.relu(self.layer1(x)), (2, 2))196 # Max pooling over a (2, 2) window197 x = F.max_pool2d(F.relu(self.layer2(x)), (2, 2))198 # If the size is a square, you can specify with a single number199 # x = F.max_pool2d(F.relu(self.conv2(x)), 2)200 # x = torch.flatten(x, 1)201 x = self.readout(x)202 # pdb.set_trace()203 x = torch.flatten(x, 1).unsqueeze(1)204 x = F.max_pool1d(x, 6)205 x = torch.flatten(x, 1)206 return x207class Net_sCC(nn.Module):208 def __init__(self):209 # an affine operation: y = Wx + b210 super(Net_sCC, self).__init__()211 self.layer1 = torch.nn.Conv2d(1, 6, 3)212 # 1 input image channel, 6 output channels, 5x5 square convolution213 # kernel214 self.layer2 = nn.Conv2d(6, 10, 3)215 # self.conv2 = nn.Conv2d(16, 32, 3)216 self.readout = nn.Conv2d(10, 1, 3)217 def forward(self, x):218 # pdb.set_trace()219 # x = torch.flatten(x, 1) # flatten all dimensions except the batch dimension220 x = F.relu(self.layer1(x))221 # Max pooling over a (2, 2) window222 x = F.relu(self.layer2(x))223 # If the size is a square, you can specify with a single number224 # x = F.max_pool2d(F.relu(self.conv2(x)), 2)225 # x = torch.flatten(x, 1)226 x = self.readout(x)227 # pdb.set_trace()228 x = torch.flatten(x, 1).unsqueeze(1)229 x = F.max_pool1d(x, 408)230 x = torch.flatten(x, 1)231 return x232class Net_sCC5(nn.Module):233 def __init__(self):234 # an affine operation: y = Wx + b235 super(Net_sCC5, self).__init__()236 self.layer1 = torch.nn.Conv2d(1, 6, 5)237 # 1 input image channel, 6 output channels, 5x5 square convolution238 # kernel239 self.layer2 = nn.Conv2d(6, 10, 5)240 # self.conv2 = nn.Conv2d(16, 32, 3)241 self.readout = nn.Conv2d(10, 1, 5)242 def forward(self, x):243 # pdb.set_trace()244 # x = torch.flatten(x, 1) # flatten all dimensions except the batch dimension245 x = F.relu(self.layer1(x))246 # Max pooling over a (2, 2) window247 x = F.relu(self.layer2(x))248 # If the size is a square, you can specify with a single number249 # x = F.max_pool2d(F.relu(self.conv2(x)), 2)250 # x = torch.flatten(x, 1)251 x = self.readout(x)252 # pdb.set_trace()253 x = torch.flatten(x, 1).unsqueeze(1)254 x = F.max_pool1d(x, 168)255 x = torch.flatten(x, 1)256 return x257class Net_sCC7(nn.Module):258 def __init__(self):259 # an affine operation: y = Wx + b260 super(Net_sCC7, self).__init__()261 self.layer1 = torch.nn.Conv2d(1, 6, 2)262 # 1 input image channel, 6 output channels, 5x5 square convolution263 # kernel264 self.layer2 = nn.Conv2d(6, 10, 7)265 # self.conv2 = nn.Conv2d(16, 32, 3)266 self.readout = nn.Conv2d(10, 1, 7)267 def forward(self, x):268 # pdb.set_trace()269 # x = torch.flatten(x, 1) # flatten all dimensions except the batch dimension270 x = F.relu(self.layer1(x))271 # Max pooling over a (2, 2) window272 x = F.relu(self.layer2(x))273 # If the size is a square, you can specify with a single number274 # x = F.max_pool2d(F.relu(self.conv2(x)), 2)275 # x = torch.flatten(x, 1)276 x = self.readout(x)277 # pdb.set_trace()278 x = torch.flatten(x, 1).unsqueeze(1)279 x = F.max_pool1d(x, 135)280 x = torch.flatten(x, 1)...
utils.py
Source:utils.py
...19# def ctrl_set_action(sim, action):20# """For torque actuators it copies the action into mujoco ctrl field.21# For position actuators it sets the target relative to the current qpos.22# """23# # pdb.set_trace()24# if sim.model.nmocap > 0:25# _, action = np.split(action, (sim.model.nmocap * 7, ))26# if sim.data.ctrl is not None:27# for i in range(action.shape[0]):28# if sim.model.actuator_biastype[i] == 0:29# sim.data.ctrl[i] = action[i]30# # pdb.set_trace()31# else:32# idx = sim.model.jnt_qposadr[sim.model.actuator_trnid[i, 0]]33# sim.data.ctrl[i] = sim.data.qpos[idx] + action[i]34# # pdb.set_trace()35def ctrl_set_action(sim, action):36 """For torque actuators it copies the action into mujoco ctrl field.37 For position actuators it sets the target relative to the current qpos.38 """39 # pdb.set_trace()40 if sim.model.nmocap > 0:41 _, action = np.split(action, (2, ))42 if sim.data.ctrl is not None:43 for i in range(action.shape[0]):44 if sim.model.actuator_biastype[i] == 0:45 sim.data.ctrl[i] = action[i]46 # pdb.set_trace()47 else:48 idx = sim.model.jnt_qposadr[sim.model.actuator_trnid[i, 0]]49 sim.data.ctrl[i] = sim.data.qpos[idx] + action[i]50 # pdb.set_trace()51# def grasp(sim, action, point):52# if action[0]>=0.5:53#54# # print("all eq constraints", sim.model.body_id2name(sim.model.eq_obj2id[-1]))55# # pdb.set_trace()56# sim.model.eq_obj2id[-1] = sim.model.body_name2id(point)57# sim.model.eq_active[-2] = True58# sim.model.eq_data[-2, :] = np.array(59# [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])60# else:61# sim.model.eq_active[-2] = False62def grasp(sim, action, point,behavior):63 # pdb.set_trace()64 if action[0]>=0.5:65 # print("all eq constraints", sim.model.body_id2name(sim.model.eq_obj2id[-1]))66 # pdb.set_trace()67 if point == 'CB0_0':68 # pdb.set_trace()69 sim.model.eq_obj2id[-1] = sim.model.body_name2id(point)70 sim.model.eq_active[-2] = True71 sim.model.eq_data[-2, :] = np.array(72 [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])73 elif point != 'CB0_0':74 # pdb.set_trace()75 sim.model.eq_obj2id[-2] = sim.model.body_name2id(point)76 if behavior == 'onehand' or behavior == 'diagonally' or behavior == 'onehand-lifting':77 sim.model.eq_active[-2] = True78 sim.model.eq_data[-2, :] = np.array(79 [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])80 else:81 sim.model.eq_active[-1] = True82 sim.model.eq_data[-1, :] = np.array(83 [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])84 else:85 sim.model.eq_active[-2] = False86 sim.model.eq_active[-1] = False87def mocap_set_action(sim, action, agent):88 """The action controls the robot using mocaps. Specifically, bodies89 on the robot (for example the gripper wrist) is controlled with90 mocap bodies. In this case the action is the desired difference91 in position and orientation (quaternion), in world coordinates,92 of the of the target body. The mocap is positioned relative to93 the target body according to the delta, and the MuJoCo equality94 constraint optimizer tries to center the welded body on the mocap.95 """96 if sim.model.nmocap > 0:97 # pdb.set_trace()98 action, _ = np.split(action, ( 7, ))99 # pdb.set_trace()100 action = action.reshape(1, 7)101 # print(action)102 # pdb.set_trace()103 pos_delta = action[:, :3]104 quat_delta = action[:, 3:]105 # print(action)106 reset_mocap2body_xpos(sim, agent)107 # pdb.set_trace()108 temp_sum = sim.data.mocap_pos+ pos_delta109 temp_sum_quat = sim.data.mocap_quat + quat_delta110 if agent == 0:111 sim.data.mocap_pos[:] = np.reshape(np.append(sim.data.mocap_pos[0,:], temp_sum[1,:]), (2,3))112 # pdb.set_trace()113 sim.data.mocap_quat[:] = np.reshape(np.append(sim.data.mocap_quat[0,:], temp_sum_quat[1,:]), (2,4))114 else:115 # pdb.set_trace()116 sim.data.mocap_pos[:] = np.reshape(np.append(temp_sum[0, :], sim.data.mocap_pos[1, :]), (2, 3))117 # pdb.set_trace()118 sim.data.mocap_quat[:] = np.reshape(np.append(temp_sum_quat[0, :],sim.data.mocap_quat[1, :]), (2, 4))119def reset_mocap_welds(sim):120 """Resets the mocap welds that we use for actuation.121 """122 if sim.model.nmocap > 0 and sim.model.eq_data is not None:123 for i in range(sim.model.eq_data.shape[0]):124 if sim.model.eq_type[i] == mujoco_py.const.EQ_WELD:125 # pdb.set_trace()126 sim.model.eq_data[i, :] = np.array(127 [0., 0., 0., 1., 0., 0., 0.])128 sim.forward()129def reset_mocap2body_xpos(sim, agent):130 """Resets the position and orientation of the mocap bodies to the same131 values as the bodies they're welded to.132 """133 if (sim.model.eq_type is None or134 sim.model.eq_obj1id is None or135 sim.model.eq_obj2id is None):136 return137 #might need similar change to the eq_type138 eq_type = sim.model.eq_type[-2]139 obj1_id = sim.model.eq_obj1id[-3]140 obj1_id_2 = sim.model.eq_obj1id[-4]141 obj2_id = sim.model.eq_obj2id[-3]142 obj2_id_2 = sim.model.eq_obj2id[-4]143 # pdb.set_trace()144 # import pdb145 # pdb.set_trace()146 # for obj1_id, obj2_id in zip(sim.model.eq_obj1id,147 # sim.model.eq_obj2id):148 # if eq_type != mujoco_py.const.EQ_WELD:149 # continue150 assert (eq_type == mujoco_py.const.EQ_WELD)151 mocap_id = sim.model.body_mocapid[obj1_id]152 mocap_id_2 = sim.model.body_mocapid[obj1_id_2]153 if mocap_id != -1:154 # pdb.set_trace()155 # obj1 is the mocap, obj2 is the welded body156 body_idx = obj2_id157 body_idx_2 = obj2_id_2158 # pdb.set_trace()159 else:160 # obj2 is the mocap, obj1 is the welded body161 mocap_id = sim.model.body_mocapid[obj2_id]162 body_idx = obj1_id163 # pdb.set_trace()164 # test_body_indx = [body_idx, body_idx_2]165 # test_mocap_id = [mocap_id, mocap_id_2]166 # assert (mocap_id_2 != -1)167 # pdb.set_trace()168 if agent == 0:169 sim.data.mocap_pos[mocap_id][:] = sim.data.body_xpos[body_idx]170 sim.data.mocap_quat[mocap_id][:] = sim.data.body_xquat[body_idx]171 else:172 sim.data.mocap_pos[mocap_id_2][:] = sim.data.body_xpos[body_idx_2]173 sim.data.mocap_quat[mocap_id_2][:] = sim.data.body_xquat[body_idx_2]174 # pdb.set_trace()175#Helper functions to convert 3d point to 2d in image176#USage label = global2label(obj_pos, cam_pos, cam_ori, output_size, fov=fov, s=s)177def global2label(obj_pos, cam_pos, cam_ori, output_size=[64, 64], fov=45, s=1):178 """179 :param obj_pos: 3D coordinates of the joint from MuJoCo in nparray [m]180 :param cam_pos: 3D coordinates of the camera from MuJoCo in nparray [m]181 :param cam_ori: camera 3D rotation (Rotation order of x->y->z) from MuJoCo in nparray [rad]182 :param fov: field of view in integer [degree]183 :return: Heatmap of the object in the 2D pixel space.184 """185 e = np.array([output_size[0]/2, output_size[1]/2, 1])186 fov = np.array([fov])187 # Converting the MuJoCo coordinate into typical computer vision coordinate.188 cam_ori_cv = np.array([cam_ori[1], cam_ori[0], -cam_ori[2]])...
eval.py
Source:eval.py
...67 target_img = create_binaryImage(target_boxes, False)68# for i in range(2):69# img = Image.fromarray(target_img[i])70# img.show()71# pdb.set_trace()72 for batch_idx, (images, loc_targets, conf_targets) in enumerate(testloader):73 if use_cuda:74 images = images.cuda()75 loc_targets = loc_targets.cuda()76 conf_targets = conf_targets.cuda()77 images = Variable(images, volatile=True)78# loc_targets = Variable(loc_targets)79# conf_targets = Variable(conf_targets)80 loc_preds, conf_preds = net(images)81 82 data_encoder = DataEncoder()83# pdb.set_trace()84 conf_preds_list = []85 for i in range(batch_size):86 s_conf = F.softmax(conf_preds[i]).data87 conf_preds_list.append(s_conf)88# pdb.set_trace() 89 try:90 boxes, labels, scores = data_encoder.decodeforbatch(loc_preds.data, conf_preds_list)91 92# print('eloc', loc_preds.data)93# print('esoftmax', conf_preds_list)94 predicted_img = create_binaryImage(boxes)95 96 for i in range(batch_size):97 dice_score += binary.dc(predicted_img[i],target_img[batch_idx*batch_size + i])98 ite+=199 print('[I %d]: %.5f' % (ite, binary.dc(predicted_img[i],target_img[batch_idx*batch_size + i])))100# print(binary.dc(predicted_img[i],target_img[batch_idx + i]))101# img = Image.fromarray(target_img[batch_idx + i])102# img.show('target')103# imgg = Image.fromarray(predicted_img[batch_idx + i])104# imgg.show('predict')105 except:106 print('err') 107# pdb.set_trace()108def calculate_precision():109 dictindex = []110 global prec 111 with open('./label.txt') as f:112 content = f.readlines()113 for symbol in content:114 symbol = symbol.replace('\n','')115 split = symbol.split(' ')116 dictindex.append(split[0])117 118 print('\nPrecision')119 net.eval()120 global dice_score121 global ite 122 global count123 global num_sym124 target_boxes = testset.boxes125 target_labels = testset.labels126 127 128 for batch_idx, (images, loc_targets, conf_targets) in enumerate(testloader):129 if use_cuda:130 images = images.cuda()131 loc_targets = loc_targets.cuda()132 conf_targets = conf_targets.cuda()133 images = Variable(images, volatile=True)134 loc_preds, conf_preds = net(images)135# pdb.set_trace() 136 data_encoder = DataEncoder()137 conf_preds_list = []138 for i in range(batch_size):139 s_conf = F.softmax(conf_preds[i]).data140 conf_preds_list.append(s_conf)141 try:142 boxes, labels, scores = data_encoder.decodeforbatch(loc_preds.data, conf_preds_list)143 for b_id in range(batch_size):144 predict_res = find_boxescoreslabel(labels[b_id], boxes[b_id])145 target_res = find_boxescoreslabel(target_labels[b_id+batch_idx*batch_size], target_boxes[b_id+batch_idx*batch_size],False)146# pdb.set_trace()'147 print('[I %d]:' % (batch_idx))148 for box_id in range(len(predict_res)):149# pdb.set_trace()150 t_label = [item[0] for item in target_res]151 la = predict_res[box_id][0]152 num_sym[0][la] += len(predict_res[box_id][1])153# pdb.set_trace() 154 if la in t_label:155 predict_img = create_binaryImageforPrec(predict_res[box_id][1])156# pdb.set_trace()157# imgg = Image.fromarray(predict_img)158# imgg.show()159 target_img = create_binaryImageforPrec(target_res[t_label.index(la)][1], False )160# img = Image.fromarray(target_img)161# img.show()162# pdb.set_trace() 163 prec[0][la]+= binary.precision(predict_img, target_img)164 print('[la %d: %.5f]' %(la, prec[0][la]))165# print(prec[0][la])166 else:167 print('no exist in t_label')168# 169 prec[1][la] += 1 170 171 except:172 print('err') 173 count+=1 174# pdb.set_trace()175 176def find_boxescoreslabel(labels, boxes, isPred=True):177 res = []178 skip=[]179# pdb.set_trace()180 for i in range(len(labels)):181 if labels[i] not in skip:182# pdb.set_trace()183 ids = np.where(labels.numpy()==labels[i]) 184 ids = torch.from_numpy(ids[0])185# pdb.set_trace()186 if(isPred):187 res.append((labels[i]-1, boxes[ids]))188 else:189 res.append((labels[i], boxes[ids]))190 skip.append(labels[i])191# pdb.set_trace()192 return res193def create_binaryImage(boxes, isPred=True):194 img = np.zeros((len(boxes),300,300))195# pdb.set_trace()196 for id_img in range(img.shape[0]):197 for i in range(len(boxes[id_img])):198# pdb.set_trace()199 if(isPred):200 boxes[id_img][i,::2] *= img.shape[1]201 boxes[id_img][i,1::2] *= img.shape[2]202 for y in range(int(round(boxes[id_img][i,1])), int(round(boxes[id_img][i,3]))):203 for x in range(int(round(boxes[id_img][i,0])), int(round(boxes[id_img][i,2]))):204 img[id_img,y,x] = 255 205# pdb.set_trace()206# imgg = Image.fromarray(img[id_img])207# imgg.show()208# pdb.set_trace()209# print('predict boxes', boxes)210 return img211def create_binaryImageforPrec(boxes, isPred = True):212 img = np.zeros((300,300))213 for i in range(len(boxes)):214# pdb.set_trace()215 if(isPred):216 boxes[i,::2] *= img.shape[0]217 boxes[i,1::2] *= img.shape[1]218 for y in range(int(round(boxes[i,1])), int(round(boxes[i,3]))):219 for x in range(int(round(boxes[i,0])), int(round(boxes[i,2]))):220 img[y,x] = 255 221# pdb.set_trace()222# if(not isPred):223# img = Image.fromarray(img)224# img.show()225 return img 226for epoch in range(1):227# eval()228 calculate_precision()229#print(dice_score/ite)230for i in range(106):231 print(prec[0][i]/float(prec[1][i]))232print('num')233for i in range(106):234 print(num_sym[0][i]) 235print(count)
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!