About Testing Multi-database Operations with pytest
Use the django_db
mark to create multiple databases in your tests with pytest:
import pytest
from django.contrib.auth.models import User
@pytest.mark.django_db(databases=["default", "archive"])
def test_multiple_databases():
User.objects.create(username="user1")
User.objects.using("archive").create(username="user2")
# Test default database
assert User.objects.filter(username="user1").exists()
assert not User.objects.filter(username="user2").exists()
# Test archive database
assert not User.objects.using("archive").filter(username="user1").exists()
assert User.objects.using("archive").filter(username="user2").exists()
Tips and Tricks Programming Testing Databases Django 5.2 Django 4.2 Django 3.2 PostgreSQL MySQL SQLite pytest
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django GDPR Cookie Consent app
For Django websites that use cookies.