Beispiel #1
0
    def test_cms_plugins_blogpost_cascade_variant(self):
        """
        If the variant is not specified on the blogpost plugin, it should render
        according to variant variable eventually present in the context of its
        container.
        """
        # Create an blogpost
        blogpost = BlogPostFactory(page_title="public title",
                                   should_publish=True)
        blogpost_page = blogpost.extended_object

        # Create a page to add the plugin to
        page = create_i18n_page("A page")
        placeholder = page.placeholders.get(slot="maincontent")

        # Add blogpost plugin with default template
        model_instance = add_plugin(placeholder,
                                    BlogPostPlugin,
                                    "en",
                                    page=blogpost_page)

        # Get generated html
        request = RequestFactory()
        request.current_page = page
        request.path_info = "/en/my-path/"
        request.user = AnonymousUser()
        context = {
            "current_page": page,
            "blogpost_variant": "xxl",
            "request": request
        }
        renderer = ContentRenderer(request=request)
        html = renderer.render_plugin(model_instance, context)

        self.assertIn("blogpost-xxl", html)
    def test_cms_plugins_organization_render_context_variant(self):
        """
        The organization plugin should render according to variant variable
        eventually present in the context of its container.
        """
        # Create an blogpost
        organization = OrganizationFactory(page_title="public title")
        organization_page = organization.extended_object

        # Create a page to add the plugin to
        page = create_i18n_page("A page")
        placeholder = page.placeholders.get(slot="maincontent")

        # Add blogpost plugin with default template
        model_instance = add_plugin(
            placeholder,
            OrganizationPlugin,
            "en",
            page=organization_page,
            variant="small",
        )

        # Get generated html
        request = RequestFactory()
        request.current_page = page
        request.user = AnonymousUser()
        context = {
            "current_page": page,
            "organization_variant": "xxl",
            "request": request,
        }
        renderer = ContentRenderer(request=request)
        html = renderer.render_plugin(model_instance, context)

        self.assertIn("organization-small", html)
Beispiel #3
0
def fake_get(path='/', user=None):
    from django.test.client import RequestFactory
    from django.contrib.auth.models import AnonymousUser

    req = RequestFactory().get(path)
    req.user = AnonymousUser() if user is None else user
    req.current_page = 'dummy'

    return req
Beispiel #4
0
 def get_page_request(self, page, user, path=None, edit=False):
     path = page and page.get_absolute_url() or path
     if edit:
         path += '?edit'
     request = RequestFactory().get(path)
     request.session = {}
     request.user = user
     request.current_page = page
     return request
Beispiel #5
0
 def get_page_request(self, page, user, path=None, edit=False):
     path = page and page.get_absolute_url() or path
     if edit:
         path += '?edit'
     request = RequestFactory().get(path)
     request.session = {}
     request.user = user
     request.current_page = page
     return request
 def _get_page_request(self, page, user):
     request = RequestFactory().get("/")
     request.session = {}
     request.user = user
     request.current_page = page
     mid = ToolbarMiddleware()
     mid.process_request(request)
     if hasattr(request, "toolbar"):
         request.toolbar.populate()
     return request
Beispiel #7
0
 def test_404_error_view_handler(self):
     """
     When a request does not found resource,
     the 404 error view should be displayed
     """
     page = create_page("Test", "richie/single_column.html", "en", published=True)
     request = RequestFactory().get("/")
     request.current_page = page
     request.user = AnonymousUser()
     with self.assertTemplateUsed("richie/error.html"):
         response = error.error_404_view_handler(request, Exception)
         self.assertContains(response, "404 - Page not found", status_code=404)
Beispiel #8
0
 def test_error_view_handler_with_unsupported_status_code(self):
     """
     When an unsupported status code is used,
     the 500 error view should be displayed
     """
     page = create_page("Test", "richie/single_column.html", "en", published=True)
     request = RequestFactory().get("/")
     request.current_page = page
     request.user = AnonymousUser()
     with self.assertTemplateUsed("richie/error.html"):
         response = error.error_view_handler(request, Exception, 405)
         self.assertContains(response, "500 - Server bad request", status_code=500)
Beispiel #9
0
 def test_403_error_view_handler(self):
     """
     When access to page is not allowed,
     the 403 error view should be displayed
     """
     page = create_page("Test", "richie/single_column.html", "en", published=True)
     request = RequestFactory().get("/")
     request.current_page = page
     request.user = AnonymousUser()
     with self.assertTemplateUsed("richie/error.html"):
         response = error.error_403_view_handler(request, Exception)
         self.assertContains(response, "403 - Forbidden", status_code=403)
