Beispiel #1
0
    def test_copy_filled_placeholder_force_copy(self):
        """
        If an existing title in the target language has plugins in a placeholder
        and the command is called with *force-copy*, the plugins are copied on
        top of the existing one
        """
        site = 1
        number_start_plugins = CMSPlugin.objects.all().count()

        # create an empty title language
        root_page = Page.objects.on_site(site).get_home()
        create_title("de", "root page de", root_page)
        ph = root_page.placeholders.get(slot="body")
        add_plugin(ph, "TextPlugin", "de", body="Hello World")

        root_plugins = CMSPlugin.objects.filter(placeholder=ph)
        text_de_orig, _ = root_plugins.get(language='de', plugin_type='TextPlugin').get_plugin_instance()

        out = StringIO()
        management.call_command(
            'cms', 'copy', 'lang', '--from-lang=en', '--to-lang=de', '--force', interactive=False,
            stdout=out
        )

        CMSPlugin.objects.filter(placeholder=root_page.placeholders.get(slot="body"))

        self.assertEqual(CMSPlugin.objects.filter(language='en').count(), number_start_plugins)
        # we have an existing plugin in one placeholder, so we have one more
        self.assertEqual(CMSPlugin.objects.filter(language='de').count(), number_start_plugins+1)
Beispiel #2
0
    def setUp(self):
        from django.core.cache import cache
        super(PlaceholderCacheTestCase, self).setUp()
        cache.clear()

        self.page = create_page(
            'en test page', 'nav_playground.html', 'en', published=True)
        # Now create and publish as 'de' title
        create_title('de', "de test page", self.page)
        self.page.publish('de')

        self.placeholder = self.page.placeholders.filter(slot="body")[0]
        plugin_pool.register_plugin(VaryCacheOnPlugin)
        add_plugin(self.placeholder, 'TextPlugin', 'en', body='English')
        add_plugin(self.placeholder, 'TextPlugin', 'de', body='Deutsch')
        add_plugin(self.placeholder, 'VaryCacheOnPlugin', 'en')
        add_plugin(self.placeholder, 'VaryCacheOnPlugin', 'de')

        self.en_request = self.get_request('/en/')
        self.en_request.current_page = Page.objects.get(pk=self.page.pk)

        self.en_us_request = self.get_request('/en/')
        self.en_us_request.META['HTTP_COUNTRY_CODE'] = 'US'

        self.en_uk_request = self.get_request('/en/')
        self.en_uk_request.META['HTTP_COUNTRY_CODE'] = 'UK'

        self.de_request = self.get_request('/de/')
        self.de_request.current_page = Page.objects.get(pk=self.page.pk)
Beispiel #3
0
    def setUp(self):
        self.template = get_cms_setting('TEMPLATES')[0][0]
        self.language = settings.LANGUAGES[0][0]
        self.root_page = api.create_page(
            'root page',
            self.template,
            self.language,
            published=True
        )
        self.app_config = ThingsConfig.objects.create(
            namespace='things', app_title='Things')
        self.page = api.create_page(
            'Things',
            self.template,
            self.language,
            published=True,
            parent=self.root_page,
            apphook='ThingsApp',
            apphook_namespace=self.app_config.namespace
        )
        self.placeholder = self.page.placeholders.all()[0]
        self.request = self.get_request('en')

        for page in [self.root_page, self.page]:
            for language, _ in settings.LANGUAGES[1:]:
                api.create_title(language, page.get_slug(), page)
                page.publish(language)

        super(TestToolbar, self).setUp()
Beispiel #4
0
    def test_command_line_publishes_selected_language_drafts(self):
        # we need to create a superuser (the db is empty)
        get_user_model().objects.create_superuser('djangocms', '*****@*****.**', '123456')

        page = create_page("en title", "nav_playground.html", "en")
        title = create_title('de', 'de title', page)
        title.published = False
        title.save()
        title = create_title('fr', 'fr title', page)
        title.published = False
        title.save()

        pages_from_output = 0
        published_from_output = 0

        with StdoutOverride() as buffer:
            # Now we don't expect it to raise, but we need to redirect IO
            call_command('cms', 'publisher_publish', language='de', include_unpublished=True)
            lines = buffer.getvalue().split('\n') #NB: readlines() doesn't work

        for line in lines:
            if 'Total' in line:
                pages_from_output = int(line.split(':')[1])
            elif 'Published' in line:
                published_from_output = int(line.split(':')[1])

        self.assertEqual(pages_from_output, 1)
        self.assertEqual(published_from_output, 1)

        self.assertEqual(Page.objects.public().count(), 1)
        public = Page.objects.public()[0]
        languages = sorted(public.title_set.values_list('language', flat=True))
        self.assertEqual(languages, ['de'])
Beispiel #5
0
 def create_root_page(self):
     root_page = api.create_page(
         'root page', self.template, self.language, published=True)
     api.create_title('de', 'root page de', root_page)
     root_page.publish('en')
     root_page.publish('de')
     return root_page.reload()
Beispiel #6
0
    def test_apphook_on_root(self):

        with SettingsOverride(ROOT_URLCONF="cms.test_utils.project.urls_for_apphook_tests"):
            apphook_pool.clear()
            superuser = get_user_model().objects.create_superuser("admin", "*****@*****.**", "admin")
            page = create_page(
                "apphooked-page", "nav_playground.html", "en", created_by=superuser, published=True, apphook="SampleApp"
            )
            blank_page = create_page(
                "not-apphooked-page",
                "nav_playground.html",
                "en",
                created_by=superuser,
                published=True,
                apphook="",
                slug="blankapp",
            )
            english_title = page.title_set.all()[0]
            self.assertEqual(english_title.language, "en")
            create_title("de", "aphooked-page-de", page)
            self.assertTrue(page.publish("en"))
            self.assertTrue(page.publish("de"))
            self.assertTrue(blank_page.publish("en"))
            with force_language("en"):
                response = self.client.get(self.get_pages_root())
            self.assertTemplateUsed(response, "sampleapp/home.html")

            response = self.client.get("/en/blankapp/")
            self.assertTemplateUsed(response, "nav_playground.html")

            apphook_pool.clear()
Beispiel #7
0
    def setUp(self):
        super(TestEventViews, self).setUp()
        root_page = self.create_root_page()
        page = api.create_page(
            "Events en",
            self.template,
            "en",
            published=True,
            parent=root_page,
            apphook="EventListAppHook",
            apphook_namespace=self.app_config.namespace,
            publication_date=tz_datetime(2014, 1, 8),
        )
        api.create_title("de", "Events de", page)
        page.publish("en")
        page.publish("de")
        page.reload()
        # aldryn apphook reload needs some time to reload test
        # server implementation so we will provide some time for him
        # otherwise test_event_detail_view is too quick, and fails.
        with override("en"):
            page_url = page.get_absolute_url()
        self.client.get(page_url)

        self.list_view_year_month = ("2015", "02")
Beispiel #8
0
    def setUp(self):
        super(CMSRequestBasedTest, self).setUp()
        self.template = get_cms_setting('TEMPLATES')[0][0]
        self.language = settings.LANGUAGES[0][0]
        self.root_page = api.create_page(
            'root page',
            self.template,
            self.language,
            published=True
        )
        self.app_config = FaqConfig.objects.create(namespace='aldryn_faq',
                                                   permalink_type='Bp',
                                                   non_permalink_handling=301)
        self.page = api.create_page(
            'faq',
            self.template,
            self.language,
            published=True,
            parent=self.root_page,
            apphook='FaqApp',
            apphook_namespace=self.app_config.namespace
        )
        self.placeholder = self.page.placeholders.all()[0]

        for page in [self.root_page, self.page]:
            for language, _ in settings.LANGUAGES[1:]:
                api.create_title(language, page.get_slug(), page)
                page.publish(language)
Beispiel #9
0
    def test_plugins_discarded_with_language_fallback(self):
        """
        Tests side effect of language fallback: if fallback enabled placeholder
        existed, it discards all other existing plugins
        """
        page_en = create_page('page_en', 'col_two.html', 'en')
        create_title("de", "page_de", page_en)
        placeholder_sidebar_en = page_en.placeholders.get(slot='col_sidebar')
        placeholder_en = page_en.placeholders.get(slot='col_left')
        add_plugin(placeholder_sidebar_en, TextPlugin, 'en', body='en body')

        context_en = SekizaiContext()
        context_en['request'] = self.get_request(language="en", page=page_en)

        conf = {
            'col_left': {
                'language_fallback': True,
            },
        }
        with self.settings(CMS_PLACEHOLDER_CONF=conf):
            # call assign plugins first, as this is what is done in real cms life
            # for all placeholders in a page at once
            assign_plugins(context_en['request'],
                           [placeholder_sidebar_en, placeholder_en], 'col_two.html')
            # if the normal, non fallback enabled placeholder still has content
            content_en = _render_placeholder(placeholder_sidebar_en, context_en)
            self.assertRegexpMatches(content_en, "^en body$")

            # remove the cached plugins instances
            del(placeholder_sidebar_en._plugins_cache)
            cache.clear()
