一段python代码如何判断它是否在unittest下运行 [英] How can a piece of python code tell if it's running under unittest

查看:43
本文介绍了一段python代码如何判断它是否在unittest下运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

解决方案

您可以检查 unittest 模块是否已加载.它应该只在测试运行时加载.

<预><代码>>>>sys.modules.keys() 中的单元测试"错误的>>>从 unittest 导入 TestCase>>>sys.modules.keys() 中的单元测试"真的

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