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
🌐
GitHub
github.com › microsoft › vscode-python-debugger › issues › 336
pytest xdist should run with -n0 in debug · Issue #336 · microsoft/vscode-python-debugger
May 6, 2024 - when debugging a (single) test with pytest, invocation of pytest should add -n 0 . This way multiple runners will not be used and start-up time is reduced.
Author   elad-eyal
🌐
Playwright
playwright.dev › locators
Locators | Playwright
Locators are the central piece of Playwright's auto-waiting and retry-ability. In a nutshell, locators represent a way to find element(s) on the page at any moment · These are the recommended built-in locators
Discussions

VS Code / Python / Debugging pytest Test with the Debugger - Stack Overflow
I guess this is a problem of pytest, which cannot be made to raise the error, so it remains uncaught, triggering the VSC debugger. 2020-08-31T11:51:09.77Z+00:00 ... @mgf Thank you for your feedback. At present, VSCode cannot automatically catch errors when debugging test scripts, unless we ... More on stackoverflow.com
🌐 stackoverflow.com
Debug of parametrized pytest fails to find test when using zsh shells
Environment data VS Code version: 1.42.1 Extension version (available under the Extensions sidebar): 2020.2.64379 OS and version: Darwin x64 19.3.0 Python version (& distribution if applicable, e.g. Anaconda): Python 3.6.8 Type of virtua... More on github.com
🌐 github.com
16
March 3, 2020
Debugging pytest fails
Environment data VS Code version: 1.20.1 Python Extension version: Latest (can't even find the version number from git hub or within vscode) Python Version: Python 3.6.4 :: Anaconda, Inc. OS an... More on github.com
🌐 github.com
3
February 27, 2018
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
🌐
Visual Studio Code
code.visualstudio.com › docs › python › testing
Python testing in Visual Studio Code
November 3, 2021 - For more information on test coverage, visit VS Code's Test Coverage documentation. To 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 ...
🌐
GitHub
gist.github.com › beaukinstler › 967a346940686daf52693d38b95d2162
vscode launch.json for python flask and pytest · GitHub
vscode launch.json for python flask and pytest. GitHub Gist: instantly share code, notes, and snippets.
🌐
GitHub
github.com › microsoft › vscode-python › issues › 10398
Debug of parametrized pytest fails to find test when using zsh shells · Issue #10398 · microsoft/vscode-python
March 3, 2020 - User belongs to experiment group 'ShowPlayIcon - start' User belongs to experiment group 'DebugAdapterFactory - experiment' User belongs to experiment group 'PtvsdWheels37 - experiment' User belongs to experiment group 'UseTerminalToGetActivatedEnvVars - control' User belongs to experiment group 'WebHostNotebook - control' ... Starting Jedi Python language engine. ... > ~/.virtualenvs/ssam/bin/python ~/.vscode/extensions/ms-python.python-2020.2.64397/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir ~/src/ssam -s --cache-clear -c ~/src/ssam/src/pytest.ini -vv cwd: ~/src/ssam > ~/.virtualenvs/ssam/bin/python -m pytest --rootdir ~/src/ssam --junitxml=/var/folders/ly/c_bdp3bd36x4y5lvckk_4hym0000gp/T/tmp-40404GqogbegWaYl.xml -c ~/src/ssam/src/pytest.ini -vv ./src/test_demo.py::test_parametrize_debug[a] ./src/test_demo.py::test_parametrize_debug[b] cwd: ~/src/ssam ·
Author   ashleybartlett
Find elsewhere
🌐
GitHub
github.com › microsoft › vscode-python › issues › 909
Debugging pytest fails · Issue #909 · microsoft/vscode-python
February 27, 2018 - First it fails: "Debug adapter process has terminated unexpectedly" Second time when I press in the bar and select the launcher again it outputs the following in the terminal: $ cd "C:\workspace\ver-virtual-vehicle" ; env "PYTHONIOENCODING=UTF-8" "PYTHONUNBUFFERED=1" python "C:\Users\A281180.vscode\extensions\ms-python.python-2018.1.0\pythonFiles\PythonTools\visualstudio_ py_launcher.py" "C:\workspace\ver-virtual-vehicle" 50990 34806ad9-833a-4524-8cd6-18ca4aa74f14 DUMMYVALUE "c:\workspace\ver-virtual-vehicle\test\test_fdx_decoder.py" Traceback (most recent call last): File "c:\workspace\ver-virtual-vehicle\test\test_fdx_decoder.py", line 7, in from vv.fdx import decoder ModuleNotFoundError: No module named 'vv'
Author   WindsOfHades
🌐
Visual Studio Code
code.visualstudio.com › docs › python › debugging
Python debugging in VS Code
November 3, 2021 - This article mainly addresses Python-specific debugging configurations, including the necessary steps for specific app types and remote debugging.
🌐
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",
          }
        }
