How to input command line arguments when using pytest in VS Code

58 Views Asked by At

I have setup my pytest testing to use optional command line arguments. I would like to run and debug these tests in VS Code. However, I am unable to get the command line arguments to work with VS Code.

Based on the VS Code instructions for debugging Python tests, I added the following configuration to launch.json:

{
    "name": "Python: Debug Tests",
    "type": "debugpy",
    "request": "launch",
    "program": "${file}",
    "purpose": ["debug-test"],
    "console": "integratedTerminal",
    "args": ["--csvfile='..\\example.csv'","--skip", "1"],
    "justMyCode": false
}

This differs from the VS code instruction only in that I have added the args to pass in my command line arguments. I have another configuration in launch.json, but its purpose is not "debug-test" (and when I add args to it, pytest still does not receive my arguments).

My conftest.py includes the following which works when using pytest outside VS Code:

def pytest_addoption(parser):
    parser.addoption(
        "--csvfile", action="store", default=None)
    parser.addoption("--skip", action="store", default=None)

@pytest.fixture(scope='session')
def skip(request):
    return request.config.option.skip

@pytest.fixture(scope='session')
def data(request):
    return pd.read_csv(request.config.option.csvfile)

The result is that request.config.option.skip and request.config.option.csvfile are always None (the default value). When I import sys and look at sys.argv, it does not include the arguments from launch.json.

I am using Python 3.12 and VS Code version 1.87.1.

1

There are 1 best solutions below

3
Ricardo Gellman On

I have an similar example where I set launch.json to runs with python, not debugpy follow the file content.

{
    "name": "Python: Debug Tests",
    "type": "python",
    "request": "launch",
    "module": "pytest",
    "args": [
        "${workspaceFolder}/path/to/your/test_file.py",
        "--csvfile=../example.csv",
        "--skip=1"
    ],
    "console": "integratedTerminal",
    "justMyCode": false
}