Exemplo n.º 1
0
    def test_user_add_to_group_action(self, users, groups):
        user = users['uid99']

        request = self.layer.new_request(type='json')
        with self.layer.authenticated('viewer'):
            self.expectError(
                HTTPForbidden,
                render_view_to_response,
                user,
                request,
                name='add_item'
            )

        request.params['id'] = 'group99'
        with self.layer.authenticated('editor'):
            res = render_view_to_response(user, request, name='add_item')
        self.assertEqual(json.loads(res.text), {
            'message': "Added user 'uid99' to group 'group99'.",
            'success': True
        })

        request.params['id'] = 'group100'
        with self.layer.authenticated('editor'):
            res = render_view_to_response(user, request, name='add_item')
        self.assertEqual(json.loads(res.text), {
            'message': "u'group100'" if compat.IS_PY2 else "'group100'",
            'success': False
        })

        self.assertEqual(user.model.group_ids, ['group99'])
Exemplo n.º 2
0
def render_list(context, request):
    request.orig_context = context
    name = request.POST['slot_name']
    if hasattr(context, 'slots'):
        for slot in context.slots:
            if slot.name == name and slot.snippets:
                snippets = request.snippets = list(slot.snippets)
                view_name = 'kottisnippets-list-%s' % name
                response = render_view_to_response(
                        snippets, 
                        request,
                        name=view_name)
                if response is None:
                    view_name = 'kottisnippets-list'
                    response = render_view_to_response(
                            snippets, 
                            request,
                            name=view_name)
                if response is None:
                    request.snippets = slot.snippets
                    return {
                            'slot_name': name,
                            'snippets': slot.snippets,
                           }
                return response
    raise PredicateMismatch()
Exemplo n.º 3
0
    def test_group_remove_user_action(self, users, groups):
        group = groups['group99']
        group.model.add('uid99')
        group.model()

        request = self.layer.new_request(type='json')
        with self.layer.authenticated('viewer'):
            self.expectError(
                HTTPForbidden,
                render_view_to_response,
                group,
                request,
                name='remove_item'
            )

        request.params['id'] = 'uid100'
        with self.layer.authenticated('editor'):
            res = render_view_to_response(group, request, name='remove_item')
        self.assertEqual(json.loads(res.text), {
            'message': "u'uid100'" if compat.IS_PY2 else "'uid100'",
            'success': False
        })

        request.params['id'] = 'uid99'
        with self.layer.authenticated('editor'):
            res = render_view_to_response(group, request, name='remove_item')
        self.assertEqual(json.loads(res.text), {
            'message': "Removed user 'uid99' from group 'group99'.",
            'success': True
        })

        self.assertEqual(group.model.users, [])
Exemplo n.º 4
0
    def test_module_list(self):
        mod = self._make_mod()
        user = self._make_user()

        request = self.make_request(
            params = MultiDict(), POST = MultiDict())
        request.session['ptah-search-term'] = 'email'

        res = render_view_to_response(mod, request, '')

        self.assertIn('value="%s"'%user.id, res.text)

        res = render_view_to_response(
            mod,
            self.make_request(params = MultiDict(), POST = MultiDict()), '')

        self.assertIn('value="%s"'%user.id, res.text)

        res = render_view_to_response(
            mod,
            self.make_request(params = MultiDict({'batch': 1}),
                         POST = MultiDict()), '')

        self.assertIn('value="%s"'%user.id, res.text)

        res = render_view_to_response(
            mod,
            self.make_request(params = MultiDict({'batch': 0}),
                         POST = MultiDict()), '')

        self.assertIn('value="%s"'%user.id, res.text)
Exemplo n.º 5
0
    def test_sqla_table_view_model_nodes(self):
        from ptah.manage.sqla import SQLAModule, TableView

        rec = TestSqlaModuleContent(title='test')
        ptah.cms.Session.add(rec)
        ptah.cms.Session.flush()

        uri = rec.__uri__
        type_uri = rec.__type__.__uri__

        request = DummyRequest(params={'batch': 1})

        mod = SQLAModule(None, request)
        table = mod['psqla-ptah_nodes']

        res = render_view_to_response(table, request, '', False).text
        self.assertIn(url_quote_plus(uri), res)
        self.assertIn(url_quote_plus(type_uri), res)

        request = DummyRequest(params={'batch': 'unknown'})
        res = render_view_to_response(table, request, '', False).text
        self.assertIn(url_quote_plus(uri), res)

        request = DummyRequest(params={'batch': '0'})
        res = render_view_to_response(table, request, '', False).text
        self.assertIn(url_quote_plus(uri), res)