Beispiel #10
0
    def test_detail_view_fallback_language(self):
        '''
        Ask for a page in elvish (doesn't exist), and assert that it fallsback
        to English
        '''
        page = create_page("page1", "nav_playground.html", "en")
        with SettingsOverride(TEMPLATE_CONTEXT_PROCESSORS=[],
            CMS_LANGUAGES={
                1:[
                    {'code':'x-klingon', 'name':'Klingon', 'public':True, 'fallbacks':[]},
                    {'code':'x-elvish', 'name':'Elvish', 'public':True, 'fallbacks':['x-klingon', 'en', ]},
                    ]},
            ):
            create_title("x-klingon", "futla ak", page, slug=page.get_slug())
            page.publish()
            from cms.views import details

            request = AttributeObject(
                REQUEST={'language': 'x-elvish'},
                GET=[],
                session={},
                path='/',
                current_page=None,
                method='GET',
                COOKIES={},
                META={},
                user=User(),
            )

            response = details(request, '')
            self.assertTrue(isinstance(response, HttpResponseRedirect))
Beispiel #11
0
    def test_get_apps(self):
        """
        Check that urlconf are dynamically loaded according to the different page the apphook is
        attached to
        """
        titles = self.create_base_structure('VariableUrlsApp', ['en', 'de'])
        titles[0].page.reverse_id = 'page1'
        titles[0].page.save()

        self.reload_urls()

        # only one urlconf is configured given that only one page is created
        with force_language('de'):
            reverse('extra_first')
            with self.assertRaises(NoReverseMatch):
                reverse('sample2-root')

        self.reload_urls()
        self.apphook_clear()

        page2 = create_page('page2', 'nav_playground.html',
                            'en', created_by=self.superuser, published=True,
                            parent=titles[0].page.parent,
                            apphook='VariableUrlsApp', reverse_id='page2')
        create_title('de', 'de_title', page2, slug='slug')
        page2.publish('de')

        self.reload_urls()

        with force_language('de'):
            reverse('sample2-root')
            reverse('extra_first')

        self.apphook_clear()
Beispiel #12
0
    def test_command_line_publishes_selected_language_drafts(self):
        # we need to create a superuser (the db is empty)
        get_user_model().objects.create_superuser("djangocms", "*****@*****.**", "123456")

        page = create_page("en title", "nav_playground.html", "en")
        title = create_title("de", "de title", page)
        title.published = False
        title.save()
        title = create_title("fr", "fr title", page)
        title.published = False
        title.save()

        pages_from_output = 0
        published_from_output = 0

        with StdoutOverride() as buffer:
            # Now we don't expect it to raise, but we need to redirect IO
            call_command("cms", "publisher_publish", language="de", include_unpublished=True)
            lines = buffer.getvalue().split("\n")  # NB: readlines() doesn't work

        for line in lines:
            if "Total" in line:
                pages_from_output = int(line.split(":")[1])
            elif "Published" in line:
                published_from_output = int(line.split(":")[1])

        self.assertEqual(pages_from_output, 1)
        self.assertEqual(published_from_output, 1)

        self.assertEqual(Page.objects.public().count(), 1)
        public = Page.objects.public()[0]
        languages = sorted(public.title_set.values_list("language", flat=True))
        self.assertEqual(languages, ["de"])
Beispiel #13
0
    def _create_page(cls, page, lang, auto_title, cms_app=None, parent=None, namespace=None):
        """
        Create a single page or titles

        :param page: Page instance
        :param lang: language code
        :param auto_title: title text for the newly created title
        :param cms_app: Apphook Class to be attached to the page
        :param parent: parent page (None when creating the home page)
        :param namespace: application instance name (as provided to the ApphookConfig)

        :return: draft copy of the created page
        """
        from cms.api import create_page, create_title
        from cms.utils.conf import get_templates

        default_template = get_templates()[0][0]
        if page is None:
            page = create_page(
                auto_title, language=lang, parent=parent,
                template=default_template, in_navigation=True, published=True
            )
            page.application_urls = cms_app
            page.application_namespace = namespace
            page.save()
            page.publish(lang)
        elif lang not in page.get_languages():
            create_title(
                language=lang, title=auto_title, page=page
            )
            page.publish(lang)
        return page.get_draft_object()
Beispiel #14
0
    def create_page(self, title=None, slug=None, namespace=None):

        if namespace is None:
            namespace = self.app_config.namespace

        if title is None:
            title = 'Jobs'

        if slug is None:
            slug = 'jobs-app'

        page = api.create_page(
            title='{0} en'.format(title),
            slug='{0}-en'.format(slug),
            template=self.template,
            language=self.language,
            published=True,
            parent=self.root_page,
            apphook='JobsApp',
            apphook_namespace=namespace)
        api.create_title(
            'de', '{0} de'.format(title), page, slug='{0}-de'.format(slug))
        page.publish('en')
        page.publish('de')
        # unfortunately aphook reload doesn't restart server fast,
        # so we do an empty request otherwise tests might
        # fail because it can't get correct url
        with override('en'):
            empty_url = page.get_absolute_url()
        self.client.get(empty_url)
        return page.reload()
Beispiel #15
0
    def test_get_page_for_apphook_on_preview_or_edit(self):

        if get_user_model().USERNAME_FIELD == "email":
            superuser = get_user_model().objects.create_superuser("admin", "*****@*****.**", "*****@*****.**")
        else:
            superuser = get_user_model().objects.create_superuser("admin", "*****@*****.**", "admin")

        page = create_page("home", "nav_playground.html", "en", created_by=superuser, published=True, apphook=APP_NAME)
        create_title("de", page.get_title(), page)
        page.publish("en")
        page.publish("de")
        public_page = page.get_public_object()

        with self.login_user_context(superuser):
            with force_language("en"):
                path = reverse("sample-settings")
                request = self.get_request(path + "?edit")
                request.LANGUAGE_CODE = "en"
                attached_to_page = applications_page_check(request, path=path[1:])  # strip leading slash
                self.assertEqual(attached_to_page.pk, public_page.pk)
            with force_language("de"):
                path = reverse("sample-settings")
                request = self.get_request(path + "?edit")
                request.LANGUAGE_CODE = "de"
                attached_to_page = applications_page_check(request, path=path[1:])  # strip leading slash
                self.assertEqual(attached_to_page.pk, public_page.pk)
Beispiel #16
0
    def test_get_i18n_apphook_with_explicit_current_app(self):
        self.apphook_clear()
        titles = self.create_base_structure(NS_APP_NAME, ['en', 'de'], 'instance_1')
        public_de_title = titles[1]
        de_title = Title.objects.get(page=public_de_title.page.publisher_draft, language="de")
        de_title.slug = "de"
        de_title.save()
        de_title.page.publish('de')

        self.reload_urls()
        self.apphook_clear()

        page2 = create_page("page2", "nav_playground.html",
                            "en", created_by=self.superuser, published=True, parent=de_title.page.parent,
                            apphook=NS_APP_NAME,
                            apphook_namespace="instance_2")
        create_title("de", "de_title", page2, slug="slug")
        page2.publish('de')
        clear_app_resolvers()
        clear_url_caches()

        if APP_MODULE in sys.modules:
            del sys.modules[APP_MODULE]

        self.reload_urls()
        with force_language("de"):
            reverse('namespaced_app_ns:current-app', current_app="instance_1")
            reverse('namespaced_app_ns:current-app', current_app="instance_2")
            reverse('namespaced_app_ns:current-app')
        with force_language("en"):
            reverse('namespaced_app_ns:current-app', current_app="instance_1")
            reverse('namespaced_app_ns:current-app', current_app="instance_2")
            reverse('namespaced_app_ns:current-app')
        self.apphook_clear()
Beispiel #17
0
    def get_or_create_page(self, base_title=None, languages=None):
        """Creates a page with a given title, or, if it already exists, just
        retrieves and returns it."""
        from cms.api import create_page, create_title
        if not base_title:
            # No title? Create one.
            base_title = self.rand_str(prefix="page", length=8)
        if not languages:
            # If no langs supplied, use'em all
            languages = self.languages
        # If there is already a page with this title, just return it.
        try:
            page_title = Title.objects.get(title=base_title)
            return page_title.page.get_draft_object()
        except:
            pass

        # No? Okay, create one.
        page = create_page(base_title, 'fullwidth.html', language=languages[0])
        # If there are multiple languages, create the translations
        if len(languages) > 1:
            for lang in languages[1:]:
                title_lang = "{0}-{1}".format(base_title, lang)
                create_title(language=lang, title=title_lang, page=page)
                page.publish(lang)
        return page.get_draft_object()
