简体   繁体   English

如何测试 __name__==“__main__” 以增加覆盖率

[英]how to test if __name__==“__main__” to increase coverage

I am new to pytest and testing.我是 pytest 和测试的新手。 I have a simple program like below say hi.py我有一个像下面这样的简单程序说hi.py

def foo():
   print('hello world')

def bar():
   print('hello python')

if __name__ == "__main__":
   foo()
   bar()

I can run the above program like我可以像这样运行上面的程序

python3 hi.py

I have a couple of test cases in test_hi.py like below我在test_hi.py中有几个测试用例,如下所示

import pytest

def test_foo()
   pass

def test_bar()
   pass

To increase code coverage, I also want to test it as python3 hi.py ie if __name__==__main__: way.为了增加代码覆盖率,我还想将其作为python3 hi.py进行测试,即 if __name__==__main__:方式。 I dont know how will I do it using a test case from test_hi.py .我不知道如何使用来自test_hi.py的测试用例来做到这一点。 Please help.请帮忙。 Thanks.谢谢。

I am testing the module using pytest我正在使用 pytest 测试模块

python -m pytest --cov=hi.py

My theory for code coverage is that you must have 100% coverage.我的代码覆盖率理论是你必须有 100% 的覆盖率。 Except where you can't, and then you must have 0% coverage.除非你不能,然后你必须有 0% 的覆盖率。

You should split your source files into two different folders.您应该将源文件拆分为两个不同的文件夹。 One folder is covered by tests and achieves 100%, the files in the other folder are never tested and has 0% coverage.一个文件夹被测试覆盖并达到 100%,另一个文件夹中的文件从未经过测试并且覆盖率为 0%。

An example of a zero coverage file is:零覆盖文件的一个示例是:

from hi import foo, bar

if __name__ == "__main__":
   foo()
   bar()

Okay so one solution I found for my problem is to exempt that if statement and achieve 100% coverage.好的,我为我的问题找到的一种解决方案是免除该 if 语句并实现 100% 的覆盖率。 To do that I have to add # pragma: no cover after if statement like below.为此,我必须在 if 语句之后添加# pragma: no cover ,如下所示。

if __name__ == "__main__":      # pragma: no cover
   foo()
   bar()

The comment will tell pytest to skip the if statement and when you running the following command I can get 100% coverage该评论将告诉 pytest 跳过 if 语句,当您运行以下命令时,我可以获得 100% 的覆盖率

python -m pytest --cov=project

However, it is skipping the statements and I would like to cover it instead of skipping it.但是,它正在跳过语句,我想覆盖它而不是跳过它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM