How to integrate VSCode with pytest ('test discovery fails')?
Answer a question
I'm unable to integrate my project's unit tests into VSCode. Test discovery fails because source files are not recognized by pytest.
(Just for clarification, this is a question about VSCode, not about pytest. I'm here because VSCode links its question section to SOF. Tests work fine if I run them manually.)
Tooling: pyenv
, pipenv
, pytest
.
Project layout:
/src -> source code
/tests/unit -> test code
.vscode/settings.json:
{
"python.envFile": "${workspaceFolder}/.env",
"python.testing.pytestEnabled": true,
"python.testing.pytestArgs": [
"tests"
],
"python.testing.unittestEnabled": false,
"python.testing.nosetestsEnabled": false
[...]
}
.env:
PYTHONPATH=./src
(Note: I don't think .env matters here, as per this comment, under Use of the PYTHONPATH variable)
Test discovery fails with:
tests/unit/test_revoke_default_sg.py:7: in <module>
from revokedefaultsg.app import RevokeDefaultSg, UnknownEventException
E ModuleNotFoundError: No module named 'revokedefaultsg'
=========================== short test summary info ============================
ERROR tests/unit/test_revoke_default_sg.py
!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
=============================== 1 error in 0.08s ===============================
This is caused by ./src
not being part of the python path, so tests cannot import source code.
I can fix this on CLI/makefile level by adding to PYTHONPATH:
PYTHONPATH=./src pytest
This works as expected.
What's the correct setup for VSCode?
Am I supposed to create a launch configuration for testing? I've started to look into this, but couldn't get it to work nicely with pipenv.
Answers
(OP here)
I think the key to integrate into VSCode creating a specific launch configuration for pytest (before, I only had the default launch configuration that's been created with the Python extension).
I now have two configurations (.vscode/launch.json
):
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Run Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"env": {
"PYTHONPATH": "./src"
}
},
{
"name": "Python: pytest",
"type": "python",
"request": "launch",
"module": "pytest",
"cwd": "${workspaceRoot}",
"env": {
"PYTHONPATH": "./src"
},
"envFile": "${workspaceRoot}/.env",
"console": "integratedTerminal",
}
]
}
(project on GitHub)
Running this configuration after launching VSCode discovers tests correctly, without raising errors. However, I have not tried it out in different projects yet.
Also, maybe I didn't find the right section of the VSCode documentation, but this feels heavily under-documented. I ended up searching GitHub for gists with launch configs and copied together whatever seemed vaguely helpful...
更多推荐
所有评论(0)