在 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/