🌐
GitHub
github.com › microsoft › vscode-docker › issues › 3946
Cannot debug pytest tests in docker · Issue #3946 · microsoft/vscode-docker
May 18, 2023 - Does this issue occur when all extensions are disabled?: Yes VS Code Version: 1.78.2 OS Version: Darwin x64 22.4.0 I'm trying to debug pytest tests inside Docker. I understand it's not supported by the Python VSCode extension yet, but I ...
Published   May 18, 2023
Author   ilaner
🌐
TMS Outsource
tms-outsource.com › home › how to run pytest in vscode for testing
How to Run Pytest in VSCode for Testing
January 7, 2025 - Debug pytest tests by setting breakpoints in your test code, then right-clicking the test and selecting “Debug Test”. VSCode launches the debugger, pauses at breakpoints, and provides access to the Debug Console for inspecting variables ...
🌐
GitHub
github.com › microsoft › vscode-python › issues › 21255
Add separate `python.testing.pytestArgs` settings for regular, debug and discovery runs · Issue #21255 · microsoft/vscode-python
May 16, 2023 - Separating the single setting into 3 (for regular runs, for debug runs and for discovery runs) would make configuring pytest much more flexible. ... "python.testing.pytestArgs": { "run": [], // equal to the current "python.testing.pytestArgs": [] "debug": [], "discovery": [] }
Published   May 16, 2023
Author   mpekurin
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!

🌐
PyPI
pypi.org › project › pytest-vscodedebug
pytest-vscodedebug · PyPI
December 4, 2020 - A pytest plugin to easily enable debugging tests within Visual Studio Code
      » pip install pytest-vscodedebug
    
Published   Dec 04, 2020
Version   0.1.0
🌐
GitHub
github.com › microsoft › debugpy › issues › 1347
When debugging a pytest unittest in VSCode, the python debugger detaches after ~60s, and I can't find an overriding timeout setting · Issue #1347 · microsoft/debugpy
August 7, 2023 - OUTPUT - Python 2023-08-07 11:59:40.858 [info] Running PYTEST execution for the following test ids: tests/operations/test_sequence_to_helm.py::test_set_breakpoint_and_watch_test_timeout 2023-08-07 11:59:40.858 [info] Server listening on port 37781 2023-08-07 11:59:40.858 [info] Running DEBUG pytest with arguments: --rootdir /home/hawk/projects/cdd_peptide_reg --capture no 2023-08-07 11:59:40.860 [info] Using launch configuration in launch.json file. 2023-08-07 11:59:41.352 [info] DAP Server launched with command: /home/hawk/projects/cdd_peptide_reg/conenv/bin/python /home/hawk/.vscode-server/extensions/ms-python.python-2023.14.0/pythonFiles/lib/python/debugpy/adapter 2023-08-07 12:00:44.798 [info] Test server connected to a client.
Author   haughki
🌐
GitHub
github.com › microsoft › debugpy › issues › 544
Can't debug my pytest unittests from VS Code · Issue #544 · microsoft/debugpy
February 12, 2021 - ============================= test session starts ============================= platform win32 -- Python 3.7.9, pytest-6.2.0, py-1.10.0, pluggy-0.13.1 rootdir: c:\dev\ingest_oba, configfile: obabr\pytest.ini plugins: hypothesis-6.0.3, forked-1.3.0, profiling-1.7.0, timeout-1.4.2, xdist-2.2.0 collected 1 item obabr\tests\download_test.py . [100%] - generated xml file: C:\Users\ppppp\AppData\Local\Temp\tmp-15396J3k1TtjEH4i3.xml - ============================== 1 passed in 0.13s ============================== And nothing happens. :-( If from my activated workspace in a _ bash shell_ I run the following command: python -m debugpy --wait-for-client --listen 0.0.0.0:5678 ../../Scripts/pytest.exe download_test.py
Author   pauloneves
🌐
GitHub
github.com › microsoft › vscode › issues › 242097
No output in Test Results panel debugging pytest from test explorer · Issue #242097 · microsoft/vscode
February 26, 2025 - Type: Bug Debugging a pytest from test explorer does not provide output to the test results panel, anything python related in the output panel, or terminal when breaking on 'assert True'. def test_print(): print("This is a print statemen...
Author   Steve2724214
🌐
GitHub
github.com › microsoft › vscode-python › issues › 13709
VSCode automatically catches errors when using pytest to debug python scripts. · Issue #13709 · microsoft/vscode-python
September 1, 2020 - Because in VSCode, pytest test only gives test results. (Success or failure). Is it possible to let VSCode automatically catch errors when using pytest to debug python scripts, just like regular debugging python scripts, automatically ju...
Author   Jill-Cheng
🌐
ComfyUI
mslinn.com › blog › 2023 › 08 › 20 › pytest-intro.html
Pytest and Visual Studio Code
August 20, 2023 - To avoid loading of plugins, use the `no:` prefix, e.g. `no:doctest`. --trace-config Trace considerations of conftest.py files --debug=[DEBUG_FILE_NAME] Store internal tracing debug information in this log file. This file is opened with 'w' and truncated as a result, care advised. Default: pytestdebug.log.
🌐
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 ... 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 ...