summaryrefslogtreecommitdiff
path: root/tests/i18n/patterns/tests.py
blob: 93284578b0b7ced53452ddf45831af29e0f45912 (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
from __future__ import unicode_literals

import os

from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse, clear_url_caches
from django.http import HttpResponsePermanentRedirect
from django.middleware.locale import LocaleMiddleware
from django.test import TestCase, override_settings
from django.template import Template, Context
from django.utils._os import upath
from django.utils import translation


class PermanentRedirectLocaleMiddleWare(LocaleMiddleware):
    response_redirect_class = HttpResponsePermanentRedirect


@override_settings(
    USE_I18N=True,
    LOCALE_PATHS=(
        os.path.join(os.path.dirname(upath(__file__)), 'locale'),
    ),
    TEMPLATE_DIRS=(
        os.path.join(os.path.dirname(upath(__file__)), 'templates'),
    ),
    LANGUAGE_CODE='en-us',
    LANGUAGES=(
        ('nl', 'Dutch'),
        ('en', 'English'),
        ('pt-br', 'Brazilian Portuguese'),
    ),
    MIDDLEWARE_CLASSES=(
        'django.middleware.locale.LocaleMiddleware',
        'django.middleware.common.CommonMiddleware',
    ),
    ROOT_URLCONF='i18n.patterns.urls.default',
)
class URLTestCaseBase(TestCase):
    """
    TestCase base-class for the URL tests.
    """

    def setUp(self):
        # Make sure the cache is empty before we are doing our tests.
        clear_url_caches()

    def tearDown(self):
        # Make sure we will leave an empty cache for other testcases.
        clear_url_caches()


class URLPrefixTests(URLTestCaseBase):
    """
    Tests if the `i18n_patterns` is adding the prefix correctly.
    """
    def test_not_prefixed(self):
        with translation.override('en'):
            self.assertEqual(reverse('not-prefixed'), '/not-prefixed/')
            self.assertEqual(reverse('not-prefixed-included-url'), '/not-prefixed-include/foo/')
        with translation.override('nl'):
            self.assertEqual(reverse('not-prefixed'), '/not-prefixed/')
            self.assertEqual(reverse('not-prefixed-included-url'), '/not-prefixed-include/foo/')

    def test_prefixed(self):
        with translation.override('en'):
            self.assertEqual(reverse('prefixed'), '/en/prefixed/')
        with translation.override('nl'):
            self.assertEqual(reverse('prefixed'), '/nl/prefixed/')

    @override_settings(ROOT_URLCONF='i18n.patterns.urls.wrong')
    def test_invalid_prefix_use(self):
        self.assertRaises(ImproperlyConfigured, lambda: reverse('account:register'))


@override_settings(ROOT_URLCONF='i18n.patterns.urls.disabled')
class URLDisabledTests(URLTestCaseBase):

    @override_settings(USE_I18N=False)
    def test_prefixed_i18n_disabled(self):
        with translation.override('en'):
            self.assertEqual(reverse('prefixed'), '/prefixed/')
        with translation.override('nl'):
            self.assertEqual(reverse('prefixed'), '/prefixed/')


@override_settings(ROOT_URLCONF='i18n.patterns.urls.path_unused')
class PathUnusedTests(URLTestCaseBase):
    """
    Check that if no i18n_patterns is used in root urlconfs, then no
    language activation happens based on url prefix.
    """

    def test_no_lang_activate(self):
        response = self.client.get('/nl/foo/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['content-language'], 'en')
        self.assertEqual(response.context['LANGUAGE_CODE'], 'en')


class URLTranslationTests(URLTestCaseBase):
    """
    Tests if the pattern-strings are translated correctly (within the
    `i18n_patterns` and the normal `patterns` function).
    """
    def test_no_prefix_translated(self):
        with translation.override('en'):
            self.assertEqual(reverse('no-prefix-translated'), '/translated/')
            self.assertEqual(reverse('no-prefix-translated-slug', kwargs={'slug': 'yeah'}), '/translated/yeah/')

        with translation.override('nl'):
            self.assertEqual(reverse('no-prefix-translated'), '/vertaald/')
            self.assertEqual(reverse('no-prefix-translated-slug', kwargs={'slug': 'yeah'}), '/vertaald/yeah/')

        with translation.override('pt-br'):
            self.assertEqual(reverse('no-prefix-translated'), '/traduzidos/')
            self.assertEqual(reverse('no-prefix-translated-slug', kwargs={'slug': 'yeah'}), '/traduzidos/yeah/')

    def test_users_url(self):
        with translation.override('en'):
            self.assertEqual(reverse('users'), '/en/users/')

        with translation.override('nl'):
            self.assertEqual(reverse('users'), '/nl/gebruikers/')
            self.assertEqual(reverse('prefixed_xml'), '/nl/prefixed.xml')

        with translation.override('pt-br'):
            self.assertEqual(reverse('users'), '/pt-br/usuarios/')


class URLNamespaceTests(URLTestCaseBase):
    """
    Tests if the translations are still working within namespaces.
    """
    def test_account_register(self):
        with translation.override('en'):
            self.assertEqual(reverse('account:register'), '/en/account/register/')

        with translation.override('nl'):
            self.assertEqual(reverse('account:register'), '/nl/profiel/registeren/')


class URLRedirectTests(URLTestCaseBase):
    """
    Tests if the user gets redirected to the right URL when there is no
    language-prefix in the request URL.
    """
    def test_no_prefix_response(self):
        response = self.client.get('/not-prefixed/')
        self.assertEqual(response.status_code, 200)

    def test_en_redirect(self):
        response = self.client.get('/account/register/', HTTP_ACCEPT_LANGUAGE='en')
        self.assertRedirects(response, '/en/account/register/')

        response = self.client.get(response['location'])
        self.assertEqual(response.status_code, 200)

    def test_en_redirect_wrong_url(self):
        response = self.client.get('/profiel/registeren/', HTTP_ACCEPT_LANGUAGE='en')
        self.assertEqual(response.status_code, 404)

    def test_nl_redirect(self):
        response = self.client.get('/profiel/registeren/', HTTP_ACCEPT_LANGUAGE='nl')
        self.assertRedirects(response, '/nl/profiel/registeren/')

        response = self.client.get(response['location'])
        self.assertEqual(response.status_code, 200)

    def test_nl_redirect_wrong_url(self):
        response = self.client.get('/account/register/', HTTP_ACCEPT_LANGUAGE='nl')
        self.assertEqual(response.status_code, 404)

    def test_pt_br_redirect(self):
        response = self.client.get('/conta/registre-se/', HTTP_ACCEPT_LANGUAGE='pt-br')
        self.assertRedirects(response, '/pt-br/conta/registre-se/')

        response = self.client.get(response['location'])
        self.assertEqual(response.status_code, 200)

    def test_pl_pl_redirect(self):
        # language from outside of the supported LANGUAGES list
        response = self.client.get('/account/register/', HTTP_ACCEPT_LANGUAGE='pl-pl')
        self.assertRedirects(response, '/en/account/register/')

        response = self.client.get(response['location'])
        self.assertEqual(response.status_code, 200)

    @override_settings(
        MIDDLEWARE_CLASSES=(
            'i18n.patterns.tests.PermanentRedirectLocaleMiddleWare',
            'django.middleware.common.CommonMiddleware',
        ),
    )
    def test_custom_redirect_class(self):
        response = self.client.get('/account/register/', HTTP_ACCEPT_LANGUAGE='en')
        self.assertRedirects(response, '/en/account/register/', 301)


class URLVaryAcceptLanguageTests(URLTestCaseBase):
    """
    Tests that 'Accept-Language' is not added to the Vary header when using
    prefixed URLs.
    """
    def test_no_prefix_response(self):
        response = self.client.get('/not-prefixed/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.get('Vary'), 'Accept-Language')

    def test_en_redirect(self):
        response = self.client.get('/account/register/', HTTP_ACCEPT_LANGUAGE='en')
        self.assertRedirects(response, '/en/account/register/')
        self.assertFalse(response.get('Vary'))

        response = self.client.get(response['location'])
        self.assertEqual(response.status_code, 200)
        self.assertFalse(response.get('Vary'))


class URLRedirectWithoutTrailingSlashTests(URLTestCaseBase):
    """
    Tests the redirect when the requested URL doesn't end with a slash
    (`settings.APPEND_SLASH=True`).
    """
    def test_not_prefixed_redirect(self):
        response = self.client.get('/not-prefixed', HTTP_ACCEPT_LANGUAGE='en')
        self.assertRedirects(response, '/not-prefixed/', 301)

    def test_en_redirect(self):
        response = self.client.get('/account/register', HTTP_ACCEPT_LANGUAGE='en', follow=True)
        # target status code of 301 because of CommonMiddleware redirecting
        self.assertIn(('http://testserver/en/account/register/', 301), response.redirect_chain)
        self.assertRedirects(response, '/en/account/register/', 302)

        response = self.client.get('/prefixed.xml', HTTP_ACCEPT_LANGUAGE='en', follow=True)
        self.assertRedirects(response, '/en/prefixed.xml', 302)


class URLRedirectWithoutTrailingSlashSettingTests(URLTestCaseBase):
    """
    Tests the redirect when the requested URL doesn't end with a slash
    (`settings.APPEND_SLASH=False`).
    """
    @override_settings(APPEND_SLASH=False)
    def test_not_prefixed_redirect(self):
        response = self.client.get('/not-prefixed', HTTP_ACCEPT_LANGUAGE='en')
        self.assertEqual(response.status_code, 404)

    @override_settings(APPEND_SLASH=False)
    def test_en_redirect(self):
        response = self.client.get('/account/register-without-slash', HTTP_ACCEPT_LANGUAGE='en')
        self.assertRedirects(response, '/en/account/register-without-slash', 302)

        response = self.client.get(response['location'])
        self.assertEqual(response.status_code, 200)


class URLResponseTests(URLTestCaseBase):
    """
    Tests if the response has the right language-code.
    """
    def test_not_prefixed_with_prefix(self):
        response = self.client.get('/en/not-prefixed/')
        self.assertEqual(response.status_code, 404)

    def test_en_url(self):
        response = self.client.get('/en/account/register/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['content-language'], 'en')
        self.assertEqual(response.context['LANGUAGE_CODE'], 'en')

    def test_nl_url(self):
        response = self.client.get('/nl/profiel/registeren/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['content-language'], 'nl')
        self.assertEqual(response.context['LANGUAGE_CODE'], 'nl')

    def test_wrong_en_prefix(self):
        response = self.client.get('/en/profiel/registeren/')
        self.assertEqual(response.status_code, 404)

    def test_wrong_nl_prefix(self):
        response = self.client.get('/nl/account/register/')
        self.assertEqual(response.status_code, 404)

    def test_pt_br_url(self):
        response = self.client.get('/pt-br/conta/registre-se/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['content-language'], 'pt-br')
        self.assertEqual(response.context['LANGUAGE_CODE'], 'pt-br')


class URLTagTests(URLTestCaseBase):
    """
    Test if the language tag works.
    """
    def test_strings_only(self):
        t = Template("""{% load i18n %}
            {% language 'nl' %}{% url 'no-prefix-translated' %}{% endlanguage %}
            {% language 'pt-br' %}{% url 'no-prefix-translated' %}{% endlanguage %}""")
        self.assertEqual(t.render(Context({})).strip().split(),
                         ['/vertaald/', '/traduzidos/'])

    def test_context(self):
        ctx = Context({'lang1': 'nl', 'lang2': 'pt-br'})
        tpl = Template("""{% load i18n %}
            {% language lang1 %}{% url 'no-prefix-translated' %}{% endlanguage %}
            {% language lang2 %}{% url 'no-prefix-translated' %}{% endlanguage %}""")
        self.assertEqual(tpl.render(ctx).strip().split(),
                         ['/vertaald/', '/traduzidos/'])

    def test_args(self):
        tpl = Template("""{% load i18n %}
            {% language 'nl' %}{% url 'no-prefix-translated-slug' 'apo' %}{% endlanguage %}
            {% language 'pt-br' %}{% url 'no-prefix-translated-slug' 'apo' %}{% endlanguage %}""")
        self.assertEqual(tpl.render(Context({})).strip().split(),
                         ['/vertaald/apo/', '/traduzidos/apo/'])

    def test_kwargs(self):
        tpl = Template("""{% load i18n %}
            {% language 'nl'  %}{% url 'no-prefix-translated-slug' slug='apo' %}{% endlanguage %}
            {% language 'pt-br' %}{% url 'no-prefix-translated-slug' slug='apo' %}{% endlanguage %}""")
        self.assertEqual(tpl.render(Context({})).strip().split(),
                         ['/vertaald/apo/', '/traduzidos/apo/'])