Reputation: 3684
I am new to pytest and testing. I have a simple program like below say 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
import pytest
def test_foo()
pass
def test_bar()
pass
To increase code coverage, I also want to test it as python3 hi.py
i.e. if __name__==__main__:
way. I dont know how will I do it using a test case from test_hi.py
. Please help. Thanks.
I am testing the module using pytest
python -m pytest --cov=hi.py
Upvotes: 1
Views: 4204
Reputation: 3684
Okay so one solution I found for my problem is to exempt that if statement and achieve 100% coverage. To do that I have to add # pragma: no cover
after if statement like below.
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
python -m pytest --cov=project
However, it is skipping the statements and I would like to cover it instead of skipping it.
Upvotes: 3
Reputation: 39404
My theory for code coverage is that you must have 100% coverage. Except where you can't, and then you must have 0% coverage.
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.
An example of a zero coverage file is:
from hi import foo, bar
if __name__ == "__main__":
foo()
bar()
Upvotes: 0