PageRenderTime 208ms CodeModel.GetById 55ms app.highlight 80ms RepoModel.GetById 41ms app.codeStats 1ms

/view_shortcuts/tests.py

https://bitbucket.org/neithere/django-view-shortcuts/
Python | 252 lines | 250 code | 1 blank | 1 comment | 0 complexity | ca1f37d3077543b4c92f23fc7068dee7 MD5 | raw file
  1# -*- coding: utf-8 -*-
  2
  3__doc__="""
  4>>> c1 = Category.objects.create(title='News', slug='news')
  5>>> c2 = Category.objects.create(title='Misc', slug='misc')
  6>>> a1 = Author.objects.create(name='John')
  7>>> a2 = Author.objects.create(name='Mary')
  8>>> a3 = Author.objects.create(name='joe')
  9>>> s1 = Story(title='s1', text='test', status=Story.PUBLISHED, paid=True)
 10>>> s1.save()
 11>>> s1.author=a1
 12>>> s1.categories=[c1,c2]
 13>>> s1.save()
 14>>> s2 = Story(title='s2', text='test', status=Story.PUBLISHED, paid=False)
 15>>> s2.save()
 16>>> s2.author=a2
 17>>> s2.categories=[c1]
 18>>> s2.save()
 19>>> s3 = Story(title='s3', text='test', status=Story.DRAFT, paid=True)
 20>>> s3.save()
 21>>> s3.author=a1
 22>>> s3.categories=[c2]
 23>>> s3.save()
 24>>> qs = Story.objects.all()
 25>>> from view_shortcuts.filters import FilterList, facet, RelationFilter
 26>>> filter_settings = (
 27...     facet('categories__slug'),
 28...     facet('author'),
 29...     facet('status'),
 30...     facet('paid')
 31... )
 32>>> request = mock_request()
 33>>> filters = FilterList(request, qs, filter_settings)
 34>>> isinstance(filters, FilterList)
 35True
 36>>> len(filters)
 374
 38>>> filters.active
 39[]
 40>>> filters
 41[<RelationFilter "categories__slug": False>, <RelationFilter "author": False>, <AllValuesFilter "status": False>, <BooleanFilter "paid": False>]
 42>>> filters.object_list
 43[<Story: s1>, <Story: s2>, <Story: s3>]
 44>>> request = mock_request(author=a1.pk)
 45>>> filters = FilterList(request, qs, filter_settings)
 46>>> filters
 47[<RelationFilter "categories__slug": False>, <RelationFilter "author": True>, <AllValuesFilter "status": False>, <BooleanFilter "paid": False>]
 48>>> filters.active
 49[<RelationFilter "author": True>]
 50>>> filters.urlencode
 51'author=1'
 52>>> filters.object_list
 53[<Story: s1>, <Story: s3>]
 54>>> request = mock_request(author=a1.pk, status=Story.PUBLISHED)
 55>>> filters = FilterList(request, qs, filter_settings)
 56>>> filters.active
 57[<RelationFilter "author": True>, <AllValuesFilter "status": True>]
 58>>> filters.urlencode
 59'author=1&status=pub'
 60>>> filters = FilterList(request, qs, filter_settings)
 61>>> filters
 62[<RelationFilter "categories__slug": False>, <RelationFilter "author": True>, <AllValuesFilter "status": True>, <BooleanFilter "paid": False>]
 63>>> filters.object_list
 64[<Story: s1>]
 65>>> flt_author = filters[1]
 66>>> flt_author
 67<RelationFilter "author": True>
 68>>> flt_author.active
 69True
 70>>> flt_author.title
 71u'Written by'
 72>>> flt_author.urlencode
 73'author=1'
 74>>> flt_author.choices
 75[<Choice author="1">, <Choice author="2">]
 76>>> [c.title for c in flt_author.choices]
 77[u'John', u'Mary']
 78>>> [c for c in flt_author.get_active_choices()]
 79[<Choice author="1">]
 80>>> c_a1 = flt_author.get_first_active_choice()
 81>>> c_a1
 82<Choice author="1">
 83>>> c_a1.title
 84u'John'
 85>>> c_a1.urlencode
 86'author=1'
 87>>> c_a1.items_count
 882
 89>>> for f in filters:
 90...     print u'%s:   [%s]' % (f.title, f.urlencode)
 91...     for c in f.choices:
 92...         print u'    - %s (%s) --> [%s]' % (c.title, c.items_count, c.urlencode)
 93Category:   [categories__slug=None]
 94    - News (2) --> [categories__slug=news]
 95    - Misc (2) --> [categories__slug=misc]
 96Written by:   [author=1]
 97    - John (2) --> [author=1]
 98    - Mary (1) --> [author=2]
 99Status:   [status=pub]
100    - Published (2) --> [status=pub]
101    - Draft (1) --> [status=draft]
102Paid:   [paid=None]
103    - yes (2) --> [paid=True]
104    - no (1) --> [paid=False]
105>>> qs_predefined = Story.objects.filter(status=Story.PUBLISHED)
106>>> filters = FilterList(request, qs_predefined, filter_settings)
107>>> for f in filters:
108...     print u'%s:   [%s]' % (f.title, f.urlencode)
109...     for c in f.choices:
110...         print u'    - %s (%s) --> [%s]' % (c.title, c.items_count, c.urlencode)
111Category:   [categories__slug=None]
112    - News (2) --> [categories__slug=news]
113    - Misc (1) --> [categories__slug=misc]
114Written by:   [author=1]
115    - John (1) --> [author=1]
116    - Mary (1) --> [author=2]
117Status:   [status=pub]
118    - Published (2) --> [status=pub]
119Paid:   [paid=None]
120    - yes (1) --> [paid=True]
121    - no (1) --> [paid=False]
122>>> qs_predefined = Story.objects.filter(author__name__contains='J')
123>>> filters = FilterList(mock_request(status=Story.PUBLISHED), qs_predefined, filter_settings)
124>>> filters._qs            # predefined query
125[<Story: s1>, <Story: s3>]
126>>> filters.clean_query    # query made from scratch, no traces of predefined stuff
127[<Story: s1>, <Story: s2>]
128>>> filters.object_list    # intersection between the two
129[<Story: s1>]
130>>> request = mock_request(categories__slug='news')
131>>> filters = FilterList(request, qs, filter_settings)
132>>> filters
133[<RelationFilter "categories__slug": True>, <RelationFilter "author": False>, <AllValuesFilter "status": False>, <BooleanFilter "paid": False>]
134>>> filters.active
135[<RelationFilter "categories__slug": True>]
136>>> filters.object_list
137[<Story: s1>, <Story: s2>]
138
139# Test custom filters
140
141>>> from view_shortcuts.filters import AlphabeticFilter
142>>> filter_settings = (
143...     facet('name', 'name', AlphabeticFilter),
144... )
145>>> request = mock_request()
146>>> qs = Author.objects.all()
147>>> filters = FilterList(request, qs, filter_settings)
148>>> filters
149[<AlphabeticFilter "name": False>]
150>>> f = filters[0]
151>>> f.choices
152[<Choice name="j">, <Choice name="m">]
153>>> for c in f.choices:
154...     print "%s --> %s" % (c.title, c.urlencode)
155J --> name=j
156M --> name=m
157>>> for value in 'j', 'm':
158...     request = mock_request(name=value)
159...     filters = FilterList(request, qs, filter_settings)
160...     print "value:", value
161...     for choice in filters[0].get_active_choices():
162...         print '    title "%s", value "%s", %d items' % (choice.title, choice.value, choice.items_count)
163value: j
164    title "J", value "j", 2 items
165value: m
166    title "M", value "m", 1 items
167
168"""
169
170import urllib
171from django.test import Client
172from django.core.handlers.wsgi import WSGIRequest
173from django.core.urlresolvers import reverse
174from django.db.models import BooleanField, CharField, ForeignKey, IntegerField, \
175                             ManyToManyField, Model, SlugField, TextField
176from django.utils.translation import ugettext_lazy as _
177
178
179class Author(Model):
180    name = CharField(max_length=255)
181
182    __unicode__ = lambda s: s.name
183
184
185class Category(Model):
186    title = CharField(max_length=255)
187    slug  = SlugField()
188
189    __unicode__ = lambda s: s.title
190
191
192class Story(Model):
193    DRAFT, PUBLISHED = 'draft', 'pub'
194    STORY_STATUS_CHOICES = (
195        (DRAFT,     _('Draft')),
196        (PUBLISHED, _('Published')),
197    )
198    title    = CharField(max_length=255)
199    status   = CharField(_('Status'), max_length=255,
200                         choices=STORY_STATUS_CHOICES, default=DRAFT)
201    author   = ForeignKey(Author, related_name='stories', null=True,
202                          verbose_name=_('Written by'))
203    categories = ManyToManyField(Category, null=True, related_name='stories',
204                               verbose_name=_('Category'))
205    text     = TextField()
206    paid     = BooleanField(_('Paid'))
207
208    __unicode__ = lambda s: s.title
209    get_url     = lambda s: reverse('example-story-detail',
210                                    urlconf=None, args=None,
211                                    kwargs=dict(object_id=s.pk))
212
213
214class RequestFactory(Client):
215    """
216    Class that lets you create mock Request objects for use in testing.
217
218    Usage:
219
220    rf = RequestFactory()
221    get_request = rf.get('/hello/')
222    post_request = rf.post('/submit/', {'foo': 'bar'})
223
224    This class re-uses the django.test.client.Client interface, docs here:
225    http://www.djangoproject.com/documentation/testing/#the-test-client
226
227    Once you have a request object you can pass it to any view function,
228    just as if that view had been hooked up using a URLconf.
229
230    Source: http://www.djangosnippets.org/snippets/963/
231    """
232    def request(self, **request):
233        """
234        Similar to parent class, but returns the request object as soon as it
235        has created it.
236        """
237        environ = {
238            'HTTP_COOKIE': self.cookies,
239            'PATH_INFO': '/',
240            'QUERY_STRING': '',
241            'REQUEST_METHOD': 'GET',
242            'SCRIPT_NAME': '',
243            'SERVER_NAME': 'testserver',
244            'SERVER_PORT': 80,
245            'SERVER_PROTOCOL': 'HTTP/1.1',
246        }
247        environ.update(self.defaults)
248        environ.update(request)
249        return WSGIRequest(environ)
250
251def mock_request(**kw):
252    return RequestFactory().request(QUERY_STRING=urllib.urlencode(kw))