Exemplo n.º 6
0
    def test_delete_group_action(self, users, groups):
        group = groups['group99']

        request = self.layer.new_request(type='json')
        with self.layer.authenticated('viewer'):
            self.expectError(
                HTTPForbidden,
                render_view_to_response,
                group,
                request,
                name='delete_item'
            )

        with self.layer.authenticated('admin'):
            res = render_view_to_response(group, request, name='delete_item')
        self.assertEqual(json.loads(res.text), {
            'message': "Deleted group from database",
            'success': True
        })

        with self.layer.authenticated('admin'):
            res = render_view_to_response(group, request, name='delete_item')
        self.assertEqual(json.loads(res.text), {
            'message': "u'group99'" if compat.IS_PY2 else "'group99'",
            'success': False
        })

        self.assertEqual(groups.keys(), [
            'group0', 'group1', 'group2', 'group3', 'group4', 'group5',
            'group6', 'group7', 'group8', 'group9', 'admin_group_1',
            'admin_group_2'
        ])
Exemplo n.º 7
0
    def test_model_list(self):
        from ptah.manage.model import ModelModule, ModelView

        content = Content1()
        content.title = 'Content test'

        ptah.cms.Session.add(content)
        ptah.cms.Session.flush()

        rowid = content.__id__
        transaction.commit()

        mod = ModelModule(None, DummyRequest())
        model = mod['content1']

        res = render_view_to_response(model, DummyRequest(), '', False)
        self.assertIn('value="%s"'%rowid, res.text)

        res = render_view_to_response(
            model, DummyRequest(params={'batch': 0}), '', False)
        self.assertIn('value="%s"'%rowid, res.text)

        res = render_view_to_response(
            model, DummyRequest(params={'batch': 'unknown'}), '', False)
        self.assertIn('value="%s"'%rowid, res.text)
Exemplo n.º 8
0
    def test_delete_user_action(self, users, groups):
        group = groups['group99']
        group.model.add('uid99')
        group.model()

        user = users['uid99']

        request = self.layer.new_request(type='json')
        with self.layer.authenticated('viewer'):
            self.expectError(
                HTTPForbidden,
                render_view_to_response,
                user,
                request,
                name='delete_item'
            )

        with self.layer.authenticated('admin'):
            res = render_view_to_response(user, request, name='delete_item')
        self.assertEqual(json.loads(res.text), {
            'message': "Deleted user 'uid99' from database.",
            'success': True
        })

        with self.layer.authenticated('admin'):
            res = render_view_to_response(user, request, name='delete_item')
        self.assertEqual(json.loads(res.text), {
            'message': "u'uid99'" if compat.IS_PY2 else "'uid99'",
            'success': False
        })

        self.assertEqual(group.model.users, [])
Exemplo n.º 9
0
    def test_after_outside_forms_context(self):
        import webob.multidict
        import schemaish
        from pyramid.view import render_view_to_response
        from pyramid_formish.zcml import FormAction
        from zope.configuration.config import ConfigurationMachine
        context = ConfigurationMachine()
        context.route_prefix = ''
        context.autocommit = True
        context.registry = self.config.registry
        request = testing.DummyRequest()
        request.registry = self.config.registry
        title = schemaish.String()
        factory = make_controller_factory(fields=[('title', title)])
        directive = self._makeOne(context, factory)
        directive._actions = [FormAction('submit','title',True)]
        directive.after()
        display = render_view_to_response(None, request, '')
        self.assertEqual(display.body, '123')

        request = testing.DummyRequest()
        request.params = webob.multidict.MultiDict()
        request.params['submit'] = True
        display = render_view_to_response(None, request, '')
        self.assertEqual(display.body, 'submitted')
