Skip to main content
 首页 » 编程设计

python之如何从 django_nose 覆盖范围中排除特定部分代码

2024年08月27日25softidea

在极少数情况下,我的方法可能包含测试期间无法访问的代码分支(例如,处理一些罕见的异常等)

我的意思是我的代码永远不想被测试覆盖。是否有一种特殊类型的注释/文档字符串/任何东西来标记此类代码,以便它与正常代码清楚地区分并从 nose 代码覆盖率报告中排除?

请您参考如下方法:

根据 coverage documentation ,你需要在代码中添加一个pragma: no cover注释:

Any line with a comment of “pragma: no cover” is excluded. If that line introduces a clause, for example, an if clause, or a function or class definition, then the entire clause is also excluded.

a = my_function1() 
if debug:   # pragma: no cover 
    msg = "blah blah" 
    log_message(msg, a) 
b = my_function2() 

您还可以使用 coverage configuration file并定义 exclude_lines配置参数,其中包含要从覆盖范围中排除的模式列表。例如,要将所有 __repr__() 方法排除在考虑范围之外:

[report] 
exclude_lines = def __repr__