Does anybody know how to run Django Tests using pytest-django against an existing (e.g. production) database?
I know that in general, this is not what unit tests are supposed to do, but in my case, I'm running the tests on Heroku. By default, Django creates a new test database, however, this is not possible on Heroku.
I found a solution that would work without pytest-django (python manage.py test
): https://gist.github.com/gregsadetsky/5018173
but as far as I understood, pytest-django doesn't make use of the test runner defined in the Django settings.
If anybody has another approach on how to run Django tests using pytest-django on Heroku (e.g. by automating a way to create the test database) I would be happy with that solution as well.
Setting Up pytest for a Django ProjectThe pytest-django plugin is maintained by the pytest development team. It provides useful tools for writing tests for Django projects using pytest .
To overcome this, pytest provides us with an option to run tests in parallel. For this, we need to first install the pytest-xdist plugin. -n <num> runs the tests by using multiple workers, here it is 3. We will not be having much time difference when there is only a few tests to run.
By default pytest-django will set up the Django databases the first time a test needs them. Once setup, the database is cached to be used for all subsequent tests and rolls back transactions, to isolate tests from each other.
Following the documentation on how to link to an existing database:
Using an existing, external database for tests
This example shows how you can connect to an existing database and use it for your tests.
This example is trivial, you just need to disable all of pytest-django and Django’s test database creation and point to the existing database. This is achieved by simply implementing a no-op django_db_setup fixture.Put this into
conftest.py
:import pytest @pytest.fixture(scope='session') def django_db_setup(): settings.DATABASES['default'] = { 'ENGINE': 'django.db.backends.mysql', 'HOST': 'db.example.com', 'NAME': 'external_db', }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With