PageRenderTime 23ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/modeltests/get_latest/tests.py

https://code.google.com/p/mango-py/
Python | 53 lines | 37 code | 9 blank | 7 comment | 0 complexity | 33365e804fd6f939fb2d88658f7d8c23 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. from datetime import datetime
  2. from django.test import TestCase
  3. from models import Article, Person
  4. class LatestTests(TestCase):
  5. def test_latest(self):
  6. # Because no Articles exist yet, latest() raises ArticleDoesNotExist.
  7. self.assertRaises(Article.DoesNotExist, Article.objects.latest)
  8. a1 = Article.objects.create(
  9. headline="Article 1", pub_date=datetime(2005, 7, 26),
  10. expire_date=datetime(2005, 9, 1)
  11. )
  12. a2 = Article.objects.create(
  13. headline="Article 2", pub_date=datetime(2005, 7, 27),
  14. expire_date=datetime(2005, 7, 28)
  15. )
  16. a3 = Article.objects.create(
  17. headline="Article 3", pub_date=datetime(2005, 7, 27),
  18. expire_date=datetime(2005, 8, 27)
  19. )
  20. a4 = Article.objects.create(
  21. headline="Article 4", pub_date=datetime(2005, 7, 28),
  22. expire_date=datetime(2005, 7, 30)
  23. )
  24. # Get the latest Article.
  25. self.assertEqual(Article.objects.latest(), a4)
  26. # Get the latest Article that matches certain filters.
  27. self.assertEqual(
  28. Article.objects.filter(pub_date__lt=datetime(2005, 7, 27)).latest(),
  29. a1
  30. )
  31. # Pass a custom field name to latest() to change the field that's used
  32. # to determine the latest object.
  33. self.assertEqual(Article.objects.latest('expire_date'), a1)
  34. self.assertEqual(
  35. Article.objects.filter(pub_date__gt=datetime(2005, 7, 26)).latest('expire_date'),
  36. a3,
  37. )
  38. def test_latest_manual(self):
  39. # You can still use latest() with a model that doesn't have
  40. # "get_latest_by" set -- just pass in the field name manually.
  41. p1 = Person.objects.create(name="Ralph", birthday=datetime(1950, 1, 1))
  42. p2 = Person.objects.create(name="Stephanie", birthday=datetime(1960, 2, 3))
  43. self.assertRaises(AssertionError, Person.objects.latest)
  44. self.assertEqual(Person.objects.latest("birthday"), p2)