VS Code

How to Run Pytest in VSCode for Testing

How to Run Pytest in VSCode for Testing

A fresh Python project in VSCode can have a tests folder full of test files and still show an empty Testing view. The cause is a setting. python.testing.pytestEnabled defaults to false (VS Code documentation, 2026 revision), so the Python extension ignores pytest until it’s told otherwise.

Python: Configure Tests flips that setting for you. After that, one configuration handles discovery, single-test runs, coverage and breakpoints across the whole workspace.

What do you need before running pytest in VSCode?

The Testing view stays empty, or throws an import error on the first run, when any one piece is missing. That means the interpreter, the Python extension, pytest in the same environment, or that environment being selected in the editor.

Install Python and the Python extension

The extension doesn’t bundle Python, so the interpreter has to be there first. Windows users grab a release from python.org. On macOS, a package manager such as Homebrew beats the system install.

The extension is published as ms-python.python on the Visual Studio Marketplace, and the Python Debugger installs automatically alongside it. You won’t think about the debugger until a test needs a breakpoint.

One small annoyance. A terminal that was already open before Python got installed may not see it, so close the terminal or restart VSCode.

Install pytest in the right environment

The latest release as of November 2026 is pytest 9.2.0 (PyPI, October 27, 2026), and it needs Python 3.10 or later.

The extension sets its own floor, with 7.0.0 as the minimum supported pytest version. If pytest is missing from the active environment, it tries to install it in the background. I wouldn’t count on that.

Activate the project’s virtual environment first, then run python -m pip install pytest in that same terminal so the package ends up where the editor looks.

Select the interpreter

The Python: Select Interpreter command in the Command Palette picks the environment VSCode uses.

When pytest sits in one environment and the editor points at another, discovery fails with import errors or an empty Testing view. Learning to change the Python interpreter takes about two minutes and clears up most of those cases.

To confirm the setup, run python -m pytest --version in the integrated terminal. If a version number comes back, the environment is ready.

How to turn on pytest and configure it in VSCode

Setting python.testing.pytestEnabled (default false) to true is all that “turning on pytest” really means. Python: Configure Tests from the Command Palette just writes it for you.

Turn on pytest with Configure Tests

  1. Open the Command Palette.
  2. Run Python: Configure Tests.
  3. Choose pytest as the framework.
  4. Pick the folder that holds the tests, or the root directory (.) for the whole project.
  5. Click the beaker icon to open the Testing view and wait for the test tree to fill.

The command writes to the workspace settings.json file, so that’s where to check its work. A working setup there has the pytestEnabled and unittestEnabled flags plus a pytestArgs entry.

{
"python.testing.pytestEnabled": true,
"python.testing.unittestEnabled": false,
"python.testing.pytestArgs": ["tests"]
}

Where each option belongs

settings.json is the place for anything that only matters to the editor. The two enabled flags and autoTestDiscoverOnSaveEnabled live there, and so does cwd when the tests folder is not the workspace root.

pytest.ini or pyproject.toml hold the options that change how pytest itself behaves. testpaths goes there, so a bare pytest call starts collecting from the same folder everywhere. addopts is the spot for something like the import mode flag. Projects with a src layout also set pythonpath in that file.

Anything in a pytest config file applies wherever pytest runs, CI and VSCode included. Options in pytestArgs only reach the editor, which is exactly how a test passes in the terminal and fails in the Testing view.

What happens when pytest and unittest are both turned on

pytest takes priority. With both frameworks enabled, only pytest runs.

That costs very little, since pytest also discovers unittest.TestCase subclasses. The Python Developers Survey 2024 (PSF and JetBrains) shows how lopsided the choice is: 53% of respondents named pytest as a unit-testing framework they use, against 23% for unittest.

Turn unittest on only if the project depends on its runner. Django is the documented case.

Documented defaults

