| 1 |
from django.db import models |
| 2 |
from django.test import SimpleTestCase |
| 3 |
from django.test.utils import isolate_apps |
| 4 |
|
| 5 |
|
| 6 |
@isolate_apps("absolute_url_overrides") |
| 7 |
class AbsoluteUrlOverrideTests(SimpleTestCase): |
| 8 |
def test_get_absolute_url(self): |
| 9 |
""" |
| 10 |
get_absolute_url() functions as a normal method. |
| 11 |
""" |
| 12 |
|
| 13 |
def get_absolute_url(o): |
| 14 |
return "/test-a/%s/" % o.pk |
| 15 |
|
| 16 |
TestA = self._create_model_class("TestA", get_absolute_url) |
| 17 |
|
| 18 |
self.assertTrue(hasattr(TestA, "get_absolute_url")) |
| 19 |
obj = TestA(pk=1, name="Foo") |
| 20 |
self.assertEqual("/test-a/%s/" % obj.pk, obj.get_absolute_url()) |
| 21 |
|
| 22 |
def test_override_get_absolute_url(self): |
| 23 |
""" |
| 24 |
ABSOLUTE_URL_OVERRIDES should override get_absolute_url(). |
| 25 |
""" |
| 26 |
|
| 27 |
def get_absolute_url(o): |
| 28 |
return "/test-b/%s/" % o.pk |
| 29 |
|
| 30 |
with self.settings( |
| 31 |
ABSOLUTE_URL_OVERRIDES={ |
| 32 |
"absolute_url_overrides.testb": lambda o: "/overridden-test-b/%s/" |
| 33 |
% o.pk, |
| 34 |
}, |
| 35 |
): |
| 36 |
TestB = self._create_model_class("TestB", get_absolute_url) |
| 37 |
obj = TestB(pk=1, name="Foo") |
| 38 |
self.assertEqual("/overridden-test-b/%s/" % obj.pk, obj.get_absolute_url()) |
| 39 |
|
| 40 |
def test_insert_get_absolute_url(self): |
| 41 |
""" |
| 42 |
ABSOLUTE_URL_OVERRIDES should work even if the model doesn't have a |
| 43 |
get_absolute_url() method. |
| 44 |
""" |
| 45 |
with self.settings( |
| 46 |
ABSOLUTE_URL_OVERRIDES={ |
| 47 |
"absolute_url_overrides.testc": lambda o: "/test-c/%s/" % o.pk, |
| 48 |
}, |
| 49 |
): |
| 50 |
TestC = self._create_model_class("TestC") |
| 51 |
obj = TestC(pk=1, name="Foo") |
| 52 |
self.assertEqual("/test-c/%s/" % obj.pk, obj.get_absolute_url()) |
| 53 |
|
| 54 |
def _create_model_class(self, class_name, get_absolute_url_method=None): |
| 55 |
attrs = { |
| 56 |
"name": models.CharField(max_length=50), |
| 57 |
"__module__": "absolute_url_overrides", |
| 58 |
} |
| 59 |
if get_absolute_url_method: |
| 60 |
attrs["get_absolute_url"] = get_absolute_url_method |
| 61 |
|
| 62 |
return type(class_name, (models.Model,), attrs) |