LoginSignup
1
0

More than 1 year has passed since last update.

VSCode で Djangoのテストを実行する

Posted at

VSCodeのテスト実行ショートカットキー(Ctrl+: A)を使って、Djangoのテスト(py manage.py tests相当)を実行するための設定

この記事では、「テストしたいDjangoプロジェクトがワークフォルダの直下ではない場所にある」場合の設定について述べる。

本記事で対象とするフォルダ構造.
Workdirectory/ <- VSCodeで開いているフォルダのルート
  git-work-dir/
    src/ <- テストしたいDjangoプロジェクト
      django-app/
        tests.py <- 実行したいテストファイル

用意するファイル

Workdirectory/.vscode/settings.json
{
    // "python.testing.pytestArgs": [
    //     "git-work-dir"
    // ],
    "python.testing.unittestEnabled": false,
    "python.testing.cwd": "${workspaceFolder}/git-work-dir/src",
    "python.testing.pytestEnabled": true
}

このファイルは、Testingタブからひな形を作れるが、なにやらうまくいかないため、以下の点を修正する。

  • python.testing.pytestArgs を削除する。
    この設定自体は、テスト対象ファイルを探す場所を pytest に教えてあげるものだが、この設定によって見つかったテストは、ショートカットキー(Ctrl+: A)でテスト実行すると失敗してしまう。
  • python.testing.cwd を追加する。
    これにより、manage.pyのある場所とテスト対象ファイルを探す場所を pytest に教えてあげる。
Workdirectory/pytest.ini
[pytest]
DJANGO_SETTINGS_MODULE = config.settings.develop
python_files = tests.py
  • Djangoの設定ファイルを開発用と本番用で分けているような場合、DJANGO_SETTINGS_MODULEを指定して、テストで使う設定ファイルを教えてあげる。
  • python_filesを指定して、探すファイル名を pytest に教えてあげる。python_filesはオプションらしいが、自環境ではこれがないとファイルが見つからなかった。
  • このファイルは、VSCodeのルートディレクトリに置く必要がある。

余談

VSCodeでPythonのテストを実行する場合、unittestとpytestが選択できる。
しかし、Djangoのテストを実行するには、pytest一択であるらしい。

テスト環境構築

py -m pip install pytest
py -m pip install pytest-django

参考
Testing python in Visual Studio Code - VSCode Doc
Configuring Django Settings - pytest-django Documents

余談2

発生するエラー

Running test with arguments: --rootdir 略\Workdirectory --override-ini junit_family=xunit1 --junit-xml=C:\Users\qwerty\AppData\Local\Temp\tmp-107122i8xbc2iq5Fl.xml
Current working directory: 略\Workdirectory
Workspace directory: 略\Workdirectory
Run completed, parsing output
Error while running tests: Workdirectory
TypeError: Cannot read property 'length' of undefined

Error while running tests:
TypeError: Cannot read property 'length' of undefined

Finished running tests!

1
0
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
1
0