VS Code / Python / Debugging pytest Test con il debugger

Aug 27 2020

Come posso fare in modo che VS Code mi metta nel debugger al punto di errore durante l'esecuzione di test con pytest?

Pytest rileva tutti gli errori e le asserzioni e il codice VS invoca il debugger solo sugli errori non rilevati (posso cambiarlo in eccezione sollevata, ma poi si ferma su tutto ciò che viene sollevato durante un tentativo).

Ho provato a impostare --pdbcome argomento pytest, ma questo porta a errori:

============================= 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 ==============================

Ho un progetto molto semplice per testarlo:

.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

È --pdbil modo corretto per farlo? O come si entra nel debugger in caso di asserzione o errore?

Risposte

2 JillCheng Aug 31 2020 at 07:54

Se vuoi accedere al debug quando esegui pytest in VSCode e rimanere su una riga di codice, puoi fare clic su " Debug Test" nella parte superiore del metodo dopo aver selezionato il test pytest, come mostrato nello screenshot:

Inoltre, "python.testing.pytestArgs": [],nel .vscode\settings.jsonè il percorso della cartella del file di test, ad esempio, il mio file di prova è in Test_ccsotto la acartella.

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

Se questo non è ciò che desideri, fammi sapere e descrivi i dettagli delle tue esigenze.

Riferimento: test di debug .

Aggiornare:

Di solito, quando eseguiamo il debug del test in VSCode, senza impostare un punto di interruzione per esso, verrà visualizzato solo il risultato del test. (successo o fallimento). Visualizzerà solo le informazioni di test rilevanti nella console OUTPUT.

Quando uso l'estensione " Python Test Explorer for Visual Studio code", visualizzerà le informazioni sul test di debug sulla console, richiedendo il problema.

mgf Sep 05 2020 at 07:53

Questa risposta risolve effettivamente il problema. Vorrei che ci fosse un modo più diretto, da Visual Studio Code o da una semplice raisebandiera da pytest.