Example #1
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)
Example #2
0
    def test_command_line_ignores_draft_page(self):
        # we need to create a superuser (the db is empty)
        User.objects.create_superuser('djangocms', '*****@*****.**', '123456')

        create_page("The page!", "nav_playground.html", "en", published=False)

        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
            com = publisher_publish.Command()
            com.handle_noargs()
            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,0)
        self.assertEqual(published_from_output,0)

        self.assertEqual(Page.objects.public().count(), 0)
Example #3
0
    def test_table_name_patching(self):
        """
        This tests the plugin models patching when publishing from the command line
        """
        User = get_user_model()
        User.objects.create_superuser('djangocms', '*****@*****.**', '123456')
        create_page("The page!", "nav_playground.html", "en", published=True)
        draft = Page.objects.drafts()[0]
        draft.reverse_id = 'a_test'  # we have to change *something*
        draft.save()
        add_plugin(draft.placeholders.get(slot=u"body"),
                   u"TextPlugin", u"en", body="Test content")
        draft.publish('en')
        add_plugin(draft.placeholders.get(slot=u"body"),
                   u"TextPlugin", u"en", body="Test content")

        # Manually undoing table name patching
        Text._meta.db_table = 'djangocms_text_ckeditor_text'
        plugin_pool.patched = False

        with disable_logger(log):
            call_command('cms', 'moderator', 'on')
        # Sanity check the database (we should have one draft and one public)
        not_drafts = len(Page.objects.filter(publisher_is_draft=False))
        drafts = len(Page.objects.filter(publisher_is_draft=True))
        self.assertEqual(not_drafts, 1)
        self.assertEqual(drafts, 1)
Example #4
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)
Example #5
0
    def test_simple_publisher(self):
        """
        Creates the stuff needed for these tests.
        Please keep this up-to-date (the docstring!)

                A
               / \
              B  C
        """
        # Create a simple tree of 3 pages
        pageA = create_page("Page A", "nav_playground.html", "en",
                            published=True)
        pageB = create_page("Page B", "nav_playground.html", "en", parent=pageA,
                            published=True)
        pageC = create_page("Page C", "nav_playground.html", "en", parent=pageA,
                            published=False)
        # Assert A and B are published, C unpublished
        self.assertTrue(pageA.published)
        self.assertTrue(pageB.published)
        self.assertTrue(not pageC.published)
        self.assertEqual(len(Page.objects.public().published()), 2)

        # Let's publish C now.
        pageC.publish()

        # Assert all are published
        self.assertTrue(pageA.published)
        self.assertTrue(pageB.published)
        self.assertTrue(pageC.published)
        self.assertEqual(len(Page.objects.public().published()), 3)
Example #6
0
    def test_subtree_needs_approval(self):
        # create page under slave_page
        page = create_page("parent", "nav_playground.html", "en",
                           parent=self.home_page)
        self.assertFalse(page.publisher_public)

        # create subpage under page
        subpage = create_page("subpage", "nav_playground.html", "en", parent=page)
        self.assertFalse(subpage.publisher_public)

        # publish both of them in reverse order 
        subpage = publish_page(subpage, self.user_master, 'en')

        # subpage should not be published, because parent is not published 
        # yet, should be marked as `publish when parent`
        self.assertFalse(subpage.publisher_public)

        # publish page (parent of subage), so subpage must be published also
        page = publish_page(page, self.user_master, 'en')
        self.assertNotEqual(page.publisher_public, None)

        # reload subpage, it was probably changed
        subpage = self.reload(subpage)

        # parent was published, so subpage must be also published..
        self.assertNotEqual(subpage.publisher_public, None)

        #check attributes
        self.check_published_page_attributes(page)
        self.check_published_page_attributes(subpage)
Example #7
0
    def test_subtree_with_super(self):
        # create page under root
        page = create_page("page", "nav_playground.html", "en")
        self.assertFalse(page.publisher_public)

        # create subpage under page
        subpage = create_page("subpage", "nav_playground.html", "en",
                              parent=page)
        self.assertFalse(subpage.publisher_public)

        # tree id must be the same
        self.assertEqual(page.tree_id, subpage.tree_id)

        # publish both of them  
        page = self.reload(page)
        page = publish_page(page, self.user_super, 'en')
        # reload subpage, there were an tree_id change
        subpage = self.reload(subpage)
        self.assertEqual(page.tree_id, subpage.tree_id)

        subpage = publish_page(subpage, self.user_super, 'en')
        # tree id must stay the same
        self.assertEqual(page.tree_id, subpage.tree_id)

        # published pages must also have the same tree_id
        self.assertEqual(page.publisher_public.tree_id, subpage.publisher_public.tree_id)

        #check attributes
        self.check_published_page_attributes(page)
        self.check_published_page_attributes(subpage)
Example #8
0
    def test_slug_url_overwrite_clash(self):
        """ Tests if a URL-Override clashes with a normal page url
        """
        with SettingsOverride(CMS_PERMISSION=False):
            create_page('home', 'nav_playground.html', 'en', published=True)
            bar = create_page('bar', 'nav_playground.html', 'en', published=False)
            foo = create_page('foo', 'nav_playground.html', 'en', published=True)
            # Tests to assure is_valid_url is ok on plain pages
            self.assertTrue(is_valid_url(bar.get_absolute_url('en'), bar))
            self.assertTrue(is_valid_url(foo.get_absolute_url('en'), foo))

            # Set url_overwrite for page foo
            title = foo.get_title_obj(language='en')
            title.has_url_overwrite = True
            title.path = '/bar/'
            title.save()
            foo.publish('en')

            try:
                url = is_valid_url(bar.get_absolute_url('en'), bar)
            except ValidationError:
                url = False
            if url:
                bar.save()
                bar.publish('en')
            self.assertFalse(bar.is_published('en'))
