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
-
create a
pytest
configuration (ex:pytest.ini
) at the same level ofmanage.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 filetests.py
is created for every app when you usepython manage.py startapp app_name
, but this file doesnβt match with the defaultpytest
file pattern, for that reason you have to add thepython_files
options if you want to use the default file name. -
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