1
from __future__ import absolute_import
3
from django.http import Http404
4
from django.shortcuts import get_object_or_404, get_list_or_404
5
from django.test import TestCase
7
from .models import Author, Article
10
class GetObjectOr404Tests(TestCase):
11
def test_get_object_or_404(self):
12
a1 = Author.objects.create(name="Brave Sir Robin")
13
a2 = Author.objects.create(name="Patsy")
15
# No Articles yet, so we should get a Http404 error.
16
self.assertRaises(Http404, get_object_or_404, Article, title="Foo")
18
article = Article.objects.create(title="Run away!")
19
article.authors = [a1, a2]
20
# get_object_or_404 can be passed a Model to query.
22
get_object_or_404(Article, title__contains="Run"),
26
# We can also use the Article manager through an Author object.
28
get_object_or_404(a1.article_set, title__contains="Run"),
32
# No articles containing "Camelot". This should raise a Http404 error.
33
self.assertRaises(Http404,
34
get_object_or_404, a1.article_set, title__contains="Camelot"
37
# Custom managers can be used too.
39
get_object_or_404(Article.by_a_sir, title="Run away!"),
43
# QuerySets can be used too.
45
get_object_or_404(Article.objects.all(), title__contains="Run"),
49
# Just as when using a get() lookup, you will get an error if more than
50
# one object is returned.
52
self.assertRaises(Author.MultipleObjectsReturned,
53
get_object_or_404, Author.objects.all()
56
# Using an empty QuerySet raises a Http404 error.
57
self.assertRaises(Http404,
58
get_object_or_404, Article.objects.none(), title__contains="Run"
61
# get_list_or_404 can be used to get lists of objects
63
get_list_or_404(a1.article_set, title__icontains="Run"),
67
# Http404 is returned if the list is empty.
68
self.assertRaises(Http404,
69
get_list_or_404, a1.article_set, title__icontains="Shrubbery"
72
# Custom managers can be used too.
74
get_list_or_404(Article.by_a_sir, title__icontains="Run"),
78
# QuerySets can be used too.
80
get_list_or_404(Article.objects.all(), title__icontains="Run"),
84
def test_bad_class(self):
85
# Given an argument klass that is not a Model, Manager, or Queryset
86
# raises a helpful ValueError message
87
self.assertRaisesMessage(ValueError,
88
"Object is of type 'str', but must be a Django Model, Manager, "
90
get_object_or_404, "Article", title__icontains="Run"
93
class CustomClass(object):
96
self.assertRaisesMessage(ValueError,
97
"Object is of type 'CustomClass', but must be a Django Model, "
98
"Manager, or QuerySet",
99
get_object_or_404, CustomClass, title__icontains="Run"
102
# Works for lists too
103
self.assertRaisesMessage(ValueError,
104
"Object is of type 'list', but must be a Django Model, Manager, "
106
get_list_or_404, [Article], title__icontains="Run"