Example #9
0
    def test_toolbar_login_view(self):
        User = get_user_model()
        create_page('Home', 'simple.html', 'en', published=True)
        ex1 = Example1.objects.create(
            char_1='char_1', char_2='char_1', char_3='char_3', char_4='char_4',
            date_field=datetime.datetime.now()
        )
        try:
            apphook_pool.register(Example1App)
        except AppAlreadyRegistered:
            pass
        self.reload_urls()
        create_page('apphook', 'simple.html', 'en', published=True,
                    apphook=Example1App)


        url = '%s/%s/?%s' % (self.live_server_url, 'apphook/detail/%s' % ex1.pk, get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON'))
        self.driver.get(url)
        username_input = self.driver.find_element_by_id("id_cms-username")
        username_input.send_keys(getattr(self.user, User.USERNAME_FIELD))
        password_input = self.driver.find_element_by_id("id_cms-password")
        password_input.send_keys("what")
        password_input.submit()
        self.wait_page_loaded()
        self.assertTrue(self.driver.find_element_by_class_name('cms-error'))
Example #10
0
    def test_delete_with_plugins(self):
        """
        Check that plugins and placeholders get correctly deleted when we delete
        a page!
        """
        home = create_page("home", "nav_playground.html", "en")
        page = create_page("page", "nav_playground.html", "en")
        page.rescan_placeholders() # create placeholders
        placeholder = page.placeholders.all()[0]
        plugin_base = CMSPlugin(
            plugin_type='TextPlugin',
            placeholder=placeholder,
            position=1,
            language=settings.LANGUAGES[0][0]
        )
        plugin_base.insert_at(None, position='last-child', save=False)

        plugin = Text(body='')
        plugin_base.set_base_attr(plugin)
        plugin.save()
        self.assertEqual(CMSPlugin.objects.count(), 1)
        self.assertEqual(Text.objects.count(), 1)
        self.assertTrue(Placeholder.objects.count() > 2)
        page.delete()
        home.delete()
        self.assertEqual(CMSPlugin.objects.count(), 0)
        self.assertEqual(Text.objects.count(), 0)
        self.assertEqual(Placeholder.objects.count(), 0)
        self.assertEqual(Page.objects.count(), 0)
Example #11
0
    def test_page_overwrite_urls(self):
        page1 = create_page('test page 1', 'nav_playground.html', 'en',
                            published=True)

        page2 = create_page('test page 2', 'nav_playground.html', 'en',
                            published=True, parent=page1)

        page3 = create_page('test page 3', 'nav_playground.html', 'en',
                            published=True, parent=page2, overwrite_url='i-want-another-url')

        self.assertEqual(page2.get_absolute_url(),
                         self.get_pages_root() + 'test-page-2/')
        self.assertEqual(page3.get_absolute_url(),
                         self.get_pages_root() + 'i-want-another-url/')

        title2 = page2.title_set.get()
        title2.slug = 'page-test-2'
        title2.save()

        page2 = Page.objects.get(pk=page2.pk)
        page3 = Page.objects.get(pk=page3.pk)

        self.assertEqual(page2.get_absolute_url(),
                         self.get_pages_root() + 'page-test-2/')
        self.assertEqual(page3.get_absolute_url(),
                         self.get_pages_root() + 'i-want-another-url/')

        # tests a bug found in 2.2 where saving an ancestor page
        # wiped out the overwrite_url for child pages
        page2.save()
        self.assertEqual(page3.get_absolute_url(),
                         self.get_pages_root() + 'i-want-another-url/')
Example #12
0
 def test_sitemap_login_required_pages(self):
     """
     Test that CMSSitemap object contains only published,public (login_required=False) pages
     """
     create_page("page", "nav_playground.html", "en", login_required=True,
                 published=True, in_navigation=True)
     self.assertEqual(CMSSitemap().items().count(), 0)
Example #13
0
    def test_templates(self):
        """
        Test the inheritance magic for templates
        """
        parent = create_page("parent", "nav_playground.html", "en")
        child = create_page("child", "nav_playground.html", "en", parent=parent)
        grand_child = create_page("child", "nav_playground.html", "en", parent=child)
        child.template = constants.TEMPLATE_INHERITANCE_MAGIC
        grand_child.template = constants.TEMPLATE_INHERITANCE_MAGIC
        child.save()
        grand_child.save()

        # kill template cache
        delattr(grand_child, '_template_cache')
        with self.assertNumQueries(1):
            self.assertEqual(child.template, constants.TEMPLATE_INHERITANCE_MAGIC)
            self.assertEqual(parent.get_template_name(), grand_child.get_template_name())

        # test template cache
        with self.assertNumQueries(0):
            grand_child.get_template()

        parent.template = constants.TEMPLATE_INHERITANCE_MAGIC
        parent.save()
        self.assertEqual(parent.template, constants.TEMPLATE_INHERITANCE_MAGIC)
        self.assertEqual(parent.get_template(), get_cms_setting('TEMPLATES')[0][0])
        self.assertEqual(parent.get_template_name(), get_cms_setting('TEMPLATES')[0][1])
Example #14
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
Example #15
0
 def test_moderator_edit_page_redirect(self):
     """
     Test that a page can be edited multiple times with moderator
     """
     create_page("home", "nav_playground.html", "en", published=True)
     superuser = self.get_superuser()
     with self.login_user_context(superuser):
         page_data = self.get_new_page_data()
         response = self.client.post(URL_CMS_PAGE_ADD, page_data)
         self.assertEqual(response.status_code, 302)
         page = Page.objects.get(title_set__slug=page_data['slug'])
         response = self.client.get('/en/admin/cms/page/%s/' % page.id)
         self.assertEqual(response.status_code, 200)
         page_data['overwrite_url'] = '/hello/'
         page_data['has_url_overwrite'] = True
         response = self.client.post('/en/admin/cms/page/%s/advanced-settings/' % page.id, page_data)
         self.assertRedirects(response, URL_CMS_PAGE)
         self.assertEqual(page.get_absolute_url(), '/en/hello/')
         Title.objects.all()[0]
         page = page.reload()
         page.publish('en')
         page_data['title'] = 'new title'
         response = self.client.post('/en/admin/cms/page/%s/' % page.id, page_data)
         page = Page.objects.get(title_set__slug=page_data['slug'], publisher_is_draft=True)
         self.assertRedirects(response, URL_CMS_PAGE)
         self.assertEqual(page.get_title(), 'new title')
Example #16
0
 def test_not_in_navigation_num_queries(self):
     """
     Test for issue 521
     
     Build the following tree:
     
         A
         |-B
           |-C
           \-D (not in nav)
     """
     a = create_page('A', 'nav_playground.html', 'en', published=True,
                     in_navigation=True, reverse_id='a')
     b =create_page('B', 'nav_playground.html', 'en', parent=a,
                    published=True, in_navigation=True)
     c = create_page('C', 'nav_playground.html', 'en', parent=b,
                     published=True, in_navigation=True)
     create_page('D', 'nav_playground.html', 'en', parent=self.reload(b),
                 published=True, in_navigation=False)
     with LanguageOverride('en'):
         context = self.get_context(a.get_absolute_url())
         with self.assertNumQueries(4):
             """
             The 4 queries should be:
                 get all pages
                 get all page permissions
                 get all titles
                 set the menu cache key
             """
             # Actually seems to run:
             tpl = Template("{% load menu_tags %}{% show_menu_below_id 'a' 0 100 100 100 %}")
             tpl.render(context)
Example #17
0
    def test_nested_apphooks_urls(self):
        # make sure that urlparams actually reach the apphook views
        with self.settings(ROOT_URLCONF='cms.test_utils.project.urls'):
            self.apphook_clear()

            superuser = get_user_model().objects.create_superuser('admin', '*****@*****.**', 'admin')
            create_page("home", "nav_playground.html", "en", created_by=superuser, published=True, )
            parent_page = create_page("parent-apphook-page", "nav_playground.html", "en",
                                      created_by=superuser, published=True, apphook="ParentApp")
            create_page("child-apphook-page", "nav_playground.html", "en", parent=parent_page,
                        created_by=superuser, published=True, apphook="ChildApp")

            parent_app_path = reverse('parentapp_view', kwargs={'path': 'parent/path/'})
            child_app_path = reverse('childapp_view', kwargs={'path': 'child-path/'})

            # Ensure the page structure is ok before getting responses
            self.assertEqual(parent_app_path, '/en/parent-apphook-page/parent/path/')
            self.assertEqual(child_app_path, '/en/parent-apphook-page/child-apphook-page/child-path/')

            # Get responses for both paths and ensure that the right view will answer
            response = self.client.get(parent_app_path)
            self.assertContains(response, 'parent app content', status_code=200)

            response = self.client.get(child_app_path)
            self.assertContains(response, 'child app content', status_code=200)

            self.apphook_clear()
Example #18
0
 def test_language_code(self):
     api.create_page("home", "nav_playground.html", "fr", published=True)
     response = self.client.get('/')
     self.assertEqual(response.status_code, 302)
     response = self.client.get('/en/')
     self.assertEqual(response.status_code, 302)
     self.assertRedirects(response, '/fr/')
Example #19
0
 def test_not_in_navigation(self):
     """
     Test for issue 521
     
     Build the following tree:
     
         A
         |-B
           |-C
           \-D (not in nav)
     """
     a = create_page('A', 'nav_playground.html', 'en', published=True,
                     in_navigation=True, reverse_id='a')
     b =create_page('B', 'nav_playground.html', 'en', parent=a,
                    published=True, in_navigation=True)
     c = create_page('C', 'nav_playground.html', 'en', parent=b,
                     published=True, in_navigation=True)
     create_page('D', 'nav_playground.html', 'en', parent=self.reload(b),
                 published=True, in_navigation=False)
     context = self.get_context(a.get_absolute_url())
     tpl = Template("{% load menu_tags %}{% show_menu_below_id 'a' 0 100 100 100 %}")
     tpl.render(context)
     nodes = context['children']
     self.assertEqual(len(nodes), 1, nodes)
     node = nodes[0]
     self.assertEqual(node.id, b.id)
     children = node.children
     self.assertEqual(len(children), 1, repr(children))
     child = children[0]
     self.assertEqual(child.id, c.id)
Example #20
0
    def test_changelist_tree(self):
        """ This test checks for proper jstree cookie unquoting.

        It should be converted to a selenium test to actually test the jstree behaviour.
        Cookie set below is just a forged example (from live session)
        """
        admin = self.get_superuser()
        first_level_page = create_page('level1', 'nav_playground.html', 'en')
        second_level_page_top = create_page('level21', "nav_playground.html", "en",
                                            created_by=admin, published=True, parent=first_level_page)
        second_level_page_bottom = create_page('level22', "nav_playground.html", "en",
                                               created_by=admin, published=True, parent=self.reload(first_level_page))
        third_level_page = create_page('level3', "nav_playground.html", "en",
                                       created_by=admin, published=True, parent=second_level_page_top)

        url = reverse('admin:cms_%s_changelist' % Page._meta.module_name)
        self.client.login(username='******', password='******')
        self.client.cookies['djangocms_nodes_open'] = 'page_1%2Cpage_2'
        response = self.client.get(url)
        self.assertEquals(response.status_code, 200)
        self.assertEquals(response.context["open_menu_trees"], [1, 2])
        # tests descendants method for the lazy load ajax call
        url = "%s%d/descendants/" % (url, first_level_page.pk)
        response = self.client.get(url)
        self.assertEquals(response.status_code, 200)
        # should include both direct descendant pages
        self.assertContains(response, 'id="page_%s"' % second_level_page_top.pk)
        self.assertContains(response, 'id="page_%s"' % second_level_page_bottom.pk)
        # but not any further down the tree
        self.assertNotContains(response, 'id="page_%s"' % third_level_page.pk)
Example #21
0
    def test_table_name_patching(self):
        """
        This tests the plugin models patching when publishing from the command line
        """
        User = get_user_model()
        User.objects.create_superuser('djangocms', '*****@*****.**', '123456')
        create_page("The page!", "nav_playground.html", "en", published=True)
        draft = Page.objects.drafts()[0]
        draft.reverse_id = 'a_test' # we have to change *something*
        draft.save()
        add_plugin(draft.placeholders.get(slot=u"body"),
                   u"TextPlugin", u"en", body="Test content")
        draft.publish('en')
        add_plugin(draft.placeholders.get(slot=u"body"),
                   u"TextPlugin", u"en", body="Test content")

        # Manually undoing table name patching
        Text._meta.db_table = 'djangocms_text_ckeditor_text'
        plugin_pool.patched = False

        with StdoutOverride():
            # Now we don't expect it to raise, but we need to redirect IO
            call_command('cms', 'publisher_publish')
        not_drafts = len(Page.objects.filter(publisher_is_draft=False))
        drafts = len(Page.objects.filter(publisher_is_draft=True))
        self.assertEqual(not_drafts, 1)
        self.assertEqual(drafts, 1)
Example #22
0
 def test_move_page_inherit(self):
     parent = create_page("Parent", 'col_three.html', "en")
     child = create_page("Child", settings.CMS_TEMPLATE_INHERITANCE_MAGIC,
                         "en", parent=parent)
     self.assertEqual(child.get_template(), parent.get_template())
     child.move_page(parent, 'left')
     self.assertEqual(child.get_template(), parent.get_template())
Example #23
0
 def test_redirect_with_toolbar(self):
     create_page("one", "nav_playground.html", "en", published=True,
                 redirect='/en/page2')
     superuser = self.get_superuser()
     with self.login_user_context(superuser):
         response = self.client.get('/en/?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON'))
         self.assertEqual(response.status_code, 200)
Example #24
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
Example #25
0
 def test_urls_need_reloading_signal_create(self):
     superuser = get_user_model().objects.create_superuser('admin', '*****@*****.**', 'admin')
     with signal_tester(urls_need_reloading) as env:
         create_page("apphooked-page", "nav_playground.html", "en",
             created_by=superuser, published=True, apphook="SampleApp")
         self.client.get('/')
         self.assertEqual(env.call_count, 1)
Example #26
0
 def test_generage_valid_slug_check_existing(self):
     title = "Hello Title"
     create_page(title, 'nav_playground.html', 'en')
     # second time with same title, it should append -1
     expected_slug = "hello-title-1"
     slug = _generate_valid_slug(title, None, 'en')
     self.assertEqual(slug, expected_slug)
Example #27
0
 def test_invalid_template(self):
     kwargs = self._get_default_create_page_arguments()
     kwargs['template'] = "not_valid.htm"
     with self.settings(CMS_TEMPLATES=[("not_valid.htm", "notvalid")]):
         self.assertRaises(TemplateDoesNotExist, create_page, **kwargs)
         kwargs['template'] = TEMPLATE_INHERITANCE_MAGIC
     create_page(**kwargs)
Example #28
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)
Example #29
0
 def test_04_redirect(self):
     redirect_one = 'https://www.django-cms.org/'
     redirect_two = '/'
     redirect_three = '/en/'
     # test external redirect
     one = create_page("one", "nav_playground.html", "en", published=True,
                       redirect=redirect_one)
     url = one.get_absolute_url()
     request = self.get_request(url)
     response = details(request, url.strip('/'))
     self.assertEqual(response.status_code, 302)
     self.assertEqual(response['Location'], redirect_one)
     
     # test internal language neutral redirect
     two = create_page("two", "nav_playground.html", "en", parent=one,
                       published=True, redirect=redirect_two)
     url = two.get_absolute_url()
     request = self.get_request(url)
     response = details(request, url.strip('/'))
     self.assertEqual(response.status_code, 302)
     self.assertEqual(response['Location'], '/en/')
     
     # test internal forced language redirect
     three = create_page("three", "nav_playground.html", "en", parent=one,
                         published=True, redirect=redirect_three)
     url = three.get_absolute_url()
     request = self.get_request(url)
     response = details(request, url.strip('/'))
     self.assertEqual(response.status_code, 302)
     self.assertEqual(response['Location'], redirect_three)
