1. 程式人生 > >遇到問題–python–pytest引用模組錯誤

遇到問題–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引用模組錯誤