PageRenderTime 102ms CodeModel.GetById 60ms app.highlight 7ms RepoModel.GetById 34ms 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
 1from datetime import datetime
 2
 3from django.test import TestCase
 4
 5from models import Article, Person
 6
 7
 8class LatestTests(TestCase):
 9    def test_latest(self):
10        # Because no Articles exist yet, latest() raises ArticleDoesNotExist.
11        self.assertRaises(Article.DoesNotExist, Article.objects.latest)
12
13        a1 = Article.objects.create(
14            headline="Article 1", pub_date=datetime(2005, 7, 26),
15            expire_date=datetime(2005, 9, 1)
16        )
17        a2 = Article.objects.create(
18            headline="Article 2", pub_date=datetime(2005, 7, 27),
19            expire_date=datetime(2005, 7, 28)
20        )
21        a3 = Article.objects.create(
22            headline="Article 3", pub_date=datetime(2005, 7, 27),
23            expire_date=datetime(2005, 8, 27)
24        )
25        a4 = Article.objects.create(
26            headline="Article 4", pub_date=datetime(2005, 7, 28),
27            expire_date=datetime(2005, 7, 30)
28        )
29
30        # Get the latest Article.
31        self.assertEqual(Article.objects.latest(), a4)
32        # Get the latest Article that matches certain filters.
33        self.assertEqual(
34            Article.objects.filter(pub_date__lt=datetime(2005, 7, 27)).latest(),
35            a1
36        )
37
38        # Pass a custom field name to latest() to change the field that's used
39        # to determine the latest object.
40        self.assertEqual(Article.objects.latest('expire_date'), a1)
41        self.assertEqual(
42            Article.objects.filter(pub_date__gt=datetime(2005, 7, 26)).latest('expire_date'),
43            a3,
44        )
45
46    def test_latest_manual(self):
47        # You can still use latest() with a model that doesn't have
48        # "get_latest_by" set -- just pass in the field name manually.
49        p1 = Person.objects.create(name="Ralph", birthday=datetime(1950, 1, 1))
50        p2 = Person.objects.create(name="Stephanie", birthday=datetime(1960, 2, 3))
51        self.assertRaises(AssertionError, Person.objects.latest)
52
53        self.assertEqual(Person.objects.latest("birthday"), p2)