Exemplo n.º 10
0
def delegate_content_view(context, request):
    delegate_view = getattr(context, 'delegate_view', False)
    if delegate_view:
        if delegate_view in context:
            return delegate_content_view(context[delegate_view], request)
    view_name = context.default_view and context.default_view or 'view'
    response = render_view_to_response(context, request, name=view_name)
    if response is None:  # pragma: no coverage
        warnings.warn("Failed to look up view called %r for %r." %
                      (view_name, context))
        response = render_view_to_response(context, request, name='view')
    return response
Exemplo n.º 11
0
def render_snippet(context, request):
    name = request.POST['slot_name']
    view_name = 'kottisnippets-view-%s' % name
    response = render_view_to_response(context, request,
            name=view_name)
    if response is None:
        view_name = 'kottisnippets-view'
        response = render_view_to_response(context, request,
                name=view_name)
    if response is None:
        raise PredicateMismatch()
    return response
Exemplo n.º 12
0
def signup(request):

    # TODO: figure out the right way to determine where the user is coming from
    # determine where user came from
    from_index = ('username' not in request.POST)
    from_agrement = request.POST.get('chkAgree','') == 'yes'

    if from_agrement:
        # redirect to the login form
        username = request.POST['username']
        login = request.route_url('login')
        login = '******' % (login, username)
        return HTTPFound(location=login)

    # get posted values and validate
    context = get_fields(request)
    if not from_index:
        context = validate_fields(context)
    valid = context['valid']

    # render the appropriate view
    if from_index or not valid:
        return render_view_to_response(context, request, name='signup-form')
    else:

        # create account
        first_name = context['first_name'].value
        last_name = context['last_name'].value
        username = context['username'].value
        display_name = '%s %s' % (first_name, last_name)
        password = context['password'].value
        recovery_key = KeyGen.generate_recovery_key()
        acct = Account(AccountType.Person, username, password, recovery_key)
        email_address = None
        mobile_phone = None

        # create person
        person = Person(first_name, last_name, email_address, mobile_phone, acct)

        # persist
        DBSession.add(person)
        transaction.commit()

        # TODO: create a pending flag to identify unconfirmed accounts

        context = {'recovery_key': recovery_key,
                   'username': username,
                   'display_name': display_name}

        return render_view_to_response(context, request, name='signup-complete')
Exemplo n.º 13
0
def mimetype_view_selector(context, request):
    mime_views = get_mimetype_views(request.registry)
    name = mime_views.get(context.mimetype, 'view')
    response = render_view_to_response(context, request, name = name)
    if response is None:
        raise HTTPNotFound()
    return response
Exemplo n.º 14
0
Arquivo: util.py Projeto: disko/Kotti
def render_view(context, request, name='', secure=True):
    from kotti.security import authz_context

    with authz_context(context, request):
        response = render_view_to_response(context, request, name, secure)
    if response is not None:
        return response.ubody
Exemplo n.º 15
0
        def call_second_view(name, status=True):
            DummyForm.status = status

            from pyramid.view import render_view_to_response
            request = testing.DummyRequest(matchdict=dict(name=name))
            context = None
            return render_view_to_response(context, request, name="second")
Exemplo n.º 16
0
def follow_subrequest(request, subrequest, **kwargs):
    """Run a subrequest (e.g. batch), and follow the redirection if any.

    :rtype: tuple
    :returns: the reponse and the redirection request (or `subrequest`
              if no redirection happened.)
    """
    try:
        try:
            return request.invoke_subrequest(subrequest, **kwargs), subrequest
        except Exception as e:
            resp = render_view_to_response(e, subrequest)
            if not resp or resp.status_code >= 500:
                raise e
            raise resp
    except httpexceptions.HTTPRedirection as e:
        new_location = e.headers["Location"]
        new_request = Request.blank(
            path=new_location,
            headers=subrequest.headers,
            POST=subrequest.body,
            method=subrequest.method,
        )
        new_request.bound_data = subrequest.bound_data
        new_request.parent = getattr(subrequest, "parent", None)
        return request.invoke_subrequest(new_request, **kwargs), new_request
