Launch test file (pytest) as debug for active file in VSCode

Viewed 339

I have a python library (module) that contains multiple modules and associated tests following a fairly standard structure

project_root
    library_folder
        __init__.py
        module_A
            __init__.py
            sub_module_AA
                __init__.py
                file_AAA.py
            file_AA.py
            file_AB.py
            file_AC.py
        module_B
            __init__.py
            file_BA.py
            file_BB.py
        module_C
            __init__.py
            file_CA.py
            file_CB.py
            file_CC.py
        ...
    tests
        module_A
            test_fileAA.py
            ...
        module_B
            test_fileBA.py
            ...
    pyproject.toml
    ...

Currently I am doing what I would call caveman debugging by dropping a import pdb; pdb.set_trace() into a buggy file and then I call the corresponding test with pytest path/to/test_fileXY.py and wait for the breakpoint. I would like to move this setup to VSCode so that I can simply hit F5 and run the corresponding tests.

My problem is that I need to call pytest {workspaceDir}/tests/{submodule_path}/test_{filename}.py to run the tests. I can get quite close via

{
    "configurations": [
        {
            "name": "Python: Run Current File's Tests",
            "type": "python",
            "request": "launch",
            "module": "pytest",
            "console": "integratedTerminal",
            "args": [
                "${workspaceFolder}/tests/${relativeFileDirname}/test_${fileBasename}"
            ]
        }
    ]
}

However, this produces {workspaceDir}/tests/library_folder/{submodule_path}/test_{filename}.py (note the additional library_folder in the path. How do I do this correctly, i.e., how do I create a reference to the active file's corresponding test?

1 Answers

The python extension has build-in this feature:

enter image description here

enter image description here

Related