The trace https://docs.python.org/3.5/library/trace.html#module-trace模块为您提供了一个非常简单的解决方案(与您所要求的不同,但足够简单,可以尝试一下。)
from trace import Trace
tracer = Trace()
response = tracer.runfunc(self.admin_client.post, url, post)
self.assertEqual(200, response.status_code, response)
一个更复杂的解决方案需要创建一个上下文管理器来保存跟踪并仅在异常时打印它,需要使用系统设置跟踪 https://docs.python.org/3.5/library/sys.html?highlight=settrace#sys.settrace。
您自己实现的模板可以是:
class MyTracer():
def __init__(self):
self.trace = None
def newscope(self, frame, event, arg):
## real work should be done here, just minimal example
self.trace.append((frame, event, arg))
return None
def pprint(self):
## real pretty printing of trace info should be done here
print(self.trace)
def __enter__(self):
self.trace = []
sys.settrace(self.newscope)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
sys.settrace(None)
if exc_type is not None:
self.pprint()
## print some info gathered from exc_type, exc_val, exc_tb
然后你可以:
with MyTracer():
response=self.admin_client.post(url, post)
self.assertEqual(200, response.status_code, response)
这个想法是 MyTracer 实例有一个跟踪器方法newscope
保存一些有用的信息self.trace
。异常退出上下文时pprint
方法被调用;在正常退出时,跟踪信息将被丢弃。
大部分工作都要在tracing方法中完成newscope
。
可以找到一些跟踪函数的具体示例here https://pymotw.com/2/sys/tracing.html.