summaryrefslogtreecommitdiff
path: root/objectapp/tests/views.py
blob: 5f4907ab8baf1dd730b35475e5aa31b79cb3177d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# Copyright (c) 2011,  2012 Free Software Foundation

#     This program is free software: you can redistribute it and/or modify
#     it under the terms of the GNU Affero General Public License as
#     published by the Free Software Foundation, either version 3 of the
#     License, or (at your option) any later version.

#     This program is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU Affero General Public License for more details.

#     You should have received a copy of the GNU Affero General Public License
#     along with this program.  If not, see <http://www.gnu.org/licenses/>.


# This project incorporates work covered by the following copyright and permission notice:  

#    Copyright (c) 2009, Julien Fache
#    All rights reserved.

#    Redistribution and use in source and binary forms, with or without
#    modification, are permitted provided that the following conditions
#    are met:

#    * Redistributions of source code must retain the above copyright
#      notice, this list of conditions and the following disclaimer.
#    * Redistributions in binary form must reproduce the above copyright
#      notice, this list of conditions and the following disclaimer in
#      the documentation and/or other materials provided with the
#      distribution.
#    * Neither the name of the author nor the names of other
#      contributors may be used to endorse or promote products derived
#      from this software without specific prior written permission.

#    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
#    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
#    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
#    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
#    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
#    SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
#    HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
#    STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
#    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
#    OF THE POSSIBILITY OF SUCH DAMAGE.

# Copyright (c) 2011,  2012 Free Software Foundation

#     This program is free software: you can redistribute it and/or modify
#     it under the terms of the GNU Affero General Public License as
#     published by the Free Software Foundation, either version 3 of the
#     License, or (at your option) any later version.

#     This program is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU Affero General Public License for more details.

#     You should have received a copy of the GNU Affero General Public License
#     along with this program.  If not, see <http://www.gnu.org/licenses/>.


"""Test cases for Objectapp's views"""
from datetime import datetime

from django.conf import settings
from django.test import TestCase
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.template import TemplateDoesNotExist
from django.utils.translation import ugettext_lazy as _

from objectapp.models import Gbobject
from objectapp.models import Objecttype
from objectapp.managers import PUBLISHED
from objectapp.settings import PAGINATION


class ViewsBaseCase(TestCase):
    """
    Setup and utility function base case.
    """

    def setUp(self):
        self.old_CONTEXT_PROCESSORS = settings.TEMPLATE_CONTEXT_PROCESSORS
        self.old_TEMPLATE_LOADERS = settings.TEMPLATE_LOADERS
        settings.TEMPLATE_LOADERS = (
            ('django.template.loaders.cached.Loader', (
                'django.template.loaders.app_directories.Loader',
                'django.template.loaders.eggs.Loader',
                )
             ),
            )
        settings.TEMPLATE_CONTEXT_PROCESSORS = (
            'django.core.context_processors.request',
            )

        self.site = Site.objects.get_current()
        self.author = User.objects.create_superuser(
            username='admin', email='admin@example.com', password='password')
        self.Objecttype = Objecttype.objects.create(title='Tests', slug='tests')
        params = {'title': 'Test 1',
                  'content': 'First test gbobject published',
                  'slug': 'test-1',
                  'tags': 'tests',
                  'creation_date': datetime(2010, 1, 1),
                  'status': PUBLISHED}
        gbobject = Gbobject.objects.create(**params)
        gbobject.sites.add(self.site)
        gbobject.objecttypes.add(self.Objecttype)
        gbobject.authors.add(self.author)

        params = {'title': 'Test 2',
                  'content': 'Second test gbobject published',
                  'slug': 'test-2',
                  'tags': 'tests',
                  'creation_date': datetime(2010, 6, 1),
                  'status': PUBLISHED}
        gbobject = Gbobject.objects.create(**params)
        gbobject.sites.add(self.site)
        gbobject.objecttypes.add(self.Objecttype)
        gbobject.authors.add(self.author)

    def tearDown(self):
        settings.TEMPLATE_CONTEXT_PROCESSORS = self.old_CONTEXT_PROCESSORS
        settings.TEMPLATE_LOADERS = self.old_TEMPLATE_LOADERS

    def create_published_gbobject(self):
        params = {'title': 'My test gbobject',
                  'content': 'My test content',
                  'slug': 'my-test-gbobject',
                  'tags': 'tests',
                  'creation_date': datetime(2010, 1, 1),
                  'status': PUBLISHED}
        gbobject = Gbobject.objects.create(**params)
        gbobject.sites.add(self.site)
        gbobject.objecttypes.add(self.Objecttype)
        gbobject.authors.add(self.author)
        return gbobject

    def check_publishing_context(self, url, first_expected,
                                 second_expected=None):
        """Test the numbers of gbobjects in context of an url,"""
        response = self.client.get(url)
        self.assertEquals(len(response.context['object_list']), first_expected)
        if second_expected:
            self.create_published_gbobject()
            response = self.client.get(url)
            self.assertEquals(
                len(response.context['object_list']), second_expected)
        return response


