Run Django tests in VS Code Test Explorer
2 min read
|
Apr 22 2024
The problem
Running tests in Django tipically involves runnig a command in the terminal, something like:
python manage.py test your_app_name.test.test_some_functionality
However, when you have multiple tests on multiple files (or apps) It can be hard to track and find the tests that are failing or passing. What if there was a more intuitive way of handeling tests?
VS Code has a python Test Explorer, that apparently fixes this problem: It allows you to visualize your test results, run a specific test and debug them individually. If your testing a non-Django python package, it works straight away with unittest or pytest. However, when using Django, it requires some more configuration.
The solution
The solution is simple:
-
Install pytest and pytest-django - this will make it possible to use pytest to run Django tests.
-
Create (or edit) a
pytest.init
file with the Django configurations. If your using tox, you should edit thetox.ini
file:# pytest.ini (or tox.ini) [pytest] DJANGO_SETTINGS_MODULE = your_project.settings # ⬅️ change ´your_project´ to your real project name # optional, but recommended to detect multiple test files: python_files = tests.py test_*.py *_tests.py
-
Ensure that each test directory should have a
__init__.py
file. -
Click on the test beaker icon on the VS Code Activity bar, click “Configure Python Tests”, choose pytest and select “Root directory” as the target, your tests should be visible in the side bar:
- Alternatively, you can also configure VS Code
settings.json
directly (either globaly for VS Code or locally in your project, under.vscode/settings.json
) :
// .vscode/settings.json
{
"python.testing.pytestArgs": [
"."
],
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true,
}
This will do exactly the same as the manual process detailed in the previous step (4.).
This solution was mostly inspired by this stackoverflow answer. Thank you for reading. Feel free to contact me if you have any questions!