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

Is there a constant that's True when unittesting, but False otherwise?

在 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

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

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

非常感谢任何帮助!

对于这种情况,我建议使用命令行参数来控制代码是否 运行。

在这种情况下,您可以有一个简单的模块,它根据 -unittest 参数是否已传递给 python 进程来定义类似 is_unit_testing 的值。

要处理命令行参数,请看这里:How do I access command line arguments in Python?

import sys
# sys.argv is a list of all commandline arguments you can check through
command_line_arguments_list = sys.argv # e.g. ["arg1", "arg2", "-unittest"]
is_unit_testing = "-unittest" in command_line_arguments_list

然后您可以按照预期通过命令行传递参数:

python myModule.py  arg1  arg2  -unittest

这适用于任何您希望来自同一代码库的多个 'builds' 的情况。比如有'no database'/'no gui'模式等

要检查您要问的内容(似乎 unittest 是否已导入),您可以检查密钥 "unittest" 是否在 sys.modules

import sys
import unittest

if "unittest" in sys.modules:
    print("I'm unittest-ing")

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。这将用一些 "mocked" 功能替换功能。这通常用于 "plotting code" 或使 "requests" 等的代码。因为您可以禁用某些您在测试时不使用的功能 need/want。

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

您还没有说您使用了哪种绘图,但如果是 matplotlib,他们确实有 some documentation to facilitate testing or see this