遇到问题–python–pytest引用模块错误

转载请注明出处:遇到问题–python–pytest引用模块错误

遇到问题

python项目结构如图:

main.py中引用了

import pandas as pd

运行main.py文件没问题,但是运行pytest报错如下:

ImportError while importing test module '/Users/joe/workspace/platform/mgap-mendel/mgap-mendel/tests/test_mendel.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
test_mendel.py:1: in <module>
    from mgap_mendel.main import *
../mgap_mendel/__init__.py:2: in <module>
    from .main import *
../mgap_mendel/main.py:3: in <module>
    import pandas as pd
E   ModuleNotFoundError: No module named 'pandas'

原因

pytest使用的环境与python运行的环境不一致

使用命令排查

(venv) zhangxiaofans-MacBook-Pro:tests joe$ which python
/Users/joe/workspace/platform/mgap-mendel/mgap-mendel/venv/bin/python
(venv) zhangxiaofans-MacBook-Pro:tests joe$ which pytest
/usr/bin/local/pytest

明显发现环境不一致

解决方法

在当前沙箱环境中重新安装pytest,然后重新打开一次终端(右键test_mendel.py文件open in terminal)。

(venv) zhangxiaofans-MacBook-Pro:tests joe$
pip3 install pytest

如下为正常

(venv) zhangxiaofans-MacBook-Pro:tests joe$ which python
/Users/joe/workspace/platform/mgap-mendel/mgap-mendel/venv/bin/python
(venv) zhangxiaofans-MacBook-Pro:tests joe$ which pytest
/Users/joe/workspace/platform/mgap-mendel/mgap-mendel/venv/bin/pytest

更多可能和解决方法

在网上的资料有其他的解决方式
一、删除tests目录下的__init__.py文件
详情参考
https://stackoverflow.com/questions/41748464/pytest-cannot-import-module-while-python-can

二、创建一个调整目录的代码文件
假如目录如下:

\test_pytest
   mypkg/
       __init__.py
       app.py
   tests/
       test_app.py

You can create a context.py file in tests:

from __future__ import absolute_import
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

import mypkg

Then in your test file, add

from .context import mypkg

三、使用conftest.py文件
新建conftest.py
内容如下:

import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

每次运行pytest前先运行conftest.py

更多参考

https://github.com/pytest-dev/pytest/issues/2421

https://stackoverflow.com/questions/10253826/path-issue-with-pytest-importerror-no-module-named-yadayadayada

ModuleNotFoundError when using the tests outside application code layout

https://github.com/pytest-dev/pytest/issues/2027

转载请注明出处:遇到问题–python–pytest引用模块错误