Beispiel #18
0
    def test_hide_untranslated(self):
        TESTLANG = get_primary_lanaguage()
        TESTLANG2 = get_secondary_lanaguage()
        page = create_page("mlpage-%s" % TESTLANG, "nav_playground.html", TESTLANG)
        create_title(TESTLANG2, "mlpage-%s" % TESTLANG2, page, slug=page.get_slug())
        page2 = create_page("mlpage-2-%s" % TESTLANG, "nav_playground.html", TESTLANG, parent=page)
        page.publish(TESTLANG)
        page.publish(TESTLANG2)
        page2.publish(TESTLANG)

        menu = CMSMenu()
        lang_settings = copy.deepcopy(get_cms_setting('LANGUAGES'))

        request_1 = self.get_request('/%s/' % TESTLANG, TESTLANG)
        request_2 = self.get_request('/%s/' % TESTLANG2, TESTLANG2)

        lang_settings[1][1]['hide_untranslated'] = False
        with SettingsOverride(CMS_LANGUAGES=lang_settings):
            list_1 = [node.id for node in menu.get_nodes(request_1)]
            list_2 = [node.id for node in menu.get_nodes(request_2)]
            self.assertEqual(list_1, list_2)
            self.assertEqual(len(list_1), 2)

        lang_settings[1][1]['hide_untranslated'] = True
        with SettingsOverride(CMS_LANGUAGES=lang_settings):
            list_1 = [node.id for node in menu.get_nodes(request_1)]
            list_2 = [node.id for node in menu.get_nodes(request_2)]
            self.assertNotEqual(list_1, list_2)
            self.assertEqual(len(list_2), 1)
            self.assertEqual(len(list_1), 2)
Beispiel #19
0
    def test_plugins_discarded_with_language_fallback(self):
        """
        Tests side effect of language fallback: if fallback enabled placeholder
        existed, it discards all other existing plugins
        """
        page_en = create_page("page_en", "col_two.html", "en")
        create_title("de", "page_de", page_en)
        placeholder_sidebar_en = page_en.placeholders.get(slot="col_sidebar")
        placeholder_en = page_en.placeholders.get(slot="col_left")
        add_plugin(placeholder_sidebar_en, TextPlugin, "en", body="en body")

        class NoPushPopContext(Context):
            def push(self):
                pass

            pop = push

        context_en = NoPushPopContext()
        context_en["request"] = self.get_request(language="en", page=page_en)

        conf = {"col_left": {"language_fallback": True}}
        with SettingsOverride(CMS_PLACEHOLDER_CONF=conf):
            # call assign plugins first, as this is what is done in real cms life
            # for all placeholders in a page at once
            assign_plugins(context_en["request"], [placeholder_sidebar_en, placeholder_en], "col_two.html")
            # if the normal, non fallback enabled placeholder still has content
            content_en = render_placeholder(placeholder_sidebar_en, context_en)
            self.assertRegexpMatches(content_en, "^en body$")

            # remove the cached plugins instances
            del (placeholder_sidebar_en._plugins_cache)
            cache.clear()
Beispiel #20
0
    def test_setup_filled(self):

        # Tests starts with no page and no config
        self.assertFalse(Page.objects.exists())
        self.assertFalse(BlogConfig.objects.exists())

        langs = get_language_list()
        home = None
        for lang in langs:
            with override(lang):
                if not home:
                    home = create_page(
                        'a new home', language=lang,
                        template='blog.html', in_navigation=True, published=True
                    )
                else:
                    create_title(
                        language=lang, title='a new home', page=home
                    )
                    home.publish(lang)

        # importing cms_app triggers the auto setup
        from djangocms_blog import cms_app  # NOQA

        # Home and blog, published and draft
        self.assertEqual(Page.objects.count(), 4)
        self.assertEqual(BlogConfig.objects.count(), 1)

        home = Page.objects.get_home()
        for lang in langs:
            self.assertEqual(home.get_title(lang), 'a new home')
Beispiel #21
0
 def create_pages(source, languages):
     """
     Build pages according to the pages data provided by :py:meth:`get_pages_data`
     and returns the list of the draft version of each
     """
     from cms.api import create_page, create_title
     pages = OrderedDict()
     has_apphook = False
     for page_data in source:
         main_data = deepcopy(page_data[languages[0]])
         if 'publish' in main_data:
             main_data['published'] = main_data.pop('publish')
         main_data['language'] = languages[0]
         if main_data.get('parent', None):
             main_data['parent'] = pages[main_data['parent']]
         page = create_page(**main_data)
         has_apphook = has_apphook or 'apphook' in main_data
         for lang in languages[1:]:
             if lang in page_data:
                 publish = False
                 title_data = deepcopy(page_data[lang])
                 if 'publish' in title_data:
                     publish = title_data.pop('publish')
                 if 'published' in title_data:
                     publish = title_data.pop('published')
                 title_data['language'] = lang
                 title_data['page'] = page
                 create_title(**title_data)
                 if publish:
                     page.publish(lang)
         page = page.get_draft_object()
         pages[page.get_slug(languages[0])] = page
     if has_apphook:
         reload_urls(settings, cms_apps=True)
     return list(pages.values())
Beispiel #22
0
    def test_detail_view_404_when_no_language_is_found(self):
        User = auth.get_user_model()
        page = create_page("page1", "nav_playground.html", "en")
        create_title("de", page.get_title(), page, slug=page.get_slug())
        page.publish()

        with SettingsOverride(TEMPLATE_CONTEXT_PROCESSORS=[],
            CMS_LANGUAGES={
                1:[
                    {'code':'x-klingon', 'name':'Klingon','public':True, 'fallbacks':[]},
                    {'code':'x-elvish', 'name':'Elvish', 'public':True, 'fallbacks':[]},
               ]}):
            from cms.views import details
            request = AttributeObject(
                REQUEST={'language': 'x-elvish'},
                GET=[],
                session={},
                path='/',
                current_page=None,
                method='GET',
                COOKIES={},
                META={},
                user=User(),
            )
            self.assertRaises(Http404, details, request, '')
Beispiel #23
0
    def test_get_page_for_apphook_on_preview_or_edit(self):
        if get_user_model().USERNAME_FIELD == 'email':
            superuser = get_user_model().objects.create_superuser('admin', '*****@*****.**', '*****@*****.**')
        else:
            superuser = get_user_model().objects.create_superuser('admin', '*****@*****.**', 'admin')

        page = create_page("home", "nav_playground.html", "en",
                           created_by=superuser, published=True, apphook=APP_NAME)
        create_title('de', page.get_title(), page)
        page.publish('en')
        page.publish('de')
        page.save()
        public_page = page.get_public_object()

        with self.login_user_context(superuser):
            with force_language("en"):
                path = reverse('sample-settings')
                request = self.get_request(path + '?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON'))
                request.LANGUAGE_CODE = 'en'
                attached_to_page = applications_page_check(request, path=path[1:])  # strip leading slash
                response = self.client.get(path+"?edit")
                self.assertContains(response, '?redirect=')
            with force_language("de"):
                path = reverse('sample-settings')
                request = self.get_request(path + '?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON'))
                request.LANGUAGE_CODE = 'de'
                attached_to_page = applications_page_check(request, path=path[1:])  # strip leading slash
                self.assertEqual(attached_to_page.pk, public_page.pk)
Beispiel #24
0
    def test_command_line_publish_multiple_languages_check_count(self):
        """
        Publishing one page with multiple languages still counts
        as one page. This test case checks whether it works
        as expected.
        """
        # we need to create a superuser (the db is empty)
        get_user_model().objects.create_superuser('djangocms', '*****@*****.**', '123456')

        # Now, let's create a page with 2 languages.
        page = create_page("en title", "nav_playground.html", "en", published=True)
        create_title("de", "de title", page)
        page.publish("de")

        pages_from_output = 0
        published_from_output = 0

        with StdoutOverride() as buffer:
            # Now we don't expect it to raise, but we need to redirect IO
            call_command('cms', 'publisher_publish')
            lines = buffer.getvalue().split('\n') #NB: readlines() doesn't work

        for line in lines:
            if 'Total' in line:
                pages_from_output = int(line.split(':')[1])
            elif 'Published' in line:
                published_from_output = int(line.split(':')[1])

        self.assertEqual(pages_from_output, 1)
        self.assertEqual(published_from_output, 1)