The VS Code Python testing documentation (2026 revision) lists the starting values. python.testing.pytestEnabled is false and python.testing.pytestArgs is an empty list. python.testing.cwd is null. Save-triggered discovery is on, since python.testing.autoTestDiscoverOnSaveEnabled is true, and python.testing.autoTestDiscoverOnSavePattern is **/*.py.

Which test files and functions does pytest discover?

Files matching test_*.py or *_test.py get collected, and inside them pytest picks up functions and methods whose names start with test. A file or function that doesn’t fit those patterns won’t show up in the Testing view at all.

File and function naming rules

Functions that sit outside a class need the test prefix. Classes take a Test prefix and can’t have an __init__ method, and TestCase subclasses from unittest are picked up too.

With no arguments, collection starts at testpaths if it is set, and at the current directory otherwise.

Rootdir, cwd and conftest.py

The python.testing.cwd setting adjusts pytest’s –rootdir. Set it when the tests folder sits outside the workspace root, for example in a monorepo subfolder.

A conftest.py file in a test directory shares its fixtures with every test at that level and below. With the Pylance language server installed, python.analysis.inlayHints.pytestParameters (default false) turns on type hints for fixture arguments once you set it to true.

The __init__.py advice: two sources disagree

VS Code’s documentation offers a quick fix when tests in a subfolder go missing: add an empty __init__.py so the tests become importable. Plenty of tutorials repeat it, and a few go further and call the file a requirement for auto-discovery.

pytest’s own documentation sees a cost. In the default prepend import mode, the __init__.py workaround puts the repository root on sys.path, which can make an uninstalled source package importable. That is a documented problem with tox.

For new projects the pytest docs recommend importlib mode, set with addopts = ["--import-mode=importlib"]. That mode leaves sys.path alone.

For a new project I’d go with importlib mode and skip the __init__.py files entirely. Older projects that already have them can keep them.

Refreshing discovery

Discovery reruns on save by default. If the tree looks stale, the Test: Refresh Tests command forces a rescan, and the Python output panel is where discovery errors show up.

How to run pytest tests in VSCode

YouTube player

The Testing view handles anything from a single test to the full suite. The gutter runs whichever test sits beside the cursor, and the integrated terminal accepts every pytest argument there is.

MethodScopeResults appear inLimitation
Testing viewAll tests, current file, test at cursor, failed testsTest Results panel and the test treeFiles must be saved first
Gutter iconOne test or class beside the iconGutter decorations and Peek ViewClick action is run unless changed
TerminalDirectories, files, node IDsTerminal outputNo Testing view status updates

Run from the Testing view

Test: Run All Tests, Test: Run Tests in Current File and Test: Run Test at Cursor are all in the Command Palette, along with Test: Rerun Failed Tests and Test: Rerun Last Run. The play buttons in the Testing sidebar trigger the same actions.

Save before running, because VSCode doesn’t save test files automatically.

Results appear as gutter decorations, in Peek View for failures, in the test tree and in the Test Results panel.

Run from the editor gutter

A green play icon sits beside every discovered test, and clicking it runs that test alone. Right-clicking the gutter opens the debug option. Setting testing.defaultGutterClickAction to debug makes a plain click debug instead of run.

It’s fast for one test, but you see nothing of the wider suite.

Run pytest in the integrated terminal

The terminal is where to go for flags the Testing view doesn’t expose. Once you open the integrated terminal in the project folder, the venv should already be active.

pytest
pytest tests/test_math.py
pytest tests/test_math.py::test_add

Command-line arguments can name directories, files, or node IDs, which is what the :: syntax above does.

Terminal runs don’t update the Testing view, and the output stays in the terminal instead of the Test Results panel.

How to debug a pytest test in VSCode

YouTube player

With a breakpoint set, the Debug Test icon in the Testing view starts the run, and so does Test: Debug Test at Cursor from the Command Palette. Execution stops at the breakpoint with the debugger attached.

Debug commands by scope

Test: Debug All Tests covers everything, and Test: Debug Tests in Current File narrows it to one file. A single test gets Test: Debug Test at Cursor. After a red run there’s Test: Debug Failed Tests, and Test: Debug Last Run repeats whatever ran most recently.

Debug Failed Tests is the one I’d reach for most, since only the red tests rerun under the debugger.

Stepping, the call stack and watch expressions work as in any Python debugging session in VSCode. Nothing about them changes for tests.

Customize the debug run with launch.json

A configuration marked with "purpose": ["debug-test"] in launch.json or settings.json controls how test debug runs start.

{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Tests",
"type": "debugpy",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"purpose": ["debug-test"],
"env": { "PYTEST_ADDOPTS": "--no-cov" }
}
]
}

Only the first matching entry gets used, which is why a workspace should hold just one test configuration. The env line is explained in the next part.

Why breakpoints get skipped when pytest-cov is installed

When a debug run never pauses at a breakpoint, pytest-cov is the likely cause.

The VS Code documentation says breakpoints may not stop when pytest-cov is installed, and it gives two fixes. One is –no-cov in pytestArgs. The other is setting PYTEST_ADDOPTS to –no-cov in the debug configuration’s env.

The cause is in the pytest-cov 7.1.0 documentation. Debuggers rely on sys.settrace, coverage uses the same mechanism, and coverage doesn’t play well when another tracer is running at the same time.

The same docs cover why a flag is needed at all. Coverage options often live in pytest.ini and pytest has no option to strip them out, so –no-cov turns coverage off entirely.

I’d put –no-cov in the debug configuration’s env and leave pytestArgs alone. A flag in pytestArgs also lands on every normal run, and Run with Coverage would stop reporting anything.

How do you read test results and run pytest with coverage?

Run with Coverage in the Testing view needs pytest-cov installed first. The extension adds --cov=. unless --cov already sits in pytestArgs, and the results land in the Test Coverage tab.

Run with coverage

  1. Install pytest-cov into the selected environment.
  2. Click the coverage run icon in the Testing view, or pick Run with coverage from any run menu.
  3. Open the Test Coverage tab and check the highlighted lines in the editor.

The Python extension’s October 2024 release added coverage runs, using pytest-cov for pytest and coverage.py for unittest. The coverage package has to be installed first.

Line-level code coverage shows which lines the suite never touched. The current pytest-cov release is 7.1.0 (PyPI, March 21, 2026), which requires Python 3.9 or later.

How the extension builds the coverage arguments

If –cov is already in pytestArgs, the extension leaves your arguments untouched. If it isn’t, --cov=. gets added, and that measures every file under the workspace, test files included.

Scope the run with something like --cov=src when the package lives in a src folder. Branch coverage needs coverage 7.7 or later (VS Code documentation, 2026 revision).

Read failures and rerun them

Test: Show Output and Test: Peek Output open the details of a failure. Test: Go to Next Test Failure and Test: Go to Previous Test Failure step between the red tests, and Test: Clear All Results empties the panel once you’re done.

A gray circle instead of a green tick or red cross means the run produced no result for that test. One reported case (GitHub issue #23948, August 2024) showed gray circles after setting python.testing.cwd to a src folder, while discovery itself worked.

Since the October 2025 release of the Python extension, the gutter menu has a Copy Test ID entry that copies the identifier in pytest format. Paste it after pytest in the integrated terminal to rerun that test with extra flags.

Why does VSCode not find or run pytest tests?

A missing pytest install, mismatched paths, import errors, a masked config file and coverage interfering with the debugger account for almost every failure. The table pairs each symptom with its documented cause.

SymptomDocumented causeFix
Empty Testing view, log says “No module named pytest”pytest is absent from the interpreter VSCode runsInstall pytest in that interpreter
Tests discovered, gray circles after a runcwd and the path arguments resolve to different foldersMake pytestArgs paths resolve from cwd, or drop cwd
ModuleNotFoundError during collectionrootdir does not change sys.path or import behaviorSet pythonpath, or install the package in editable mode
Options in pyproject.toml have no effectThe first matching config file wins and files are never mergedKeep all options in one file
Debug run never pausesCoverage and the debugger share sys.settraceAdd –no-cov to the debug env

Reproduce the command VSCode ran

Discovery is a plain pytest call. Logs posted to the vscode-python tracker in November 2025 show python -m pytest -p vscode_pytest --collect-only tests --rootdir=.

Copy that line from the Python log, drop the -p vscode_pytest part (it comes from the extension), and run it in the integrated terminal with the same interpreter. A failure there means the problem is pytest itself, and a pass points back at VSCode, specifically the interpreter, cwd or the arguments.

Adding -v to the args and setting the VSCode log level to trace makes the Python log list every discovered test.

The config file precedence trap

pytest checks its configuration files in a fixed order and stops at the first match, so the order below matters.

  1. pytest.toml or .pytest.toml (added in pytest 9.0), which matches even when empty
  2. pytest.ini or .pytest.ini, which also matches even when empty
  3. pyproject.toml, only if it holds a [tool.pytest] or [tool.pytest.ini_options] table
  4. tox.ini, only with a [pytest] section
  5. setup.cfg, only with a [tool:pytest] section

A leftover empty pytest.ini therefore hides every option in pyproject.toml. The tests still run, which is why nobody notices until a pythonpath or addopts line stops working.

When cwd and pytestArgs disagree

Setting python.testing.cwd to a subfolder fixes some import layouts and breaks others. In the reported case, the error read “file or directory not found” for a test path resolved from the new working folder.

A custom cwd changes where every relative path starts, so use absolute workspaceFolder paths in pytestArgs whenever cwd points somewhere else.

pytest in VSCode FAQ

Can pytest tests run in parallel from VSCode?

Yes, through the pytest-xdist package. If xdist is turned on and the arguments name no worker count, the extension picks the number of workers from how many tests are selected in the Testing view.

How do I load a .env file for my tests?

The extension loads a .env file from the project root by default. If the file sits elsewhere, or you use variable substitution, set python.envFile to a path such as ${workspaceFolder}/config/.env.

Does the Testing view work for Django projects?

Yes, through unittest, which is the route the VS Code documentation describes. Set python.testing.unittestEnabled to true, add MANAGE_PY_PATH to a root .env file, and keep only Django-compatible entries in unittestArgs.

Use an absolute path for MANAGE_PY_PATH if a relative one fails.

When should I change the pytestPath setting?

Rarely. The default is “pytest”, and the docs advise a full path only when pytest is installed outside the current environment.

In most projects, installing pytest into the selected interpreter removes the need for it.

What to Commit for pytest in VSCode on a Team

Everyone on the team gets the same pytest behavior in VSCode once the repo holds a pytest config file and .vscode/settings.json. A launch.json debug entry finishes the job.

Commit them in this order.

  1. pytest.ini or pyproject.toml, holding testpaths, addopts and pythonpath
  2. settings.json, with pytestEnabled and pytestArgs
  3. launch.json, with one debug-test entry that carries –no-cov

The config file goes first because its options reach the terminal and every other runner, while the two VSCode files only reach the editor.

A new project on pytest 9.0 or later can use pytest.toml, which takes precedence over every other config file (verified against pytest 9.2.0, November 2026).

The third file has a cost. Its debug entry turns coverage off for every debug run, for the whole team, though normal and coverage runs stay untouched.

The same config file then applies unchanged to test jobs in continuous integration.

Bogdan Sandu

Stay sharp. Ship better code.

Every week: one curated article, one tool worth knowing, one tip you can use tomorrow. No noise, no padding.