Exemplo n.º 17
0
    def test_forbidden_user(self):
        from ptahcrowd.forbidden import Forbidden

        class Context(object):
            """ """
            __name__ = 'test'

        request = self.request
        request.root = Context()
        ptah.auth_service.set_userid('user')

        class Principal(object):
            pass

        def get_principal():
            return Principal()

        orig = ptah.auth_service.get_current_principal
        ptah.auth_service.get_current_principal = get_principal

        res = render_view_to_response(HTTPForbidden(), request)
        ptah.auth_service.get_current_principal = orig

        self.assertEqual(text_(res.status), '403 Forbidden')
        self.assertIn(
            '<h1>Your are not allowed to access this part of site.</h1>',
            res.text)
Exemplo n.º 18
0
def delegate_content_view(context, request):
    view_name = context.default_view and context.default_view or 'view'
    response = render_view_to_response(context, request, name=view_name)
    if response is None:  # pragma: no coverage
        warnings.warn("Failed to look up view called %r for %r." %
                      (view_name, context))
        raise HTTPNotFound()
    return response
Exemplo n.º 19
0
    def test_layout_renderer(self, m):
        import player

        m.choice.return_value = 'red'

        self.config.add_layout('test', view=View,
                               renderer='player:tests/test-layout.pt')
        self.config.add_view(
            name='view.html',
            renderer=player.layout('player:tests/dir1/view.pt', 'test'))

        from pyramid.view import render_view_to_response

        res1 = render_view_to_response(Context(), self.request, 'view.html')
        res2 = render_view_to_response(Context(), self.request, 'view.html')
        self.assertEqual(res1.text, res2.text)
        self.assertEqual('<div><h1>Test</h1></div>', res1.text.strip())
Exemplo n.º 20
0
    def test_sqla_view(self):
        from ptah.manage.sqla import SQLAModule, MainView

        request = DummyRequest()

        mod = SQLAModule(None, request)

        res = render_view_to_response(mod, request, '', False)
        self.assertEqual(res.status, '200 OK')
Exemplo n.º 21
0
    def test_subscribers(self):
        from ptah.manage.introspect import IntrospectModule, Introspector

        mod = IntrospectModule(None, self.request)

        intr = mod['ptah.config:subscriber']

        res = render_view_to_response(intr, self.request)
        self.assertIn('Event subscribers', res.text)
Exemplo n.º 22
0
    def test_fields(self):
        from ptah.manage.introspect import IntrospectModule, Introspector

        mod = IntrospectModule(None, self.request)

        intr = mod['ptah.form:field']

        res = render_view_to_response(intr, self.request)
        self.assertIn('List of registered fields', res.text)
Exemplo n.º 23
0
    def test_perms_view(self):
        from ptah.manage.permissions import PermissionsModule, PermissionsView

        request = DummyRequest()

        mod = PermissionsModule(None, request)

        res = render_view_to_response(mod, request, '', False)
        self.assertEqual(res.status, '200 OK')
Exemplo n.º 24
0
    def test_settings_view(self):
        from ptah.manage.settings import SettingsModule, SettingsView

        request = DummyRequest()

        mod = SettingsModule(None, request)

        res = render_view_to_response(mod, request, "", False)
        self.assertEqual(res.status, "200 OK")
Exemplo n.º 25
0
 def test_registerView_defaults(self):
     from pyramid import testing
     view = testing.registerView('moo.html')
     import types
     self.assertTrue(isinstance(view, types.FunctionType))
     from pyramid.view import render_view_to_response
     request = DummyRequest()
     request.registry = self.registry
     response = render_view_to_response(None, request, 'moo.html')
     self.assertEqual(view(None, None).body, response.body)
Exemplo n.º 26
0
    def test_intr_view_default(self):
        from ptah.manage.introspect import IntrospectModule

        request = self.make_request()
        mod = IntrospectModule(None, request)

        intr = mod['pform:field-preview']

        res = render_view_to_response(intr, request)
        self.assertIn('pform:field-preview', res.text)
Exemplo n.º 27
0
    def test_intr_view_default(self):
        from ptah.manage.introspect import IntrospectModule

        request = self.make_request()
        mod = IntrospectModule(None, request)

        intr = mod['ptah.form:field-preview']

        res = render_view_to_response(intr, request)
        self.assertIn('ptah.form:field-preview', res.text)