Beispiel #25
0
    def test_session_language(self):
        page = api.create_page("home", "nav_playground.html", "en", published=True)
        api.create_title('fr', "home", page)
        page.publish('fr')
        page.publish('en')
        response = self.client.get('/')
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, '/en/')
        engine = import_module(settings.SESSION_ENGINE)
        store = engine.SessionStore()
        store.save()  # we need to make load() work, or the cookie is worthless
        self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key

        #   ugly and long set of session
        session = self.client.session
        session[LANGUAGE_SESSION_KEY] = 'fr'
        session.save()
        response = self.client.get('/')
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, '/fr/')
        self.client.get('/en/')
        self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], 'en')
        response = self.client.get('/')
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, '/en/')
Beispiel #26
0
    def test_calendar_plugin_with_not_existing_ns(self, timezone_mock):
        timezone_mock.now.return_value = tz_datetime(2014, 1, 2)
        self.create_base_pages()
        new_config = EventsConfig.objects.create(namespace='new_namespace')
        page = api.create_page('Plugin test en', self.template, 'en',
                               published=True, slug='plugin-test-en')
        api.create_title('de', 'Plugin test de', page)
        ph = page.placeholders.get(slot='content')
        api.add_plugin(ph, 'CalendarPlugin', 'en', app_config=new_config)
        api.add_plugin(ph, 'CalendarPlugin', 'de', app_config=new_config)
        page.publish('en')
        page.publish('de')

        with force_language('en'):
            event = Event.objects.create(
                title='Test event namespace',
                slug='test-event-namespace',
                start_date=tz_datetime(2014, 1, 10),
                publish_at=tz_datetime(2014, 1, 1),
                app_config=new_config
            )
        event.create_translation(
            'de',
            title='Test event namespace de',
            slug='test-event-namespace-de')
        for language in ('en', 'de'):
            page_url = page.get_absolute_url(language)
            response = self.client.get(page_url)
            self.assertEqual(response.status_code, 200)
Beispiel #27
0
def create_essential_pages(page_publisher):
    languages = [entry[0] for entry in settings.LANGUAGES]

    if not Page.objects.count():
        create_page(
            title='Home',
            template='cms/content-types/homepage.html',
            language=languages[0],
            published=True
        )
        # Having the Home page in all languages is not essential.

    if not Page.objects.filter(reverse_id='search-results').exists():
        search_page = create_page(
            title='Search',
            template='cms/content-types/page.html',
            language=languages[0],
            apphook='AldrynSearchApphook',
            reverse_id='search-results',
            published=True
        )
        # The search results page must exist in all languages.
        for lang in languages[1:]:
            create_title(language=lang, title='Search', page=search_page)
            publish_page(page=search_page, user=page_publisher, language=lang)
Beispiel #28
0
    def test_copy_existing_title(self):
        """
        Even if a title already exists the copy is successfull, the original
        title remains untouched
        """
        site = 1
        number_start_plugins = CMSPlugin.objects.all().count()

        # create an empty title language
        root_page = Page.objects.on_site(site).get_home()
        create_title("de", "root page de", root_page)

        out = StringIO()
        management.call_command(
            'cms', 'copy', 'lang', '--from-lang=en', '--to-lang=de', interactive=False, stdout=out
        )
        pages = Page.objects.on_site(site).drafts()
        for page in pages:
            self.assertEqual(set((u'en', u'de')), set(page.get_languages()))

        # Original Title untouched
        self.assertEqual("root page de", Page.objects.on_site(site).get_home().get_title("de"))

        # Plugins still copied
        self.assertEqual(CMSPlugin.objects.all().count(), number_start_plugins*2)
        self.assertEqual(CMSPlugin.objects.filter(language='en').count(), number_start_plugins)
        self.assertEqual(CMSPlugin.objects.filter(language='de').count(), number_start_plugins)
Beispiel #29
0
    def test_copy_existing_title(self):
        """
        Even if a title already exists the copy is successfull, the original
        title remains untouched
        """
        site = 1
        number_start_plugins = CMSPlugin.objects.all().count()

        # create an empty title language
        root_page = Page.objects.on_site(site).get_home()
        create_title("de", "root page de", root_page)

        out = StringIO()
        command = cms.Command()
        command.stdout = out
        command.handle("copy-lang", "en", "de")
        pages = Page.objects.on_site(site).drafts()
        for page in pages:
            self.assertEqual(set((u'en', u'de')), set(page.get_languages()))

        # Original Title untouched
        self.assertEqual("root page de", Page.objects.on_site(site).get_home().get_title("de"))

        # Plugins still copied
        self.assertEqual(CMSPlugin.objects.all().count(), number_start_plugins*2)
        self.assertEqual(CMSPlugin.objects.filter(language='en').count(), number_start_plugins)
        self.assertEqual(CMSPlugin.objects.filter(language='de').count(), number_start_plugins)
    def test_show_placeholder_lang_parameter(self):
        from django.core.cache import cache

        cache.clear()
        page = create_page('Test', 'col_two.html', 'en')
        create_title('fr', 'Fr Test', page)
        placeholder = page.placeholders.all()[0]
        add_plugin(placeholder, TextPlugin, 'en', body='<b>En Test</b>')
        add_plugin(placeholder, TextPlugin, 'fr', body='<b>Fr Test</b>')

        request = RequestFactory().get('/')
        request.user = AnonymousUser()
        request.current_page = page

        template = "{% load cms_tags sekizai_tags %}{% show_placeholder slot page 'en' 1 %}{% render_block 'js' %}"
        output = self.render_template_obj(template, {'page': page, 'slot': placeholder.slot}, request)
        self.assertIn('<b>En Test</b>', output)

        template = "{% load cms_tags sekizai_tags %}{% show_placeholder slot page 'fr' 1 %}{% render_block 'js' %}"
        output = self.render_template_obj(template, {'page': page, 'slot': placeholder.slot}, request)
        self.assertIn('<b>Fr Test</b>', output)

        # Cache is now primed for both languages
        template = "{% load cms_tags sekizai_tags %}{% show_placeholder slot page 'en' 1 %}{% render_block 'js' %}"
        output = self.render_template_obj(template, {'page': page, 'slot': placeholder.slot}, request)
        self.assertIn('<b>En Test</b>', output)

        template = "{% load cms_tags sekizai_tags %}{% show_placeholder slot page 'fr' 1 %}{% render_block 'js' %}"
        output = self.render_template_obj(template, {'page': page, 'slot': placeholder.slot}, request)
        self.assertIn('<b>Fr Test</b>', output)
Beispiel #31
0
    def test_hide_untranslated(self):
        TESTLANG = get_primary_language()
        TESTLANG2 = get_secondary_language()
        page = create_page("mlpage-%s" % TESTLANG, "nav_playground.html",
                           TESTLANG)
        create_title(TESTLANG2,
                     "mlpage-%s" % TESTLANG2,
                     page,
                     slug=page.get_slug())
        page2 = create_page("mlpage-2-%s" % TESTLANG,
                            "nav_playground.html",
                            TESTLANG,
                            parent=page)
        page.publish(TESTLANG)
        page.publish(TESTLANG2)
        page2.publish(TESTLANG)

        menu = CMSMenu()
        lang_settings = copy.deepcopy(get_cms_setting('LANGUAGES'))

        request_1 = self.get_request('/%s/' % TESTLANG, TESTLANG)
        request_2 = self.get_request('/%s/' % TESTLANG2, TESTLANG2)

        lang_settings[1][1]['hide_untranslated'] = False
        with self.settings(CMS_LANGUAGES=lang_settings):
            list_1 = [node.id for node in menu.get_nodes(request_1)]
            list_2 = [node.id for node in menu.get_nodes(request_2)]
            self.assertEqual(list_1, list_2)
            self.assertEqual(len(list_1), 2)

        lang_settings[1][1]['hide_untranslated'] = True
        with self.settings(CMS_LANGUAGES=lang_settings):
            list_1 = [node.id for node in menu.get_nodes(request_1)]
            list_2 = [node.id for node in menu.get_nodes(request_2)]
            self.assertNotEqual(list_1, list_2)
            self.assertEqual(len(list_2), 1)
            self.assertEqual(len(list_1), 2)
Beispiel #32
0
    def test_plugins_discarded_with_language_fallback(self):
        """
        Tests side effect of language fallback: if fallback enabled placeholder
        existed, it discards all other existing plugins
        """
        page_en = create_page('page_en', 'col_two.html', 'en')
        create_title("de", "page_de", page_en)
        placeholder_sidebar_en = page_en.placeholders.get(slot='col_sidebar')
        placeholder_en = page_en.placeholders.get(slot='col_left')
        add_plugin(placeholder_sidebar_en, TextPlugin, 'en', body='en body')

        class NoPushPopContext(Context):
            def push(self):
                pass

            pop = push

        context_en = NoPushPopContext()
        context_en['request'] = self.get_request(language="en", page=page_en)

        conf = {
            'col_left': {
                'language_fallback': True,
            },
        }
        with SettingsOverride(CMS_PLACEHOLDER_CONF=conf):
            # call assign plugins first, as this is what is done in real cms life
            # for all placeholders in a page at once
            assign_plugins(context_en['request'],
                           [placeholder_sidebar_en, placeholder_en], 'col_two.html')
            # if the normal, non fallback enabled placeholder still has content
            content_en = render_placeholder(placeholder_sidebar_en, context_en)
            self.assertRegexpMatches(content_en, "^en body$")

            # remove the cached plugins instances
            del(placeholder_sidebar_en._plugins_cache)
            cache.clear()
