python - 是否有一个常量在单元测试时为真,否则为假?

标签 python python-unittest

在 Python 的 typing 模块中,它们有一个非常有用的常量,它在类型检查时为 True,否则为 False。这意味着,例如,如果 TYPE_CHECKING 的计算结果为 True,您可以动态导入类。

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from module import Class

如果 unittest 有类似的东西,那将非常有用。我可以在 __init__.py 文件中看到,存在一个定义为 __unittest = True 的变量:

__all__ = ['TestResult', 'TestCase', 'TestSuite',
           'TextTestRunner', 'TestLoader', 'FunctionTestCase', 'main',
           'defaultTestLoader', 'SkipTest', 'skip', 'skipIf', 'skipUnless',
           'expectedFailure', 'TextTestResult', 'installHandler',

__unittest = True

有什么方法可以像 type_checking 一样使用 __unittest typing 吗?

这样做的原因:我的代码库中有一些可以运行和绘制图表的用户示例。我想将这些示例作为单元测试的一部分运行,以查看它们何时损坏并需要修复。但是,我需要一种动态的方式来停止尝试打开绘图窗口并阻止单元测试的示例。

非常感谢任何帮助!

最佳答案

Reason for this: I have some user examples in my code-base which can be run and plot graphs. I would like to run these examples as part of the unit tests to see when they break and need fixing. I need a dynamic way of stopping the examples trying to open a plotting window and blocking the unit tests, however.

实现这一目标的最佳方法是 mocking .这将用一些“模拟”功能替换功能。这通常用于“绘制代码”或发出“请求”等的代码。因为您可以在测试时禁用某些不需要/不需要的功能。

它还避免了与单元测试相关的东西使生产代码困惑。对于类型检查,这是必需的,因为它发生在运行时,但单元测试通常不会在运行时发生,或者应该在运行时产生任何影响。

您还没有说您使用了哪种绘图,但如果是 matplotlib,他们确实有 some documentation to facilitate testing或查看此 QA .

关于python - 是否有一个常量在单元测试时为真,否则为假?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46157630/

相关文章:

python - 如何在 Python 安装中重用模块?

python elasticsearch客户端在创建索引期间设置映射

python - 在同一个python函数中模拟两个具有不同返回值的redis hget

python - 如何运行 Odoo 测试 unittest2?

python - 从 ORM 中提取数据并按日期分组

python - 使用 PIL.Image._getexif() 访问 exif 信息时遇到问题

python - 如何在 pytest 中迭代 test_function 以获得多个值?

python - 使用 py.test 但在命令行上排除测试列表?

python - 在 Python 中模拟无限生成器

python - 根据唯一 ID Pandas 数据框收集行