Teste de pytest de código VS / Python / depuração com o depurador

Aug 27 2020

Como posso fazer com que o VS Code me coloque no depurador no ponto de falha ao executar testes com o pytest?

O Pytest captura todos os erros e afirma, e o código do VS invoca o depurador apenas em erros não detectados (posso alterar isso para exceção levantada, mas ele para em tudo que foi levantado em uma tentativa).

Tentei definir --pdbcomo argumento pytest, mas isso levou a erros:

============================= test session starts =============================
platform win32 -- Python 3.8.1, pytest-5.3.2, py-1.8.1, pluggy-0.13.1
rootdir: c:\Projects\debugtest, inifile: pytest.ini
collected 1 item

test.py F
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> traceback >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Traceback (most recent call last):
  File "C:\Projects\debugtest\test.py", line 4, in test_with_assert
    assert 42==2.71828
AssertionError: assert 42 == 2.71828
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> entering PDB >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

>>>>>>>>>>>>>>>>>> PDB post_mortem (IO-capturing turned off) >>>>>>>>>>>>>>>>>>
> c:\projects\debugtest\test.py(4)test_with_assert()
-> assert 42==2.71828
(Pdb)

PYDEV DEBUGGER WARNING:
sys.settrace() should not be used when the debugger is being used.
This may cause the debugger to stop working correctly.
If this is needed, please check: 
http://pydev.blogspot.com/2007/06/why-cant-pydev-debugger-work-with.html
to see how to restore the debug tracing back correctly.
Call Location:
  File "C:\Program Files\Python38\lib\bdb.py", line 359, in set_quit
    sys.settrace(None)


- generated xml file: C:\Users\tzhgfma1\AppData\Local\Temp\tmp-24044mEWMyB1nPYAu.xml -
!!!!!!!!!!!!!!!!!! _pytest.outcomes.Exit: Quitting debugger !!!!!!!!!!!!!!!!!!!
============================== 1 failed in 0.43s ==============================

Tenho um projeto muito simples para testar isso:

.vscode \ settings.json

{
    "python.testing.pytestArgs": [
        "--pdb"
    ],
    "python.testing.unittestEnabled": false,
    "python.testing.nosetestsEnabled": false,
    "python.testing.pytestEnabled": true,
    "git.ignoreLimitWarning": false
}

.vscode \ launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        
        
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}", "console": "internalConsole", "justMyCode":false }, { "name": "Python: Attach using Process Id", "type": "python", "request": "attach", "processId": "${command:pickProcess}",
            "justMyCode": false
        },
        {
            "name": "Debug Tests",
            "type": "python",
            "request": "test",
            "console": "internalConsole",
            "justMyCode": false
        }
    ]
}

pytest.ini

[pytest]

python_files = test*.py
python_classes = Test
python_functions = test
addopts = --tb=native
console_output_style = classic
junit_duration_report = call
filterwarnings =
    ignore::RuntimeWarning

e test.py:

def test_with_assert():
    assert 42==2.71828

É --pdba maneira correta de fazer isso? Ou como entro no depurador após uma declaração ou erro?

Respostas

2 JillCheng Aug 31 2020 at 07:54

Se você deseja entrar na depuração ao executar pytest no VSCode e permanecer em uma linha de código, você pode clicar em ' Debug Test' na parte superior do método após selecionar o teste pytest, conforme mostrado na imagem:

Além disso, "python.testing.pytestArgs": [],em .vscode\settings.jsoné o caminho da pasta do arquivo testado, por exemplo, meu arquivo de teste está em Test_ccsob a apasta.

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

Se não é isso que você deseja, por favor me avise e descreva os detalhes de suas necessidades.

Referência: testes de depuração .

Atualizar:

Normalmente, quando depuramos o teste no VSCode, sem definir um ponto de interrupção para ele, ele apenas exibirá o resultado do teste. (sucesso ou fracasso). Ele só exibirá informações de teste relevantes no console OUTPUT.

Quando eu uso a extensão ' Python Test Explorer for Visual Studio code', ela exibe as informações do teste de depuração no console, alertando sobre o problema.

mgf Sep 05 2020 at 07:53

Esta resposta realmente resolve o problema. Eu gostaria que houvesse uma maneira mais direta, a partir do Visual Studio Code ou um raisesinalizador simples do pytest.