Missing test coverage pytest python class
Asked Answered
G

1

6

I am testing my code with pytest --cov but one of my modules gets 0% coverage.

The module has one class declaration as such:

class DataBaseMaker:
    @staticmethod
    def create_database():
        conn = sqlite3.connect("database.db")
        
    def __init__(self):
        self.foo = 'bar'
        

The test does the following:

def test_create_database():
    DataBaseMaker.create_database()
    assert Path("database.db").is_file()

Test coverage for this is 0% - what am I doing wrong here?

Guerra answered 10/2, 2021 at 22:19 Comment(6)
Hard to say with a reproducible case, but it sounds like you aren't running the file you think you are. Try adding an exception to create_database, and see if the test fails.Sakovich
@Ned Thanks for replying. I guess I am running the correct tests and files as the database file gets created when running the tests. Also all tests pass. Or am I misunderstanding?Guerra
It's very easy to have another copy of the code, either because of an editing mistake, or an extra installation, or other reasons.Sakovich
@Ned I don’t. This project lives in one folder with main.py in the root folder and a modules folder containing the DataBaseMaker.py with the mentioned class and a test folder with the Python file containing the test. It‘s literally 3 files + requirements.txt and the stuff pytest and coverage generate.Guerra
It's a mystery. I wish I had the answer for you.Sakovich
See the answer I posted. If you have an explanation for that I'd be so happy to hear it.Guerra
G
2

I was able to find out what the issue is. It was not with the code itself but with my invocation of pytest. I did pytest --cov *projectname* where projectname was also the name of the folder the project is in. I think I got this from the pytest documentation? Not sure.

The solution: I ran pytest --cov . and sure enough my classes have 100% coverage now. If someone has an explanation for that behavior I'd be happy to learn.

Guerra answered 12/2, 2021 at 19:19 Comment(3)
You told coverage to only measure the code in the projectname directory. By changing to . you told it to measure any code found within the current directory. But isn't your DataBaseMaker class in the projectname directory? It should have been measured.Sakovich
It is. Structure is projectname/class.py and projectname/tests/testclass.py so both are in the same directory.Guerra
If you can package up the code and commands in a way for other people to reproduce the problem, we might be able to find a good answer.Sakovich

© 2022 - 2024 — McMap. All rights reserved.