Beispiel #33
0
    def test_command_line_publishes_selected_language_drafts(self):
        # we need to create a superuser (the db is empty)
        get_user_model().objects.create_superuser('djangocms',
                                                  '*****@*****.**', '123456')

        page = create_page("en title", "nav_playground.html", "en")
        title = create_title('de', 'de title', page)
        title.published = False
        title.save()
        title = create_title('fr', 'fr title', page)
        title.published = False
        title.save()

        pages_from_output = 0
        published_from_output = 0

        with StdoutOverride() as buffer:
            # Now we don't expect it to raise, but we need to redirect IO
            call_command('publisher_publish',
                         language='de',
                         include_unpublished=True)
            lines = buffer.getvalue().split(
                '\n')  #NB: readlines() doesn't work

        for line in lines:
            if 'Total' in line:
                pages_from_output = int(line.split(':')[1])
            elif 'Published' in line:
                published_from_output = int(line.split(':')[1])

        self.assertEqual(pages_from_output, 1)
        self.assertEqual(published_from_output, 1)

        self.assertEqual(Page.objects.public().count(), 1)
        public = Page.objects.public()[0]
        languages = sorted(public.title_set.values_list('language', flat=True))
        self.assertEqual(languages, ['de'])
Beispiel #34
0
    def setUp(self):
        User = get_user_model()

        self.admin, self.normal_guy = self._get_guys()

        if get_user_model().USERNAME_FIELD == 'email':
            self.no_page_permission_user = User.objects.create_user('no_page_permission', '*****@*****.**', '*****@*****.**')
        else:
            self.no_page_permission_user = User.objects.create_user('no_page_permission', '*****@*****.**', 'no_page_permission')

        self.no_page_permission_user.is_staff = True
        self.no_page_permission_user.is_active = True
        self.no_page_permission_user.save()
        [self.no_page_permission_user.user_permissions.add(p) for p in Permission.objects.filter(
            codename__in=[
                'change_mypageextension', 'change_mytitleextension',
                'add_mypageextension', 'add_mytitleextension',
                'delete_mypageextension', 'delete_mytitleextension',
            ]
        )]
        self.site = Site.objects.get(pk=1)
        self.page = create_page(
            'My Extension Page', 'nav_playground.html', 'en',
            site=self.site, created_by=self.admin)
        self.page_title = self.page.get_title_obj('en')
        create_title('de', 'de title', self.page)
        self.page_extension = MyPageExtension.objects.create(
            extended_object=self.page,
            extra="page extension text")
        self.title_extension = MyTitleExtension.objects.create(
            extended_object=self.page.get_title_obj(),
            extra_title="title extension text")

        self.page_without_extension = create_page(
            'A Page', 'nav_playground.html', 'en',
            site=self.site, created_by=self.admin)
        self.page_title_without_extension = self.page_without_extension.get_title_obj()
Beispiel #35
0
def create_cms_index_pages(placeholder_slot="content"):
    """
    create cms home page and fill >content< placeholder with TextPlugin
    """
    try:
        index_page = Page.objects.get(is_home=True, publisher_is_draft=False)
    except Page.DoesNotExist:
        log.debug('Create index page in "en" and...')

        index_page = create_page(
            title="index in English",
            template=TEMPLATE_INHERITANCE_MAGIC,
            language=settings.LANGUAGE_CODE,
            published=False,
            in_navigation=True,
        )
        placeholder, created = index_page.placeholders.get_or_create(
            slot=placeholder_slot)
        for language_code, lang_name in settings.LANGUAGES:
            with translation.override(language_code):
                title = "index in %s" % lang_name
                log.info("create %r", title)
                if language_code != settings.LANGUAGE_CODE:
                    create_title(language_code, title, index_page)
                add_plugin(
                    placeholder=placeholder,
                    plugin_type="TextPlugin",  # djangocms_text_ckeditor
                    language=language_code,
                    body="index page in %s" % lang_name,
                )
                index_page.publish(language_code)
        created = True
    else:
        created = False
        log.debug("Index page already exists.")

    return index_page, created
    def test_page_language_url_for_apphook(self):

        apphook_pool.clear()
        superuser = User.objects.create_superuser('admin', '*****@*****.**',
                                                  'admin')
        page = create_page("home",
                           "nav_playground.html",
                           "en",
                           created_by=superuser)
        create_title('de', page.get_title(), page)
        page.publish()

        child_page = create_page("child_page",
                                 "nav_playground.html",
                                 "en",
                                 created_by=superuser,
                                 parent=page)
        create_title('de', child_page.get_title(), child_page)
        child_page.publish()

        child_child_page = create_page("child_child_page",
                                       "nav_playground.html",
                                       "en",
                                       created_by=superuser,
                                       parent=child_page,
                                       apphook='SampleApp')
        create_title("de", '%s_de' % child_child_page.get_title(),
                     child_child_page)
        child_child_page.publish()

        # publisher_public is set to draft on publish, issue with one to one reverse
        child_child_page = self.reload(child_child_page)
        with force_language("en"):
            path = reverse('extra_first')

        request = self.get_request(path)
        request.LANGUAGE_CODE = 'en'
        request.current_page = child_child_page

        fake_context = {'request': request}
        tag = DumbPageLanguageUrl()

        output = tag.get_context(fake_context, 'en')
        url = output['content']

        self.assertEqual(url, '/en/child_page/child_child_page/extra_1/')

        output = tag.get_context(fake_context, 'de')
        url = output['content']
        # look the extra "_de"
        self.assertEqual(url, '/de/child_page/child_child_page_de/extra_1/')

        output = tag.get_context(fake_context, 'fr')
        url = output['content']
        self.assertEqual(url, '/fr/child_page/child_child_page/extra_1/')

        apphook_pool.clear()
Beispiel #37
0
    def test_copy_existing_title(self):
        """
        Even if a title already exists the copy is successfull, the original
        title remains untouched
        """
        site = 1
        number_start_plugins = CMSPlugin.objects.all().count()

        # create an empty title language
        root_page = Page.objects.get_home(site)
        create_title("de", "root page de", root_page)

        out = StringIO()
        management.call_command('cms',
                                'copy',
                                'lang',
                                '--from-lang=en',
                                '--to-lang=de',
                                interactive=False,
                                stdout=out)
        pages = Page.objects.on_site(site).drafts()
        for page in pages:
            self.assertEqual(set((u'en', u'de')), set(page.get_languages()))

        # Original Title untouched
        self.assertEqual("root page de",
                         Page.objects.get_home(site).get_title("de"))

        # Plugins still copied
        self.assertEqual(CMSPlugin.objects.all().count(),
                         number_start_plugins * 2)
        self.assertEqual(
            CMSPlugin.objects.filter(language='en').count(),
            number_start_plugins)
        self.assertEqual(
            CMSPlugin.objects.filter(language='de').count(),
            number_start_plugins)
    def test_multi_edit(self):
        user = self.get_staff()
        page = create_page('Test', 'col_two.html', 'en', published=True)
        title = create_title("fr", "test", page)

        exm = MultilingualExample1()
        exm.translate("en")
        exm.char_1 = 'one'
        exm.char_2 = 'two'
        exm.save()
        exm.translate("fr")
        exm.char_1 = "un"
        exm.char_2 = "deux"
        exm.save()

        request = self.get_page_request(page, user, edit=True)
        response = detail_view_multi(request, exm.pk)
        self.assertContains(
            response,
            '<h1><span id="cms_placeholder-model-placeholderapp-%s-%s" class="cms_placeholder-generic">one</span></h1>'
            % (exm.pk, 'char_1'))
        self.assertContains(
            response,
            "/admin/placeholderapp/multilingualexample1/edit-field/%s/en/" %
            exm.pk)
        self.assertTrue(
            re.search(self.edit_fields_rx % "char_1",
                      response.content.decode('utf8')))
        self.assertTrue(
            re.search(self.edit_fields_rx % "char_1%2Cchar_2",
                      response.content.decode('utf8')))

        with SettingsOverride(LANGUAGE_CODE="fr"):
            request = self.get_page_request(title.page,
                                            user,
                                            edit=True,
                                            lang_code="fr")
            response = detail_view_multi(request, exm.pk)
            self.assertContains(
                response,
                '<h1><span id="cms_placeholder-model-placeholderapp-%s-%s" class="cms_placeholder-generic">un</span></h1>'
                % (exm.pk, 'char_1'))
            self.assertContains(
                response,
                "/admin/placeholderapp/multilingualexample1/edit-field/%s/fr/"
                % exm.pk)
            self.assertTrue(
                re.search(self.edit_fields_rx % "char_1%2Cchar_2",
                          response.content.decode('utf8')))
Beispiel #39
0
    def setUp(self):
        super(EventManagerAppConfigTestCase, self).setUp()
        # Ensure that all test events are assigned to an app_config
        self.events = [self.ev1, self.ev2, self.ev3, self.ev4, self.ev5,
                       self.ev6, self.ev7]
        for event in self.events:
            event.app_config = self.app_config

        self.root_page = self.create_root_page()
        self.page = api.create_page(
            'Events en', self.template, 'en', published=True,
            parent=self.root_page,
            apphook='EventListAppHook',
            apphook_namespace=self.app_config.namespace,
            publication_date=tz_datetime(2014, 1, 8)
        )
        api.create_title('de', 'Events de', self.page)
        self.page.publish('en')
        self.page.publish('de')
        self.page.reload()
        # aldryn apphook reload needs a page load to work
        with override('en'):
            page_url = self.page.get_absolute_url()
        self.client.get(page_url)
