Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing test coverage for class declaration with pytest-cov

I'm trying to achieve 100% coverage.

I have file (app/ifaces.py):

import netifaces

class NoIPException(Exception):
    pass

def get_local_ips():
    ...(code here)

and I have test:

import pytest
import mock
import netifaces

from app import ifaces

def test_get_local_ips_normal_case():
....

When I run test manually:

py.test -v --cov app --cov-report term-missing

it reports 100% code coverage: app/ifaces 16 0 100%

but when I add it as 'self-run' to the test, it reports that first six lines are not covered:

if __name__ == "__main__":
    import sys
    pytest.main("-v %s --cov app/ifaces.py --cov-report term-missing" % sys.argv[0])

report:

Name           Stmts   Miss  Cover   Missing
--------------------------------------------
app/ifaces        16      4    75%   1-6

How can I add self-run test to get same result as manual py.test execution? And what the difference between results? Why 6 lines in the app/ifaces.py are reported as not covered in second case?

Thanks.

like image 681
George Shuklin Avatar asked Jan 19 '16 16:01

George Shuklin


1 Answers

Ok, I found a reason.

When pytest is invoked from test itself, all imports are done already, and, therefore, they are not counted as covered.

To make it covered they need to be imported during pytest-cov execution.

My solution was to use pytest fixtures to make import: 1. remove "from app import ifaces" from the top of the test program. 2. Add fixture:

 @pytest.fixture
 def ifaces():
     from app import ifaces
     return ifaces

3.Make it passable as variable to the tests:

def test_get_local_ips_normal_case(ifaces)
    ....
like image 80
George Shuklin Avatar answered Sep 28 '22 19:09

George Shuklin