LoginSignup
0
1

VSCode GUIからのpytestでModuleNotFoundErrorが起きたら

Posted at

エラー内容

VSCodeのGUIからpytestを実行するとテスト対象モジュールのimportで失敗する。

スクリーンショット 2024-02-04 12.00.24.png

解決方法

__init__.pyにパスを追加する。

目次

  1. VSCodeのセットアップ
  2. ディレクトリ構成と対象ファイル
  3. init.pyでパスを追加する
  4. poetryからテスト実行する場合

VSCodeのセットアップ

拡張機能としてPython Test Explorer for Visual Studio Codeを追加しておきます。
追加後はフラスコのアイコンが表示されます。

スクリーンショット 2024-02-01 21.04.54.png

インストールが完了次第、ルートディレクトリを聞かれます。
今回はtest_projectをルートとます。

ディレクトリ構成と対象ファイル

test_project 
├── src
│   └── main.py
└── tests
    └── test_main.py
main.py
def add(a,b):
    return a + b
test_main.py
from main import add


def test_add():
    res = add(10,20)
    assert res==30

__init__.pyでパスを追加する

tests/__ini__.py
import os
import sys

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'src')))

このコードは現在のファイルの親ディレクトリ(src ディレクトリ)をPythonのシステムパスに追加していて、具体的には以下のようなステップを踏んでいます。

  1. __file__ は現在実行中のPythonファイルのフルパスを表します(/Users/yoshimasa/Desktop/test_project/tests/_init_.py)

  2. os.path.dirname() 関数は、与えられたパスのディレクトリ名を返します。これを用いて、現在のファイルが存在するディレクトリを取得します。
    (/Users/yoshimasa/Desktop/test_project/tests)

  3. その後、'..'と'src'を連結します。
    (/Users/yoshimasa/Desktop/test_project/tests/../src)

  4. さらにos.path.abspath()でパスを正規化します
    (/Users/yoshimasa/Desktop/test_project/src)

最後に、sys.path.append() を使用して、この src ディレクトリをPythonのシステムパスに追加します。これにより、このディレクトリ内のモジュールやパッケージを、他の場所からインポートして使用できるようになります

poetryからテスト実行する場合

poetryでプロジェクを管理していて、コマンドライン(poetry run pytest)からテスト実行する場合はpoetry.tomlに以下を追記して対応するもよし。

[tool.pytest.ini_options]
addopts = [
    "--import-mode=importlib",
]

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1