Beispiel #40
0
    def test_publish_admin(self):
        name = 'test_admin'
        drafts = Page.objects.drafts()
        public = Page.objects.public()
        page = self.create_page(name, published=False)
        create_title('de', 'de-page', page)
        create_title('fr', 'fr-page', page)

        self.assertNeverPublished(page)
        self.assertObjectExist(drafts, title_set__title=name)
        self.assertObjectDoesNotExist(public, title_set__title=name)
        self.assertObjectDoesNotExist(public.published(language="en"), title_set__title=name)

        with self.login_user_context(self.get_superuser()):
            response = self.client.post(admin_reverse("cms_page_publish_page", args=[page.pk, 'en']))
            self.assertEqual(response.status_code, 302)

        page = page.reload()
        self.assertPublished(page)
        self.assertObjectExist(drafts, title_set__title=name)
        self.assertObjectExist(public, title_set__title=name)
        self.assertFalse(public.published(language="de").exists())
        self.assertFalse(public.published(language="fr").exists())
        self.assertSequenceEqual(page.publisher_public.get_languages(), ['en'])
    def test_command_line_publish_multiple_languages(self):
        # we need to create a superuser (the db is empty)
        get_user_model().objects.create_superuser('djangocms',
                                                  '*****@*****.**', '123456')

        # Create a draft page with two published titles
        page = create_page(u"The page!",
                           "nav_playground.html",
                           "en",
                           published=False)
        title = create_title('de', 'ja', page)
        title.published = True
        title.save()
        title = create_title('fr', 'non', page)
        title.published = True
        title.save()

        with StdoutOverride():
            # Now we don't expect it to raise, but we need to redirect IO
            call_command('cms', 'publisher-publish')

        public = Page.objects.public()[0]
        languages = sorted(public.title_set.values_list('language', flat=True))
        self.assertEqual(languages, ['de', 'fr'])
Beispiel #42
0
 def test_multilingual_page(self):
     TESTLANG = get_primary_language()
     TESTLANG2 = get_secondary_language()
     page = create_page("mlpage", "nav_playground.html", TESTLANG)
     create_title(TESTLANG2, page.get_title(), page, slug=page.get_slug())
     page.rescan_placeholders()
     page = self.reload(page)
     placeholder = page.placeholders.all()[0]
     add_plugin(placeholder, "TextPlugin", TESTLANG2, body="test")
     add_plugin(placeholder, "TextPlugin", TESTLANG, body="test")
     self.assertEqual(
         placeholder.cmsplugin_set.filter(language=TESTLANG2).count(), 1)
     self.assertEqual(
         placeholder.cmsplugin_set.filter(language=TESTLANG).count(), 1)
     user = get_user_model().objects.create_superuser(
         'super', '*****@*****.**', 'super')
     page = publish_page(page, user, TESTLANG)
     page = publish_page(page, user, TESTLANG2)
     public = page.publisher_public
     placeholder = public.placeholders.all()[0]
     self.assertEqual(
         placeholder.cmsplugin_set.filter(language=TESTLANG2).count(), 1)
     self.assertEqual(
         placeholder.cmsplugin_set.filter(language=TESTLANG).count(), 1)
Beispiel #43
0
def create_section_page(sender, instance, created, raw, using, update_fields,
                        **kwargs):

    if not instance.slug:
        instance.slug = slugify(instance.name)

    if created:
        if instance.namespace == "" or not instance.namespace:
            instance.namespace = slugify(instance.name)

        if instance.create_page:

            page = create_page(title=instance.name,
                               template=TEMPLATE_INHERITANCE_MAGIC,
                               language=LANGUAGE_CODE,
                               slug=instance.slug,
                               apphook=PostApp,
                               apphook_namespace=instance.namespace,
                               published=True,
                               in_navigation=True)

            for code, lang in LANGUAGES:

                if code != LANGUAGE_CODE:
                    title = getattr(instance, "name_%s" % code, instance.name)
                    slug = getattr(instance, "slug_%s" % code, instance.slug)

                    try:
                        create_title(language=code,
                                     title=title,
                                     page=page,
                                     slug=slug)
                    except IntegrityError:
                        pass

        instance.save()
Beispiel #44
0
    def test_plugins_language_fallback(self):
        """ Tests language_fallback placeholder configuration """
        page_en = create_page('page_en', 'col_two.html', 'en')
        title_de = create_title("de", "page_de", page_en)
        placeholder_en = page_en.placeholders.get(slot='col_left')
        placeholder_de = title_de.page.placeholders.get(slot='col_left')
        add_plugin(placeholder_en, TextPlugin, 'en', body='en body')

        class NoPushPopContext(Context):
            def push(self):
                pass

            pop = push

        context_en = NoPushPopContext()
        context_en['request'] = self.get_request(language="en", page=page_en)
        context_de = NoPushPopContext()
        context_de['request'] = self.get_request(language="de", page=page_en)

        # First test the default (non-fallback) behavior)
        ## English page should have the text plugin
        content_en = render_placeholder(placeholder_en, context_en)
        self.assertRegexpMatches(content_en, "^en body$")

        ## Deutsch page should have no text
        content_de = render_placeholder(placeholder_de, context_de)
        self.assertNotRegex(content_de, "^en body$")
        self.assertEqual(len(content_de), 0)

        conf = {
            'col_left': {
                'language_fallback': True,
            },
        }
        with SettingsOverride(CMS_PLACEHOLDER_CONF=conf):
            ## Deutsch page should have no text
            del(placeholder_de._plugins_cache)
            cache.clear()
            content_de = render_placeholder(placeholder_de, context_de)
            self.assertRegexpMatches(content_de, "^en body$")

            # remove the cached plugins instances
            del(placeholder_de._plugins_cache)
            cache.clear()
            # Then we add a plugin to check for proper rendering
            add_plugin(placeholder_de, TextPlugin, 'de', body='de body')
            content_de = render_placeholder(placeholder_de, context_de)
            self.assertRegexpMatches(content_de, "^de body$")
Beispiel #45
0
    def test_nested_plugins_language_fallback(self):
        """ Tests language_fallback placeholder configuration for nested plugins"""
        page_en = create_page('page_en', 'col_two.html', 'en')
        title_de = create_title("de", "page_de", page_en)
        placeholder_en = page_en.placeholders.get(slot='col_left')
        placeholder_de = title_de.page.placeholders.get(slot='col_left')
        link_en = add_plugin(placeholder_en, 'LinkPlugin', 'en', name='en name', external_link='http://example.com/en')
        add_plugin(placeholder_en, 'TextPlugin', 'en',  target=link_en, body='en body')

        context_en = SekizaiContext()
        context_en['request'] = self.get_request(language="en", page=page_en)
        context_de = SekizaiContext()
        context_de['request'] = self.get_request(language="de", page=page_en)

        conf = {
            'col_left': {
                'language_fallback': True,
            },
        }
        with self.settings(CMS_PLACEHOLDER_CONF=conf):
            content_de = _render_placeholder(placeholder_de, context_de)
            self.assertRegexpMatches(content_de, "<a href=\"http://example.com/en\"")
            self.assertRegexpMatches(content_de, "en body")
            context_de2 = SekizaiContext()
            request = self.get_request(language="de", page=page_en)
            request.session['cms_edit'] = True
            request.user = self.get_superuser()
            request.toolbar = CMSToolbar(request)
            context_de2['request'] = request
            del(placeholder_de._plugins_cache)
            cache.clear()
            content_de2 = _render_placeholder(placeholder_de, context_de2)
            self.assertFalse("en body" in content_de2)
            # remove the cached plugins instances
            del(placeholder_de._plugins_cache)
            cache.clear()
            # Then we add a plugin to check for proper rendering
            link_de = add_plugin(
                placeholder_en,
                'LinkPlugin',
                language='de',
                name='de name',
                external_link='http://example.com/de',
            )
            add_plugin(placeholder_en, 'TextPlugin', 'de',  target=link_de, body='de body')
            content_de = _render_placeholder(placeholder_de, context_de)
            self.assertRegexpMatches(content_de, "<a href=\"http://example.com/de\"")
            self.assertRegexpMatches(content_de, "de body")