Beispiel #10
0
    def test_cms_plugins_htmlsitemap_no_exclusion(self):
        """
        Non regression test.
        A sitemap configuration that does not trigger any exclusion should not be empty.
        """
        self.create_page_tree(parent_kwargs={"login_required": True})

        page = PageFactory(title__title="Sitemap")
        placeholder = Placeholder.objects.create(slot="maincontent")
        page.placeholders.add(placeholder)

        context = self.get_practical_plugin_context()
        request = RequestFactory()
        request.current_page = page
        request.user = UserFactory()
        context["request"] = request

        parent_instance = add_plugin(placeholder, HTMLSitemapPlugin, "en")
        add_plugin(
            placeholder,
            plugin_type="HTMLSitemapPagePlugin",
            language="en",
            target=parent_instance,
        )

        html = context["cms_content_renderer"].render_placeholder(
            placeholder, context=context, language="en"
        )
        self.assertHTMLEqual(
            html,
            """
            <div class="sitemap">
              <ul>
                <li><a href="/en/root/">Root</a>
                  <ul>
                    <li><a href="/en/parent/">Parent</a>
                      <ul>
                        <li><a href="/en/page/">Page</a></li>
                        <li><a href="/en/sibling/">Sibling</a></li>
                      </ul>
                    </li>
                    <li><a href="/en/uncle/">Uncle</a></li>
                  </ul>
                </li>
                <li><a href="/en/sitemap/">Sitemap</a></li>
              </ul>
            </div>
            """,
        )
Beispiel #11
0
 def get_page_request(self, page, user, path=None, edit=False, lang_code="en"):
     path = path or page and page.get_absolute_url()
     if edit:
         path += "?edit"
     request = RequestFactory().get(path)
     request.session = {}
     request.user = user
     request.LANGUAGE_CODE = lang_code
     if edit:
         request.GET = {"edit": None}
     else:
         request.GET = {"edit_off": None}
     request.current_page = page
     mid = ToolbarMiddleware()
     mid.process_request(request)
     return request
Beispiel #12
0
    def setup_toolbar(self, page, user, is_edit_mode=True):
        page.set_publisher_state('en', state=PUBLISHER_STATE_DIRTY)  # make page dirty

        if is_edit_mode:
            edit_mode = get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')
        else:
            edit_mode = get_cms_setting('CMS_TOOLBAR_URL__EDIT_OFF')

        request = RequestFactory().get('{}?{}'.format(page.get_absolute_url('en'), edit_mode))
        request.current_page = page
        request.user = user
        request.session = self.client.session
        ToolbarMiddleware().process_request(request)
        self.toolbar = request.toolbar
        self.toolbar.populate()
        self.toolbar.post_template_populate()
        self.toolbar_left_items = self.toolbar.get_left_items()
        self.toolbar_right_items = self.toolbar.get_right_items()
Beispiel #13
0
 def get_page_request(self, page, user, path=None, edit=False,
                      lang_code='en', disable=False):
     path = path or page and page.get_absolute_url()
     if edit:
         path += '?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')
     request = RequestFactory().get(path)
     request.session = {}
     request.user = user
     request.LANGUAGE_CODE = lang_code
     if edit:
         request.GET = {'edit': None}
     else:
         request.GET = {'edit_off': None}
     if disable:
         request.GET[get_cms_setting('CMS_TOOLBAR_URL__DISABLE')] = None
     request.current_page = page
     mid = MessageMiddleware()
     mid.process_request(request)
     return request
 def get_page_request(self,
                      page,
                      user,
                      path=None,
                      edit=False,
                      lang_code='en'):
     path = path or page and page.get_absolute_url()
     if edit:
         path += '?edit'
     request = RequestFactory().get(path)
     request.session = {}
     request.user = user
     request.LANGUAGE_CODE = lang_code
     if edit:
         request.GET = {'edit': None}
     else:
         request.GET = {'edit_off': None}
     request.current_page = page
     mid = ToolbarMiddleware()
     mid.process_request(request)
     return request
Beispiel #15
0
 def get_page_request(self, page, user, path=None, edit=False,
                      lang_code='en', disable=False):
     path = path or page and page.get_absolute_url()
     if edit:
         path += '?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')
     request = RequestFactory().get(path)
     request.session = {}
     request.user = user
     request.LANGUAGE_CODE = lang_code
     if edit:
         request.GET = {'edit': None}
     else:
         request.GET = {'edit_off': None}
     if disable:
         request.GET[get_cms_setting('CMS_TOOLBAR_URL__DISABLE')] = None
     request.current_page = page
     mid = ToolbarMiddleware()
     mid.process_request(request)
     if hasattr(request, 'toolbar'):
         request.toolbar.populate()
     return request
