Code

Ticket #1496: models.py

File models.py, 1.5 KB (added by akaihola, 8 years ago)

Unit test for enhanced equality test. Could go in tests/modeltests/wrappers/.

Line 
1"""
2XX. Equality test for wrapper classes
3
4Compare wrapper class instances to real objects.
5"""
6
7from django.db import models
8
9class Article(models.Model):
10    headline = models.CharField(maxlength=100, default='Default headline')
11API_TESTS = '''
12
13# Create and save an Article.
14>>> u1 = Article(id=1, headline='Django 1.0 Released')
15>>> u1.save()
16>>> u1.id
171L
18
19# Create and save another Article.
20>>> u2 = Article(id=2, headline='Django Saves the World')
21>>> u2.save()
22>>> u2.id
232L
24
25# Compare articles.
26>>> u1 == u2
27False
28
29>>> u1 != u2
30True
31
32>>> u1 == u1
33True
34
35>>> u1 != u1
36False
37
38# Create ArticleWrapper objects.
39>>> class ArticleWrapper(object):
40...     """
41...     Proxy to lazily load an article object.  Similar to
42...     django.contrib.auth.middleware.UserWrapper.
43...     """
44...     def __init__(self, id):
45...         self._id = id
46...         self._cached_article = None
47...
48...     def _get_article(self):
49...         if not self._cached_article:
50...             self._cached_article = Article.objects.get(pk=self._id)
51...         return self._cached_article
52...
53...     _article = property(_get_article)
54...
55...     def __getattr__(self, name):
56...         return getattr(self._article, name)
57>>> w1 = ArticleWrapper(1) ; w2 = ArticleWrapper(2)
58
59# Compare Article and ArticleWrapper objects.
60>>> w1 == u1
61True
62
63>>> w1 != u1
64False
65
66>>> w1 == u2
67False
68
69>>> w1 != u2
70True
71
72# Compare ArticleWrapper objects.
73>>> w1 == w2
74False
75
76>>> w1 != w2
77True
78
79>>> w1 == w1
80True
81
82>>> w1 != w1
83False
84'''