Exemplo n.º 28
0
 def show_last_poll_result(self):
     query = Eq('type_name', 'Poll') & Eq('path', resource_path(self.request.meeting)) & \
             Eq('workflow_state', ['closed'])
     docids = self.request.root.catalog.query(query, sort_index='end_time', limit=1, reverse=True)[1]
     poll = None
     for poll in self.request.resolve_docids(docids):
         break
     if poll:
         return render_view_to_response(poll, self.request, name='__show_results__')
     raise HTTPNotFound(_("No closed polls yet"))
Exemplo n.º 29
0
    def test_intr_view(self):
        from ptah.manage.introspect import IntrospectModule

        request = self.make_request()
        mod = IntrospectModule(None, request)

        intr = mod['ptah:resolver']

        res = render_view_to_response(intr, request)
        self.assertIn('System super user', res.text)
Exemplo n.º 30
0
    def test_sqla_table_view_inheritance(self):
        from ptah.manage.sqla import SQLAModule, TableView

        request = DummyRequest()

        mod = SQLAModule(None, request)
        table = mod['psqla-ptah_tokens']

        res = render_view_to_response(table, request, '', False)
        self.assertEqual(res.status, '200 OK')
Exemplo n.º 31
0
 def test_registerView_withresult(self):
     from pyramid import testing
     view = testing.registerView('moo.html', 'yo')
     import types
     self.assertTrue(isinstance(view, types.FunctionType))
     from pyramid.view import render_view_to_response
     request = DummyRequest()
     request.registry = self.registry
     response = render_view_to_response(None, request, 'moo.html')
     self.assertEqual(response.body, b'yo')
Exemplo n.º 32
0
    def test_perms_roles(self):
        from ptah.manage.permissions import PermissionsModule, RolesView

        request = DummyRequest()

        mod = PermissionsModule(None, request)

        res = render_view_to_response(mod, request, 'roles.html', False)
        self.assertEqual(res.status, '200 OK')
        self.assertIn('<h2>Roles</h2>', res.text)
Exemplo n.º 33
0
    def test_sqla_table_view_inheritance(self):
        from ptah.manage.sqla import SQLAModule, TableView

        request = DummyRequest()

        mod = SQLAModule(None, request)
        table = mod['psqla-ptah_tokens']

        res = render_view_to_response(table, request, '', False)
        self.assertEqual(res.status, '200 OK')
Exemplo n.º 34
0
 def test_registerView_withresult(self):
     from pyramid import testing
     view = testing.registerView('moo.html', 'yo')
     import types
     self.failUnless(isinstance(view, types.FunctionType))
     from pyramid.view import render_view_to_response
     request = DummyRequest()
     request.registry = self.registry
     response = render_view_to_response(None, request, 'moo.html')
     self.assertEqual(response.body, 'yo')
Exemplo n.º 35
0
    def test_intr_view(self):
        from ptah.manage.introspect import IntrospectModule

        request = self.make_request()
        mod = IntrospectModule(None, request)

        intr = mod['ptah:resolver']

        res = render_view_to_response(intr, request)
        self.assertIn('System super user', res.text)
Exemplo n.º 36
0
    def test_source(self):
        from ptah.manage.source import SourceView
        from ptah.manage.manage import PtahManageRoute

        ptah.auth_service.set_userid(ptah.SUPERUSER_URI)

        request = DummyRequest()
        manage = PtahManageRoute(request)
        res = render_view_to_response(manage, request, 'source.html', False)
        self.assertIsInstance(res, HTTPFound)
        self.assertEqual(res.headers['location'], '.')
Exemplo n.º 37
0
    def test_scan_integration_with_ignore(self):
        from zope.interface import alsoProvides
        from pyramid.view import render_view_to_response
        import tests.test_config.pkgs.scannable as package

        config = self._makeOne(autocommit=True)
        config.scan(package, ignore='tests.test_config.pkgs.scannable.another')

        ctx = DummyContext()
        req = DummyRequest()
        alsoProvides(req, IRequest)
        req.registry = config.registry

        req.method = 'GET'
        result = render_view_to_response(ctx, req, '')
        self.assertEqual(result, 'grokked')

        # ignored
        v = render_view_to_response(ctx, req, 'another_stacked_class2')
        self.assertEqual(v, None)
