Pytest importterror和ModuleNotFoundError当从子目录运行test时



我有下面的项目结构

- root
- main.py
- test/
- __init__.py
- conftest.py
- test.py

conftest.py中,我使用mysql.connector有一些自定义装置。因此我要导入:

import mysql.connector
@pytest.fixture(scope='module')  # maintain connection for all tests
def cnx(database, username, password):
cnx = mysql.connector.connect(database=database, user=username, password=password)
yield cnx
cnx.close()

当我从根目录下的终端运行test.py时,使用以下命令:

pytest tests/test.py

我得到下面的错误:

ImportError while loading conftest '/tests/conftest.py'.
tests/conftest.py:5: in <module>
import mysql.connector
E   ModuleNotFoundError: No module named 'mysql'

为什么会发生这种情况?已安装mysql

你试过在CLI上运行python吗?然后尝试如果import mysql.connector是工作?另一个解决方案是卸载当前版本的MySQL,并尝试这个包代替pip install mysql-connector-python-rf

使用pytest运行测试脚本的命令不是pytest tests/test.py,而是

python -m pytest tests/test.py

详见官方文档

最新更新