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

人走茶凉 提交于 2020-08-10 18:53:26

问题


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?


回答1:


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

That should work.



来源:https://stackoverflow.com/questions/63273804/why-is-module-not-found-only-when-doing-unit-testing-with-pytest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!