一段python代码如何判断它是否在unittest下运行 [英] How can a piece of python code tell if it's running under unittest
问题描述
我有一个使用 Python unittest 模块进行单元测试的大型项目.
我有一个小方法来控制系统行为的大方面.我需要这种方法在 UT 下运行时返回一个固定的结果,以提供一致的测试运行,但对我来说,为每个 UT 模拟它会很昂贵.
有没有办法让这个单一的方法,unittest 知道,以便它可以在 unittest 下运行时修改它的行为?
您可以检查 unittest
模块是否已加载.它应该只在测试运行时加载.
I have a large project that is unit tested using the Python unittest module.
I have one small method that controls large aspects of the system's behaviour. I need this method to return a fixed result when running under the UTs to give consistent test runs, but it would be expensive for me to mock this out for every single UT.
Is there a way that I can make this single method, unittest aware, so that it can modify its behaviour when running under the unittest?
You can check, if the unittest
module is loaded. It should be loaded only, if a test runs.
>>> 'unittest' in sys.modules.keys()
False
>>> from unittest import TestCase
>>> 'unittest' in sys.modules.keys()
True
这篇关于一段python代码如何判断它是否在unittest下运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!