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
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
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
Cant get python pytest debugging working
Take the test on the official document as an example, i add a breakpoint before self.assertEqual(inc_dec.decrement(3), 4) , no matter how many times i choose debug tests, it would still stop at the breakpoint. so can you post your code for me to try to reproduce your qeustion if it's convenient and not that privacy? More on reddit.com
🌐 r/vscode
7
5
February 2, 2021
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.
🌐
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
🌐
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.
🌐
Donjayamanne
donjayamanne.github.io › pythonVSCodeDocs › docs › unittests_pytest-framework
py.test | Python in Visual Studio Code
This section outlines the details necessary to get you up and started with using the pytest testing framework with Visual Studio Code.
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.
🌐
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.
🌐
YouTube
m.youtube.com › watch
Configuring VSCode to Debug PyTest
Share your videos with friends, family, and the world
Published   July 7, 2023
🌐
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.
🌐
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 (.) ...
🌐
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 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!

🌐
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).
🌐
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.
🌐
Medium
andypickup.com › developing-in-python-with-dev-containers-part-3-a-simple-guide-to-tdd-with-pytest-and-fastapi-6dd11fb1f1f4
Developing in Python with Dev Containers — Part 3: A Simple Guide to TDD with pytest and FastAPI | by Andy Pickup | Medium
June 11, 2024 - Right click the green arrow and select Debug Test: ... Here we can see that the Debugger being used is our new pytest config as we expected, we’re paused on line 12 and the value of exc is actually a TypeError and not a ValueError.
🌐
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
🌐
DEV Community
dev.to › yamakanto › how-i-set-up-vscode-for-python-tests-coverage-profiling-2jf4
How I set up VSCode for Python (tests, coverage, profiling) - DEV Community
January 7, 2021 - There's a solution to integrate coverage to VSCode while not breaking debugging of tests. A found it at github.com/microsoft/vscode-python... ... [tool:pytest] testpaths = src/ addopts = -n4 --cov=src --cov-report=term --cov-report=lcov:.coverage-dir/lcov.info --cov-report=html:.coverage-dir/html required_plugins = pytest-cov pytest-xdist [coverage:run] omit = **/*/tests/* branch = true data_file = .coverage [coverage:report] fail_under = 100