Skip to main content
 首页 » 编程设计

python之只为单元测试启用 Python 代码

2025年05月04日13kerrycode

假设我有以下功能:

def f(): 
    if TESTING: 
        # Run expensive sanity check code 
    ... 

仅当我们运行单元测试时运行测试代码块的正确方法是什么?

[编辑:是否有一些“全局”变量我可以访问以查明单元测试是否开启?]

请您参考如下方法:

一般来说,我建议不要这样做。您的生产代码真的不应该意识到单元测试的存在。这样做的一个原因是,您可能在 if TESTING block 中包含使测试(意外)通过的代码,并且由于代码的生产运行不会运行这些位,可能会让您暴露在外即使您的测试通过了,也会导致生产失败。

但是,如果您坚持这样做,有两种可能的方法(我能想到)可以做到这一点。

首先,您可以使用您在测试用例中设置为 True 的模块级 TESTING var。例如:

生产代码:

TESTING = False    # This is false until overridden in tests 
 
def foo(): 
    if TESTING: 
        print "expensive stuff..." 

单元测试代码:

import production 
 
def test_foo(): 
    production.TESTING = True 
    production.foo()    # Prints "expensive stuff..." 

第二种方法是使用 python 的内置 assert 关键字。当 python 使用 -O 运行时,解释器将去除(或忽略)代码中的所有 assert 语句,允许您在整个过程中散布这些昂贵的 gem,并且知道如果它在以下位置执行它们将不会运行优化模式。请确保在没有 -O 标志的情况下运行测试。

示例(生产代码):

def expensive_checks(): 
    print "expensive stuff..." 
    return True 
 
def foo(): 
    print "normal, speedy stuff." 
    assert expensive_checks() 
 
foo() 

输出(使用python mycode.py运行)

normal, speedy stuff. 
expensive stuff... 

输出(使用python -O mycode.py 运行)

normal, speedy stuff. 

关于 assert 语句的警告...如果 assert 语句的计算结果不是真值,将引发 AssertionError。