import inspect
def in_unit_test():
current_stack = inspect.stack()
for stack_frame in current_stack:
for program_line in stack_frame[4]: # This element of the stack frame contains
if "unittest" in program_line: # some contextual program lines
return True
return False
我的解决方案是在运行
unittest
之前设置一个TEST_FLAG=true
环境变量。例如:那么这只是一个检查变量是否设置的问题。例如:
我对
unittest
模块了解不多,但是如果直接为单元测试运行文件,则可以在测试代码中包含以下内容:if语句中的任何代码只有在直接调用特定模块而不是导入其他模块时才会执行。根据文档,这就是您应该首先调用
unittest.main()
的方式。https://docs.python.org/2/library/unittest.html
这假设您不是从命令行运行的。
编辑:您可以查看函数堆栈,尝试找到
unittest.main()
函数。https://docs.python.org/2/library/inspect.html
这是一种老套的解决方案,但是
inspect
模块有很多有用的自省功能。您可以在运行时仅为测试修改函数。例如:
模块.py
测试.py
现在,每当
module
中的代码调用func()
时,它实际上会回调到您的replacement_func()
。相关问题 更多 >
编程相关推荐