Beispiel #16
0
    def test_emulate_admin_index(self):
        """ Call methods that emulate the adminsite instance's index.
        This test was basically the reason for the new manager, in light of the
        problem highlighted in ticket #1120, which asserts that giving a user
        no site-specific rights when creating a GlobalPagePermission should
        allow access to all sites.
        """
        # create and then ignore this user.
        superuser = self._create_user("super", is_staff=True, is_active=True,
                                      is_superuser=True)
        superuser.set_password("super")
        superuser.save()

        site_1 = Site.objects.get(pk=1)
        site_2 = Site.objects.create(domain='example2.com', name='example2.com')

        SITES = [site_1, site_2]

        # create 2 staff users
        USERS = [
            self._create_user("staff", is_staff=True, is_active=True),
            self._create_user("staff_2", is_staff=True, is_active=True),
        ]
        for user in USERS:
            user.set_password('staff')
            # re-use the same methods the UserPage form does.
            # Note that it internally calls .save(), as we've not done so.
            save_permissions({
                'can_add_page': True,
                'can_change_page': True,
                'can_delete_page': False
            }, user)

        GlobalPagePermission.objects.create(can_add=True, can_change=True,
                                            can_delete=False, user=USERS[0])
        # we're querying here to ensure that even though we've created two users
        # above, we should have successfully filtered to just one perm.
        self.assertEqual(1, GlobalPagePermission.objects.with_user(USERS[0]).count())

        # this will confirm explicit permissions still work, by adding the first
        # site instance to the many2many relationship 'sites'
        GlobalPagePermission.objects.create(can_add=True, can_change=True,
                                            can_delete=False,
                                            user=USERS[1]).sites.add(SITES[0])
        self.assertEqual(1, GlobalPagePermission.objects.with_user(USERS[1]).count())

        homepage = create_page(title="master", template="nav_playground.html",
                               language="en", in_navigation=True, slug='/')
        publish_page(page=homepage, user=superuser, language='en')

        with self.settings(CMS_PERMISSION=True):
            # for all users, they should have access to site 1
            request = RequestFactory().get(path='/', data={'site__exact': site_1.pk})
            request.session = {}
            request.current_page = None
            for user in USERS:
                request.user = user
                # Note, the query count is inflated by doing additional lookups
                # because there's a site param in the request.
                with self.assertNumQueries(FuzzyInt(4,5)):
                    # internally this calls PageAdmin.has_[add|change|delete]_permission()
                    self.assertEqual({'add': True, 'change': True, 'delete': False},
                                     site._registry[Page].get_model_perms(request))

            # can't use the above loop for this test, as we're testing that
            # user 1 has access, but user 2 does not, as they are only assigned
            # to site 1
            request = RequestFactory().get('/', data={'site__exact': site_2.pk})
            request.session = {}
            request.current_page = None

            # Refresh internal user cache
            USERS[0] = self.reload(USERS[0])
            USERS[1] = self.reload(USERS[1])

            # As before, the query count is inflated by doing additional lookups
            # because there's a site param in the request
            with self.assertNumQueries(FuzzyInt(5, 15)):
                # this user shouldn't have access to site 2
                request.user = USERS[1]
                self.assertEqual({'add': False, 'change': False, 'delete': False},
                                 site._registry[Page].get_model_perms(request))
                # but, going back to the first user, they should.
                request = RequestFactory().get('/', data={'site__exact': site_2.pk})
                request.user = USERS[0]
                request.current_page = None
                self.assertEqual({'add': True, 'change': True, 'delete': False},
                                 site._registry[Page].get_model_perms(request))
Beispiel #17
0
    def test_cms_plugins_htmlsitemap_login_required(self):
        """
        Pages requiring login can be excluded from a sitemap page for an anonymous user.
        """
        self.create_page_tree(parent_kwargs={"login_required": True})

        page = PageFactory(title__title="Sitemap")
        placeholder = Placeholder.objects.create(slot="maincontent")
        page.placeholders.add(placeholder)

        context = self.get_practical_plugin_context()
        parent_instance = add_plugin(placeholder, HTMLSitemapPlugin, "en")
        add_plugin(
            placeholder,
            plugin_type="HTMLSitemapPagePlugin",
            language="en",
            target=parent_instance,
        )

        html = context["cms_content_renderer"].render_placeholder(
            placeholder, context=context, language="en"
        )
        self.assertHTMLEqual(
            html,
            """
            <div class="sitemap">
              <ul>
                <li><a href="/en/root/">Root</a>
                  <ul>
                    <li><a href="/en/uncle/">Uncle</a></li>
                  </ul>
                </li>
                <li><a href="/en/sitemap/">Sitemap</a></li>
              </ul>
            </div>
            """,
        )

        # Check that a logged in user can see the page
        request = RequestFactory()
        request.current_page = page
        request.user = UserFactory()
        context["request"] = request
        html = context["cms_content_renderer"].render_placeholder(
            placeholder, context=context, language="en"
        )

        self.assertHTMLEqual(
            html,
            """
            <div class="sitemap">
              <ul>
                <li><a href="/en/root/">Root</a>
                  <ul>
                    <li><a href="/en/parent/">Parent</a>
                      <ul>
                        <li><a href="/en/page/">Page</a></li>
                        <li><a href="/en/sibling/">Sibling</a></li>
                      </ul>
                    </li>
                    <li><a href="/en/uncle/">Uncle</a></li>
                  </ul>
                </li>
                <li><a href="/en/sitemap/">Sitemap</a></li>
              </ul>
            </div>
            """,
        )
