1# -*- coding: utf-8 -*-
2from django.contrib.auth import get_user_model
3from django.template import Template
4from django.test import RequestFactory
5from django.test.utils import override_settings
6from django.urls import clear_url_caches
7
8from cms.api import create_page
9from cms.middleware.toolbar import ToolbarMiddleware
10from cms.models import Page, CMSPlugin
11from cms.test_utils.testcases import (CMSTestCase,
12                                      URL_CMS_PAGE_ADD,
13                                      URL_CMS_PAGE_CHANGE_TEMPLATE)
14from cms.toolbar.toolbar import CMSToolbar
15from cms.utils.conf import get_cms_setting
16
17overrides = dict(
18    LANGUAGE_CODE='en-us',
19    LANGUAGES=[],
20    CMS_LANGUAGES={},
21    USE_I18N=False,
22    ROOT_URLCONF='cms.test_utils.project.urls_no18n',
23    TEMPLATE_CONTEXT_PROCESSORS=[
24        'django.contrib.auth.context_processors.auth',
25        'django.contrib.messages.context_processors.messages',
26        'django.core.context_processors.debug',
27        'django.core.context_processors.request',
28        'django.core.context_processors.media',
29        'django.core.context_processors.csrf',
30        'cms.context_processors.cms_settings',
31        'sekizai.context_processors.sekizai',
32        'django.core.context_processors.static',
33    ],
34    MIDDLEWARE=[
35        'django.contrib.sessions.middleware.SessionMiddleware',
36        'django.contrib.auth.middleware.AuthenticationMiddleware',
37        'django.contrib.messages.middleware.MessageMiddleware',
38        'django.middleware.csrf.CsrfViewMiddleware',
39        'django.middleware.common.CommonMiddleware',
40        'django.middleware.cache.FetchFromCacheMiddleware',
41        'cms.middleware.user.CurrentUserMiddleware',
42        'cms.middleware.page.CurrentPageMiddleware',
43        'cms.middleware.toolbar.ToolbarMiddleware',
44    ]
45)
46
47
48@override_settings(**overrides)
49class TestNoI18N(CMSTestCase):
50
51    def setUp(self):
52        clear_url_caches()
53        super(TestNoI18N, self).setUp()
54
55    def tearDown(self):
56        super(TestNoI18N, self).tearDown()
57        clear_url_caches()
58
59    def get_page_request(self, page, user, path=None, edit=False, lang_code='en', disable=False):
60        path = path or page and page.get_absolute_url()
61        if edit:
62            path += '?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')
63        request = RequestFactory().get(path)
64        request.session = {}
65        request.user = user
66        request.LANGUAGE_CODE = lang_code
67        request.GET = request.GET.copy()
68
69        if edit:
70            request.GET['edit'] = None
71        else:
72            request.GET['edit_off'] = None
73
74        if disable:
75            request.GET[get_cms_setting('CMS_TOOLBAR_URL__DISABLE')] = None
76        request.current_page = page
77        mid = ToolbarMiddleware()
78        mid.process_request(request)
79        if hasattr(request, 'toolbar'):
80            request.toolbar.populate()
81        return request
82
83    def test_language_chooser(self):
84        # test simple language chooser with default args
85        create_page("home", template="col_two.html", language="en-us", published=True)
86        context = self.get_context(path="/")
87        del context['request'].LANGUAGE_CODE
88        tpl = Template("{% load menu_tags %}{% language_chooser %}")
89        tpl.render(context)
90        self.assertEqual(len(context['languages']), 1)
91        # try a different template and some different args
92        tpl = Template("{% load menu_tags %}{% language_chooser 'menu/test_language_chooser.html' %}")
93        tpl.render(context)
94        self.assertEqual(context['template'], 'menu/test_language_chooser.html')
95        tpl = Template("{% load menu_tags %}{% language_chooser 'short' 'menu/test_language_chooser.html' %}")
96        tpl.render(context)
97        self.assertEqual(context['template'], 'menu/test_language_chooser.html')
98        for lang in context['languages']:
99            self.assertEqual(*lang)
100
101    def test_page_language_url(self):
102        with self.settings(ROOT_URLCONF='cms.test_utils.project.urls_no18n'):
103            create_page("home", template="col_two.html", language="en-us", published=True)
104            path = "/"
105            context = self.get_context(path=path)
106            del context['request'].LANGUAGE_CODE
107            context['request'].urlconf = "cms.test_utils.project.urls_no18n"
108            tpl = Template("{%% load menu_tags %%}{%% page_language_url '%s' %%}" % "en-us")
109            url = tpl.render(context)
110            self.assertEqual(url, "%s" % path)
111
112    def test_url_redirect(self):
113        overrides = dict(
114            USE_I18N=True,
115            CMS_LANGUAGES={1: []},
116            LANGUAGES=[('en-us', 'English')],
117            MIDDLEWARE=[
118                'django.contrib.sessions.middleware.SessionMiddleware',
119                'django.contrib.auth.middleware.AuthenticationMiddleware',
120                'django.contrib.messages.middleware.MessageMiddleware',
121                'django.middleware.csrf.CsrfViewMiddleware',
122                'django.middleware.locale.LocaleMiddleware',
123                'django.middleware.common.CommonMiddleware',
124                'django.middleware.cache.FetchFromCacheMiddleware',
125                'cms.middleware.user.CurrentUserMiddleware',
126                'cms.middleware.page.CurrentPageMiddleware',
127                'cms.middleware.toolbar.ToolbarMiddleware',
128            ]
129        )
130        with self.settings(**overrides):
131            homepage = create_page(
132                "home",
133                template="col_two.html",
134                language="en-us",
135                published=True,
136                redirect='/foobar/',
137            )
138            homepage.set_as_homepage()
139            response = self.client.get('/', follow=False)
140            self.assertTrue(response['Location'].endswith("/foobar/"))
141
142    def test_plugin_add_edit(self):
143        page_data = {
144            'title': 'test page 1',
145            'slug': 'test-page1',
146            'language': "en-us",
147            'parent': '',
148            'site': 1,
149        }
150        # required only if user haves can_change_permission
151        self.super_user = self._create_user("test", True, True)
152        self.client.login(username=getattr(self.super_user, get_user_model().USERNAME_FIELD),
153                          password=getattr(self.super_user, get_user_model().USERNAME_FIELD))
154
155        self.client.post(URL_CMS_PAGE_ADD[3:], page_data)
156        page = Page.objects.drafts().first()
157        self.client.post(URL_CMS_PAGE_CHANGE_TEMPLATE[3:] % page.pk, page_data)
158        page = Page.objects.drafts().first()
159        placeholder = page.placeholders.latest('id')
160        data = {'name': 'Hello', 'external_link': 'http://www.example.org/'}
161        add_url = self.get_add_plugin_uri(placeholder, 'LinkPlugin', 'en-us')
162
163        response = self.client.post(add_url, data)
164        self.assertEqual(response.status_code, 200)
165        created_plugin = CMSPlugin.objects.all()[0]
166        # now edit the plugin
167        edit_url = self.get_change_plugin_uri(created_plugin)
168        response = self.client.get(edit_url)
169        self.assertEqual(response.status_code, 200)
170        data['name'] = 'Hello World'
171        response = self.client.post(edit_url, data)
172        self.assertEqual(response.status_code, 200)
173        Link = self.get_plugin_model('LinkPlugin')
174        link = Link.objects.get(pk=created_plugin.pk)
175        self.assertEqual("Hello World", link.name)
176
177    def test_toolbar_no_locale(self):
178        page = create_page('test', 'nav_playground.html', 'en-us', published=True)
179        sub = create_page('sub', 'nav_playground.html', 'en-us', published=True, parent=page)
180        # loads the urlconf before reverse below
181        sub.get_absolute_url('en-us')
182        request = self.get_page_request(sub, self.get_superuser(), edit=True)
183        del request.LANGUAGE_CODE
184        toolbar = CMSToolbar(request)
185        toolbar.set_object(sub)
186        self.assertEqual(toolbar.get_object_public_url(), '/test/sub/')
187