[Fixed]-Can't debug Django unit tests within Visual Studio Code

6πŸ‘

βœ…

You need to load the django configuration previous to run any test, for that reason the code in __init__.py file.

If pytest is an option for you, you have to install pytest and pytest-django

pip install pytest pytest-django
  1. create a pytest configuration (ex: pytest.ini) at the same level of manage.py file with the following content.

    [pytest]
    DJANGO_SETTINGS_MODULE=mysite.settings
    python_files=test*.py
    

    The configuration DJANGO_SETTINGS_MODULE is the import needed for the project setting (settings.py file). By default, the file tests.py is created for every app when you use python manage.py startapp app_name, but this file doesn’t match with the default pytest file pattern, for that reason you have to add the python_files options if you want to use the default file name.

  2. Update the setting.json configuration file with:

    {
        "python.pythonPath": "venv/bin/python",
        "python.testing.pytestArgs": [
            "mysite",
            "-s",
            "-vv"
        ],
        "python.testing.pytestEnabled": true,
        "python.testing.nosetestsEnabled": false,
        "python.testing.unittestEnabled": false
    }
    

About the error unresolved import 'polls.models', you need to configure the Python extension on VSCode creating a .env file in the root of your project with PYTHONPATH=source_code_folder (for more information VS Code Python Environment):

PYTHONPATH=mysite/

Finally, your project structure should be

.  <-- vs code root
β”œβ”€β”€ .env  <-- file created with the PYTHONPATH entry
└── mysite
    β”œβ”€β”€ pytest.ini  <-- pytest configuration
    β”œβ”€β”€ db.sqlite3
    β”œβ”€β”€ manage.py
    β”œβ”€β”€ mysite
    β”‚   β”œβ”€β”€ __init__.py
    β”‚   β”œβ”€β”€ asgi.py
    β”‚   β”œβ”€β”€ settings.py
    β”‚   β”œβ”€β”€ urls.py
    β”‚   └── wsgi.py
    └── polls
        β”œβ”€β”€ __init__.py
        β”œβ”€β”€ admin.py
        β”œβ”€β”€ apps.py
        β”œβ”€β”€ migrations
        β”œβ”€β”€ models.py
        β”œβ”€β”€ mydate.py
        β”œβ”€β”€ tests.py
        β”œβ”€β”€ urls.py
        └── views.py
πŸ‘€Motakjuq

Leave a comment