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?

Franz
  • 235
  • 3
  • 14
  • 1
    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. – Ned Batchelder Feb 11 '21 at 12:18
  • @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? – Franz Feb 11 '21 at 13:21
  • 1
    It's very easy to have another copy of the code, either because of an editing mistake, or an extra installation, or other reasons. – Ned Batchelder Feb 11 '21 at 17:32
  • @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. – Franz Feb 11 '21 at 20:12
  • It's a mystery. I wish I had the answer for you. – Ned Batchelder Feb 12 '21 at 00:12
  • See the answer I posted. If you have an explanation for that I'd be so happy to hear it. – Franz Feb 12 '21 at 19:19

1 Answers1

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.

Franz
  • 235
  • 3
  • 14
  • 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. – Ned Batchelder Feb 12 '21 at 23:59
  • It is. Structure is projectname/class.py and projectname/tests/testclass.py so both are in the same directory. – Franz Feb 13 '21 at 10:45
  • 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. – Ned Batchelder Feb 13 '21 at 15:48