Beispiel #46
0
    def test_publish_status(self):
        p1 = create_page("page", "nav_playground.html", "en", published=True)
        public = p1.get_public_object()
        draft = p1.get_draft_object()
        self.assertEqual(set(public.get_languages()), set(('en',)))
        self.assertEqual(set(public.get_published_languages()), set(('en',)))
        self.assertEqual(set(draft.get_languages()), set(('en',)))
        self.assertEqual(set(draft.get_published_languages()), set(('en',)))

        p1 = create_title('de', 'page de', p1).page
        public = p1.get_public_object()
        draft = p1.get_draft_object()
        self.assertEqual(set(public.get_languages()), set(('en',)))
        self.assertEqual(set(public.get_published_languages()), set(('en',)))
        self.assertEqual(set(draft.get_languages()), set(('en', 'de')))
        self.assertEqual(set(draft.get_published_languages()), set(('en', 'de')))

        p1.publish('de')
        p1 = p1.reload()
        public = p1.get_public_object()
        draft = p1.get_draft_object()
        self.assertEqual(set(public.get_languages()), set(('en', 'de')))
        self.assertEqual(set(public.get_published_languages()), set(('en', 'de')))
        self.assertEqual(set(draft.get_languages()), set(('en', 'de')))
        self.assertEqual(set(draft.get_published_languages()), set(('en', 'de')))

        p1.unpublish('de')
        p1 = p1.reload()

        public = p1.get_public_object()
        draft = p1.get_draft_object()
        self.assertEqual(set(public.get_languages()), set(('en', 'de')))
        self.assertEqual(set(public.get_published_languages()), set(('en',)))
        self.assertEqual(set(draft.get_languages()), set(('en', 'de')))
        self.assertEqual(set(draft.get_published_languages()), set(('en', 'de')))

        p1.publish('de')
        p1 = p1.reload()
        p1.unpublish('en')
        p1 = p1.reload()

        public = p1.get_public_object()
        draft = p1.get_draft_object()
        self.assertEqual(set(public.get_languages()), set(('en', 'de')))
        self.assertEqual(set(public.get_published_languages()), set(('de',)))
        self.assertEqual(set(draft.get_languages()), set(('en', 'de')))
        self.assertEqual(set(draft.get_published_languages()), set(('en', 'de')))
Beispiel #47
0
    def setUp(self):
        Site.objects.create(domain='example.org', name='example.org')

        self.page = create_page('Home', 'simple.html', 'en', published=True)
        self.italian_title = create_title('it', 'Home italian', self.page)

        self.placeholder = self.page.placeholders.all()[0]

        add_plugin(self.placeholder, 'TextPlugin', 'en', body='test')

        self.base_url = self.live_server_url

        self.user = self._create_user('admin', True, True, True)

        self.driver.implicitly_wait(5)

        super(PlaceholderBasicTests, self).setUp()
Beispiel #48
0
 def create_title(self, page):
     """
     Create page title in all other languages with cms.api.create_title()
     """
     for language_code, lang_name in iter_languages(self.languages):
         try:
             title = Title.objects.get(page=page, language=language_code)
         except Title.DoesNotExist:
             slug = self.get_slug(language_code, lang_name)
             assert slug != "", "No slug for %r" % language_code
             title = create_title(language=language_code,
                                  title=self.get_title(
                                      language_code, lang_name),
                                  page=page,
                                  slug=slug)
             log.debug("Title created: %s", title)
         else:
             log.debug("Page title exist: %s", title)
Beispiel #49
0
    def test_create_with_revision(self):
        page_c_type = ContentType.objects.get_for_model(Page)

        user = get_user_model().objects.create_user(
            username='******',
            email='*****@*****.**',
            password='******',
        )

        page_attrs = self._get_default_create_page_arguments()
        page_attrs['language'] = 'en'
        page_attrs['created_by'] = user
        page_attrs['with_revision'] = True

        page = create_page(**page_attrs)

        latest_revision = Revision.objects.latest('pk')
        versions = (latest_revision.version_set.filter(
            content_type=page_c_type, object_id_int=page.pk))

        # assert a new version for the page has been created
        self.assertEqual(1, versions.count())

        # assert revision comment was set correctly
        self.assertEqual(
            latest_revision.comment,
            REVISION_INITIAL_COMMENT,
        )

        # assert revision user was set correctly
        self.assertEqual(
            latest_revision.user_id,
            user.pk,
        )

        title_c_type = ContentType.objects.get_for_model(Title)
        title = create_title('de', 'test de', page, with_revision=True)

        latest_revision = Revision.objects.latest('pk')
        versions = (latest_revision.version_set.filter(
            content_type=title_c_type, object_id_int=title.pk))

        # assert a new version for the title has been created
        self.assertEqual(1, versions.count())
Beispiel #50
0
    def test_frontend_lang(self):
        superuser = self.get_superuser()
        lang_settings = copy.deepcopy(get_cms_setting('LANGUAGES'))
        lang_settings[1][0]['public'] = False
        with self.settings(CMS_LANGUAGES=lang_settings, LANGUAGE_CODE="en"):
            page = create_page("page1", "nav_playground.html", "en")
            create_title("de", page.get_title(), page, slug=page.get_slug())
            page2 = create_page("page2", "nav_playground.html", "en")
            create_title("de", page2.get_title(), page2, slug=page2.get_slug())
            page3 = create_page("page2", "nav_playground.html", "en")
            create_title("de", page3.get_title(), page3, slug=page3.get_slug())
            page4 = create_page("page4", "nav_playground.html", "de")
            page.publish('en')
            page.publish('de')
            page2.publish('en')
            page2.publish('de')
            page3.publish('de')
            page3.publish('en')
            page4.publish('de')

            page.set_as_homepage()

            # The "en" language is set to public -> False.
            # Because the request is to the root (homepage),
            # the page is redirected to the default language's homepage
            response = self.client.get("/en/")
            self.assertRedirects(response, '/de/')

            # Authenticated requests to a private language
            # will render the page normally as long as the language
            # is available on the page
            with self.login_user_context(superuser):
                response = self.client.get("/en/")
                self.assertEqual(response.status_code, 200)

            response = self.client.get("/en/page2/")
            self.assertEqual(response.status_code, 404)
            response = self.client.get("/de/")
            self.assertEqual(response.status_code, 200)
            response = self.client.get("/de/page2/")
            self.assertEqual(response.status_code, 200)

            # check if the admin can see non-public langs
            with self.login_user_context(self.get_superuser()):
                response = self.client.get("/en/page2/")
                self.assertEqual(response.status_code, 200)
                response = self.client.get("/en/page4/")
                self.assertEqual(response.status_code, 302)
            self.client.logout()
            response = self.client.get("/en/page4/")
            self.assertEqual(response.status_code, 404)
Beispiel #51
0
    def test_get_page_for_apphook(self):
            
        with SettingsOverride(ROOT_URLCONF='cms.test_utils.project.second_urls_for_apphook_tests'):
    
            apphook_pool.clear()    
            superuser = User.objects.create_superuser('admin', '*****@*****.**', 'admin')
            page = create_page("home", "nav_playground.html", "en",
                               created_by=superuser, published=True)
            create_title('de', page.get_title(), page)
            child_page = create_page("child_page", "nav_playground.html", "en",
                         created_by=superuser, published=True, parent=page)
            create_title('de', child_page.get_title(), child_page)
            child_child_page = create_page("child_child_page", "nav_playground.html",
                "en", created_by=superuser, published=True, parent=child_page, apphook='SampleApp')
            create_title("de", child_child_page.get_title(), child_child_page, apphook='SampleApp')
            
            child_child_page.publish()
            # publisher_public is set to draft on publish, issue with onetoone reverse
            child_child_page = self.reload(child_child_page) 
            
            en_title = child_child_page.publisher_public.get_title_obj('en')

            path = reverse('en:sample-settings')
            
            request = self.get_request(path)
            request.LANGUAGE_CODE = 'en'
            
            attached_to_page = applications_page_check(request, path=path[1:]) # strip leading slash
            self.assertEquals(attached_to_page.pk, en_title.page.pk)            
            
            response = self.client.get(path)
            self.assertEquals(response.status_code, 200)

            self.assertTemplateUsed(response, 'sampleapp/home.html')
            self.assertContains(response, en_title.title)
            
            de_title = child_child_page.publisher_public.get_title_obj('de')
            path = reverse('de:sample-settings')
        
            request = self.get_request(path)
            request.LANGUAGE_CODE = 'de'
            
            attached_to_page = applications_page_check(request, path=path[4:]) # strip leading slash and language prefix
            self.assertEquals(attached_to_page.pk, de_title.page.pk)            
            
            response = self.client.get(path)
            self.assertEquals(response.status_code, 200)
            self.assertTemplateUsed(response, 'sampleapp/home.html')
            self.assertContains(response, de_title.title)
            
            apphook_pool.clear()
    def test_get_i18n_apphook_with_explicit_current_app(self):
        with SettingsOverride(
                ROOT_URLCONF=
                'cms.test_utils.project.second_urls_for_apphook_tests'):
            titles = self.create_base_structure(NS_APP_NAME, ['en', 'de'],
                                                'instance_1')
            public_de_title = titles[1]
            de_title = Title.objects.get(
                page=public_de_title.page.publisher_draft, language="de")
            de_title.slug = "de"
            de_title.save()
            de_title.page.publish()

            page2 = create_page("page2",
                                "nav_playground.html",
                                "en",
                                created_by=self.superuser,
                                published=True,
                                parent=de_title.page.parent,
                                apphook=NS_APP_NAME,
                                apphook_namespace="instance_2")
            de_title2 = create_title("de", "de_title", page2, slug="slug")

            page2.publish()
            clear_app_resolvers()
            clear_url_caches()

            if APP_MODULE in sys.modules:
                del sys.modules[APP_MODULE]

            self.reload_urls()
            with force_language("de"):
                path = reverse('namespaced_app_ns:current-app',
                               current_app="instance_1")
                path = reverse('namespaced_app_ns:current-app',
                               current_app="instance_2")
                path = reverse('namespaced_app_ns:current-app')
            with force_language("en"):
                path = reverse('namespaced_app_ns:current-app',
                               current_app="instance_1")
                path = reverse('namespaced_app_ns:current-app',
                               current_app="instance_2")
                path = reverse('namespaced_app_ns:current-app')
