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

tom*_*dee 18 python unit-testing

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

我有一个小方法来控制系统行为的大部分方面.我需要这种方法在UT下运行时返回一个固定的结果,以提供一致的测试运行,但是对于每个单独的UT来说,这样做是很昂贵的.

有没有办法可以让这个单一方法,单元测试识别,以便它可以在unittest下运行时修改它的行为?

kwa*_*nke 7

您可以检查unittest模块是否已加载。如果测试运行,它应该只加载。

>>> 'unittest' in sys.modules.keys()
False
>>> from unittest import TestCase
>>> 'unittest' in sys.modules.keys()
True
Run Code Online (Sandbox Code Playgroud)

  • 如果您跳过`.keys()`并仅在sys.modules`中使用`'unittest',它应该会更有效。 (4认同)

The*_*nse 6

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

if __name__ == "__main__":
Run Code Online (Sandbox Code Playgroud)

位于 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
Run Code Online (Sandbox Code Playgroud)

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

这有点像hacky解决方案,但该inspect模块有很多有用的内省功能。

  • 警告:此函数将始终返回 `True`,因为函数名称是 `in_unittest`,并且将在 program_line:` 中由 `if "unittest" 断言 (2认同)

Fra*_*nco 6

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

TEST_FLAG=true python -m unittest discover -s tests -b
Run Code Online (Sandbox Code Playgroud)

然后只需检查是否设置了变量。例如:

MONGODB_URI =
    os.environ.get('MONGODB_URI') if not os.environ.get('TEST_FLAG') 
        else os.environ.get('MONGODB_TEST_URI')
Run Code Online (Sandbox Code Playgroud)


Ste*_*nes 1

我确信还有其他更好的方法,但您始终可以从 main 设置一个全局标志,而不是在单元测试下,然后在您的方法中访问它。

当然,另一种方法是重写该方法作为单元测试设置的一部分 - 如果调用您的方法brian并且您有一个test_brianthen 只需在预测试设置期间brian = test_brian就可以完成这项工作,您可能需要放置模块名称插入前面的语句中