diff --git a/django/contrib/contenttypes/tests.py b/django/contrib/contenttypes/tests.py index e25503c715b..fd624c33777 100644 --- a/django/contrib/contenttypes/tests.py +++ b/django/contrib/contenttypes/tests.py @@ -1,11 +1,33 @@ +import urllib from django import db from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django.contrib.contenttypes.views import shortcut -from django.core.exceptions import ObjectDoesNotExist -from django.http import HttpRequest +from django.http import HttpRequest, Http404 from django.test import TestCase +from django.db import models +from django.utils.encoding import smart_str + + +class FooWithoutUrl(models.Model): + """ + Fake model not defining ``get_absolute_url`` for + :meth:`ContentTypesTests.test_shortcut_view_without_get_absolute_url`""" + name = models.CharField(max_length=30, unique=True) + + def __unicode__(self): + return self.name + + +class FooWithUrl(FooWithoutUrl): + """ + Fake model defining ``get_absolute_url`` for + :meth:`ContentTypesTests.test_shortcut_view` + """ + + def get_absolute_url(self): + return "/users/%s/" % urllib.quote(smart_str(self.name)) class ContentTypesTests(TestCase): @@ -58,9 +80,8 @@ class ContentTypesTests(TestCase): "SERVER_NAME": "Example.com", "SERVER_PORT": "80", } - from django.contrib.auth.models import User - user_ct = ContentType.objects.get_for_model(User) - obj = User.objects.create(username="john") + user_ct = ContentType.objects.get_for_model(FooWithUrl) + obj = FooWithUrl.objects.create(name="john") if Site._meta.installed: current_site = Site.objects.get_current() @@ -72,3 +93,19 @@ class ContentTypesTests(TestCase): response = shortcut(request, user_ct.id, obj.id) self.assertEqual("http://Example.com/users/john/", response._headers.get("location")[1]) + + def test_shortcut_view_without_get_absolute_url(self): + """ + Check that the shortcut view (used for the admin "view on site" + functionality) returns 404 when get_absolute_url is not defined. + """ + + request = HttpRequest() + request.META = { + "SERVER_NAME": "Example.com", + "SERVER_PORT": "80", + } + user_ct = ContentType.objects.get_for_model(FooWithoutUrl) + obj = FooWithoutUrl.objects.create(name="john") + + self.assertRaises(Http404, shortcut, request, user_ct.id, obj.id)