VSCode: デバッガーで実行中の pytest コマンドライン引数を渡すにはどうすればいいですか? 質問する

VSCode: デバッガーで実行中の pytest コマンドライン引数を渡すにはどうすればいいですか? 質問する

私は、VSCode プロジェクトで pytest によって実行されるテストを作成しました。構成ファイル .vscode/settings.json を使用すると、次のコマンドライン パラメータを pytest に渡すことができます。

    "python.testing.pytestArgs": [
        "test/",
        "--exitfirst",
        "--verbose"
    ],

次のようにして、コマンド ラインから pytest を呼び出すなど、カスタム スクリプト引数をテスト スクリプト自体に渡すこともできます。

pytest --exitfirst --verbose test/ --test_arg1  --test_arg2

ベストアンサー1

何度も実験した結果、ようやくやり方がわかりました。必要なのは、コードがテスト サーバーにログインできるように、ユーザー名とパスワードをスクリプトに渡すことでした。私のテストは次のようになりました。
my_module_test.py

import pytest
import my_module

def login_test(username, password):
    instance = my_module.Login(username, password)
    # ...more...

conftest.py

import pytest

def pytest_addoption(parser):
    parser.addoption('--username', action='store', help='Repository user')
    parser.addoption('--password', action='store', help='Repository password')

def pytest_generate_tests(metafunc):
    username = metafunc.config.option.username
    if 'username' in metafunc.fixturenames and username is not None:
        metafunc.parametrize('username', [username])

    password = metafunc.config.option.password
    if 'password' in metafunc.fixturenames and password is not None:
        metafunc.parametrize('password', [password])

次に、設定ファイルで以下を使用します。
.vscode/設定.json

{
    // ...more...
    "python.testing.autoTestDiscoverOnSaveEnabled": true,
    "python.testing.unittestEnabled": false,
    "python.testing.nosetestsEnabled": false,
    "python.testing.pytestEnabled": true,
    "python.testing.pytestArgs": [
        "--exitfirst",
        "--verbose",
        "test/",
        "--username=myname",
        "--password=secret",
    // ...more...
    ],
}

別の方法としては、pytest.ini ファイルを使用する方法があります。
pytest.ini

[pytest]
junit_family=legacy
addopts = --username=myname --password=secret

おすすめ記事