PageRenderTime 31ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/modeltests/get_object_or_404/tests.py

https://code.google.com/p/mango-py/
Python | 80 lines | 51 code | 16 blank | 13 comment | 0 complexity | 3685f1b238aa946b26f80e75347e114e MD5 | raw file
Possible License(s): BSD-3-Clause
  1. from django.http import Http404
  2. from django.shortcuts import get_object_or_404, get_list_or_404
  3. from django.test import TestCase
  4. from models import Author, Article
  5. class GetObjectOr404Tests(TestCase):
  6. def test_get_object_or_404(self):
  7. a1 = Author.objects.create(name="Brave Sir Robin")
  8. a2 = Author.objects.create(name="Patsy")
  9. # No Articles yet, so we should get a Http404 error.
  10. self.assertRaises(Http404, get_object_or_404, Article, title="Foo")
  11. article = Article.objects.create(title="Run away!")
  12. article.authors = [a1, a2]
  13. # get_object_or_404 can be passed a Model to query.
  14. self.assertEqual(
  15. get_object_or_404(Article, title__contains="Run"),
  16. article
  17. )
  18. # We can also use the Article manager through an Author object.
  19. self.assertEqual(
  20. get_object_or_404(a1.article_set, title__contains="Run"),
  21. article
  22. )
  23. # No articles containing "Camelot". This should raise a Http404 error.
  24. self.assertRaises(Http404,
  25. get_object_or_404, a1.article_set, title__contains="Camelot"
  26. )
  27. # Custom managers can be used too.
  28. self.assertEqual(
  29. get_object_or_404(Article.by_a_sir, title="Run away!"),
  30. article
  31. )
  32. # QuerySets can be used too.
  33. self.assertEqual(
  34. get_object_or_404(Article.objects.all(), title__contains="Run"),
  35. article
  36. )
  37. # Just as when using a get() lookup, you will get an error if more than
  38. # one object is returned.
  39. self.assertRaises(Author.MultipleObjectsReturned,
  40. get_object_or_404, Author.objects.all()
  41. )
  42. # Using an EmptyQuerySet raises a Http404 error.
  43. self.assertRaises(Http404,
  44. get_object_or_404, Article.objects.none(), title__contains="Run"
  45. )
  46. # get_list_or_404 can be used to get lists of objects
  47. self.assertEqual(
  48. get_list_or_404(a1.article_set, title__icontains="Run"),
  49. [article]
  50. )
  51. # Http404 is returned if the list is empty.
  52. self.assertRaises(Http404,
  53. get_list_or_404, a1.article_set, title__icontains="Shrubbery"
  54. )
  55. # Custom managers can be used too.
  56. self.assertEqual(
  57. get_list_or_404(Article.by_a_sir, title__icontains="Run"),
  58. [article]
  59. )
  60. # QuerySets can be used too.
  61. self.assertEqual(
  62. get_list_or_404(Article.objects.all(), title__icontains="Run"),
  63. [article]
  64. )