def test_trace_merge(): with hunter.trace(function='a'): with hunter.trace(function='b'): with hunter.trace(function='c'): assert sys.gettrace().handler == When(Q(function='c'), CallPrinter) assert sys.gettrace().handler == When(Q(function='b'), CallPrinter) assert sys.gettrace().handler == When(Q(function='a'), CallPrinter)
def test_trace_merge(): with hunter.trace(function="a"): with hunter.trace(function="b"): with hunter.trace(function="c"): assert sys.gettrace().handler == When(Q(function="c"), CodePrinter) assert sys.gettrace().handler == When(Q(function="b"), CodePrinter) assert sys.gettrace().handler == When(Q(function="a"), CodePrinter)
def test_trace_merge(): with hunter.trace(function="a"): with hunter.trace(function="b"): with hunter.trace(function="c"): assert sys.gettrace().handler == When(Q(function="c"), CallPrinter) assert sys.gettrace().handler == When(Q(function="b"), CallPrinter) assert sys.gettrace().handler == When(Q(function="a"), CallPrinter)
def test_trace_merge(): trace(function="a") trace(function="b") assert trace(function="c")._handler == Or( When(Q(function="a"), CodePrinter), When(Q(function="b"), CodePrinter), When(Q(function="c"), CodePrinter), )
def exit(self, status): """Extend QApplication::exit to log the event.""" log.destroy.debug("Now calling QApplication::exit.") if self._args.debug_exit: if hunter is None: print("Not logging late shutdown because hunter could not be " "imported!", file=sys.stderr) else: print("Now logging late shutdown.", file=sys.stderr) hunter.trace() super().exit(status)
def _shutdown_3(self, status: int) -> None: """Finally shut down the QApplication.""" log.destroy.debug("Now calling QApplication::exit.") if 'debug-exit' in objects.debug_flags: if hunter is None: print("Not logging late shutdown because hunter could not be " "imported!", file=sys.stderr) else: print("Now logging late shutdown.", file=sys.stderr) hunter.trace() objects.qapp.exit(status)
def test_examples(): print(""" CodePrinter """) with hunter.trace(stdlib=False, actions=[CodePrinter, VarsSnooper]): os.path.join(*map(str, range(10))) print(""" CallPrinter """) with hunter.trace(stdlib=False, actions=[CallPrinter, VarsSnooper]): os.path.join(*map(str, range(10)))
def __init__(self, *args, **kwargs): self._calls = [] threading_support = kwargs.pop('threading_support', False) clear_env_var = kwargs.pop('clear_env_var', False) self.handler = hunter._prepare_predicate(*args, **kwargs) self.is_pure = hunter.Tracer.__module__ == 'hunter.tracer' self._tracer = hunter.trace(self._append, threading_support=threading_support, clear_env_var=clear_env_var)
def test_tracing_vars(LineMatcher): lines = StringIO() with hunter.trace(actions=[VarsPrinter('b', stream=lines), CodePrinter(stream=lines)]): def a(): b = 1 b = 2 return 1 b = a() b = 2 try: raise Exception("BOOM!") except Exception: pass print(lines.getvalue()) lm = LineMatcher(lines.getvalue().splitlines()) lm.fnmatch_lines([ "*test_hunter.py* call def a():", "*test_hunter.py* line b = 1", "* vars b => 1", "*test_hunter.py* line b = 2", "* vars b => 2", "*test_hunter.py* line return 1", "* vars b => 2", "*test_hunter.py* return return 1", "* ... return value: 1", ])
def test_tracing_reinstall(LineMatcher): lines = StringIO() with hunter.trace(CodePrinter(stream=lines)): def foo(): a = 2 sys.settrace(sys.gettrace()) a = 3 def bar(): a = 1 foo() a = 4 bar() print(lines.getvalue()) lm = LineMatcher(lines.getvalue().splitlines()) lm.fnmatch_lines([ "*test_hunter.py:* call def bar():", "*test_hunter.py:* line a = 1", "*test_hunter.py:* line foo()", "*test_hunter.py:* call def foo():", "*test_hunter.py:* line a = 2", "*test_hunter.py:* line sys.settrace(sys.gettrace())", "*test_hunter.py:* line a = 3", "*test_hunter.py:* return a = 3", "* ... return value: None", "*test_hunter.py:* line a = 4", "*test_hunter.py:* return a = 4", "* ... return value: None", ])
def test_tracing_vars(LineMatcher): lines = StringIO() with hunter.trace(actions=[ VarsPrinter('b', stream=lines), CodePrinter(stream=lines) ]): def a(): b = 1 b = 2 return 1 b = a() b = 2 try: raise Exception("BOOM!") except Exception: pass print(lines.getvalue()) lm = LineMatcher(lines.getvalue().splitlines()) lm.fnmatch_lines([ "*test_hunter.py* call def a():", "*test_hunter.py* line b = 1", "* vars b => 1", "*test_hunter.py* line b = 2", "* vars b => 2", "*test_hunter.py* line return 1", "* vars b => 2", "*test_hunter.py* return return 1", "* ... return value: 1", ])
def test_depth(): calls = [] tracer = hunter.trace(action=lambda event: calls.append( (event.kind, event.module, event.function, event.depth))) try: def bar(): for i in range(2): yield i def foo(): gen = bar() next(gen) while True: try: gen.send('foo') except StopIteration: break list(i for i in range(2)) x = [i for i in range(2)] foo() finally: tracer.stop() pprint(calls) assert ('call', 'test_hunter', 'bar', 1) in calls assert ('return', 'test_hunter', 'foo', 0) in calls
def test_tracing_vars(): lines = StringIO() with trace(actions=[VarsPrinter('b', stream=lines), CodePrinter(stream=lines)]): def a(): b = 1 b = 2 return 1 b = a() b = 2 try: raise Exception("BOOM!") except Exception: pass print(lines.getvalue()) for line, expected in izip_longest(lines.getvalue().splitlines(), [ "* *hunter.py* call def __enter__(self):", "* *hunter.py* line return self", "* *hunter.py* return return self", "* * ... return value: <hunter.Tracer *", "* *test_hunter.py* call def a():", "* *test_hunter.py* line b = 1", "* * vars b => 1", "* *test_hunter.py* line b = 2", "* * vars b => 2", "* *test_hunter.py* line return 1", "* * vars b => 2", "* *test_hunter.py* return return 1", "* * ... return value: 1", "* *hunter.py* call def __exit__(self, exc_type, exc_val, exc_tb):", "* *hunter.py* line self.stop()", "* *hunter.py* call def stop(self):", "* *hunter.py* line sys.settrace(self._previous_tracer)", ], fillvalue="MISSING"): assert fnmatchcase(line, expected), "%r didn't match %r" % (line, expected)
def test_debugger(LineMatcher): out = StringIO() calls = [] class FakePDB: def __init__(self, foobar=1): calls.append(foobar) def set_trace(self, frame): calls.append(frame.f_code.co_name) with hunter.trace( lambda event: event.locals.get("node") == "Foobar", module="test_hunter", function="foo", actions=[VarsPrinter("a", "node", "foo", "test_debugger", globals=True, stream=out), Debugger(klass=FakePDB, foobar=2)] ): def foo(): a = 1 node = "Foobar" node += "x" a += 2 return a foo() print(out.getvalue()) assert calls == [2, 'foo'] lm = LineMatcher(out.getvalue().splitlines()) pprint(lm.lines) lm.fnmatch_lines_random([ "* test_debugger => <function test_debugger at *", "* node => 'Foobar'", "* a => 1", ])
def test_pid_prefix(LineMatcher, Action, force_pid, capfd): def main(): a = 1 pid = os.fork() if pid: os.waitpid(pid, 0) else: os._exit(0) # child with hunter.trace(actions=[ Action(force_pid=force_pid, stream=sys.stdout), VarsPrinter('a', force_pid=force_pid, stream=sys.stdout) ], stdlib=False, threading_support=True): main() out, err = capfd.readouterr() print('OUT', out) print('ERR', err) lm = LineMatcher(out.splitlines()) prefix = '[[]*[]] *' if force_pid else '' lm.fnmatch_lines_random([ prefix + "MainThread *test_hunter.py:* line * a = 1", prefix + "MainThread *test_hunter.py:* line * if pid:", prefix + "MainThread * * vars * a => 1", prefix + "MainThread *test_hunter.py:* line * os.waitpid(pid, 0)", "[[]*[]] *MainThread *test_hunter.py:* line * os._exit(0) # child", "[[]*[]] *MainThread * * vars * a => 1", ])
def test_tracing_printing_failures(): lines = StringIO() with trace(CodePrinter(stream=lines), VarsPrinter("x", stream=lines)): class Bad(Exception): def __repr__(self): raise RuntimeError("I'm a bad class!") def a(): x = Bad() return x def b(): x = Bad() raise x a() try: b() except Exception as exc: pass print(lines.getvalue()) for line, expected in izip_longest(lines.getvalue().splitlines(), [ """* ****hunter.py:* call def __enter__(self):""", """* ****hunter.py:* line return self""", """* ****hunter.py:* return return self""", """* * ... return value: <hunter.Tracer *""", """* tests*test_hunter.py:* call class Bad(Exception):""", """* tests*test_hunter.py:* line class Bad(Exception):""", """* tests*test_hunter.py:* line def __repr__(self):""", """* tests*test_hunter.py:* return def __repr__(self):""", """* * ... return value: *""", """* tests*test_hunter.py:* call def a():""", """* tests*test_hunter.py:* line x = Bad()""", """* tests*test_hunter.py:* line return x""", """* * vars x => !!! FAILED REPR: RuntimeError("I'm a bad class!",)""", """* tests*test_hunter.py:* return return x""", """* * ... return value: !!! FAILED REPR: RuntimeError("I'm a bad class!",)""", """* * vars x => !!! FAILED REPR: RuntimeError("I'm a bad class!",)""", """* tests*test_hunter.py:* call def b():""", """* tests*test_hunter.py:* line x = Bad()""", """* tests*test_hunter.py:* line raise x""", """* * vars x => !!! FAILED REPR: RuntimeError("I'm a bad class!",)""", """* tests*test_hunter.py:* exception raise x""", """* * ... exception value: !!! FAILED REPR: RuntimeError("I'm a bad class!",)""", """* * vars x => !!! FAILED REPR: RuntimeError("I'm a bad class!",)""", """* tests*test_hunter.py:* return raise x""", """* * ... return value: None""", """* * vars x => !!! FAILED REPR: RuntimeError("I'm a bad class!",)""", """* ****hunter.py:* call def __exit__(self, exc_type, exc_val, exc_tb):""", """* ****hunter.py:* line self.stop()""", """* ****hunter.py:* call def stop(self):""", """* ****hunter.py:* line sys.settrace(self._previous_tracer)""", ], fillvalue="MISSING"): assert fnmatchcase(line, expected), "%r didn't match %r" % (line, expected)
def test_stack_printer_2(LineMatcher): buff = StringIO() with trace(Q(function="five", action=StackPrinter(limit=2, stream=buff))): from sample7 import one one() output = buff.getvalue() lm = LineMatcher(output.splitlines()) lm.fnmatch_lines([ "*sample7.py:??:five <= tests/sample7.py:??:four <= tests/sample7.py:??:three <= tests/sample7.py:??:two <= tests/sample7.py:?:one <= tests/test_integration.py:???:test_stack_printer*", ])
def import_and_trace_script(module_name, module_path): """ As the name suggests, this imports and traces the target script. Filters for the running script and delegates the resulting calls to the result_handler function. NOTE: script_path is necessary here for relative imports to work """ with script_path(os.path.abspath(os.path.dirname(module_path))): with trace(filename_filter(module_path), action=result_handler): import_file(module_name, module_path)
def on_message_received(self, msg): if TRACE: hunter.trace(module_contains="canopen_301_402") print "on_message_received" # print "--" # print "raw", msg # convert message to canopen message if type(msg) == can.Message: msg = CanOpenMessage.from_can_msg(msg, self) # parse message into higher level canopen message types if type(msg) == CanOpenMessage: msg = self.msgs.try_to_upgrage_canopen_message(msg) print can_msg_to_str(msg.to_can_msg()) if self.collect_messages: self.collected_messages.append(msg) # print "msg type: ", type(msg) # print msg.__dict__ # print "" # route canopen message to responsible service if msg.broadcast: for node in self.nodes.itervalues(): service = node.services[msg.service] if service is not None: service.process_msg(msg) else: node = self.get_node(msg.node_id) service = node.services[msg.service] # print "service",service if service is not None: service.process_msg(msg)
def on_message_received(self, msg): if TRACE: hunter.trace(module_contains="canopen_301_402") # convert message to canopen message if type(msg) == can.Message: msg = CanOpenMessage.from_can_msg(msg, self) # parse message into higher level canopen message types if type(msg) == CanOpenMessage: msg = self.msgs.try_to_upgrage_canopen_message(msg) # print "---" # print type(msg), msg # print msg.__dict__ # print "" # history if self.enable_history: self.msg_history.append(msg) # enqueue CanOpenMessage self.msg_queues[msg.node_id].put(msg)
def setup_hunter_call(): sys.path.insert(0, '/Users/alberthan/VSCodeProjects/HDLogger') lines = io.StringIO() try: with hunter.trace(filename__contains="youtube", action=hunter.CallPrinter(stream=lines)): youtube_dl.main() except: wf(stackprinter.format(sys.exc_info()), 'logs/error.except.main.log', 'a') raise finally: output = lines.getvalue() wf(output, 'logs/huntercall.finally.log', 'a') return (inspect.currentframe(), globals(), locals())
def test_locals(): out = StringIO() with hunter.trace(lambda event: event.locals.get("node") == "Foobar", module="test_hunter", function="foo", action=CodePrinter(stream=out)): def foo(): a = 1 node = "Foobar" node += "x" a += 2 return a foo() assert out.getvalue().endswith('node += "x"\n')
def test_tracing_vars_expressions(LineMatcher): lines = StringIO() with hunter.trace(actions=[VarsPrinter('Foo.bar', 'vars(Foo)', 'len(range(2))', 'Foo.__dict__["bar"]', stream=lines)]): def main(): class Foo(object): bar = 1 main() print(lines.getvalue()) lm = LineMatcher(lines.getvalue().splitlines()) lm.fnmatch_lines_random([ '* [[]Foo.bar => 1[]]', '* [[]vars(Foo) => *[]]', '* [[]len(range(2)) => 2[]]', '* [[]Foo.__dict__[[]"bar"[]] => 1[]]', ])
def test_locals(): out = StringIO() with hunter.trace(lambda event: event.locals.get('node') == 'Foobar', module=__name__, function='foo', action=CodePrinter(stream=out)): def foo(): a = 1 node = 'Foobar' node += 'x' a += 2 return a foo() assert out.getvalue().endswith("node += 'x'\n")
def test_locals(): out = StringIO() with hunter.trace( lambda event: event.locals.get("node") == "Foobar", module="test_hunter", function="foo", action=CodePrinter(stream=out) ): def foo(): a = 1 node = "Foobar" node += "x" a += 2 return a foo() assert out.getvalue().endswith('node += "x"\n')
def test_threading_support(LineMatcher): lines = StringIO() idents = set() names = set() started = threading.Event() def record(event): idents.add(event.threadid) names.add(event.threadname) return True with hunter.trace(record, actions=[ CodePrinter(stream=lines), VarsPrinter('a', stream=lines), CallPrinter(stream=lines) ], threading_support=True): def foo(a=1): started.set() print(a) def main(): foo() t = threading.Thread(target=foo) t.start() started.wait(10) main() lm = LineMatcher(lines.getvalue().splitlines()) assert idents - {t.ident} == {None} assert 'MainThread' in names assert any(name.startswith('Thread-') for name in names) lm.fnmatch_lines_random([ 'Thread-* *test_hunter.py:* call def foo(a=1):', 'Thread-* * vars a => 1', 'Thread-* *test_hunter.py:* call => foo(a=1)', 'Thread-* * vars a => 1', 'MainThread *test_hunter.py:* call def foo(a=1):', 'MainThread * vars a => 1', 'MainThread *test_hunter.py:* call => foo(a=1)', 'MainThread * vars a => 1', ])
def test_profile(LineMatcher, options): stream = StringIO() with hunter.trace(action=ProfileAction(stream=stream), **options): from sample8errors import notsilenced from sample8errors import silenced1 from sample8errors import silenced3 from sample8errors import silenced4 silenced1() print('Done silenced1') silenced3() print('Done silenced3') silenced4() print('Done silenced4') try: notsilenced() except ValueError: print('Done not silenced') lm = LineMatcher(stream.getvalue().splitlines()) if 'profile' in options: lm.fnmatch_lines([ "sample8errors.error raised exception: None. Duration: ?.????s", "sample8errors.silenced1 returned: None. Duration: ?.????s", "sample8errors.error raised exception: None. Duration: ?.????s", "sample8errors.silenced3 returned: mwhahaha. Duration: ?.????s", "sample8errors.error raised exception: None. Duration: ?.????s", "<builtin>.repr raised exception: None. Duration: ?.????s", "sample8errors.silenced4 returned: None. Duration: ?.????s", "sample8errors.error raised exception: None. Duration: ?.????s", "sample8errors.notsilenced raised exception: None. Duration: ?.????s", ]) else: lm.fnmatch_lines([ "sample8errors.error raised exception: (*RuntimeError*, *). Duration: ?.????s", "sample8errors.silenced1 returned: None. Duration: ?.????s", "sample8errors.error raised exception: (*RuntimeError*, *). Duration: ?.????s", "sample8errors.silenced3 returned: mwhahaha. Duration: ?.????s", "sample8errors.error raised exception: (*RuntimeError*, *). Duration: ?.????s", "sample8errors.silenced4 returned: None. Duration: ?.????s", "sample8errors.error raised exception: (*RuntimeError*, *). Duration: ?.????s", "sample8errors.notsilenced raised exception: (*ValueError(RuntimeError*, *). Duration: ?.????s", ])
def test_thread_filtering(LineMatcher, query): lines = StringIO() idents = set() names = set() started = threading.Event() def record(event): idents.add(event.threadid) names.add(event.threadname) return True with hunter.trace(~Q(**query), record, actions=[ CodePrinter(stream=lines), VarsPrinter('a', stream=lines), CallPrinter(stream=lines) ], threading_support=True): def foo(a=1): started.set() print(a) def main(): foo() t = threading.Thread(target=foo) t.start() started.wait(10) main() lm = LineMatcher(lines.getvalue().splitlines()) print(lines.getvalue()) assert None not in idents assert 'MainThread' not in names pprint(lm.lines) lm.fnmatch_lines_random([ 'Thread-* *test_hunter.py:* call def foo(a=1):', 'Thread-* * vars a => 1', 'Thread-* *test_hunter.py:* call => foo(a=1)', 'Thread-* * vars a => 1', ])
def test_debugger(LineMatcher): out = StringIO() calls = [] class FakePDB: def __init__(self, foobar=1): calls.append(foobar) def set_trace(self, frame): calls.append(frame.f_code.co_name) with hunter.trace(lambda event: event.locals.get("node") == "Foobar", module="test_hunter", function="foo", actions=[ CodePrinter, VarsPrinter("a", "node", "foo", "test_debugger", globals=True, stream=out), Debugger(klass=FakePDB, foobar=2) ]): def foo(): a = 1 node = "Foobar" node += "x" a += 2 return a foo() print(out.getvalue()) assert calls == [2, 'foo'] lm = LineMatcher(out.getvalue().splitlines()) pprint(lm.lines) lm.fnmatch_lines_random([ "* test_debugger => <function test_debugger at *", "* node => 'Foobar'", "* a => 1", ])
def test_tracing_bare(LineMatcher): lines = StringIO() with hunter.trace(CodePrinter(stream=lines)): def a(): return 1 b = a() b = 2 try: raise Exception('BOOM!') except Exception: pass print(lines.getvalue()) lm = LineMatcher(lines.getvalue().splitlines()) lm.fnmatch_lines([ "*test_*.py* call def a():", "*test_*.py* line return 1", "*test_*.py* return return 1", "* ... return value: 1", ])
def test_tracing_bare(LineMatcher): lines = StringIO() with hunter.trace(CodePrinter(stream=lines)): def a(): return 1 b = a() b = 2 try: raise Exception("BOOM!") except Exception: pass print(lines.getvalue()) lm = LineMatcher(lines.getvalue().splitlines()) lm.fnmatch_lines([ "*test_hunter.py* call def a():", "*test_hunter.py* line return 1", "*test_hunter.py* return return 1", "* ... return value: 1", ])
def test_debugger(LineMatcher): out = StringIO() calls = [] class FakePDB: def __init__(self, foobar=1): calls.append(foobar) def set_trace(self, frame): calls.append(frame.f_code.co_name) with hunter.trace(lambda event: event.locals.get('node') == 'Foobar', module='test_hunter', function='foo', actions=[ CodePrinter, VarsPrinter('a', 'node', 'foo', 'test_debugger', stream=out), Debugger(klass=FakePDB, foobar=2) ]): def foo(): a = 1 node = 'Foobar' node += 'x' a += 2 return a foo() print(out.getvalue()) assert calls == [2, 'foo'] lm = LineMatcher(out.getvalue().splitlines()) pprint(lm.lines) lm.fnmatch_lines_random([ "* [[]test_debugger => <function test_debugger at *[]]", "* [[]node => 'Foobar'[]]", "* [[]a => 1[]]", ])
def test_threading_support(LineMatcher): lines = StringIO() idents = set() names = set() started = threading.Event() def record(event): idents.add(event.threadid) names.add(event.threadname) return True with hunter.trace(record, actions=[CodePrinter(stream=lines), VarsPrinter('a', stream=lines), CallPrinter(stream=lines)], threading_support=True): def foo(a=1): started.set() print(a) def main(): foo() t = threading.Thread(target=foo) t.start() started.wait(10) main() lm = LineMatcher(lines.getvalue().splitlines()) assert idents - {t.ident} == {None} assert names.issuperset({'MainThread', 'Thread-1'}) pprint(lm.lines) lm.fnmatch_lines_random([ 'Thread-* *test_hunter.py:* call def foo(a=1):', 'Thread-* * vars a => 1', 'Thread-* *test_hunter.py:* call => foo(a=1)', 'Thread-* * vars a => 1', 'MainThread *test_hunter.py:* call def foo(a=1):', 'MainThread * vars a => 1', 'MainThread *test_hunter.py:* call => foo(a=1)', 'MainThread * vars a => 1', ])
def test_dump_exceptions(LineMatcher): stream = StringIO() with hunter.trace(stdlib=False, action=DumpExceptions(stream=stream)): silenced1() silenced2() silenced3() silenced4() print("Done silenced") try: notsilenced() print("Done not silenced") except ValueError: pass lm = LineMatcher(stream.getvalue().splitlines()) lm.fnmatch_lines([ '*>>>>>>>>>>>>>>>>>>>>>> tracing silenced1 on RuntimeError()', '*test_cookbook.py:*** exception error()', '* *** ... exception value: *RuntimeError*', '*test_cookbook.py:*** line except Exception:', '*test_cookbook.py:*** line pass', '*---------------------- function exit', '*>>>>>>>>>>>>>>>>>>>>>> tracing silenced2 on RuntimeError()', '*test_cookbook.py:*** exception error()', '* ... exception value: *RuntimeError*', '*test_cookbook.py:*** line except Exception as exc:', '*test_cookbook.py:*** line print(exc)', '*---------------------- too many lines', '*>>>>>>>>>>>>>>>>>>>>>> tracing silenced3 on RuntimeError()', '*test_cookbook.py:*** exception error()', '* ... exception value: *RuntimeError*', '*test_cookbook.py:*** line return "mwhahaha"', '*---------------------- function exit', '*>>>>>>>>>>>>>>>>>>>>>> tracing silenced4 on RuntimeError()', '*test_cookbook.py:*** exception error()', '* ... exception value: *RuntimeError*', '*test_cookbook.py:*** line except Exception as exc:', '*test_cookbook.py:*** line logger.info(repr(exc))', '*---------------------- too many lines', ])
def test_profile_mode(LineMatcher, module): lines = StringIO() with trace(profile=True, action=CallPrinter(stream=lines)): def a(): foo = 1 sys.getsizeof(foo, 2) return getattr(a, 'b', foo) a() print(lines.getvalue()) lm = LineMatcher(lines.getvalue().splitlines()) if module == 'sys': lm.fnmatch_lines([ '* <sys> call * => getsizeof: *', '* <sys> return * <= getsizeof', ]) else: lm.fnmatch_lines([ "* <*builtin*> * call * => getattr: *", '* <*builtin*> * return * <= getattr', ])
def test_thread_filtering(LineMatcher, query): lines = StringIO() idents = set() names = set() started = threading.Event() def record(event): idents.add(event.threadid) names.add(event.threadname) return True with hunter.trace(~Q(**query), record, actions=[CodePrinter(stream=lines), VarsPrinter('a', stream=lines), CallPrinter(stream=lines)], threading_support=True): def foo(a=1): started.set() print(a) def main(): foo() t = threading.Thread(target=foo) t.start() started.wait(10) main() lm = LineMatcher(lines.getvalue().splitlines()) print(lines.getvalue()) assert None not in idents assert 'MainThread' not in names pprint(lm.lines) lm.fnmatch_lines_random([ 'Thread-* *test_hunter.py:* call def foo(a=1):', 'Thread-* * vars a => 1', 'Thread-* *test_hunter.py:* call => foo(a=1)', 'Thread-* * vars a => 1', ])
from canopen_301_402.async.sdo_read import SdoRead from canopen_301_402.canopen_msgs.msgs import CanOpenMessageSdoReadRequest from canopen_301_402.canopen_msgs.msgs import CanOpenMessageSdoReadResponse from canopen_301_402.canopen_msgs.msgs import CanOpenMessageSdoError from time import sleep import mock evt_done_timeout = 2.0 TRACE = True if TRACE: import hunter hunter.trace(module_contains="canopen_301_402") def test_sdo_read_success(): global evt_done_timeout node = mock.MagicMock() index,subindex = 1,2 data = [3,4] read = SdoRead(node,index,subindex) read.start() assert node.canopen.send.called msg, = node.canopen.send.call_args[0]
import os, sys, hunter from .code-coverage_testing.input_code_files.input_data import input_data hunter.trace(module= input_data, action=hunter.CallPrinter)
# import gym # # env = gym.make('FetchReach-v1') # for i_episode in range(20): # observation = env.reset() # for t in range(100): # env.render() # print(observation) # action = env.action_space.sample() # observation, reward, done, info = env.step(action) # print("reward", reward) # print("info", info) # if done: # print("Episode finished after {} timesteps".format(t+1)) # break # env.close() from hunter import trace, Q, Debugger from pdb import Pdb import subprocess trace( # drop into a Pdb session on``myscript.mainMethod()`` call subprocess.call(['./run_bash.sh']))
def __init__(self, *args, **kwargs): self._calls = [] threading_support = kwargs.pop('threading_support', False) self.handler = hunter._prepare_predicate(*args, **kwargs) self._tracer = hunter.trace(self._append, threading_support=threading_support)
import hunter class HuntLocals: def __init__(self): self.last_locals = {} def __call__(self, event): if self.last_locals != event.locals: self.last_locals = dict(event.locals) print self.last_locals # docs http://python-hunter.readthedocs.io/en/latest/reference.html # how hunter.When works: When Query hunter.Q then Actions. hunter.trace(hunter.When( hunter.Q(module="test.test", function="foo"), HuntLocals()))
def test_trace_api_expansion(): # simple use with trace(function="foobar") as t: assert t._handler == When(Q(function="foobar"), CodePrinter) # "or" by expression with trace(module="foo", function="foobar") as t: assert t._handler == When(Q(module="foo", function="foobar"), CodePrinter) # pdb.set_trace with trace(function="foobar", action=Debugger) as t: assert t._handler == When(Q(function="foobar"), Debugger) # pdb.set_trace on any hits with trace(module="foo", function="foobar", action=Debugger) as t: assert t._handler == When(Q(module="foo", function="foobar"), Debugger) # pdb.set_trace when function is foobar, otherwise just print when module is foo with trace(Q(function="foobar", action=Debugger), module="foo") as t: assert t._handler == When(Or( When(Q(function="foobar"), Debugger), Q(module="foo") ), CodePrinter) # dumping variables from stack with trace(Q(function="foobar", action=VarsPrinter("foobar")), module="foo") as t: assert t._handler == When(Or( When(Q(function="foobar"), VarsPrinter("foobar")), Q(module="foo"), ), CodePrinter) with trace(Q(function="foobar", action=VarsPrinter("foobar", "mumbojumbo")), module="foo") as t: assert t._handler == When(Or( When(Q(function="foobar"), VarsPrinter("foobar", "mumbojumbo")), Q(module="foo"), ), CodePrinter) # multiple actions with trace(Q(function="foobar", actions=[VarsPrinter("foobar"), Debugger]), module="foo") as t: assert t._handler == When(Or( When(Q(function="foobar"), VarsPrinter("foobar"), Debugger), Q(module="foo"), ), CodePrinter) # customization assert trace(lambda event: event.locals.get("node") == "Foobar", module="foo", function="foobar") assert trace(Q(lambda event: event.locals.get("node") == "Foobar", function="foobar", actions=[VarsPrinter("foobar"), Debugger]), module="foo",) assert trace(Q(function="foobar", actions=[VarsPrinter("foobar"), lambda event: print("some custom output")]), module="foo",)
import hunter class HuntLocals: def __init__(self): self.last_locals = {} def __call__(self, event): if self.last_locals != event.locals: self.last_locals = dict(event.locals) print self.last_locals # docs http://python-hunter.readthedocs.io/en/latest/reference.html # how hunter.When works: When Query hunter.Q then Actions. hunter.trace( hunter.When(hunter.Q(module="test.test", function="foo"), HuntLocals()))
def test_trace_with_class_actions(): with trace(CodePrinter): def a(): pass a()