Exemplo n.º 38
0
    def test_settings_view(self):
        from ptah.manage.settings import SettingsModule, SettingsView

        request = DummyRequest()

        mod = SettingsModule(None, request)
        SettingsView.grps = ('ptah', )
        res = render_view_to_response(mod, request, '', False)
        SettingsView.grps = None
        self.assertEqual(res.status, '200 OK')
        self.assertIn('Ptah settings', text_(res.body))
Exemplo n.º 39
0
    def test_model_view(self):
        from ptahcms.manage.model import ModelModule, ModelModuleView

        request = DummyRequest()

        mod = ModelModule(None, request)

        res = render_view_to_response(mod, request, '', False)
        self.assertEqual(res.status, '200 OK')
        self.assertIn('content1', res.text)
        self.assertIn('content2', res.text)
Exemplo n.º 40
0
    def test_sqla_table_view(self):
        from ptah.manage.sqla import SQLAModule

        request = self.make_request()

        mod = SQLAModule(None, request)
        table = mod['psqla-ptah_tokens']

        res = render_view_to_response(table, request, '', False)
        self.assertEqual(res.status, '200 OK')
        self.assertIn('form.buttons.add', res.text)
Exemplo n.º 41
0
    def test_view(self):
        from ptah.manage.introspect import IntrospectModule

        request = self.make_request()
        mod = IntrospectModule(None, request)

        res = render_view_to_response(mod, request)
        self.assertIn('ptah:resolver', res.text)
        self.assertIn(
            '<a href="http://example.com/ptah-manage/introspect/ptah:resolver/">',
            res.text)
Exemplo n.º 42
0
    def test_form_render_view_config(self):
        from ptah import form
        request = DummyRequest()

        class CustomForm(form.Form):
            fields = form.Fieldset(form.TextField('test'))

        self.config.add_view(name='test', view=CustomForm)

        resp = render_view_to_response(None, request, 'test', False).body
        self.assertIn('<form action="http://example.com"', text_(resp))
Exemplo n.º 43
0
 def _owrapped_view(context, request):
     response = view(context, request)
     request.wrapped_response = response
     request.wrapped_body = response.body
     request.wrapped_view = view
     wrapped_response = render_view_to_response(context, request,
                                                wrapper_viewname)
     if wrapped_response is None:
         raise ValueError(
             'No wrapper view named %r found when executing view '
             'named %r' % (wrapper_viewname, viewname))
     return wrapped_response
Exemplo n.º 44
0
    def test_delete_user_action(self):
        root = get_root()
        groups = root['groups']
        users = root['users']

        group = groups['group_1']
        user = users['user_1']

        events_called = []

        @classhandler.handler(UserDeletedEvent)
        def on_user_deleted(event):
            events_called.append('UserDeletedEvent')

        request = self.layer.new_request(type='json')
        with self.layer.authenticated('viewer'):
            self.expectError(
                HTTPForbidden,
                render_view_to_response,
                user,
                request,
                name='delete_item'
            )

        with self.layer.authenticated('admin'):
            res = render_view_to_response(user, request, name='delete_item')

        self.assertEqual(json.loads(res.text), {
            'message': "Deleted user 'user_1' from database.",
            'success': True
        })

        with self.layer.authenticated('admin'):
            res = render_view_to_response(user, request, name='delete_item')
        json_res = json.loads(res.text)
        self.assertFalse(json_res['success'])
        self.assertTrue(json_res['message'].find("'user_1'") > -1)

        self.assertEqual(group.model.users, [])
        self.assertTrue('UserDeletedEvent' in events_called)
Exemplo n.º 45
0
    def test_sqla_table_view_model_nodes(self):
        from ptah.manage.sqla import SQLAModule

        rec = TestSqlaModuleContent(title='test')
        ptah.get_session().add(rec)
        ptah.get_session().flush()

        #uri = rec.__uri__
        #type_uri = rec.__type__.__uri__

        request = DummyRequest(params={'batch': 1})

        mod = SQLAModule(None, request)
        table = mod['psqla-ptah_nodes']

        render_view_to_response(table, request, '', False).text
        #self.assertIn(url_quote_plus(uri), res)
        #self.assertIn(url_quote_plus(type_uri), res)

        request = DummyRequest(params={'batch': 'unknown'})
        render_view_to_response(table, request, '', False).text
        #self.assertIn(url_quote_plus(uri), res)

        request = DummyRequest(params={'batch': '0'})
        render_view_to_response(table, request, '', False).text
