pythondjangounit-testingpytestpytest-django

How to test Django models against a DB without manage.py in a standalone package using pytest and GitHub Actions?


Context:

Problems Encountered:

  1. Database Setup:

    • Since this is a standalone package, it does not include a manage.py file.
    • This makes it challenging to run typical Django management commands like migrate to set up the database schema for testing.
  2. Table Creation:

    • I encounter errors indicating that the table for my model does not exist because the necessary migrations are not applied.
    • This is problematic because my tests need to interact with the database tables directly.
  3. Fixtures and Setup:

    • I need to ensure the database tables are created and populated with initial data before the tests run.
    • My attempts to use pytest fixtures and manually create database tables within the tests have not been successful.

What I've Tried:

Desired Outcome:

Additional Information:

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.


Solution

  • 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.