If you want to enter debugging when running pytest in VSCode and stay at a line of code, you could click 'Debug Test' at the top of the method after selecting the pytest test, as shown in the screenshot:

In addition, "python.testing.pytestArgs": [], in .vscode\settings.json is the folder path of the tested file, for example, my test file is in Test_cc under the a folder.

>      "python.testing.pytestArgs": [
>             "a/Test_cc"
>         ],

If this is not what you want, please let me know and describe the details of your needs.

Reference: Debug tests.

Update:

Usually, when we debug the test in VSCode, without setting a breakpoint for it, it will only display the test result. (success or failure). It will only display relevant test information in the console OUTPUT.

When I use the extension 'Python Test Explorer for Visual Studio code', it will display the debugging test information on the console, prompting the issue.

Answer from Jill Cheng on Stack Overflow
🌐
Visual Studio Code
code.visualstudio.com › docs › python › testing
Python testing in Visual Studio Code
November 3, 2021 - For more information on test coverage, ... debug tests, right-click on the gutter decoration next to the function definition and select Debug Test, or select the Debug Test icon next to that test in the Test Explorer....
Discussions

How to setup VScode to debug Django app tests (pytest)?
I just use the built-in breakpoint() (since python 3.7) on anything. Doesn't matter if it's django or otherwise. Docs: https://docs.python.org/3/library/functions.html#breakpoint More on reddit.com
🌐 r/djangolearning
4
7
March 28, 2023
Debug Pytest in docker container using VS Code - Stack Overflow
Now open the file you want to test, ... in the debug configuration with the name "Python: Pytest", which is the config you just added. If instead of running a unique file you want to run all tests or run a single test, in the previous config file put "your pytest arguments" instead of "$file" inside "args" option. ... Alternatively to step 5. and 6., you can open the folder .vscode (which will ... More on stackoverflow.com
🌐 stackoverflow.com
Python separate pytest config for running tests vs debugging
Unfortunately, as of now, there's no built-in way in VS Code to specify a different pytest configuration when debugging a single test. More on reddit.com
🌐 r/vscode
3
2
February 15, 2024
vscode debugger - How to configure VS code for pytest with environment variable - Stack Overflow
I am trying to debug pytest. I would like to inject an environment variable. More on stackoverflow.com
🌐 stackoverflow.com
People also ask

How do I configure pytest.ini for VSCode?
Create a pytest.ini file in the project root and define options such as test paths, markers, or default arguments. VS Code reads this configuration automatically during test discovery.
🌐
tms-outsource.com
tms-outsource.com › home › how to run pytest in vscode for testing
How to Run Pytest in VSCode for Testing - TMS Outsource
Why is pytest not showing in VSCode?
Pytest may not appear if it is not installed in the currently selected Python interpreter or if testing is disabled. Verify installation using pip show pytest in the terminal, then enable pytest in VS Code testing settings.
🌐
tms-outsource.com
tms-outsource.com › home › how to run pytest in vscode for testing
How to Run Pytest in VSCode for Testing - TMS Outsource
Can I use pytest fixtures in VSCode?
Yes. Define fixtures in a conftest.py file or directly in your test files. VS Code test discovery detects fixtures automatically and they work the same as when running pytest from the terminal.
🌐
tms-outsource.com
tms-outsource.com › home › how to run pytest in vscode for testing
How to Run Pytest in VSCode for Testing - TMS Outsource
🌐
Pytest with Eric
pytest-with-eric.com › introduction › how-to-run-pytest-in-vscode
How To Run Pytest In VS Code (Easy To Follow Step-By-Step Tutorial) | Pytest with Eric
August 13, 2023 - After configuring Pytest, VS Code will automatically discover your Unit Tests. You can customise which folder to look for tests in the settings under "python.testing.cwd" parameter in the .vscode/settings.json file.
🌐
TMS Outsource
tms-outsource.com › home › how to run pytest in vscode for testing
How to Run Pytest in VSCode for Testing - TMS Outsource
January 7, 2025 - You get instant feedback on test results, easy navigation to failing code, and breakpoint debugging without leaving your editor. This guide walks through complete pytest configuration in VSCode: installing the Python extension, setting up your test environment, running tests from both the GUI and terminal, and debugging failures.
🌐
PyPI
pypi.org › project › pytest-vscodedebug
pytest-vscodedebug · PyPI
December 4, 2020 - Distributed under the terms of the MIT license, “pytest-vscodedebug” is free and open source software. This code is largely based on adriencaccia’s tutorial “Flask Debugging in VS Code with Hot-Reload 🔥”.
      » pip install pytest-vscodedebug
    
Published   Dec 04, 2020
Version   0.1.0
🌐
Donjayamanne
donjayamanne.github.io › pythonVSCodeDocs › docs › debugging_debugging-pytest
py.test | Python in Visual Studio Code
-> Debugger · -> Virtual Env · -> Linting · -> Formatting · -> Autocomplete · -> Jupyter · Roadmap · Create a file named xyz.py in the root directory · Add the following code · import pytest pytest.main() Add a break point in you test method (the test method you wish to debug) Start debugging
Find elsewhere
🌐
Reddit
reddit.com › r/djangolearning › how to setup vscode to debug django app tests (pytest)?
r/djangolearning on Reddit: How to setup VScode to debug Django app tests (pytest)?
March 28, 2023 -

I need to stop debugger on one breakpoint in tests but i don't know how to do it.

How "configurations" in launch.json file should looks like? I trying with something like that but its doesnt work:

```

"version": "0.2.0",

"configurations": [

{

"name": "Python: Django:web_cloud tests",

"python": "/home/szymon/app_project/venv/web_cloud/bin/python3",

"type": "python",

"request": "launch",

"program": "/home/szymon/app_project/app/web_cloud/manage.py",

"args": [

"pytest"

],

"console": "internalConsole",

"django": true,

"justMyCode": true

}

]

```

🌐
ComfyUI
mslinn.com › blog › 2023 › 08 › 20 › pytest-intro.html
Pytest and Visual Studio Code
August 20, 2023 - --doctest-modules Run doctests in all .py modules --doctest-report={none,cdiff,ndiff,udiff,only_first_failure} Choose another output format for diffs on doctest failure --doctest-glob=pat Doctests file matching pattern, default: test*.txt --doctest-ignore-import-errors Ignore doctest ImportErrors --doctest-continue-on-failure For a given doctest, continue to run after the first failure test session debugging and configuration: --basetemp=dir Base temporary directory for this test run. (Warning: this directory is removed if it exists.) -V, --version Display pytest version and information about plugins.
🌐
YouTube
m.youtube.com › watch
Configuring VSCode to Debug PyTest
Share your videos with friends, family, and the world
Published   July 7, 2023
🌐
Vercel
website-nine-gules.vercel.app › blog › vscode-pytest-debug-3rd-party-library
Effortless VSCode Setup: Debug 3rd Party Libraries with Pytest in Minutes! | Random Digressions
April 8, 2023 - Every time I work on a Python project, I find myself having to look up the VS Code launch configuration to enable Pytest to step into 3rd party libraries when using the interactive debugger. It became quite frustrating, and I knew I couldn't be the only one facing this issue. So, I decided to create a video tutorial to share my knowledge and help fellow developers set up their projects more efficiently.
🌐
DZone
dzone.com › coding › languages › how to set up visual studio code for python testing and development
How to Set Up Visual Studio Code for Python Testing and Development
August 30, 2019 - From the settings, you can configure the debugger, selecting default debugger here. Open Command Palette (ctrl +shift +P) and start typing ‘python: select linter.’ It will display a list of available Python linters. You can add any of the settings to your user settings.json file (opened with the File > Preferences > Settings: The VS Code Python extension supports unit tests as well as pytest.
🌐
Medium
therightstuff.medium.com › configuring-vscode-to-run-python-tests-with-both-code-coverage-and-debugging-enabled-dff91db808ef
Configuring VSCode To Run Python Tests With Both Code Coverage And Debugging Enabled | by Adam Fisher / fisher king (@therightstuff) | Medium
October 6, 2022 - Over the course of the past few months I’ve dabbled in setting up VSCode to produce code coverage reports, and while I haven’t quite got coverage gutters working (apparently all of those extensions require lcov reports, and apparently that’s not a trivial thing for pytest to produce) I have finally got code coverage reports and debugging working without having to rewrite my configuration files every time, so I thought I’d share my learnings with the rest of the class.
🌐
Databricks Documentation
docs.databricks.com › local development tools › databricks extension for visual studio code and cursor › run tests
Run Python tests using the Databricks extension for Visual Studio Code | Databricks on AWS
September 5, 2024 - Click the green arrow (Start Debugging) icon. The pytest results display in the Debug Console (View > Debug Console on the main menu). For example, these results show that at least one test was found in the spark_test.py file, and a dot (.) ...
Top answer
1 of 3
6

I encountered the same issue and your post almost solves the problem. When I tried implementing your solution I encountered the following issue:

ImportError while loading conftest '/app/tests/conftest.py'.
     tests/conftest.py:36: in <module>
ptvsd.enable_attach("secret_text", address=("0.0.0.0", 5678))
E   TypeError: enable_attach() got multiple values for argument 'address'

Removing the "secret_text" value allowed me to hit the wait_for_attach() point and successfully attach the debugger to the code. I was able to hit breakpoints in my tests. Thank you!

.vscode/launch.json

{
  "name": "Python: Attach",
  "type": "python",
  "request": "attach",
  "localRoot": "${workspaceFolder}/path/to/code",
  "remoteRoot": "/app",
  "port": 5678,
  "host": "localhost"
}

docker-compose.yml

ports:
 - "5678:5678"

conftest.py

import ptvsd
ptvsd.enable_attach(address=("0.0.0.0", 5678))
ptvsd.wait_for_attach()

Note: The ptvsd lines are placed after all the imports.

CLI command to execute tests:

import subprocess
import click

@click.command()
def cli():
    return subprocess.call("pytest test", shell=True)

Sequence to debug tests:

  1. docker-compose up (get container running)
  2. docker-compose exec MODULE CONTAINER_NAME FUNCTION_THAT_EXECUTES_TEST
  3. Attach debugger in VSCode

Tests will execute and hit whatever breakpoint you have setup.

2 of 3
3

I couldn't connect neither, even following https://github.com/microsoft/vscode-docker/issues/3946. What worked for me was after following @therightstuff answer, which I think it needs better explanation.

Steps to reproduce:

  1. Go to VS code extensions and install Dev Containers from Microsoft.

  2. In your VS code window, in the left-bottom corner there's the button >< in blue. Click it! (or green if you are connected to a remote host) (in this image the is purple).

  3. This will open a contextual menu on top of VS Code. After installing the previous extension now you can click "Attach to Running Container". Click there.

  4. VS Code will open a new window that is running within your docker. Now in this window you must install Python extension from Microsoft to enable debugging.

  5. Go to debug panel in this window and add a new configuration for Python. Add the following:

     {
      "configurations": [
       {
       "name": "Python: Pytest",
       "type": "python",
       "request": "launch",
       "module": "pytest",
       "args": [
         "$file"
       ],
       },
     ]
    }
    
  6. Now open the file you want to test, and click on the green triangle in the debug configuration with the name "Python: Pytest", which is the config you just added. If instead of running a unique file you want to run all tests or run a single test, in the previous config file put "your pytest arguments" instead of "$file" inside "args" option.

EDIT

Alternatively to step 5. and 6., you can open the folder .vscode (which will be added automatically, or if not create it) and create a new file called settings.json with the following code:

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

app/tests is where I have my tests, and for the rest of options, enable the kind of framework you use for testing (in my case that was only for pytest). Then go to menu View->Command Palette and type: Python: Configure Tests and click the option from the menu you'll see.

After this, vs code will detect all tests in that path, and you'll see a little green triangle next to every test definition so by clicking over you can run it. If instead of left click you press right click, there's an option for "debug test", which allows you to debug that test. Remember that, at least in the case of pytest all tests definitions must start by "test_". Otherwise vs code won't detect it!

🌐
Reddit
reddit.com › r/vscode › python separate pytest config for running tests vs debugging
r/vscode on Reddit: Python separate pytest config for running tests vs debugging
February 15, 2024 -

Hello, I am hoping someone here has an idea on how to do this.

I have a pytest.ini that looks like this
[pytest]
addopts = -n auto --dist worksteal --cov-report xml:coverage.xml

This works great when running the tests so they run quickly and I get test coverage. However, when I try to debug a single by right clicking on the green arrow for the test and selecting debug it won't hit any breakpoints in the test. If I remove the pytest.ini config then it will hit the breakpoints.

Does anyone know of a way to have a separate config when running a single test.

Thanks

UPDATE: I figured out a way to make this work. It turns out using type debugpy will not work and doesn't even read the environment variable. However, if I set the type to python it works just fine. It looks like this is a feature that debugpy needs to support.

{
            "name": "Python: Debug Tests",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "purpose": ["debug-test"],
            "console": "integratedTerminal",
            "justMyCode": false,
            "env": {
                "PYTEST_ADDOPTS": "-c pytest_alt.ini",
          }
        }
Top answer
1 of 4
22

pytest-env

Install

Per https://stackoverflow.com/a/39162893/13697228:

conda install -c conda-forge pytest-env

Or:

pip install pytest-env

pytest.ini

Create pytest.ini file in project directory:

[pytest]
env = 
    ENV_VAR=RandomStuff

Python

In your code, load environment variables as you normally would:

import os
env_var = os.environ["ENV_VAR"]

pytest / VS Code

Either run:

pytest

(Notice how it says configfile: pytest.ini)

C:\Users\sterg\Documents\GitHub\sparks-baird\mp-time-split> pytest
==================================== test session starts ===================================== platform win32 -- Python 3.9.12, pytest-7.1.1, pluggy-1.0.0 rootdir:
C:\Users\sterg\Documents\GitHub\sparks-baird\mp-time-split,
configfile: pytest.ini plugins: anyio-3.6.1, cov-3.0.0, env-0.6.2
collecting ...

Or:

This only seems to work with breakpoints that have manually been set, I'm guessing some other change is needed to pause on errors.

Python for VS Code Extension

Apparently the Python for VS Code extension recognizes a .env file automatically. E.g. .env file:

ENV_VAR=RandomStuff

Haven't verified, but I'd assume this has the same behavior as using pytest-env with a pytest.ini file.

When all else fails

When I don't feel like dealing with the strange hackery necessary to get VS Code, Anaconda environments, and pytest playing nicely together (and/or forget how I fixed it before), I call my tests manually and run it like a normal script (see below). This may not work with more advanced pytest trickery using fixtures for example. At the end of your Python script, you can add something like:

if __name__ == "__main__":
    my_first_test()
    my_second_test()

and run it in debug mode (F5) as normal.

2 of 4
9

Could not really figure out how to fix "unit" test debugging with Vscode. But with Pytest one can call tests like python -m pytest <test file>(https://docs.pytest.org/en/stable/usage.html#cmdline) That means Vscode can be configured like a module

"configurations": [
        {
            "name": "Python: Module",
            "type": "python",
            "request": "launch",
            "module": "pytest",
            "args": ["--headful","--capture=no", "--html=report.html"],
        }

This is good enough to do debugging of python tests. Also you can then insert environment variables

   "env": {
        "ENV_VAR":"RandomStuff"
    }
🌐
Graycode
graycode.ie › home › how to set up testing explorer with python pytest in vscode
How to set up Testing Explorer with Python Pytest in VSCode - Graycode
October 5, 2023 - If your tests are failing, you can run them with debug by pressing the play button with the little bug icon on is as show above, this will display the output of the test in the Debug Console for you to investigate more (shown below).
🌐
Visual Studio Marketplace
marketplace.visualstudio.com › items
Python Test Explorer for Visual Studio Code - Visual Studio Marketplace
February 3, 2024 - Extension for Visual Studio Code - Run your Python tests in the Sidebar of Visual Studio Code
🌐
Ubc-library-rc
ubc-library-rc.github.io › intro-development-environment › content › 02-3.Run,Debug,Test.html
Run, Debug, and Test | Setting up a Development Environment
Visual Studio Code provides a set of toolkits and a strong interface for running, debugging, and testing your codes. In this section, we will learn the basics of running a Python code with VS Code and using frameworks and extensions to debug and test the code.