pytest
and pytest-django
.Database Setup:
manage.py
file.migrate
to set up the database schema for testing.Table Creation:
Fixtures and Setup:
pytest
fixtures and manually create database tables within the tests have not been successful.pytest
fixtures to set up the initial database state.mixer
library to populate the database with test data.manage.py
commands.I am looking for guidance on how to approach this problem or best practices for testing Django models in a standalone package using pytest
and pytest-django
. Any advice or solutions would be greatly appreciated.
You don't need manage.py
to run migrate
. The same commands are available via the django-admin
command that Django installs, but you'll need to set the DJANGO_SETTINGS_MODULE
variable that manage.py
would ordinarily set.
IOW, if you'd generally run python manage.py
and your project settings are myproject.settings
, you can just as well run env DJANGO_SETTINGS_MODULE=myproject.settings django-admin migrate
.
That said, that's not your issue here – pytest-django will deal with setting up and tearing down a testing database for you. Generally, when developing a Django package, you'd have a testing project and app next to it to host the package for development use.
An example (of a standalone package, tested with GitHub Actions) is here (repository maintained by yours truly); lippukala
is the reusable package, and lippukala_test_app
is the package that hosts the settings for pytest-django
to use; there's a stanza
[tool.pytest.ini_options]
DJANGO_SETTINGS_MODULE = "lippukala_test_app.settings"
in the pyproject.toml file that makes that work.