Search code examples
pythonvisual-studio-codepytestdocstringdoctest

Pytesting Doctests in Visual Studio Code Debugger


Suppose I have the following code in foo.py:

def start():
    """
    >>> start()
    Hello world
    """
    test = 10
    print('Hello world')

Normally, I would run the doctest by running pytest foo.py --doctest-modules -v in the terminal. I instead want to be able to test it through Visual Studio Code's built-in debugger to track the variables and call stack.

I have the following configuration in my project's launch.json:

"name": "PyTest",
"type": "python",
"request": "launch",
"stopOnEntry": false,
"pythonPath": "${config:python.pythonPath}",
"module": "pytest",
"args": [
    "${file}",
    "--doctest-modules",
    "-v"
],
"cwd": "${workspaceRoot}",
"env": {},
"envFile": "${workspaceRoot}/.env",
"debugOptions": [
    "RedirectOutput"
]

However, when I open the file and run the PyTest debugging configuration in the VSCode debugger, the doctests are only run in the built-in terminal - nothing shows up in the debugger panel. How should I configure the debugger to be able to use its variables and call stack?


Solution

  • VSCode 35.x (at least) seems to have built-in support for PyTest, and does not need a launch.json section:

    These are the relevant .vscode/settings.json

    {
        "python.testing.pytestArgs": [
            "--doctest-modules", 
            "--doctest-report", "ndiff",
        ],
        "python.testing.pytestEnabled": true
    }
    
    

    Of course, I have pytest installed in the specified virtual-environment.

    If you need to configure PyTest, you may configure it, as usual, in one of the

    pyproject.toml, setup.cfg, pytest.ini, tox.ini, setup.cfg files:

    [tool:pytest]
    addopts          = --doctest-modules --doctest-report ndiff
    doctest_optionflags= NORMALIZE_WHITESPACE ELLIPSIS