从子目录运行测试时 Pytest ImportError 和 ModuleNotFoundError

问题描述

我有以下项目结构

- 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 肯定已安装。

解决方法

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

python -m pytest tests/test.py

详见official docs

,

你试过在 CLI 上运行那个 python 吗?然后试试 import mysql.connector 是否工作?另一种解决方案是您卸载当前版本的 MySQL 并尝试使用此软件包 pip install mysql-connector-python-rf