只为单元测试启用 Python 代码?
假设我有以下函数:
def f():
if TESTING:
# Run expensive sanity check code
...
仅当我们运行单元测试时,运行测试代码块的正确方法是什么?
[编辑:是否有一些“全局”变量我可以访问以查明单元测试是否开启?]
Let's say I have the following function:
def f():
if TESTING:
# Run expensive sanity check code
...
What is the correct way to run the TESTING code block only if we are running a unittest?
[edit: Is there some "global" variable I can access to find out if unittests are on?]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般来说,我建议不要这样做。您的生产代码确实不应该意识到单元测试的存在。原因之一是,您的
if TESTING
块中可能包含使测试通过(意外)的代码,并且由于代码的生产运行不会运行这些位,因此可能会让您暴露在外即使您的测试通过了,也会导致生产失败。但是,如果您坚持这样做,有两种可能的方法(我能想到的)可以做到这一点。
首先,您可以使用在测试用例中设置为
True
的模块级TESTING
var。例如:生产代码:
单元测试代码:
第二种方法是使用 python 的内置
assert
关键字。当 python 使用-O
运行时,解释器将删除(或忽略)代码中的所有断言语句,允许您在整个过程中散布这些昂贵的 gem,并知道如果在以下位置执行它们将不会运行优化模式。请确保在不使用-O
标志的情况下运行测试。示例(生产代码):
输出(使用
python mycode.py
运行)输出(使用
python -O mycode 运行.py
)关于断言语句的一点警告...如果断言语句的计算结果不是真值,则会引发
AssertionError
。Generally, I'd suggest not doing this. Your production-code really shouldn't realize that the unit-tests exist. One reason for this, is that you could have code in your
if TESTING
block that makes the tests pass (accidentally), and since production runs of your code won't run these bits, could leave you exposed to failure in production even when your tests pass.However, if you insist of doing this, there are two potential ways (that I can think of) this can be done.
First of, you could use a module level
TESTING
var that you set in your test case toTrue
. For example:Production Code:
Unit-Test Code:
The second way is to use python's builtin
assert
keyword. When python is run with-O
, the interpreter will strip (or ignore) all assert statements in your code, allowing you to sprinkle these expensive gems throughout and know they will not be run if it is executed in optimized mode. Just be sure to run your tests without the-O
flag.Example (Production Code):
Output (run with
python mycode.py
)Output (run with
python -O mycode.py
)One word of caution about the assert statements... if the assert statement does not evaluate to a true value, an
AssertionError
will be raised.