Search code examples
pythonunit-testingpytestpytest-cov

Why is module not found only when doing unit testing with pytest?


I'm having a problem running unit tests. I have a project structure like this:

Given this directory

who-said-what/
    |
    |_ wave_encoder.py
    | 
    |_ tests/
        |_ test_wave_encoder.py

where test_wave_encoder.py looks like this:

from wave_encoder import *

class TestEncoder():
    def test_plot_no_fit1(self):
        encoder = WaveEncoder()
        self.assertRaises(ValueError, encoder.plot_signal)

    def test_plot_no_fit2(self):
        encoder = WaveEncoder()
        self.assertRaises(ValueError, encoder.plot_transform)

    def test_plot_no_fit3(self):
        encoder = WaveEncoder()
        self.assertRaises(ValueError, encoder.plot_components)

If I run this test file individually, no issues. However, if I try to run pytest from any directory in the project:

pytest -v --cov ./tests 
# or
pytest -v --cov .

I get a ModuleNotFoundError: No module named 'wave_encoder'.

However, if I move test_wave_encoder.py to the parent directory, it does work (there are other errors, but that's a different question).

I don't really want a bunch of test files in the parent directory. How do I sort this out?


Solution

  • Step 1: place an empty conftest.py in your root. Step 2: run tests from root folder with python -m pytest

    That should work.