[Fixed]-Run Django tests in the VSCode Test explorer?


Please consider the following checks:

  1. you should have __init__.py in your test directory

  2. in vscode on test configuration use pytest framework

  3. use: pip install pytest-django

  4. copy pytest.ini in the root with this content:

# -- FILE: pytest.ini (or tox.ini)
DJANGO_SETTINGS_MODULE = <your-web-project-name>.settings (like mysite.settings)
# -- recommended but optional:
python_files = tests.py test_*.py *_tests.py

Now it should work as you wish.
You can see this stackoverflow link


I’ve been looking into this as well. The thing is that python unittest pytest and nose are not alternative to Django tests, because they would not be able to load everything Django tests do.

Django Test Runner might work for you:

— I was having trouble with this still since my project root does not directly contain my app(s), but judging on your project structure may work for you.



Here is generic way to get Django tests to run with full vscode support

  1. Configure python tests
    1. Choose unittest
    2. Root Directory
    3. test*.py
  2. Then each test case will need to look like the following:
from django.test import TestCase

class views(TestCase):

    def setUpClass(cls):
        import django

    def test_something(self,):
        from user.model import something

Any functions you want to import have to be imported inside the test case (like shown). The setUpClass runs before the test class is setup and will setup your django project. Once it’s setup you can import functions inside the test methods. If you try to import models/views at the top of your script, it will raise an exception since django isn’t setup. If you have any other preinitialization that needs to run for your django project to work, run it inside setUpClass

Leave a comment