Exemplo n.º 46
0
 def test_registerView_custom(self):
     from pyramid import testing
     def view(context, request):
         from webob import Response
         return Response('123')
     view = testing.registerView('moo.html', view=view)
     import types
     self.assertTrue(isinstance(view, types.FunctionType))
     from pyramid.view import render_view_to_response
     request = DummyRequest()
     request.registry = self.registry
     response = render_view_to_response(None, request, 'moo.html')
     self.assertEqual(response.body, '123')
Exemplo n.º 47
0
    def test_layout_renderer_no_template(self):
        import djed.templates
        from pyramid.view import render_view_to_response

        def view(request):
            return 'test'

        self.config.add_view(name='view.html',
                             view=view,
                             renderer=djed.templates.layout())
        self.config.add_layout('', view=View, renderer='tests:test-layout.pt')

        res = render_view_to_response(Context(), self.request, 'view.html')
        self.assertEqual('<div>test</div>', res.text.strip())
Exemplo n.º 48
0
    def test_sqla_table_view_model(self):
        from ptah.manage.sqla import SQLAModule

        ptah.get_session().add(TestSqlaModuleContent(title='test'))

        request = self.make_request()

        mod = SQLAModule(None, request)
        table = mod['psqla-test_sqla_content']

        res = render_view_to_response(table, request, '', False).text
        self.assertIn('Inherits from:', res)
        self.assertIn('ptah_node', res)
        self.assertNotIn('form.buttons.add', res)
Exemplo n.º 49
0
    def test_layout_return_response(self):
        import djed.templates
        from pyramid.view import render_view_to_response
        from pyramid.httpexceptions import HTTPFound

        def view(request):
            return HTTPFound(location='/')

        self.config.add_view(name='view.html',
                             renderer=djed.templates.layout())
        self.config.add_layout('', view=view, renderer='tests:test-layout.pt')

        res = render_view_to_response(Context(), self.request, 'view.html')
        self.assertIsInstance(res, HTTPFound)
Exemplo n.º 50
0
 def test_registerView_with_permission_allowing(self):
     from pyramid import testing
     def view(context, request):
         from webob import Response
         return Response('123')
     view = testing.registerView('moo.html', view=view, permission='bar')
     testing.registerDummySecurityPolicy(permissive=True)
     import types
     self.assertTrue(isinstance(view, types.FunctionType))
     from pyramid.view import render_view_to_response
     request = DummyRequest()
     request.registry = self.registry
     result = render_view_to_response(None, request, 'moo.html')
     self.assertEqual(result.app_iter, ['123'])
Exemplo n.º 51
0
    def test_model_view_disabled(self):
        from ptahcms.manage.model import ModelModule, ModelModuleView

        cfg = ptah.get_settings(ptah.CFG_ID_PTAH, self.registry)
        cfg['disable_models'] = ['type:content2']

        request = DummyRequest()

        mod = ModelModule(None, request)

        res = render_view_to_response(mod, request, '', False)
        self.assertEqual(res.status, '200 OK')
        self.assertIn('content1', res.text)
        self.assertNotIn('content2', res.text)
Exemplo n.º 52
0
    def test_form_render_view_config_layout(self):
        import ptah.form, ptah.renderer
        request = self.make_request()

        class CustomForm(ptah.form.Form):
            fields = ptah.form.Fieldset(ptah.form.TextField('test'))

        self.config.add_view(
            name='test', view=CustomForm, renderer=ptah.renderer.layout())
        self.config.add_layout(
            renderer='ptah.form:tests/test-layout.pt')

        resp = render_view_to_response(None, request, 'test', False)
        self.assertIn('<form action="http://example.com"', str(resp))
Exemplo n.º 53
0
def view_content_default(context, request):
    """This view is always registered as the default view for any Content.

    Its job is to delegate to a view of which the name may be defined
    per instance.  If a instance level view is not defined for
    'context' (in 'context.defaultview'), we will fall back to a view
    with the name 'view'.
    """
    view_name = context.default_view or 'view'
    response = render_view_to_response(context, request, name=view_name)
    if response is None:  # pragma: no coverage
        warnings.warn("Failed to look up default view called %r for %r" %
                      (view_name, context))
        raise NotFound()
    return response