Beispiel #53
0
    def create_translation(self, page):
        data = self.cleaned_data
        title_kwargs = {
            'page': page,
            'language': self._language,
            'slug': data['slug'],
            'path': data['path'],
            'title': data['title'],
        }

        if 'menu_title' in data:
            title_kwargs['menu_title'] = data['menu_title']

        if 'page_title' in data:
            title_kwargs['page_title'] = data['page_title']

        if 'meta_description' in data:
            title_kwargs['meta_description'] = data['meta_description']
        return api.create_title(**title_kwargs)
 def get_pages(self):
     from cms.api import create_page, create_title
     page_1 = create_page('page one', 'page.html', language='en')
     page_2 = create_page('page two', 'page.html', language='en')
     page_3 = create_page('page three', 'page.html', language='en')
     create_title(language='fr', title='page un', page=page_1)
     create_title(language='it', title='pagina uno', page=page_1)
     create_title(language='fr', title='page trois', page=page_3)
     for lang in self.languages:
         page_1.publish(lang)
     page_2.publish('en')
     page_3.publish('en')
     page_3.publish('fr')
     return page_1.get_draft_object(), page_2.get_draft_object(), page_3.get_draft_object()
Beispiel #55
0
    def test_add_change(self, admin_client):
        page = create_page('Test Page', 'INHERIT', 'en-us')
        title_de = create_title(language='de', page=page, title='Test Page de')
        title_en = page.get_title_obj(language='en-us')
        extension_de = ExtensionModel.objects.create(name='de',
                                                     extended_object=title_de)
        expected_url_add = (
            '/admin/cmsapp/extensionmodel/add/?extended_object={0}')
        expected_url_change = '/admin/cmsapp/extensionmodel/{0}/change/'

        response = admin_client.get('{0}?edit=on'.format(
            page.get_absolute_url()))
        toolbar = response.context['request'].toolbar
        menu = toolbar.get_menu('page')
        item = menu.items[5]
        extensions = {ext.name: ext for ext in item.items}

        assert extensions['English Extension...'].url == (
            expected_url_add.format(title_en.pk))
        assert extensions['German Extension...'].url == (
            expected_url_change.format(extension_de.pk))
Beispiel #56
0
    def test_add(self, admin_client):
        page = create_page('Test Page', 'INHERIT', 'en-us')
        title_de = create_title(language='de', page=page, title='Test Page de')
        title_en = page.get_title_obj(language='en-us')
        expected_url = '/admin/cmsapp/extensionmodel/add/?extended_object={0}'

        response = admin_client.get('{0}?edit=on'.format(
            page.get_absolute_url()))
        toolbar = response.context['request'].toolbar
        menu = toolbar.get_menu('page')
        item = menu.items[5]
        extensions = {ext.name: ext for ext in item.items}

        assert isinstance(item, SubMenu)
        assert item.name == 'Extension'
        assert len(item.items) == 2
        assert 'English Extension...' in extensions
        assert 'German Extension...' in extensions
        assert extensions['English Extension...'].url == (expected_url.format(
            title_en.pk))
        assert extensions['German Extension...'].url == (expected_url.format(
            title_de.pk))
Beispiel #57
0
    def test_fallback_title_extension(self):
        page = create_page('Test Fallback Title Extension',
                           "nav_playground.html", "en")
        title_en = page.get_title_obj('en')
        title_extension_en = MyTitleExtension(extended_object=title_en,
                                              extra_title='title extension EN')
        title_extension_en.save()
        page.publish('en')

        self.assertEqual(
            page.get_title_obj('en', True).mytitleextension.extra_title,
            'title extension EN')

        title_de = create_title(title="de page", language="de", page=page)
        title_extension_de = MyTitleExtension(extended_object=title_de,
                                              extra_title='title extension DE')
        title_extension_de.save()
        page.publish('de')

        self.assertEqual(
            page.get_title_obj('de', True).mytitleextension.extra_title,
            'title extension DE')
Beispiel #58
0
    def create_base_structure(self, apphook, title_langs, reverse_id=None):
        apphook_pool.clear()
        superuser = User.objects.create_superuser('admin', '*****@*****.**',
                                                  'admin')
        page = create_page("home",
                           "nav_playground.html",
                           "en",
                           created_by=superuser,
                           published=True)
        create_title('de', page.get_title(), page)
        child_page = create_page("child_page",
                                 "nav_playground.html",
                                 "en",
                                 created_by=superuser,
                                 published=True,
                                 parent=page)
        create_title('de', child_page.get_title(), child_page)
        child_child_page = create_page("child_child_page",
                                       "nav_playground.html",
                                       "en",
                                       created_by=superuser,
                                       published=True,
                                       parent=child_page,
                                       apphook=apphook,
                                       reverse_id=reverse_id)
        create_title("de",
                     child_child_page.get_title(),
                     child_child_page,
                     apphook=apphook)

        child_child_page.publish()
        # publisher_public is set to draft on publish, issue with onetoone reverse
        child_child_page = self.reload(child_child_page)

        if isinstance(title_langs, basestring):
            titles = child_child_page.publisher_public.get_title_obj(
                title_langs)
        else:
            titles = [
                child_child_page.publisher_public.get_title_obj(l)
                for l in title_langs
            ]

        self.reload_urls()

        return titles
    def test_edit_field_multilingual(self):
        from django.contrib.admin import site
        exadmin = site._registry[MultilingualExample1]

        user = self.get_superuser()
        page = create_page('Test', 'col_two.html', 'en', published=True)
        title = create_title("fr", "test", page)

        exm = MultilingualExample1()
        exm.translate("en")
        exm.char_1 = 'one'
        exm.char_2 = 'two'
        exm.save()
        exm.translate("fr")
        exm.char_1 = "un"
        exm.char_2 = "deux"
        exm.save()

        request = self.get_page_request(page, user, edit=True)
        request.GET['edit_fields'] = 'char_2'

        response = exadmin.edit_field(request, exm.pk, "en")
        self.assertContains(response, 'id="id_char_2"')
        self.assertContains(response, 'value="two"')

        response = exadmin.edit_field(request, exm.pk, "fr")
        self.assertContains(response, 'id="id_char_2"')
        self.assertContains(response, 'value="deux"')

        with SettingsOverride(LANGUAGE_CODE="fr"):
            request = self.get_page_request(title.page,
                                            user,
                                            edit=True,
                                            lang_code="fr")
            request.GET['edit_fields'] = 'char_2'
            response = exadmin.edit_field(request, exm.pk, "fr")
            self.assertContains(response, 'id="id_char_2"')
            self.assertContains(response, 'value="deux"')
Beispiel #60
0
    def create_base_structure(self, apphook, title_langs, namespace=None):
        self.apphook_clear()
        superuser = get_user_model().objects.create_superuser(
            'admin', '*****@*****.**', 'admin')
        self.superuser = superuser
        page = create_page("home",
                           "nav_playground.html",
                           "en",
                           created_by=superuser,
                           published=True)
        create_title('de', page.get_title(), page)
        page.publish('de')
        child_page = create_page("child_page",
                                 "nav_playground.html",
                                 "en",
                                 created_by=superuser,
                                 published=True,
                                 parent=page)
        create_title('de', child_page.get_title(), child_page)
        child_page.publish('de')
        child_child_page = create_page("child_child_page",
                                       "nav_playground.html",
                                       "en",
                                       created_by=superuser,
                                       published=True,
                                       parent=child_page,
                                       apphook=apphook,
                                       apphook_namespace=namespace)
        create_title("de", child_child_page.get_title(), child_child_page)
        child_child_page.publish('de')
        # publisher_public is set to draft on publish, issue with onetoone reverse
        child_child_page = self.reload(child_child_page)

        if isinstance(title_langs, six.string_types):
            titles = child_child_page.publisher_public.get_title_obj(
                title_langs)
        else:
            titles = [
                child_child_page.publisher_public.get_title_obj(l)
                for l in title_langs
            ]

        self.reload_urls()

        return titles