class ObjectappViewsTestCase(ViewsBaseCase):
    """
    Test cases for generic views used in the application,
    for reproducing and correcting issue :
    http://github.com/Fantomas42/django-blog-objectapp/issues#issue/3
    """
    urls = 'objectapp.tests.urls'

    def test_objectapp_gbobject_archive_index(self):
        self.check_publishing_context('/', 2, 3)

    def test_objectapp_gbobject_archive_year(self):
        self.check_publishing_context('/2010/', 2, 3)

    def test_objectapp_gbobject_archive_month(self):
        self.check_publishing_context('/2010/01/', 1, 2)

    def test_objectapp_gbobject_archive_day(self):
        self.check_publishing_context('/2010/01/01/', 1, 2)

    def test_objectapp_gbobject_shortlink(self):
        response = self.client.get('/1/', follow=True)
        self.assertEquals(response.redirect_chain,
                          [('http://testserver/2010/01/01/test-1/', 301)])

    def test_objectapp_gbobject_detail(self):
        gbobject = self.create_published_gbobject()
        gbobject.sites.clear()
        # Check a 404 error, but the 404.html may no exist
        try:
            self.assertRaises(TemplateDoesNotExist, self.client.get,
                              '/2010/01/01/my-test-gbobject/')
        except AssertionError:
            response = self.client.get('/2010/01/01/my-test-gbobject/')
            self.assertEquals(response.status_code, 404)

        gbobject.template = 'objectapp/_gbobject_detail.html'
        gbobject.save()
        gbobject.sites.add(Site.objects.get_current())
        response = self.client.get('/2010/01/01/my-test-gbobject/')
        self.assertEquals(response.status_code, 200)
        self.assertTemplateUsed(response, 'objectapp/_gbobject_detail.html')

    def test_objectapp_gbobject_detail_login(self):
        gbobject = self.create_published_gbobject()
        gbobject.login_required = True
        gbobject.save()
        response = self.client.get('/2010/01/01/my-test-gbobject/')
        self.assertTemplateUsed(response, 'objectapp/login.html')

    def test_objectapp_gbobject_detail_password(self):
        gbobject = self.create_published_gbobject()
        gbobject.password = 'password'
        gbobject.save()
        response = self.client.get('/2010/01/01/my-test-gbobject/')
        self.assertTemplateUsed(response, 'objectapp/password.html')
        self.assertEquals(response.context['error'], False)
        response = self.client.post('/2010/01/01/my-test-gbobject/',
                                    {'password': 'bad_password'})
        self.assertTemplateUsed(response, 'objectapp/password.html')
        self.assertEquals(response.context['error'], True)
        response = self.client.post('/2010/01/01/my-test-gbobject/',
                                    {'password': 'password'})
        self.assertEquals(response.status_code, 302)

    def test_objectapp_gbobject_channel(self):
        self.check_publishing_context('/channel-test/', 2, 3)

    def test_objectapp_Objecttype_list(self):
        self.check_publishing_context('/objecttypes/', 1)
        gbobject = Gbobject.objects.all()[0]
        gbobject.objecttypes.add(Objecttype.objects.create(title='New Objecttype',
                                                     slug='new-Objecttype'))
        self.check_publishing_context('/objecttypes/', 2)

    def test_objectapp_Objecttype_detail(self):
        response = self.check_publishing_context('/objecttypes/tests/', 2, 3)
        self.assertTemplateUsed(response, 'objectapp/Objecttype/gbobject_list.html')
        self.assertEquals(response.context['Objecttype'].slug, 'tests')

    def test_objectapp_Objecttype_detail_paginated(self):
        """Test case reproducing issue #42 on Objecttype
        detail view paginated"""
        for i in range(PAGINATION):
            params = {'title': 'My gbobject %i' % i,
                      'content': 'My content %i' % i,
                      'slug': 'my-gbobject-%i' % i,
                      'creation_date': datetime(2010, 1, 1),
                      'status': PUBLISHED}
            gbobject = Gbobject.objects.create(**params)
            gbobject.sites.add(self.site)
            gbobject.objecttypes.add(self.Objecttype)
            gbobject.authors.add(self.author)
        response = self.client.get('/objecttypes/tests/')
        self.assertEquals(len(response.context['object_list']), PAGINATION)
        response = self.client.get('/objecttypes/tests/?page=2')
        self.assertEquals(len(response.context['object_list']), 2)
        response = self.client.get('/objecttypes/tests/page/2/')
        self.assertEquals(len(response.context['object_list']), 2)
        self.assertEquals(response.context['Objecttype'].slug, 'tests')

    def test_objectapp_author_list(self):
        self.check_publishing_context('/authors/', 1)
        gbobject = Gbobject.objects.all()[0]
        gbobject.authors.add(User.objects.create(username='new-user',
                                              email='new_user@example.com'))
        self.check_publishing_context('/authors/', 2)

    def test_objectapp_author_detail(self):
        response = self.check_publishing_context('/authors/admin/', 2, 3)
        self.assertTemplateUsed(response, 'objectapp/author/gbobject_list.html')
        self.assertEquals(response.context['author'].username, 'admin')

    def test_objectapp_tag_list(self):
        self.check_publishing_context('/tags/', 1)
        gbobject = Gbobject.objects.all()[0]
        gbobject.tags = 'tests, tag'
        gbobject.save()
        self.check_publishing_context('/tags/', 2)

    def test_objectapp_tag_detail(self):
        response = self.check_publishing_context('/tags/tests/', 2, 3)
        self.assertTemplateUsed(response, 'objectapp/tag/gbobject_list.html')
        self.assertEquals(response.context['tag'].name, 'tests')

    def test_objectapp_gbobject_search(self):
        self.check_publishing_context('/search/?pattern=test', 2, 3)
        response = self.client.get('/search/?pattern=ab')
        self.assertEquals(len(response.context['object_list']), 0)
        self.assertEquals(response.context['error'],
                          _('The pattern is too short'))
        response = self.client.get('/search/')
        self.assertEquals(len(response.context['object_list']), 0)
        self.assertEquals(response.context['error'],
                          _('No pattern to search found'))

    def test_objectapp_sitemap(self):
        response = self.client.get('/sitemap/')
        self.assertEquals(len(response.context['gbobjects']), 2)
        self.assertEquals(len(response.context['objecttypes']), 1)
        gbobject = self.create_published_gbobject()
        gbobject.objecttypes.add(Objecttype.objects.create(title='New Objecttype',
                                                     slug='new-Objecttype'))
        response = self.client.get('/sitemap/')
        self.assertEquals(len(response.context['gbobjects']), 3)
        self.assertEquals(len(response.context['objecttypes']), 2)

    def test_objectapp_trackback(self):
        # Check a 404 error, but the 404.html may no exist
        try:
            self.assertRaises(TemplateDoesNotExist, self.client.post,
                              '/trackback/404/')
        except AssertionError:
            response = self.client.post('/trackback/404/')
            self.assertEquals(response.status_code, 404)
        self.assertEquals(
            self.client.post('/trackback/1/').status_code, 301)
        self.assertEquals(
            self.client.get('/trackback/1/').status_code, 301)
        gbobject = Gbobject.objects.get(slug='test-1')
        gbobject.pingback_enabled = False
        gbobject.save()
        self.assertEquals(
            self.client.post('/trackback/1/',
                             {'url': 'http://example.com'}).content,
            '<?xml version="1.0" encoding="utf-8"?>\n<response>\n  \n  '
            '<error>1</error>\n  <message>Trackback is not enabled for '
            'Test 1</message>\n  \n</response>\n')
        gbobject.pingback_enabled = True
        gbobject.save()
        self.assertEquals(
            self.client.post('/trackback/1/',
                             {'url': 'http://example.com'}).content,
            '<?xml version="1.0" encoding="utf-8"?>\n<response>\n  \n  '
            '<error>0</error>\n  \n</response>\n')
        self.assertEquals(
            self.client.post('/trackback/1/',
                             {'url': 'http://example.com'}).content,
            '<?xml version="1.0" encoding="utf-8"?>\n<response>\n  \n  '
            '<error>1</error>\n  <message>Trackback is already registered'
            '</message>\n  \n</response>\n')


class ObjectappCustomDetailViews(ViewsBaseCase):
    """
    Tests with an alternate urls.py that modifies how author_detail,
    tags_detail and objecttypes_detail views to be called with a custom
    template_name keyword argument and an extra_context.
    """
    urls = 'objectapp.tests.custom_views_detail_urls'

    def test_custom_Objecttype_detail(self):
        response = self.check_publishing_context('/objecttypes/tests/', 2, 3)
        self.assertTemplateUsed(response, 'objectapp/gbobject_list.html')
        self.assertEquals(response.context['Objecttype'].slug, 'tests')
        self.assertEquals(response.context['extra'], 'context')

    def test_custom_author_detail(self):
        response = self.check_publishing_context('/authors/admin/', 2, 3)
        self.assertTemplateUsed(response, 'objectapp/gbobject_list.html')
        self.assertEquals(response.context['author'].username, 'admin')
        self.assertEquals(response.context['extra'], 'context')

    def test_custom_tag_detail(self):
        response = self.check_publishing_context('/tags/tests/', 2, 3)
        self.assertTemplateUsed(response, 'objectapp/gbobject_list.html')
        self.assertEquals(response.context['tag'].name, 'tests')
        self.assertEquals(response.context['extra'], 'context')