Example #30
0
 def test_subtree_needs_approvement(self):
     # create page under slave_page
     page = create_page("parent", "nav_playground.html", "en",
                        parent=self.home_page)
     self.assertFalse(page.publisher_public)
     
     # create subpage uner page
     subpage = create_page("subpage", "nav_playground.html", "en", parent=page)
     self.assertFalse(subpage.publisher_public)
     
     # publish both of them in reverse order 
     subpage = publish_page(subpage, self.user_master, True) 
     
     # subpage should not be published, because parent is not published 
     # yet, should be marked as `publish when parent`
     self.assertFalse(subpage.publisher_public) 
     
     # pagemoderator state must be set
     self.assertEqual(subpage.moderator_state, Page.MODERATOR_APPROVED_WAITING_FOR_PARENTS)
     
     # publish page (parent of subage), so subpage must be published also
     page = publish_page(page, self.user_master, True)
     self.assertNotEqual(page.publisher_public, None)
     
     # reload subpage, it was probably changed
     subpage = self.reload_page(subpage)
     
     # parent was published, so subpage must be also published..
     self.assertNotEqual(subpage.publisher_public, None) 
     
     #check attributes
     self.check_published_page_attributes(page)
     self.check_published_page_attributes(subpage)
Example #31
0
 def test_assign_user_to_page_nothing(self):
     page = create_page(**self._get_default_create_page_arguments())
     user = get_user_model().objects.create_user(
         username='******', email='*****@*****.**', password='******')
     user.is_staff = True
     self.assertFalse(page.has_change_permission(user))
Example #32
0
    def insert_test_content(self):
        # Insert a page
        p = create_page(self.test_data['title'], TEMPLATE_NAME, 'en',
                        slug=self.test_data['slug'], created_by=self.test_user,
                        reverse_id=self.test_data['reverse_id'], published=True)
        # Placeholders have been inserted on post_save signal:
        self.test_placeholders = {}
        for placeholder in p.placeholders.all():
            self.test_placeholders[placeholder.slot] = placeholder
            # Insert some test Text plugins
        add_plugin(self.test_placeholders['main'], 'TextPlugin', 'en',
                   body=self.test_data['text_main'])
        add_plugin(self.test_placeholders['sub'], 'TextPlugin', 'en',
                   body=self.test_data['text_sub'])
        p.publish('en')

        # Insert another page that is not the home page
        p2 = create_page(self.test_data2['title'], INHERIT_TEMPLATE_NAME, 'en',
                         parent=p, slug=self.test_data2['slug'], published=True,
                         reverse_id=self.test_data2['reverse_id'])
        p2.publish('en')

        # Insert another page that is not the home page
        p3 = create_page(self.test_data3['title'], INHERIT_TEMPLATE_NAME, 'en',
                         slug=self.test_data3['slug'], parent=p2,
                         reverse_id=self.test_data3['reverse_id'], published=True)
        # Placeholders have been inserted on post_save signal:
        self.test_placeholders3 = {}
        for placeholder in p3.placeholders.all():
            self.test_placeholders3[placeholder.slot] = placeholder
            # # Insert some test Text plugins
        add_plugin(self.test_placeholders3['sub'], 'TextPlugin', 'en',
                   body=self.test_data3['text_sub'])
        p3.publish('en')

        # Insert another page that is not the home
        p4 = create_page(self.test_data4['title'], 'extra_context.html', 'en', parent=p)
        # Placeholders have been inserted on post_save signal:
        self.test_placeholders4 = {}
        for placeholder in p4.placeholders.all():
            self.test_placeholders4[placeholder.slot] = placeholder
            # Insert some test plugins
        add_plugin(self.test_placeholders4['extra_context'], 'ExtraContextPlugin', 'en')
        p4.publish('en')

        # Insert another page that is not the home page
        p5 = create_page(self.test_data5['title'], INHERIT_TEMPLATE_NAME, 'en',
                         parent=p, slug=self.test_data5['slug'], published=True,
                         reverse_id=self.test_data5['reverse_id'])
        # Placeholders have been inserted on post_save signal:
        self.test_placeholders5 = {}
        for placeholder in p5.placeholders.all():
            self.test_placeholders5[placeholder.slot] = placeholder
            # # Insert some test Text plugins
        add_plugin(self.test_placeholders5['sub'], 'TextPlugin', 'en',
                   body=self.test_data5['text_sub'])
        add_plugin(self.test_placeholders5['main'], 'TextPlugin', 'en',
                   body=self.test_data5['text_main'])
        p5.publish('en')

        # Insert another page that is not the home page
        p6 = create_page(self.test_data6['title'], INHERIT_TEMPLATE_NAME, 'en',
                         slug=self.test_data6['slug'], parent=p5,
                         reverse_id=self.test_data6['reverse_id'], published=True)
        # Placeholders have been inserted on post_save signal:
        self.test_placeholders6 = {}
        for placeholder in p6.placeholders.all():
            self.test_placeholders6[placeholder.slot] = placeholder
            # # Insert some test Text plugins
        add_plugin(self.test_placeholders6['sub'], 'TextPlugin', 'en',
                   body=self.test_data6['text_sub'])
        p6.publish('en')
        p7 = create_page(self.test_data7['title'], INHERIT_TEMPLATE_NAME, 'en',
                         slug=self.test_data7['slug'], parent=p6,
                         reverse_id=self.test_data7['reverse_id'], published=True)
        p8 = create_page(self.test_data8['title'], INHERIT_WITH_OR_TEMPLATE_NAME, 'en',
                         slug=self.test_data8['slug'], parent=p7,
                         reverse_id=self.test_data8['reverse_id'], published=True)

        p9 = create_page(self.test_data9['title'], INHERIT_WITH_OR_TEMPLATE_NAME, 'en',
                         slug=self.test_data9['slug'],
                         reverse_id=self.test_data9['reverse_id'], published=True)
        p10 = create_page(self.test_data10['title'], INHERIT_WITH_OR_TEMPLATE_NAME, 'en',
                         slug=self.test_data10['slug'], parent=p9,
                         reverse_id=self.test_data10['reverse_id'], published=True)

        # Reload test pages
        self.test_page = self.reload(p.publisher_public)
        self.test_page2 = self.reload(p2.publisher_public)
        self.test_page3 = self.reload(p3.publisher_public)
        self.test_page4 = self.reload(p4.publisher_public)
        self.test_page5 = self.reload(p5.publisher_public)
        self.test_page6 = self.reload(p6.publisher_public)
        self.test_page7 = self.reload(p7.publisher_public)
        self.test_page8 = self.reload(p8.publisher_public)
        self.test_page9 = self.reload(p9.publisher_public)
        self.test_page10 = self.reload(p10.publisher_public)
Example #33
0
 def setUp(self):
     super(GooglePlusPluginTestCase, self).setUp()
     self.page = create_page("render test", "nav_playground.html", "en")
     self.ph = self.page.placeholders.get(slot="body")
