为什么只有在使用 pytest 进行单元测试时才找到模块? [英] 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:
给定这个目录
who-said-what/
|
|_ wave_encoder.py
|
|_ tests/
|_ test_wave_encoder.py
其中 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)
如果我单独运行这个测试文件,没有问题.但是,如果我尝试从项目中的任何目录运行 pytest:
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 .
我收到一个 ModuleNotFoundError: No module named 'wave_encoder'
.
但是,如果我将 test_wave_encoder.py
移动到父目录,它确实可以工作(还有其他错误,但这是一个不同的问题).
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:在您的根目录中放置一个空的 conftest.py
.第 2 步:使用 python -m pytest
Step 1: place an empty conftest.py
in your root.
Step 2: run tests from root folder with python -m pytest
应该可以.
这篇关于为什么只有在使用 pytest 进行单元测试时才找到模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!