diff options
| author | Ben Cail <bcail@crossway.org> | 2023-11-15 14:32:03 -0500 |
|---|---|---|
| committer | Mariusz Felisiak <felisiak.mariusz@gmail.com> | 2024-02-05 08:25:23 +0100 |
| commit | 02a600ff67f7b106cdcab22310bacea98c1a26ba (patch) | |
| tree | 5806f49c4417747082eceed3f84422c0f3203016 /tests/admin_views/test_multidb.py | |
| parent | a47de0d6cd440d4515ede48df8335d91d7ac7793 (diff) | |
Fixed #16281 -- Fixed ContentType.get_object_for_this_type() in a multiple database setup.
Diffstat (limited to 'tests/admin_views/test_multidb.py')
| -rw-r--r-- | tests/admin_views/test_multidb.py | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/tests/admin_views/test_multidb.py b/tests/admin_views/test_multidb.py index d868321a4b..654161e11d 100644 --- a/tests/admin_views/test_multidb.py +++ b/tests/admin_views/test_multidb.py @@ -2,6 +2,8 @@ from unittest import mock from django.contrib import admin from django.contrib.auth.models import User +from django.contrib.contenttypes.models import ContentType +from django.http import HttpResponse from django.test import TestCase, override_settings from django.urls import path, reverse @@ -23,8 +25,15 @@ class Router: site = admin.AdminSite(name="test_adminsite") site.register(Book) + +def book(request, book_id): + b = Book.objects.get(id=book_id) + return HttpResponse(b.title) + + urlpatterns = [ path("admin/", site.urls), + path("books/<book_id>/", book), ] @@ -88,3 +97,47 @@ class MultiDatabaseTests(TestCase): {"post": "yes"}, ) mock.atomic.assert_called_with(using=db) + + +class ViewOnSiteRouter: + def db_for_read(self, model, instance=None, **hints): + if model._meta.app_label in {"auth", "sessions", "contenttypes"}: + return "default" + return "other" + + def db_for_write(self, model, **hints): + if model._meta.app_label in {"auth", "sessions", "contenttypes"}: + return "default" + return "other" + + def allow_relation(self, obj1, obj2, **hints): + return obj1._state.db in {"default", "other"} and obj2._state.db in { + "default", + "other", + } + + def allow_migrate(self, db, app_label, **hints): + return True + + +@override_settings(ROOT_URLCONF=__name__, DATABASE_ROUTERS=[ViewOnSiteRouter()]) +class ViewOnSiteTests(TestCase): + databases = {"default", "other"} + + def test_contenttype_in_separate_db(self): + ContentType.objects.using("other").all().delete() + book = Book.objects.using("other").create(name="other book") + user = User.objects.create_superuser( + username="super", password="secret", email="super@example.com" + ) + + book_type = ContentType.objects.get(app_label="admin_views", model="book") + + self.client.force_login(user) + + shortcut_url = reverse("admin:view_on_site", args=(book_type.pk, book.id)) + response = self.client.get(shortcut_url, follow=False) + self.assertEqual(response.status_code, 302) + self.assertRegex( + response.url, f"http://(testserver|example.com)/books/{book.id}/" + ) |
