我有下面的项目结构
- 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
详见官方文档