Beispiel #18
0
    def test_emulate_admin_index(self):
        """ Call methods that emulate the adminsite instance's index.
        This test was basically the reason for the new manager, in light of the
        problem highlighted in ticket #1120, which asserts that giving a user
        no site-specific rights when creating a GlobalPagePermission should
        allow access to all sites.
        """
        # create and then ignore this user.
        superuser = self._create_user("super",
                                      is_staff=True,
                                      is_active=True,
                                      is_superuser=True)
        superuser.set_password("super")
        superuser.save()

        site_1 = Site.objects.get(pk=1)
        site_2 = Site.objects.create(domain='example2.com',
                                     name='example2.com')

        SITES = [site_1, site_2]

        # create 2 staff users
        USERS = [
            self._create_user("staff", is_staff=True, is_active=True),
            self._create_user("staff_2", is_staff=True, is_active=True),
        ]
        for user in USERS:
            user.set_password('staff')
            # re-use the same methods the UserPage form does.
            # Note that it internally calls .save(), as we've not done so.
            save_permissions(
                {
                    'can_add_page': True,
                    'can_change_page': True,
                    'can_delete_page': False
                }, user)

        GlobalPagePermission.objects.create(can_add=True,
                                            can_change=True,
                                            can_delete=False,
                                            user=USERS[0])
        # we're querying here to ensure that even though we've created two users
        # above, we should have successfully filtered to just one perm.
        self.assertEqual(
            1,
            GlobalPagePermission.objects.with_user(USERS[0]).count())

        # this will confirm explicit permissions still work, by adding the first
        # site instance to the many2many relationship 'sites'
        GlobalPagePermission.objects.create(can_add=True,
                                            can_change=True,
                                            can_delete=False,
                                            user=USERS[1]).sites.add(SITES[0])
        self.assertEqual(
            1,
            GlobalPagePermission.objects.with_user(USERS[1]).count())

        homepage = create_page(title="master",
                               template="nav_playground.html",
                               language="en",
                               in_navigation=True,
                               slug='/')
        publish_page(page=homepage, user=superuser, language='en')

        with self.settings(CMS_PERMISSION=True):
            # for all users, they should have access to site 1
            request = RequestFactory().get(path='/')
            request.session = {'cms_admin_site': site_1.pk}
            request.current_page = None
            for user in USERS:
                request.user = user
                # Note, the query count is inflated by doing additional lookups
                # because there's a site param in the request.
                # max_queries = 5 for >dj21 because it's introduce default view permissions
                max_queries = 4 if DJANGO_2_0 else 5
                with self.assertNumQueries(FuzzyInt(3, max_queries)):
                    # internally this calls PageAdmin.has_[add|change|delete|view]_permission()
                    expected_perms = {
                        'add': True,
                        'change': True,
                        'delete': False
                    }
                    if not DJANGO_2_0:
                        expected_perms.update({'view': True})
                    self.assertEqual(
                        expected_perms,
                        site._registry[Page].get_model_perms(request))

            # can't use the above loop for this test, as we're testing that
            # user 1 has access, but user 2 does not, as they are only assigned
            # to site 1
            request = RequestFactory().get(path='/')
            request.session = {'cms_admin_site': site_2.pk}
            request.current_page = None

            # Refresh internal user cache
            USERS[0] = self.reload(USERS[0])
            USERS[1] = self.reload(USERS[1])

            # As before, the query count is inflated by doing additional lookups
            # because there's a site param in the request
            with self.assertNumQueries(FuzzyInt(5, 15)):
                # this user shouldn't have access to site 2
                request.user = USERS[1]
                expected_perms = {
                    'add': False,
                    'change': False,
                    'delete': False
                }
                if not DJANGO_2_0:
                    expected_perms.update({'view': False})
                self.assertEqual(expected_perms,
                                 site._registry[Page].get_model_perms(request))
                # but, going back to the first user, they should.
                request = RequestFactory().get('/',
                                               data={'site__exact': site_2.pk})
                request.user = USERS[0]
                request.current_page = None
                request.session = {}
                expected_perms = {'add': True, 'change': True, 'delete': False}
                if not DJANGO_2_0:
                    expected_perms.update({'view': True})
                self.assertEqual(expected_perms,
                                 site._registry[Page].get_model_perms(request))