Example #34
0
 def get_data(self):
     page = create_page("page", "nav_playground.html", "en")
     placeholder = page.placeholders.get(slot='body')
     superuser = self.get_superuser()
     staff = self.get_staff_user_with_no_permissions()
     return page, placeholder, superuser, staff
    def test_revision_on_plugin_move_a_copy(self):
        from cms.plugin_pool import plugin_pool

        def get_plugin_id_from_response(response):
            # Expects response to be a JSON response
            # with a structure like so:
            # {"urls": {"edit_plugin": "/en/admin/placeholderapp/example1/edit-plugin/3/"}
            data = json.loads(response.content.decode('utf-8'))
            return data['urls']['edit_plugin'].split('/')[-2]

        placeholder_c_type = ContentType.objects.get_for_model(Placeholder)
        placeholder_versions = Version.objects.filter(
            content_type=placeholder_c_type)
        placeholder_versions_initial_count = placeholder_versions.count()

        LinkPluginModel = plugin_pool.get_plugin('LinkPlugin').model
        link_plugin_c_type = ContentType.objects.get_for_model(LinkPluginModel)

        # three placeholder types
        # native - native CMS placeholder (created using a placeholder tag)
        # manual - Manual placeholder (created using a PlaceholderField)
        # static - Static placeholder (created using the staticplaceholder tag)

        native_placeholder_page = create_page('test page', 'simple.html',
                                              u'en')
        native_placeholder = native_placeholder_page.placeholders.get(
            slot='placeholder')
        native_placeholder_pk = native_placeholder.pk
        native_placeholder_admin = self.get_page_admin()
        native_placeholder_versions = placeholder_versions.filter(
            object_id_int=native_placeholder_pk)
        native_placeholder_versions_initial_count = native_placeholder_versions.count(
        )

        example = Example1.objects.create(
            char_1='one',
            char_2='two',
            char_3='tree',
            char_4='four',
        )
        manual_placeholder = example.placeholder
        manual_placeholder_admin = self.get_example_admin()

        static_placeholder_obj = StaticPlaceholder.objects.create(
            name='static',
            code='static',
            site_id=1,
        )
        static_placeholder = static_placeholder_obj.draft
        static_placeholder_admin = self.get_staticplaceholder_admin()

        # Add plugin to manual placeholder
        data = {
            'placeholder': manual_placeholder,
            'plugin_type': 'LinkPlugin',
            'language': 'en',
        }

        link_plugin = add_plugin(**data)
        link_plugin_versions = Version.objects.filter(
            content_type=link_plugin_c_type, )

        # copy plugin from manual to native placeholder
        request = self.get_post_request({
            'placeholder_id': native_placeholder.pk,
            'plugin_id': link_plugin.pk,
            'plugin_order': ['__COPY__'],
            'move_a_copy': 'true',
        })
        response = manual_placeholder_admin.move_plugin(request)

        self.assertEqual(response.status_code, 200)

        # Point to the newly created text plugin
        link_plugin_pk = get_plugin_id_from_response(response)

        # assert a new version for the native placeholder has been created
        self.assertEqual(
            native_placeholder_versions.count(),
            native_placeholder_versions_initial_count + 1,
        )

        # assert a new version for the link plugin has been created
        self.assertEqual(
            link_plugin_versions.filter(object_id_int=link_plugin_pk).count(),
            1,
        )

        # Assert revision comment was set correctly
        self.assertEqual(
            Revision.objects.latest('pk').comment,
            'Copied plugins to %s' % force_text(native_placeholder),
        )

        # copy plugin from native to manual placeholder
        request = self.get_post_request({
            'placeholder_id': manual_placeholder.pk,
            'plugin_id': link_plugin_pk,
            'plugin_order': ['__COPY__'],
            'move_a_copy': 'true',
        })
        response = native_placeholder_admin.move_plugin(request)

        self.assertEqual(response.status_code, 200)

        # Point to the newly created text plugin
        link_plugin_pk = get_plugin_id_from_response(response)

        # assert revision count remains the same
        self.assertEqual(
            placeholder_versions.count(),
            placeholder_versions_initial_count + 1,
        )

        # copy plugin from manual to static placeholder
        request = self.get_post_request({
            'placeholder_id': static_placeholder.pk,
            'plugin_id': link_plugin_pk,
            'plugin_order': ['__COPY__'],
            'move_a_copy': 'true',
        })
        response = manual_placeholder_admin.move_plugin(request)

        self.assertEqual(response.status_code, 200)

        # Point to the newly created text plugin
        link_plugin_pk = get_plugin_id_from_response(response)

        # assert revision count remains the same
        self.assertEqual(
            placeholder_versions.count(),
            placeholder_versions_initial_count + 1,
        )

        # copy plugin from static to manual placeholder
        request = self.get_post_request({
            'placeholder_id': manual_placeholder.pk,
            'plugin_id': link_plugin_pk,
            'plugin_order': ['__COPY__'],
            'move_a_copy': 'true',
        })
        response = static_placeholder_admin.move_plugin(request)
        self.assertEqual(response.status_code, 200)

        # assert revision count remains the same
        self.assertEqual(
            placeholder_versions.count(),
            placeholder_versions_initial_count + 1,
        )

        # copy plugin from static to native placeholder
        request = self.get_post_request({
            'placeholder_id': native_placeholder.pk,
            'plugin_id': link_plugin_pk,
            'plugin_order': ['__COPY__'],
            'move_a_copy': 'true',
        })
        response = static_placeholder_admin.move_plugin(request)

        self.assertEqual(response.status_code, 200)

        # Point to the newly created text plugin
        link_plugin_pk = get_plugin_id_from_response(response)

        # assert a new version for the native placeholder has been created
        self.assertEqual(
            native_placeholder_versions.count(),
            native_placeholder_versions_initial_count + 2,
        )

        # assert a new version for the link plugin has been created
        self.assertEqual(
            link_plugin_versions.filter(object_id_int=link_plugin_pk).count(),
            1,
        )

        # assert revision comment was set correctly
        self.assertEqual(
            Revision.objects.latest('pk').comment,
            'Copied plugins to %s' % force_text(native_placeholder),
        )
    def test_revision_on_plugin_move(self):
        from cms.plugin_pool import plugin_pool

        placeholder_c_type = ContentType.objects.get_for_model(Placeholder)
        placeholder_versions = Version.objects.filter(
            content_type=placeholder_c_type)

        LinkPluginModel = plugin_pool.get_plugin('LinkPlugin').model
        link_plugin_c_type = ContentType.objects.get_for_model(LinkPluginModel)

        # three placeholder types
        # native - native CMS placeholder (created using a placeholder tag)
        # manual - Manual placeholder (created using a PlaceholderField)
        # static - Static placeholder (created using the staticplaceholder tag)

        native_placeholder_page = create_page('test page', 'simple.html',
                                              u'en')
        native_placeholder = native_placeholder_page.placeholders.get(
            slot='placeholder')
        native_placeholder_pk = native_placeholder.pk
        native_placeholder_admin = self.get_page_admin()
        native_placeholder_versions = placeholder_versions.filter(
            object_id_int=native_placeholder_pk)
        native_placeholder_versions_initial_count = native_placeholder_versions.count(
        )

        example = Example1.objects.create(
            char_1='one',
            char_2='two',
            char_3='tree',
            char_4='four',
        )
        manual_placeholder = example.placeholder
        manual_placeholder_admin = self.get_example_admin()

        static_placeholder_obj = StaticPlaceholder.objects.create(
            name='static',
            code='static',
            site_id=1,
        )
        static_placeholder = static_placeholder_obj.draft
        static_placeholder_admin = self.get_staticplaceholder_admin()

        data = {
            'placeholder': native_placeholder,
            'plugin_type': 'LinkPlugin',
            'language': 'en',
        }

        # Add plugin to feature
        link_plugin = add_plugin(**data)
        link_plugin_pk = link_plugin.pk
        link_plugin_versions = Version.objects.filter(
            content_type=link_plugin_c_type,
            object_id_int=link_plugin_pk,
        )
        link_plugin_versions_initial_count = link_plugin_versions.count()

        # move plugin to manual placeholder
        request = self.get_post_request({
            'placeholder_id': manual_placeholder.pk,
            'plugin_id': link_plugin_pk,
        })
        response = native_placeholder_admin.move_plugin(request)
        self.assertEqual(response.status_code, 200)

        # assert a new version for the native placeholder has been created
        self.assertEqual(
            native_placeholder_versions.count(),
            native_placeholder_versions_initial_count + 1,
        )

        # assert revision comment was set correctly
        self.assertEqual(
            Revision.objects.latest('pk').comment,
            'Moved plugins to %s' % force_text(manual_placeholder),
        )

        # move plugin back to native
        request = self.get_post_request({
            'placeholder_id': native_placeholder_pk,
            'plugin_id': link_plugin_pk,
        })
        response = manual_placeholder_admin.move_plugin(request)
        self.assertEqual(response.status_code, 200)

        # assert a new version for the native placeholder has been created
        self.assertEqual(
            native_placeholder_versions.count(),
            native_placeholder_versions_initial_count + 2,
        )

        # assert a new version for the link plugin has been created
        self.assertEqual(
            link_plugin_versions.count(),
            link_plugin_versions_initial_count + 1,
        )

        # assert revision comment was set correctly
        self.assertEqual(
            Revision.objects.latest('pk').comment,
            'Moved plugins to %s' % force_text(native_placeholder),
        )

        # move plugin to static placeholder
        request = self.get_post_request({
            'placeholder_id': static_placeholder.pk,
            'plugin_id': link_plugin_pk,
        })
        response = native_placeholder_admin.move_plugin(request)
        self.assertEqual(response.status_code, 200)

        # assert a new version for the native placeholder has been created
        self.assertEqual(
            native_placeholder_versions.count(),
            native_placeholder_versions_initial_count + 3,
        )

        # assert revision comment was set correctly
        self.assertEqual(
            Revision.objects.latest('pk').comment,
            'Moved plugins to %s' % force_text(static_placeholder),
        )

        # move plugin back to native
        request = self.get_post_request({
            'placeholder_id': native_placeholder.pk,
            'plugin_id': link_plugin_pk,
        })
        response = static_placeholder_admin.move_plugin(request)
        self.assertEqual(response.status_code, 200)

        # assert a new version for the native placeholder has been created
        self.assertEqual(
            native_placeholder_versions.count(),
            native_placeholder_versions_initial_count + 4,
        )

        # assert a new version for the link plugin has been created
        self.assertEqual(
            link_plugin_versions.count(),
            link_plugin_versions_initial_count + 2,
        )

        # assert revision comment was set correctly
        self.assertEqual(
            Revision.objects.latest('pk').comment,
            'Moved plugins to %s' % force_text(native_placeholder),
        )
Example #37
0
 def test_create_page_can_overwrite_url(self):
     page_attrs = self._get_default_create_page_arguments()
     page_attrs["overwrite_url"] = 'test/home'
     page = create_page(**page_attrs)
     self.assertTrue(page.get_title_obj_attribute('has_url_overwrite'))
     self.assertEqual(page.get_title_obj_attribute('path'), 'test/home')
Example #38
0
    def setUp(self):
        # create super user
        self.user_super = User(username="******",
                               is_staff=True,
                               is_active=True,
                               is_superuser=True)
        self.user_super.set_password("super")
        self.user_super.save()
        with self.login_user_context(self.user_super):

            self.home_page = create_page("home",
                                         "nav_playground.html",
                                         "en",
                                         created_by=self.user_super)

            # master page & master user

            self.master_page = create_page("master", "nav_playground.html",
                                           "en")

            # create master user
            self.user_master = User.objects.create(
                username="******",
                email="*****@*****.**",
                password="******",
                is_staff=True)
            self.user_master.user_permissions.add(
                Permission.objects.get(codename='publish_page'))
            #self.user_master = create_page_user(self.user_super, master, grant_all=True)

            # assign master user under home page
            assign_user_to_page(self.home_page,
                                self.user_master,
                                grant_on=ACCESS_DESCENDANTS,
                                grant_all=True)

            # and to master page
            assign_user_to_page(self.master_page,
                                self.user_master,
                                grant_all=True)

            # slave page & slave user

            self.slave_page = create_page("slave-home",
                                          "nav_playground.html",
                                          "en",
                                          parent=self.master_page,
                                          created_by=self.user_super)
            slave = User(username='******',
                         email='*****@*****.**',
                         is_staff=True,
                         is_active=True)
            slave.set_password('slave')
            slave.save()
            self.user_slave = create_page_user(self.user_super,
                                               slave,
                                               can_add_page=True,
                                               can_change_page=True,
                                               can_delete_page=True)

            assign_user_to_page(self.slave_page,
                                self.user_slave,
                                grant_all=True)

            # create page_a - sample page from master

            page_a = create_page("pageA",
                                 "nav_playground.html",
                                 "en",
                                 created_by=self.user_super)
            assign_user_to_page(page_a,
                                self.user_master,
                                can_add=True,
                                can_change=True,
                                can_delete=True,
                                can_publish=True,
                                can_move_page=True)

            # publish after creating all drafts
            publish_page(self.home_page, self.user_super)
            publish_page(self.master_page, self.user_super)

        with self.login_user_context(self.user_slave):

            # all of them are under moderation...
            self.pa = create_page("pa",
                                  "nav_playground.html",
                                  "en",
                                  parent=self.slave_page)
            self.pb = create_page("pb",
                                  "nav_playground.html",
                                  "en",
                                  parent=self.pa,
                                  position="right")
            self.pc = create_page("pc",
                                  "nav_playground.html",
                                  "en",
                                  parent=self.pb,
                                  position="right")

            self.pd = create_page("pd",
                                  "nav_playground.html",
                                  "en",
                                  parent=self.pb)
            self.pe = create_page("pe",
                                  "nav_playground.html",
                                  "en",
                                  parent=self.pd,
                                  position="right")

            self.pf = create_page("pf",
                                  "nav_playground.html",
                                  "en",
                                  parent=self.pe)
            self.pg = create_page("pg",
                                  "nav_playground.html",
                                  "en",
                                  parent=self.pf,
                                  position="right")
            self.ph = create_page("ph",
                                  "nav_playground.html",
                                  "en",
                                  parent=self.pf,
                                  position="right")

            self.assertFalse(self.pg.publisher_public)

            # login as master for approval
            publish_page(self.slave_page, self.user_master)

            # publish and approve them all
            publish_page(self.pa, self.user_master)
            publish_page(self.pb, self.user_master)
            publish_page(self.pc, self.user_master)
            publish_page(self.pd, self.user_master)
            publish_page(self.pe, self.user_master)
            publish_page(self.pf, self.user_master)
            publish_page(self.pg, self.user_master)
            publish_page(self.ph, self.user_master)
