You click the green play icon next to a pytest test in VS Code, and nothing runs. Or worse, the test runner fails immediately because it cannot import your internal packages, while Pyright floods your Problems tab with false import errors.
Here is the traceback that shows up in the Python Test Log output channel:
text============================= test session starts =============================
collecting ...
tests/unit/test_auth.py:4: in <module>
from service.auth import TokenManager
E ModuleNotFoundError: No module named 'service'
=========================== no tests ran in 0.04s ============================
ERROR: exit code 2
At the same time, Pyright or Pylance paints the import line in red:
textCannot resolve import "service.auth" from source Pylance (reportMissingImports)
Running pytest directly in your terminal works fine because you activated your virtualenv or you ran pip install -e . months ago. The editor fails because VS Code executes test discovery, language server analysis, and interactive debugging in three isolated subprocess environments. Each one evaluates your directory root differently unless you explicitly align them.
The Directory Layout
Consider a standard src-layout or flat enterprise microservice:
textbackend/
βββ .venv/
βββ .vscode/
β βββ launch.json
β βββ settings.json
βββ pyproject.toml
βββ src/
β βββ service/
β βββ __init__.py
β βββ auth.py
βββ tests/
βββ __init__.py
βββ unit/
βββ test_auth.py
When you open the backend folder in VS Code, the workspace root is backend. If your code uses from service.auth import TokenManager, Python expects service to exist directly on sys.path. It does not. It sits inside src/.
Terminal sessions often hide this problem if you set PYTHONPATH=. or if an editable wheel is cached in your virtual environment site-packages. The VS Code test daemon and Pyright do not inherit random terminal shell exports. They need workspace-level directives.
Step 1: Align Settings for Discovery and Type Checking
You fix discovery and typing first by telling both Pyright and the pytest runner where the source root lives. Open .vscode/settings.json.
json{
"python.defaultInterpreterPath": "${workspaceFolder}/.venv/Scripts/python.exe",
"python.testing.pytestEnabled": true,
"python.testing.unittestEnabled": false,
"python.testing.autoTestDiscoverOnSaveEnabled": true,
"python.testing.pytestArgs": [
"tests",
"-v",
"-o",
"pythonpath=src"
],
"python.analysis.extraPaths": [
"${workspaceFolder}/src"
],
"python.analysis.typeCheckingMode": "standard"
}
If you are on Linux or macOS, change Scripts/python.exe to bin/python.
Notice the line -o pythonpath=src in python.testing.pytestArgs. This uses pytestβs built-in configuration override flag to inject src into sys.path during discovery and test execution. It removes the need for hacky sys.path.insert(0, ...) statements inside conftest.py.
The python.analysis.extraPaths entry does the same thing for Pylance and Pyright. Once added, Pyright traverses ${workspaceFolder}/src, resolves service.auth, and clears the reportMissingImports warning.
If your project uses pyproject.toml, you can move the pytest configuration there instead of polluting settings.json:
ini[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
addopts = "-ra -q"
If you define it in pyproject.toml, trim python.testing.pytestArgs in .vscode/settings.json down to just ["tests"]. Do not define conflicting paths in both places.
Step 2: Configure Debugging in launch.json
Clicking the debug icon on a test editor gutter uses the internal test runner configuration. But when you need to inspect a complex failure with manual arguments, attach to a running process, or step through a specific module CLI entry point, you need .vscode/launch.json.
Create .vscode/launch.json with two configurations: one for targeted test debugging and one for running your module code:
json{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Debug Current Test File",
"type": "debugpy",
"request": "launch",
"module": "pytest",
"args": [
"${file}",
"-v",
"-s",
"--no-cov"
],
"cwd": "${workspaceFolder}",
"env": {
"PYTHONPATH": "${workspaceFolder}/src",
"PYTHONDONTWRITEBYTECODE": "1"
},
"console": "integratedTerminal",
"justMyCode": true
},
{
"name": "Python: Run Service Module",
"type": "debugpy",
"request": "launch",
"module": "service.auth",
"cwd": "${workspaceFolder}",
"env": {
"PYTHONPATH": "${workspaceFolder}/src"
},
"console": "integratedTerminal",
"justMyCode": true
}
]
}
There are a few key fields here that prevent standard debugging issues:
"type": "debugpy" is mandatory for current versions of the VS Code Python extension. The older "type": "python" is deprecated and fails to bind breakpoints correctly in newer extension releases.
"-s" tells pytest not to capture standard output. Without this, your print statements and debug output will be swallowed by the test runner instead of appearing in the terminal.
"--no-cov" turns off coverage measurement if you have pytest-cov installed. Coverage tracing interferes with Python trace hooks, causing breakpoints to be skipped entirely or hit on the wrong lines.
"justMyCode": true keeps the debugger out of standard library modules and third-party wheels. If an exception raises inside urllib3, the debugger stops at your application code that made the request, rather than stranding you ten frames deep inside internal socket loops.
Step 3: Verify the Setup
To confirm discovery works:
- Press
Ctrl+Shift+P(orCmd+Shift+Pon macOS). - Type
Test: Refresh Testsand hit Enter. - Open the Testing view from the sidebar. Your tests should appear in an expandable tree rather than showing a red exclamation mark.
To confirm breakpoints work:
- Open
tests/unit/test_auth.py. - Place a breakpoint on an assertion line by clicking the margin next to the line number.
- Open the Run and Debug view (
Ctrl+Shift+D). - Select
Python: Debug Current Test Filefrom the dropdown and pressF5. - The terminal opens, pytest executes only that file, and the execution pauses cleanly at your breakpoint with full access to local variables in the left panel.
textpytest tests/unit/test_auth.py -v -s --no-cov
============================= test session starts =============================
collected 1 item
tests/unit/test_auth.py::test_token_generation
The execution stops, highlighting your line in yellow.
Gotcha 1: The Coverage Hook Stealing Breakpoints
This is the most common reason breakpoints fail to hit in an otherwise working setup. If your pyproject.toml or pytest.ini contains --cov, pytest instruments the code through sys.settrace.
text[tool.pytest.ini_options]
addopts = "--cov=src --cov-report=term-missing"
When you launch debugpy, it also instruments execution using sys.settrace. The two debug hooks collide. The test runs, passes, and completely ignores your breakpoint.
Do not remove --cov from your repository if continuous integration needs it. Instead, override it in your .vscode/launch.json arguments list by passing -o addopts="" or passing --no-cov.
json"args": [
"${file}",
"-o",
"addopts=",
"-s"
]
This clears the global options defined in pyproject.toml specifically for that interactive debug session without touching tracked files.
Gotcha 2: Windows Path Separators in Extra Paths
When developing on Windows, mixing path separators breaks Pyright indexers silently. Pyright does not crash; it just stops resolving modules.
Never write this in .vscode/settings.json:
json"python.analysis.extraPaths": [
"${workspaceFolder}\\src"
]
Always use forward slashes, even on Windows:
json"python.analysis.extraPaths": [
"${workspaceFolder}/src"
]
VS Code normalizes forward slashes across all supported operating systems. Pyright expects forward slashes in URI handling internally. Backslashes can lead to duplicate entries in its internal virtual path map, creating ghost import errors where the type checker sees the file on disk but flags it as unresolvable.
Gotcha 3: The Subprocess Test Discovery Hang
Sometimes pytest discovery spins forever. The spinner next to the test explorer icon keeps rotating, consuming a full CPU core.
This happens when test discovery executes application code that has side effects. If your tests/__init__.py or root conftest.py imports a module that starts a background thread, connects to an external database, or builds a network client at import time, the discovery worker blocks waiting for that network socket or thread to terminate.
Test discovery should only inspect ASTs and load test classes. It must not run application startup routines.
To locate the hanging file, open your terminal and run discovery manually with tracing:
bashpython -m pytest --collect-only -vv
The output will halt right after the file causing the block. For instance:
texttests/unit/test_auth.py::test_token_generation
tests/integration/test_database.py:
If it freezes immediately after printing test_database.py, look at the top-level module imports in that file. Move database connection logic or heavy client initializations inside pytest fixtures with explicit scopes instead of letting them run at module evaluation time.
python# Broken: runs during collection phase
db_connection = create_production_pool()
def test_query():
assert db_connection.ping()
# Fixed: runs only when test executes
import pytest
@pytest.fixture
def db_connection():
pool = create_production_pool()
yield pool
pool.close()
def test_query(db_connection):
assert db_connection.ping()
Once the top-level execution is removed, discovery finishes in milliseconds and test statuses populate immediately in the sidebar.


