一段python代码如何判断它是否在unittes下运行

2024-04-27 02:31:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个大型项目是使用Python unittest模块进行单元测试的。

我有一个控制系统行为大方面的小方法。当在UTs下运行时,我需要这个方法返回一个固定的结果,以提供一致的测试运行,但是对于我来说,为每个UTs模拟这个结果是很昂贵的。

有没有一种方法可以让这个单一的方法unittest知道,以便它在unittest下运行时可以修改其行为?


Tags: 模块方法单元测试unittest大型项目uts
3条回答

我的解决方案是在运行unittest之前设置一个TEST_FLAG=true环境变量。例如:

TEST_FLAG=true python -m unittest discover -s tests -b

那么这只是一个检查变量是否设置的问题。例如:

MONGODB_URI =
    os.environ.get('MONGODB_URI') if not os.environ.get('TEST_FLAG') 
        else os.environ.get('MONGODB_TEST_URI')

我对unittest模块了解不多,但是如果直接为单元测试运行文件,则可以在测试代码中包含以下内容:

if __name__ == "__main__":

if语句中的任何代码只有在直接调用特定模块而不是导入其他模块时才会执行。根据文档,这就是您应该首先调用unittest.main()的方式。

https://docs.python.org/2/library/unittest.html

这假设您不是从命令行运行的。

编辑:您可以查看函数堆栈,尝试找到unittest.main()函数。

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

https://docs.python.org/2/library/inspect.html

这是一种老套的解决方案,但是inspect模块有很多有用的自省功能。

您可以在运行时仅为测试修改函数。例如:

模块.py

def func():
    return random.randint()

测试.py

import module

def replacement_func():
    return 4 # chosen by fair dice roll

module.func = replacement_func

# run unit tests here

现在,每当module中的代码调用func()时,它实际上会回调到您的replacement_func()

相关问题 更多 >