Example #39
0
    def test_untranslated_language_url(self):
        """ Tests page_language_url templatetag behavior when used on a page
          without the requested translation, both when CMS_HIDE_UNTRANSLATED is
          True and False.
          When True it should return the root page URL if the current page is
           untranslated (PR #1125)

        """
        page_1 = create_page('Page 1',
                             'nav_playground.html',
                             'en',
                             published=True,
                             in_navigation=True,
                             reverse_id='page1')
        create_title("de", "Seite 1", page_1, slug="seite-1")
        page_1.publish('en')
        page_1.publish('de')
        page_2 = create_page('Page 2',
                             'nav_playground.html',
                             'en',
                             page_1,
                             published=True,
                             in_navigation=True,
                             reverse_id='page2')
        create_title("de", "Seite 2", page_2, slug="seite-2")
        page_2.publish('en')
        page_2.publish('de')
        page_3 = create_page('Page 3',
                             'nav_playground.html',
                             'en',
                             page_2,
                             published=True,
                             in_navigation=True,
                             reverse_id='page3')
        tpl = Template("{% load menu_tags %}{% page_language_url 'de' %}")
        lang_settings = copy.deepcopy(get_cms_setting('LANGUAGES'))
        lang_settings[1][1]['hide_untranslated'] = False
        with self.settings(CMS_LANGUAGES=lang_settings):
            context = self.get_context(page_2.get_absolute_url())
            context['request'].current_page = page_2
            res = tpl.render(context)
            self.assertEqual(res, "/de/seite-2/")

            # Default configuration has CMS_HIDE_UNTRANSLATED=False
            context = self.get_context(page_2.get_absolute_url())
            context['request'].current_page = page_2.publisher_public
            res = tpl.render(context)
            self.assertEqual(res, "/de/seite-2/")

            context = self.get_context(page_3.get_absolute_url())
            context['request'].current_page = page_3.publisher_public
            res = tpl.render(context)
            self.assertEqual(res, "/de/page-3/")
        lang_settings[1][1]['hide_untranslated'] = True

        with self.settings(CMS_LANGUAGES=lang_settings):
            context = self.get_context(page_2.get_absolute_url())
            context['request'].current_page = page_2.publisher_public
            res = tpl.render(context)
            self.assertEqual(res, "/de/seite-2/")

            context = self.get_context(page_3.get_absolute_url())
            context['request'].current_page = page_3.publisher_public
            res = tpl.render(context)
            self.assertEqual(res, "/de/")
Example #40
0
    def setUp(self):
        # create super user
        self.user_super = self._create_user("super", is_superuser=True)
        self.user_staff = self._create_user("staff")
        self.user_master = self._create_user("master")
        self.user_slave = self._create_user("slave")
        self.user_normal = self._create_user("normal", is_staff=False)
        self.user_normal.user_permissions.add(
            Permission.objects.get(codename='publish_page'))

        with self.login_user_context(self.user_super):

            self.home_page = create_page("home",
                                         "nav_playground.html",
                                         "en",
                                         created_by=self.user_super)

            # master page & master user

            self.master_page = create_page("master", "nav_playground.html",
                                           "en")

            # create non global, non staff user
            self.user_non_global = User(username="******", is_active=True)
            self.user_non_global.set_password("nonglobal")
            self.user_non_global.save()

            # assign master user under home page
            assign_user_to_page(self.home_page,
                                self.user_master,
                                grant_on=ACCESS_DESCENDANTS,
                                grant_all=True)

            # and to master page
            assign_user_to_page(self.master_page,
                                self.user_master,
                                grant_on=ACCESS_PAGE_AND_DESCENDANTS,
                                grant_all=True)

            # slave page & slave user

            self.slave_page = create_page("slave-home",
                                          "nav_playground.html",
                                          "en",
                                          parent=self.master_page,
                                          created_by=self.user_super)

            assign_user_to_page(self.slave_page,
                                self.user_slave,
                                grant_all=True)

            # create page_b
            page_b = create_page("pageB",
                                 "nav_playground.html",
                                 "en",
                                 created_by=self.user_super)
            # Normal user

            # it's allowed for the normal user to view the page
            assign_user_to_page(page_b, self.user_normal, can_view=True)

            # create page_a - sample page from master

            page_a = create_page("pageA",
                                 "nav_playground.html",
                                 "en",
                                 created_by=self.user_super)
            assign_user_to_page(page_a,
                                self.user_master,
                                can_add=True,
                                can_change=True,
                                can_delete=True,
                                can_publish=True,
                                can_move_page=True)

            # publish after creating all drafts
            publish_page(self.home_page, self.user_super)

            publish_page(self.master_page, self.user_super)

            self.page_b = publish_page(page_b, self.user_super)
Example #41
0
    def test_copy_site_safe(self):
        """
        Check that copy of languages on one site does not interfere with other
        sites
        """
        site_other = 1
        site_active = 2
        origina_site1_langs = {}

        number_start_plugins = CMSPlugin.objects.all().count()
        site_obj = Site.objects.create(domain="sample2.com",
                                       name="sample2.com",
                                       pk=site_active)

        for page in Page.objects.on_site(1).drafts():
            origina_site1_langs[page.pk] = set(page.get_languages())

        p1 = create_page('page1',
                         published=True,
                         in_navigation=True,
                         language='de',
                         template='nav_playground.html',
                         site=site_obj)
        create_page('page4',
                    published=True,
                    in_navigation=True,
                    language='de',
                    template='nav_playground.html',
                    site=site_obj)
        create_page('page2',
                    published=True,
                    in_navigation=True,
                    parent=p1,
                    language='de',
                    template='nav_playground.html',
                    site=site_obj)

        for page in Page.objects.on_site(site_active).drafts():
            self._fill_page_body(page, 'de')

        number_site2_plugins = CMSPlugin.objects.all().count(
        ) - number_start_plugins

        out = StringIO()
        management.call_command('cms',
                                'copy',
                                'lang',
                                '--from-lang=de',
                                '--to-lang=fr',
                                '--site=%s' % site_active,
                                interactive=False,
                                stdout=out)

        for page in Page.objects.on_site(site_other).drafts():
            self.assertEqual(origina_site1_langs[page.pk],
                             set(page.get_languages()))

        for page in Page.objects.on_site(site_active).drafts():
            self.assertEqual(set(('de', 'fr')), set(page.get_languages()))

        # plugins for site 1
        self.assertEqual(
            CMSPlugin.objects.filter(language='en').count(),
            number_start_plugins)
        # plugins for site 2 de
        self.assertEqual(
            CMSPlugin.objects.filter(language='de').count(),
            number_site2_plugins)
        # plugins for site 2 fr
        self.assertEqual(
            CMSPlugin.objects.filter(language='fr').count(),
            number_site2_plugins)
        # global number of plugins
        self.assertEqual(CMSPlugin.objects.all().count(),
                         number_start_plugins + number_site2_plugins * 2)
Example #42
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()
Example #43
0
 def create_fixtures(self):
     """
     top
         root
             aaa
                 111
                     ccc
                         ddd
                 222
             bbb
                 333
                 444
     
     # all in nav, published and NOT softroot
     """
     defaults = {
         'template': 'nav_playground.html',
         'language': 'en',
         'in_navigation': True,
         'published': True,
     }
     with SettingsOverride(CMS_PERMISSION=False):
         top = create_page('top', **defaults)
         root = create_page('root', parent=top, **defaults)
         aaa = create_page('aaa', parent=root, **defaults)
         _111 = create_page('111', parent=aaa, **defaults)
         ccc = create_page('ccc', parent=_111, **defaults)
         create_page('ddd', parent=ccc, **defaults)
         aaa = Page.objects.get(pk=aaa.pk)
         create_page('222', parent=aaa, **defaults)
         root = Page.objects.get(pk=root.pk)
         bbb = create_page('bbb', parent=root, **defaults)
         create_page('333', parent=bbb, **defaults)
         bbb = Page.objects.get(pk=bbb.pk)
         create_page('444', parent=bbb, **defaults)
Example #44
0
    def test_context_current_page(self):
        """
        Asserts the number of queries triggered by
        `cms.context_processors.cms_settings` and `cms.middleware.page`
        """
        from django.template import context

        page_template = "nav_playground.html"
        original_context = {'TEMPLATES': settings.TEMPLATES}
        page = create_page("page", page_template, "en", published=True)
        page_2 = create_page("page-2",
                             page_template,
                             "en",
                             published=True,
                             parent=page)

        # Tests for standard django applications
        # 1 query is executed in get_app_patterns(), not related
        # to cms.context_processors.cms_settings.
        # Executing this oputside queries assertion context ensure
        # repetability
        self.client.get("/en/plain_view/")

        cache.clear()
        menu_pool.clear()
        context._standard_context_processors = None

        # Number of queries when context processor is enabled
        with self.settings(**original_context):
            with self.assertNumQueries(FuzzyInt(0, 17)):
                response = self.client.get("/en/plain_view/")
            # One query when determining current page
            with self.assertNumQueries(FuzzyInt(0, 1)):
                self.assertFalse(response.context['request'].current_page)
                self.assertFalse(
                    response.context['request']._current_page_cache)
            # Zero more queries when determining the current template
            with self.assertNumQueries(0):
                # Template is the first in the CMS_TEMPLATES list
                template = Variable('CMS_TEMPLATE').resolve(response.context)
                self.assertEqual(template, get_cms_setting('TEMPLATES')[0][0])
        cache.clear()
        menu_pool.clear()

        # Number of queries when context processors is enabled
        with self.settings(**original_context):
            with self.assertNumQueries(FuzzyInt(13, 25)) as context:
                response = self.client.get("/en/page-2/")
                template = Variable('CMS_TEMPLATE').resolve(response.context)
                self.assertEqual(template, page_template)
                num_queries_page = len(context.captured_queries)
        cache.clear()
        menu_pool.clear()
        page_2.template = 'INHERIT'
        page_2.save()
        page_2.publish('en')
        with self.settings(**original_context):
            # One query more triggered as page inherits template from ancestor
            with self.assertNumQueries(num_queries_page + 1):
                response = self.client.get("/en/page-2/")
                template = Variable('CMS_TEMPLATE').resolve(response.context)
                self.assertEqual(template, page_template)