Exemplo n.º 54
0
def render_list(context, request):
    request.orig_context = context
    name = request.POST['slot_name']
    if hasattr(context, 'slots'):
        for slot in context.slots:
            if slot.name == name and slot.snippets:
                snippets = request.snippets = list(slot.snippets)
                view_name = 'kottisnippets-list-%s' % name
                response = render_view_to_response(snippets,
                                                   request,
                                                   name=view_name)
                if response is None:
                    view_name = 'kottisnippets-list'
                    response = render_view_to_response(snippets,
                                                       request,
                                                       name=view_name)
                if response is None:
                    request.snippets = slot.snippets
                    return {
                        'slot_name': name,
                        'snippets': slot.snippets,
                    }
                return response
    raise PredicateMismatch()
Exemplo n.º 55
0
    def test_form_render_view_config_return_none(self):
        import ptah.form

        class CustomForm(ptah.form.Form):
            fields = ptah.form.Fieldset(ptah.form.TextField('test'))

            def update_form(self):
                return

        self.config.add_view(
            name='test', view=CustomForm,
            renderer='ptah.form:tests/test-form.pt')

        resp = render_view_to_response(None, self.request, 'test', False)
        self.assertIn('<h1>Custom form</h1>', str(resp))
Exemplo n.º 56
0
def item_view(context, request):
    frame = request.params.get('frame', 'page')
    if getattr(request, '__parent__', None) is None:
        # We need the response headers from non subrequests
        try:
            return render_view_to_response(context, request, name=frame)
        except PredicateMismatch:
            # Avoid this view emitting PredicateMismatch
            exc_class, exc, tb = sys.exc_info()
            exc.__class__ = HTTPNotFound
            raise_with_traceback(exc, tb)
    path = request.resource_path(context, '@@' + frame)
    if request.query_string:
        path += '?' + request.query_string
    return request.embed(path, as_user=True)
Exemplo n.º 57
0
    def test_view_view(self):
        from ptahcms.manage.rest import RestModule, RestModuleView

        request = DummyRequest()

        mod = RestModule(None, request)

        res = render_view_to_response(mod, request, '', False)
        self.assertEqual(res.status, '200 OK')

        view = RestModuleView(mod, request)
        view.update()

        self.assertEqual(view.url,
                         '{0}/__rest__/cms/'.format(request.application_url))
Exemplo n.º 58
0
    def test_form_render_view_config_renderer(self):
        from ptah import form
        request = DummyRequest()

        class CustomForm(form.Form):
            fields = form.Fieldset(form.TextField('test'))

        self.config.add_view(name='test',
                             view=CustomForm,
                             renderer='ptah.form:tests/test-form.pt')

        resp = render_view_to_response(None, request, 'test', False).body

        self.assertIn(b'<h1>Custom form</h1>', resp)
        self.assertIn(b'<form action="http://example.com"', resp)
Exemplo n.º 59
0
    def test_scan_integration_dottedname_package(self):
        from zope.interface import alsoProvides
        from pyramid.view import render_view_to_response

        config = self._makeOne(autocommit=True)
        config.scan('tests.test_config.pkgs.scannable')

        ctx = DummyContext()
        req = DummyRequest()
        alsoProvides(req, IRequest)
        req.registry = config.registry

        req.method = 'GET'
        result = render_view_to_response(ctx, req, '')
        self.assertEqual(result, 'grokked')
Exemplo n.º 60
0
 def admin_breadcrumbs(self):
     """Breadcrumbs which include named resources of each ancestor"""
     breadcrumbs = []
     resources = [self.context, *self.context.iter_ancestors()]
     resources.reverse()
     for resource in resources:
         resource_view = render_view_to_response(resource,
                                                 self.request,
                                                 "internal-view",
                                                 secure=False)
         breadcrumbs.append({
             "title": resource.title,
             "path": resource.path_names,
             "named_resources": resource_view.admin_named_resources,
             "links": resource_view.admin_links,
         })
     return breadcrumbs