Example #45
0
def create_i18n_page(title=None, languages=None, is_homepage=False, **kwargs):
    """
    Creating a multilingual page is not straightforward so we should have a helper

    This content argument should be a dictionary with the title of the page in each language:

        {
            'en': 'About',
            'fr': 'A propos',
            'de': 'Impressum',
        }

    """
    template = kwargs.pop("template", None) or "richie/fullwidth.html"

    if title is None:
        # Create realistic titles in each language with faker
        languages = languages or [settings.LANGUAGE_CODE]
        i18n_titles = {
            language: factory.Faker("catch_phrase", locale=language).generate({})
            for language in languages
        }

    elif isinstance(title, dict):
        # Check that the languages passed are coherent with the languages requested if any
        if languages:
            assert set(languages).issubset(title.keys())
        else:
            languages = title.keys()
        i18n_titles = title

    elif isinstance(title, str):
        # Add a marker at the end of the string to differentiate each language
        languages = languages or [settings.LANGUAGE_CODE]
        i18n_titles = {language: title for language in languages}

    else:
        raise ValueError(
            "Title should be a string or a dictionary of language/string pairs"
        )

    # Assert that the languages passed are declared in settings
    assert set(languages).issubset({l[0] for l in settings.LANGUAGES})
    # Make a copy of languages to avoid muting it in what follows
    languages = list(languages)
    # Create the page with a first language from what is given to us
    first_language = languages.pop(0)

    slug = slugify(i18n_titles[first_language])
    page = create_page(
        language=first_language,
        menu_title=i18n_titles[first_language],
        title=i18n_titles[first_language],
        slug=slug,
        template=template,
        **kwargs,
    )

    if is_homepage is True:
        page.set_as_homepage()

    # Add a title for each additional language
    for language in languages:
        create_title(
            language=language,
            menu_title=i18n_titles[language],
            title=i18n_titles[language],
            slug=slugify(i18n_titles[language]),
            page=page,
        )
        # Publish page in each additional language
        if kwargs.get("published") is True:
            page.publish(language)

    return page
Example #46
0
 def create_fixtures(self):
     """
     Tree from fixture:
         
         + P1
         | + P2
         |   + P3
         + P4
         | + P5
         + P6 (not in menu)
           + P7
           + P8
     """
     defaults = {
         'template': 'nav_playground.html',
         'language': 'en',
     }
     with SettingsOverride(CMS_PERMISSION=False):
         p1 = create_page('P1',
                          published=True,
                          in_navigation=True,
                          **defaults)
         p4 = create_page('P4',
                          published=True,
                          in_navigation=True,
                          **defaults)
         p6 = create_page('P6',
                          published=True,
                          in_navigation=False,
                          **defaults)
         p1 = Page.objects.get(pk=p1.pk)
         p2 = create_page('P2',
                          published=True,
                          in_navigation=True,
                          parent=p1,
                          **defaults)
         create_page('P3',
                     published=True,
                     in_navigation=True,
                     parent=p2,
                     **defaults)
         p4 = Page.objects.get(pk=p4.pk)
         create_page('P5',
                     published=True,
                     in_navigation=True,
                     parent=p4,
                     **defaults)
         p6 = Page.objects.get(pk=p6.pk)
         create_page('P7',
                     published=True,
                     in_navigation=True,
                     parent=p6,
                     **defaults)
         p6 = Page.objects.get(pk=p6.pk)
         create_page('P8',
                     published=True,
                     in_navigation=True,
                     parent=p6,
                     **defaults)
Example #47
0
    def test_cms_modal_html5_validation_error(self):
        User = get_user_model()
        try:
            apphook_pool.register(Example1App)
        except AppAlreadyRegistered:
            pass
        self.reload_urls()
        create_page('Home', 'simple.html', 'fr', published=True)
        ex1 = Example1.objects.create(char_1='char_1',
                                      char_2='char_1',
                                      char_3='char_3',
                                      char_4='char_4',
                                      date_field=datetime.datetime.now())
        create_page('apphook',
                    'simple.html',
                    'fr',
                    published=True,
                    apphook=Example1App)
        url = '%s/%s/?%s' % (self.live_server_url,
                             'fr/apphook/detail/class/%s' % ex1.pk,
                             get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON'))
        self.driver.get(url)
        username_input = self.driver.find_element_by_id("id_cms-username")
        username_input.send_keys(getattr(self.user, User.USERNAME_FIELD))
        password_input = self.driver.find_element_by_id("id_cms-password")
        password_input.send_keys(getattr(self.user, User.USERNAME_FIELD))
        password_input.submit()
        self.wait_page_loaded()

        # Load modal iframe
        add_button = self.driver.find_element_by_css_selector(
            '.cms-plugin-placeholderapp-example1-add-0')
        open_modal_actions = ActionChains(self.driver)
        open_modal_actions.double_click(add_button)
        open_modal_actions.perform()
        WebDriverWait(self.driver, 10).until(
            EC.frame_to_be_available_and_switch_to_it((By.XPATH, '//iframe')))
        # Fills form with an html5 error
        char_1_input = self.driver.find_element_by_id("id_char_1")
        char_1_input.send_keys("test")
        char_2_input = self.driver.find_element_by_id("id_char_2")
        char_2_input.send_keys("test")
        char_3_input = self.driver.find_element_by_id("id_char_3")
        char_3_input.send_keys("test")
        char_4_input = self.driver.find_element_by_id("id_char_4")
        char_4_input.send_keys("test")
        id_date_input = self.driver.find_element_by_id("id_date_field")
        id_date_input.send_keys('2036-01-01')
        id_decimal_input = self.driver.find_element_by_id("id_decimal_field")
        id_decimal_input.send_keys('t')

        self.driver.switch_to_default_content()
        submit_button = self.driver.find_element_by_css_selector('.default')
        submit_button.click()

        # check if the iframe is still displayed because of the html5 error
        modal_iframe = self.driver.find_element_by_css_selector('iframe')
        self.assertTrue(modal_iframe.is_displayed())

        # corrects html5 error
        self.driver.switch_to_frame(modal_iframe)
        id_decimal_input = self.driver.find_element_by_id("id_decimal_field")
        id_decimal_input.send_keys(Keys.BACK_SPACE + '1.2')
        self.driver.switch_to_default_content()
        submit_button = self.driver.find_element_by_css_selector('.default')
        submit_button.click()
        time.sleep(10)
        with self.assertRaises(NoSuchElementException):
            self.driver.find_element_by_css_selector('iframe')
        example = Example1.objects.get(char_1='test')
        self.assertEqual(float(example.decimal_field), 1.2)
Example #48
0
    def setUp(self):
        # create super user
        self.user_super = User(username="******",
                               is_staff=True,
                               is_active=True,
                               is_superuser=True)
        self.user_super.set_password("super")
        self.user_super.save()
        # create staff user
        self.user_staff = User(username="******", is_staff=True, is_active=True)
        self.user_staff.set_password("staff")
        self.user_staff.save()

        with self.login_user_context(self.user_super):

            self._home_page = create_page("home",
                                          "nav_playground.html",
                                          "en",
                                          created_by=self.user_super)

            # master page & master user

            self._master_page = create_page("master", "nav_playground.html",
                                            "en")

            # create master user
            master = User(username="******",
                          email="*****@*****.**",
                          is_staff=True,
                          is_active=True)
            master.set_password('master')
            master.save()
            master.user_permissions.add(
                Permission.objects.get(codename='add_text'))
            master.user_permissions.add(
                Permission.objects.get(codename='delete_text'))
            master.user_permissions.add(
                Permission.objects.get(codename='change_text'))

            self.user_master = create_page_user(self.user_super,
                                                master,
                                                grant_all=True)
            # create non global, non staff user
            self.user_non_global = User(username="******", is_active=True)
            self.user_non_global.set_password("nonglobal")
            self.user_non_global.save()

            # assign master user under home page
            assign_user_to_page(self.home_page,
                                self.user_master,
                                grant_on=ACCESS_DESCENDANTS,
                                grant_all=True)

            # and to master page
            assign_user_to_page(self.master_page,
                                self.user_master,
                                grant_on=ACCESS_PAGE_AND_DESCENDANTS,
                                grant_all=True)

            # slave page & slave user

            self._slave_page = create_page("slave-home",
                                           "nav_playground.html",
                                           "en",
                                           parent=self.master_page,
                                           created_by=self.user_super)

            slave = User(username='******',
                         email='*****@*****.**',
                         is_staff=True)
            slave.set_password('slave')
            slave.save()
            slave.user_permissions.add(
                Permission.objects.get(codename='add_text'))
            slave.user_permissions.add(
                Permission.objects.get(codename='delete_text'))
            slave.user_permissions.add(
                Permission.objects.get(codename='change_text'))

            self.user_slave = create_page_user(self.user_super,
                                               slave,
                                               can_add_page=True,
                                               can_change_page=True,
                                               can_delete_page=True)

            assign_user_to_page(self.slave_page,
                                self.user_slave,
                                grant_all=True)

            # create page_b
            page_b = create_page("pageB",
                                 "nav_playground.html",
                                 "en",
                                 created_by=self.user_super)
            # Normal user
            normal = User(username='******',
                          email='*****@*****.**',
                          is_active=True)
            normal.set_password('normal')
            normal.save()
            self.user_normal = create_page_user(self.user_master, normal)
            # it's allowed for the normal user to view the page
            assign_user_to_page(page_b, self.user_normal, can_view=True)
            self.user_normal = self.reload(self.user_normal)
            # create page_a - sample page from master

            page_a = create_page("pageA",
                                 "nav_playground.html",
                                 "en",
                                 created_by=self.user_super)
            assign_user_to_page(page_a,
                                self.user_master,
                                can_add=True,
                                can_change=True,
                                can_delete=True,
                                can_publish=True,
                                can_move_page=True,
                                can_moderate=True)

            # publish after creating all drafts
            publish_page(self.home_page, self.user_super)

            publish_page(self.master_page, self.user_super)

            self.page_b = publish_page(page_b, self.user_super)
            # logg in as master, and request moderation for slave page and descendants
            self.request_moderation(self.slave_page, 7)
Example #49
0
    def test_render_child_plugin_endpoint(self):
        simple_page = create_page('test page', 'page.html', u'en')
        simple_placeholder = get_page_placeholders(simple_page,
                                                   'en').get(slot='content')
        text_plugin = add_plugin(
            simple_placeholder,
            'TextPlugin',
            'en',
            body="I'm the first",
        )
        text_plugin_class = text_plugin.get_plugin_class_instance()
        child_plugin = self._add_child_plugin(text_plugin)
        text_plugin = self.add_plugin_to_text(text_plugin, child_plugin)

        with self.login_user_context(self.get_superuser()):
            request = self.get_request()
            action_token = text_plugin_class.get_action_token(
                request, text_plugin)
            endpoint = self.get_custom_admin_url(TextPlugin, 'render_plugin')
            endpoint += '?token={}&plugin={}'.format(action_token,
                                                     child_plugin.pk)
            response = self.client.get(endpoint)

            self.assertEqual(response.status_code, 200)

            context = RequestContext(request)
            context['request'] = request
            rendered_content = _render_cms_plugin(child_plugin, context)
            rendered_child_plugin = plugin_to_tag(
                child_plugin,
                content=rendered_content,
                admin=True,
            )

            self.assertEqual(force_text(response.content),
                             rendered_child_plugin)

        child_plugin = self._add_child_plugin(
            text_plugin, plugin_type='PreviewDisabledPlugin')
        text_plugin = self.add_plugin_to_text(text_plugin, child_plugin)

        with self.login_user_context(self.get_superuser()):
            request = self.get_request()
            action_token = text_plugin_class.get_action_token(
                request, text_plugin)
            endpoint = self.get_custom_admin_url(TextPlugin, 'render_plugin')
            endpoint += '?token={}&plugin={}'.format(action_token,
                                                     child_plugin.pk)
            response = self.client.get(endpoint)

            self.assertEqual(response.status_code, 200)

            # it is important that we do not add any extra whitespace inside of
            # <cms-plugin></cms-plugin>
            rendered_child_plugin = (
                '<cms-plugin render-plugin=false '
                'alt="Preview Disabled Plugin - 3 '
                '"title="Preview Disabled Plugin - 3" '
                'id="3"><span>Preview is disabled for this plugin</span>'
                '</cms-plugin>')

            self.assertEqual(force_text(response.content),
                             rendered_child_plugin)
    def _setup_tree_pages(self):
        stdkwargs = {
            'template': 'nav_playground.html',
            'language': 'en',
            'published': True,
            'in_navigation': True,
        }
        page_a = create_page("page_a", **stdkwargs) # first page slug is /
        page_b = create_page("page_b", **stdkwargs)
        page_c = create_page("page_c", **stdkwargs)
        page_d = create_page("page_d", **stdkwargs)

        page_b_a = create_page("page_b_a", parent=page_b, **stdkwargs)
        page_b_b = create_page("page_b_b", parent=page_b, **stdkwargs)
        page_b_b_a = create_page("page_b_b_a", parent=page_b_b, **stdkwargs)
        page_b_b_b = create_page("page_b_b_b", parent=page_b_b, **stdkwargs)
        page_b_b_c = create_page("page_b_b_c", parent=page_b_b, **stdkwargs)
        page_b_b_a_a = create_page("page_b_b_a_a", parent=page_b_b_a, **stdkwargs)

        page_b_c = create_page("page_b_c", parent=page_b, **stdkwargs)
        page_b_d = create_page("page_b_d", parent=page_b, **stdkwargs)
        page_b_d_a = create_page("page_b_d_a", parent=page_b_d, **stdkwargs)
        page_b_d_b = create_page("page_b_d_b", parent=page_b_d, **stdkwargs)
        page_b_d_c = create_page("page_b_d_c", parent=page_b_d, **stdkwargs)

        page_c_a = create_page("page_c_a", parent=page_c, **stdkwargs)
        page_c_b = create_page("page_c_b", parent=page_c, **stdkwargs)

        page_d_a = create_page("page_d_a", parent=page_d, **stdkwargs)
        page_d_b = create_page("page_d_b", parent=page_d, **stdkwargs)
        page_d_c = create_page("page_d_c", parent=page_d, **stdkwargs)
        page_d_d = create_page("page_d_d", parent=page_d, **stdkwargs)

        pages = [
            page_a,
            page_b,
            page_b_a,
            page_b_b,
            page_b_b_a,
            page_b_b_a_a,
            page_b_b_b,
            page_b_b_c,
            page_b_c,
            page_b_d,
            page_b_d_a,
            page_b_d_b,
            page_b_d_c,
            page_c,
            page_c_a,
            page_c_b,
            page_d,
            page_d_a,
            page_d_b,
            page_d_c,
            page_d_d,
        ]

        new_pages = []
        for page in pages:
            new_pages.append(page.reload())
        return new_pages
 def _create_page(self, **data):
     return create_page(title='test_page',
                        reverse_id='testpage',
                        template='test.html',
                        language='en',
                        **data)
Example #52
0
 def setUp(self):
     super(DjangoCMSTranslationsIntegrationTestCase, self).setUp()
     self.page = create_page('test page', 'page.html', 'en', published=True)
     self.placeholder = get_page_placeholders(self.page,
                                              'en').get(slot='content')
Example #53
0
    def test_publish_works_with_descendants(self):
        """
        For help understanding what this tests for, see:
        http://articles.sitepoint.com/print/hierarchical-data-database

        Creates this published structure:
                            home
                          /      \
                       item1   item2
                              /     \
                         subitem1 subitem2
        """
        home_page = create_page("home",
                                "nav_playground.html",
                                "en",
                                published=True,
                                in_navigation=False)

        create_page("item1",
                    "nav_playground.html",
                    "en",
                    parent=home_page,
                    published=True)
        item2 = create_page("item2",
                            "nav_playground.html",
                            "en",
                            parent=home_page,
                            published=True)

        create_page("subitem1",
                    "nav_playground.html",
                    "en",
                    parent=item2,
                    published=True)
        create_page("subitem2",
                    "nav_playground.html",
                    "en",
                    parent=item2,
                    published=True)
        item2 = item2.reload()

        self.assertEqual(
            Page.objects.filter(publisher_is_draft=False).count(), 5)
        self.assertEqual(TreeNode.objects.count(), 5)

        child_nodes = list(TreeNode.objects.filter(parent__isnull=False))

        for idx, node in enumerate(child_nodes):
            self.assertEqual(node.path[0:4], node.parent.path[0:4])
            self.assertTrue(node.parent in node.get_ancestors())
            self.assertTrue(node in node.parent.get_descendants())
            self.assertTrue(node in node.parent.get_children())

        # Now call publish again. The structure should not change.
        item2.publish('en')

        self.assertEqual(
            Page.objects.filter(publisher_is_draft=False).count(), 5)
        self.assertEqual(TreeNode.objects.count(), 5)

        child_nodes = list(TreeNode.objects.filter(parent__isnull=False))

        for idx, node in enumerate(child_nodes):
            self.assertEqual(node.path[0:4], node.parent.path[0:4])
            self.assertTrue(node.parent in node.get_ancestors())
            self.assertTrue(node in node.parent.get_descendants())
            self.assertTrue(node in node.parent.get_children())
Example #54
0
    def test_add_and_cancel_child_plugin(self):
        """
        Test that you can add a text plugin
        """
        admin = self.get_superuser()
        simple_page = create_page('test page', 'page.html', u'en')
        simple_placeholder = get_page_placeholders(simple_page,
                                                   'en').get(slot='content')

        text_plugin = add_plugin(
            simple_placeholder,
            'TextPlugin',
            'en',
            body="I'm the first",
        )

        text_plugin_class = text_plugin.get_plugin_class_instance()

        child_plugin_1 = add_plugin(
            simple_placeholder,
            'PicturePlugin',
            'en',
            target=text_plugin,
            picture=self.create_filer_image_object(),
            caption_text='Foo',
        )
        child_plugin_2 = add_plugin(
            simple_placeholder,
            'PicturePlugin',
            'en',
            target=text_plugin,
            picture=self.create_filer_image_object(),
            caption_text='Foo',
        )
        child_plugin_3 = add_plugin(
            simple_placeholder,
            'PicturePlugin',
            'en',
            target=text_plugin,
            picture=self.create_filer_image_object(),
            caption_text='Foo',
        )
        child_plugin_4 = add_plugin(
            simple_placeholder,
            'PicturePlugin',
            'en',
            target=text_plugin,
            picture=self.create_filer_image_object(),
            caption_text='Foo',
        )

        text_plugin = self.add_plugin_to_text(text_plugin, child_plugin_1)
        text_plugin = self.add_plugin_to_text(text_plugin, child_plugin_4)

        with self.login_user_context(admin):
            request = self.get_request()
            action_token = text_plugin_class.get_action_token(
                request, text_plugin)

            # Assert user is unable to delete a saved child plugin
            data = {
                'token': action_token,
                'child_plugins': [child_plugin_1.pk]
            }
            request = self.get_post_request(data)
            response = text_plugin_class.delete_on_cancel(request)
            self.assertEqual(response.status_code, 400)
            self.assertObjectExist(CMSPlugin.objects.all(),
                                   pk=child_plugin_1.pk)

            # Assert user is unable to delete if plugins array contains
            # an unsaved plugin.
            plugin_ids = [
                child_plugin_1.pk,
                child_plugin_2.pk,
                child_plugin_3.pk,
                child_plugin_4.pk,
            ]
            data = {'token': action_token, 'child_plugins': plugin_ids}
            request = self.get_post_request(data)
            response = text_plugin_class.delete_on_cancel(request)
            self.assertEqual(response.status_code, 400)
            self.assertObjectExist(CMSPlugin.objects.all(),
                                   pk=child_plugin_1.pk)
            self.assertObjectExist(CMSPlugin.objects.all(),
                                   pk=child_plugin_2.pk)
            self.assertObjectExist(CMSPlugin.objects.all(),
                                   pk=child_plugin_3.pk)
            self.assertObjectExist(CMSPlugin.objects.all(),
                                   pk=child_plugin_4.pk)

            plugin_ids = [
                child_plugin_2.pk,
                child_plugin_3.pk,
            ]
            data = {'token': action_token, 'child_plugins': plugin_ids}
            request = self.get_post_request(data)
            response = text_plugin_class.delete_on_cancel(request)
            self.assertEqual(response.status_code, 204)

            self.assertObjectDoesNotExist(CMSPlugin.objects.all(),
                                          pk=child_plugin_2.pk)
            self.assertObjectDoesNotExist(CMSPlugin.objects.all(),
                                          pk=child_plugin_3.pk)
Example #55
0
    def test_link(self):

        page = create_page(
            title='help',
            template='page.html',
            language='en',
        )

        plugin = add_plugin(page.placeholders.get(slot='content'),
                            'LinkPlugin',
                            'en',
                            external_link='http://example.com')
        self.assertEqual(plugin.get_link(), 'http://example.com')

        plugin = add_plugin(
            page.placeholders.get(slot='content'),
            'LinkPlugin',
            'en',
            external_link='http://example.com',
            anchor='some-h1',
        )
        self.assertEqual(plugin.get_link(), 'http://example.com#some-h1')

        plugin = add_plugin(
            page.placeholders.get(slot='content'),
            'LinkPlugin',
            'en',
            phone='555-123-555',
        )
        self.assertEqual(plugin.get_link(), 'tel:555-123-555')

        plugin = add_plugin(
            page.placeholders.get(slot='content'),
            'LinkPlugin',
            'en',
            mailto='*****@*****.**',
        )
        self.assertEqual(plugin.get_link(), 'mailto:[email protected]')

        plugin = add_plugin(
            page.placeholders.get(slot='content'),
            'LinkPlugin',
            'en',
            external_link='http://example.com',
        )
        self.assertEqual(plugin.get_link(), 'http://example.com')

        plugin = add_plugin(
            page.placeholders.get(slot='content'),
            'LinkPlugin',
            'en',
            internal_link=page,
        )
        self.assertEqual(plugin.get_link(), '/en/')

        plugin = add_plugin(
            page.placeholders.get(slot='content'),
            'LinkPlugin',
            'en',
            internal_link=page,
            anchor='some-h1',
        )
        self.assertEqual(plugin.get_link(), '/en/#some-h1')

        plugin = add_plugin(
            page.placeholders.get(slot='content'),
            'LinkPlugin',
            'en',
            name='some text',
        )
        self.assertEqual(plugin.get_link(), '')
        self.assertEqual(force_text(plugin), 'some text')
Example #56
0
    def test_site_publish(self):
        self._login_context.__exit__(None, None, None)
        pages = {"2": list(range(0, 5)), "3": list(range(0, 5))}
        lang_settings = copy.deepcopy(get_cms_setting('LANGUAGES'))
        lang_settings[3][1]['public'] = True

        with SettingsOverride(CMS_LANGUAGES=lang_settings, LANGUAGE_CODE="de"):
            with SettingsOverride(SITE_ID=self.site2.pk):
                pages["2"][0] = create_page("page_2",
                                            "nav_playground.html",
                                            "de",
                                            site=self.site2)
                pages["2"][0].publish('de')
                pages["2"][1] = create_page("page_2_1",
                                            "nav_playground.html",
                                            "de",
                                            parent=pages["2"][0],
                                            site=self.site2)
                pages["2"][2] = create_page("page_2_2",
                                            "nav_playground.html",
                                            "de",
                                            parent=pages["2"][0],
                                            site=self.site2)
                pages["2"][3] = create_page("page_2_1_1",
                                            "nav_playground.html",
                                            "de",
                                            parent=pages["2"][1],
                                            site=self.site2)
                pages["2"][4] = create_page("page_2_1_2",
                                            "nav_playground.html",
                                            "de",
                                            parent=pages["2"][1],
                                            site=self.site2)

                for page in pages["2"]:
                    page.publish('de')
                for page in pages["2"]:
                    if page.is_home:
                        page_url = "/de/"
                    else:
                        page_url = page.get_absolute_url(language='de')
                    response = self.client.get(page_url)
                    self.assertEqual(response.status_code, 200)

            with SettingsOverride(SITE_ID=self.site3.pk):
                pages["3"][0] = create_page("page_3",
                                            "nav_playground.html",
                                            "de",
                                            site=self.site3)
                pages["3"][0].publish('de')
                pages["3"][1] = create_page("page_3_1",
                                            "nav_playground.html",
                                            "de",
                                            parent=pages["3"][0],
                                            site=self.site3)
                pages["3"][2] = create_page("page_3_2",
                                            "nav_playground.html",
                                            "de",
                                            parent=pages["3"][0],
                                            site=self.site3)
                pages["3"][3] = create_page("page_3_1_1",
                                            "nav_playground.html",
                                            "de",
                                            parent=pages["3"][1],
                                            site=self.site3)
                pages["3"][4] = create_page("page_3_1_2",
                                            "nav_playground.html",
                                            "de",
                                            parent=pages["3"][1],
                                            site=self.site3)

                for page in pages["3"]:
                    page.publish('de')
                for page in pages["3"]:
                    if page.is_home:
                        page_url = "/de/"
                    else:
                        page_url = page.get_absolute_url(language='de')
                    response = self.client.get(page_url)
                    self.assertEqual(response.status_code, 200)
Example #57
0
    def test_no_cache_plugin(self):
        page1 = create_page('test page 1', 'nav_playground.html', 'en',
                            published=True)

        placeholder1 = page1.placeholders.filter(slot='body')[0]
        placeholder2 = page1.placeholders.filter(slot='right-column')[0]
        try:
            plugin_pool.register_plugin(NoCachePlugin)
        except PluginAlreadyRegistered:
            pass
        add_plugin(placeholder1, 'TextPlugin', 'en', body="English")
        add_plugin(placeholder2, 'TextPlugin', 'en', body="Deutsch")
        template = "{% load cms_tags %}{% placeholder 'body' %}{% placeholder 'right-column' %}"

        # Ensure that we're testing in an environment WITHOUT the MW cache, as
        # we are testing the internal page cache, not the MW cache.
        exclude = [
            'django.middleware.cache.UpdateCacheMiddleware',
            'django.middleware.cache.CacheMiddleware',
            'django.middleware.cache.FetchFromCacheMiddleware'
        ]
        mw_classes = [mw for mw in settings.MIDDLEWARE_CLASSES if mw not in exclude]

        with self.settings(MIDDLEWARE_CLASSES=mw_classes):
            # Request the page without the 'no-cache' plugin
            request = self.get_request('/en/')
            request.current_page = Page.objects.get(pk=page1.pk)
            request.toolbar = CMSToolbar(request)
            with self.assertNumQueries(FuzzyInt(18, 25)):
                response1 = self.client.get('/en/')
                content1 = response1.content

            # Fetch it again, it is cached.
            request = self.get_request('/en/')
            request.current_page = Page.objects.get(pk=page1.pk)
            request.toolbar = CMSToolbar(request)
            with self.assertNumQueries(0):
                response2 = self.client.get('/en/')
                content2 = response2.content
            self.assertEqual(content1, content2)

            # Once again with PAGE_CACHE=False, to prove the cache can
            # be disabled
            request = self.get_request('/en/')
            request.current_page = Page.objects.get(pk=page1.pk)
            request.toolbar = CMSToolbar(request)
            with self.settings(CMS_PAGE_CACHE=False):
                with self.assertNumQueries(FuzzyInt(5, 24)):
                    response3 = self.client.get('/en/')
                    content3 = response3.content
            self.assertEqual(content1, content3)

            # Add the 'no-cache' plugin
            add_plugin(placeholder1, "NoCachePlugin", 'en')
            page1.publish('en')
            request = self.get_request('/en/')
            request.current_page = Page.objects.get(pk=page1.pk)
            request.toolbar = CMSToolbar(request)
            with self.assertNumQueries(FuzzyInt(4, 6)):
                output = self.render_template_obj(template, {}, request)
            with self.assertNumQueries(FuzzyInt(14, 24)):
                response = self.client.get('/en/')
                self.assertTrue("no-cache" in response['Cache-Control'])
                resp1 = response.content.decode('utf8').split("$$$")[1]

            request = self.get_request('/en/')
            request.current_page = Page.objects.get(pk=page1.pk)
            request.toolbar = CMSToolbar(request)
            with self.assertNumQueries(4):
                output2 = self.render_template_obj(template, {}, request)
            with self.settings(CMS_PAGE_CACHE=False):
                with self.assertNumQueries(FuzzyInt(8, 13)):
                    response = self.client.get('/en/')
                    resp2 = response.content.decode('utf8').split("$$$")[1]
            self.assertNotEqual(output, output2)
            self.assertNotEqual(resp1, resp2)

        plugin_pool.unregister_plugin(NoCachePlugin)
Example #58
0
 def create_page(self, title=None, **kwargs):
     return create_page(title or self._testMethodName,
                        "nav_playground.html", "en", **kwargs)
Example #59
0
    def test_cache_page(self):
        # Ensure that we're testing in an environment WITHOUT the MW cache...
        exclude = [
            'django.middleware.cache.UpdateCacheMiddleware',
            'django.middleware.cache.FetchFromCacheMiddleware'
        ]
        mw_classes = [mw for mw in settings.MIDDLEWARE_CLASSES if mw not in exclude]

        with self.settings(MIDDLEWARE_CLASSES=mw_classes):

            # Silly to do these tests if this setting isn't True
            page_cache_setting = get_cms_setting('PAGE_CACHE')
            self.assertTrue(page_cache_setting)

            # Create a test page
            page1 = create_page('test page 1', 'nav_playground.html', 'en', published=True)

            # Add some content
            placeholder = page1.placeholders.filter(slot="body")[0]
            add_plugin(placeholder, "TextPlugin", 'en', body="English")
            add_plugin(placeholder, "TextPlugin", 'de', body="Deutsch")

            # Create a request object
            request = self.get_request(page1.get_path(), 'en')

            # Ensure that user is NOT authenticated
            self.assertFalse(request.user.is_authenticated())

            # Test that the page is initially uncached
            with self.assertNumQueries(FuzzyInt(1, 24)):
                response = self.client.get('/en/')
            self.assertEqual(response.status_code, 200)

            #
            # Test that subsequent requests of the same page are cached by
            # asserting that they require fewer queries.
            #
            with self.assertNumQueries(0):
                response = self.client.get('/en/')
            self.assertEqual(response.status_code, 200)

            #
            # Test that the cache is invalidated on unpublishing the page
            #
            old_version = _get_cache_version()
            page1.unpublish('en')
            self.assertGreater(_get_cache_version(), old_version)

            #
            # Test that this means the page is actually not cached.
            #
            page1.publish('en')
            with self.assertNumQueries(FuzzyInt(1, 24)):
                response = self.client.get('/en/')
            self.assertEqual(response.status_code, 200)

            #
            # Test that the above behavior is different when CMS_PAGE_CACHE is
            # set to False (disabled)
            #
            with self.settings(CMS_PAGE_CACHE=False):

                # Test that the page is initially un-cached
                with self.assertNumQueries(FuzzyInt(1, 20)):
                    response = self.client.get('/en/')
                self.assertEqual(response.status_code, 200)

                #
                # Test that subsequent requests of the same page are still requires DB
                # access.
                #
                with self.assertNumQueries(FuzzyInt(1, 20)):
                    response = self.client.get('/en/')
                self.assertEqual(response.status_code, 200)
Example #60
0
def create_i18n_page(title, languages=None, is_homepage=False, **kwargs):
    """
    Creating a multilingual page is not straightforward so we should have a helper

    This content argument should be a dictionary with the title of the page in each language:

        {
            'en': 'About',
            'fr': 'A propos',
            'de': 'Impressum',
        }

    """
    kwargs["template"] = kwargs.get("template", "richie/single_column.html")

    if isinstance(title, dict):
        # Check that the languages passed are coherent with the languages requested if any
        if languages:
            invalid_languages = set(languages) - set(title.keys())
            if invalid_languages:
                languages_string = ",".join(invalid_languages)
                raise ValueError(
                    f"Page titles are missing in some requested languages: {languages_string:s}"
                )
        else:
            languages = title.keys()
        i18n_titles = title

    elif isinstance(title, str):
        # Add a marker at the end of the string to differentiate each language
        languages = languages or [settings.LANGUAGE_CODE]
        i18n_titles = {language: title for language in languages}

    else:
        raise ValueError(
            "Title should be a string or a dictionary of language/string pairs"
        )

    # Assert that the languages passed are declared in settings
    invalid_languages = set(languages) - {
        language[0] for language in settings.LANGUAGES
    }
    if invalid_languages:
        languages_string = ",".join(invalid_languages)
        raise ValueError(
            f"You can't create pages in languages that are not declared: {languages_string:s}"
        )

    # Make a copy of languages to avoid muting it in what follows
    languages = list(languages)
    # Create the page with a first language from what is given to us
    first_language = languages.pop(0)

    slug = slugify(i18n_titles[first_language])
    page = create_page(
        language=first_language, title=i18n_titles[first_language], slug=slug, **kwargs
    )

    if is_homepage is True:
        page.set_as_homepage()

    # Add a title for each additional language
    for language in languages:
        create_title(
            language=language,
            title=i18n_titles[language],
            slug=slugify(i18n_titles[language]),
            page=page,
        )
        # Publish page in each additional language
        if kwargs.get("published") is True:
            page.publish(language)

    return page