Example #1
0
    def testSaverColumnNames(self):
        ''' test save data adapter's getColumnNames function '''

        self.createSaver()

        self.assertTrue('saver' in get_actions(self.ff1))
        saver = get_actions(self.ff1)['saver']

        cn = saver.getColumnNames()
        self.assertTrue(len(cn) == 3)
        self.assertTrue(cn[0] == 'replyto')
        self.assertTrue(cn[1] == 'topic')
        self.assertTrue(cn[2] == 'comments')

        # Use selective field saving
        saver.showFields = ('topic', 'comments')
        cn = saver.getColumnNames()
        self.assertTrue(len(cn) == 2)
        self.assertTrue(cn[0] == 'topic')
        self.assertTrue(cn[1] == 'comments')
        saver.showFields = tuple()

        # Add an extra column
        saver.ExtraData = ('dt', )
        cn = saver.getColumnNames()
        self.assertTrue(len(cn) == 4)
        self.assertTrue(cn[3] == 'dt')
Example #2
0
    def testSaverDataFormShowFields(self):
        ''' test saver data form show fields '''

        self.createSaver()

        self.assertTrue('saver' in get_actions(self.ff1))
        saver = get_actions(self.ff1)['saver']
        self.assertEqual(saver.itemsSaved(), 0)
        request = FakeRequest(topic='test subject',
                              replyto='*****@*****.**',
                              comments='test comments')
        saver.showFields = ('topic', 'comments')
        saver.onSuccess(request.form, request)

        view = self.ff1.restrictedTraverse('@@actions')
        view = view.publishTraverse(view.request, 'saver')
        view = view.publishTraverse(view.request, 'data')
        view.update()
        form = view.form_instance
        message = form.description()
        self.assertEqual(message.mapping, {'items': 1})
        item = form.get_items()[0]
        self.assertEqual(item[1]['id'], item[0])
        self.assertEqual(item[1]['topic'], 'test subject')
        self.assertEqual(item[1]['comments'], 'test comments')
        self.assertTrue('replyto' not in item[1])
    def testSetSavedFormInput(self):
        ''' test setSavedFormInput functionality '''

        # set up saver
        self.createSaver()
        self.assertTrue('saver' in get_actions(self.ff1))
        saver = get_actions(self.ff1)['saver']
        self.assertEqual(saver.getSavedFormInputForEdit(), '')

        # save a row
        fields = list(get_fields(self.ff1))
        saver.addDataRow(dict(zip(fields, ['one', 'two', 'three'])))
        self.assertEqual(saver.itemsSaved(), 1)
        items = saver.getSavedFormInputItems()
        self.assertEqual(
            items[0][1], dict(zip(['id'] + fields, [items[0][0], 'one', 'two', 'three'])))
        self.assertEqual(saver.getSavedFormInputForEdit(), 'one,two,three\r\n')

        # save a couple of \n-delimited rows - \n eol
        saver.addDataRow(dict(zip(fields, ['four', 'five', 'six'])))
        self.assertEqual(saver.itemsSaved(), 2)
        items = saver.getSavedFormInputItems()
        self.assertEqual(
            items[0][1], dict(zip(['id'] + fields, [items[0][0], 'one', 'two', 'three'])))
        self.assertEqual(
            items[1][1], dict(zip(['id'] + fields, [items[1][0], 'four', 'five', 'six'])))
        self.assertEqual(
            saver.getSavedFormInputForEdit(), 'one,two,three\r\nfour,five,six\r\n')

        # save empty string
        saver.clearSavedFormInput()
        self.assertEqual(saver.itemsSaved(), 0)
        self.assertEqual(saver.getSavedFormInputForEdit(), '')
Example #4
0
    def testSaver(self):
        """ test save data adapter action """

        self.createSaver()

        self.assertTrue("saver" in get_actions(self.ff1))
        saver = get_actions(self.ff1)["saver"]

        self.assertEqual(saver.itemsSaved(), 0)

        res = saver.getSavedFormInputForEdit()
        self.assertEqual(res, "")

        request = FakeRequest(
            add_auth=True,
            method="POST",
            topic="test subject",
            replyto="*****@*****.**",
            comments="test comments",
        )
        saver.onSuccess(request.form, request)

        self.assertEqual(saver.itemsSaved(), 1)

        res = saver.getSavedFormInputForEdit()
        self.assertEqual(res.strip(),
                         "[email protected],test subject,test comments")
Example #5
0
    def testSaverInputAsDictionaries(self):
        ''' test save data adapter's InputAsDictionaries '''

        self.createSaver()

        self.assertTrue('saver' in get_actions(self.ff1))
        saver = get_actions(self.ff1)['saver']

        # self.ff1.setActionAdapter(('saver',))

        # self.assertEqual(saver.inputAsDictionaries,
        # saver.InputAsDictionaries)

        self.assertEqual(saver.itemsSaved(), 0)

        request = FakeRequest(add_auth=True,
                              method='POST',
                              topic='test subject',
                              replyto='*****@*****.**',
                              comments='test comments')
        saver.onSuccess(request.form, request)
        # errors = self.ff1.fgvalidate(REQUEST=request)
        # self.assertEqual(errors, {})

        self.assertEqual(saver.itemsSaved(), 1)

        iad = saver.getSavedFormInput()
        row = iter(iad).next()
        self.assertEqual(len(row), 4)
        self.assertEqual(row['topic'], 'test subject')
Example #6
0
    def testSaverDataFormShowFields(self):
        """ test saver data form show fields """

        self.createSaver()

        self.assertTrue("saver" in get_actions(self.ff1))
        saver = get_actions(self.ff1)["saver"]
        self.assertEqual(saver.itemsSaved(), 0)
        request = FakeRequest(topic="test subject",
                              replyto="*****@*****.**",
                              comments="test comments")
        saver.showFields = ("topic", "comments")
        saver.onSuccess(request.form, request)

        view = self.ff1.restrictedTraverse("@@actions")
        view = view.publishTraverse(view.request, "saver")
        view = view.publishTraverse(view.request, "data")
        view.update()
        form = view.form_instance
        message = form.description()
        self.assertEqual(message.mapping, {"items": 1})
        item = form.get_items()[0]
        self.assertEqual(item[1]["id"], item[0])
        self.assertEqual(item[1]["topic"], "test subject")
        self.assertEqual(item[1]["comments"], "test comments")
        self.assertTrue("replyto" not in item[1])
    def test_ActionExecutor(self):

        self.createIFTTTAction()

        # configure easyform actions
        self.assertTrue('ifttt' in get_actions(self.ff1))
        ifttt_trigger = get_actions(self.ff1)['ifttt']
        ifttt_trigger.ifttt_event_name = u'ifttt applet'
        ifttt_trigger.payload_fields = ['replyto', 'topic', 'comments']

        request = FakeRequest(
            add_auth=True,
            method='POST',
            topic='test subject',
            replyto='*****@*****.**',
            comments='test comments'
        )

        self.assertFalse(ifttt_trigger.onSuccess(request.form, request))

        # set secret key
        api.portal.set_registry_record(
            name='ifttt.ifttt_secret_key',
            value=u'secret',
        )

        # inspect logs
        handler = InstalledHandler('collective.ifttt.requests')

        # execute action
        self.assertTrue(ifttt_trigger.onSuccess(request.form, request))

        messages = [record.getMessage() for record in handler.records]
        self.assertGreater(len(messages), 0)
        self.assertTrue(messages[0].startswith('Dispatched requests.post'))
Example #8
0
    def testDeleteSavedFormInput(self):
        ''' test manage_deleteData functionality '''

        # set up saver
        self.createSaver()
        self.assertTrue('saver' in get_actions(self.ff1))
        saver = get_actions(self.ff1)['saver']

        # save a few rows
        fields = list(get_schema(self.ff1))
        saver.addDataRow(dict(zip(fields, ['one', 'two', 'three'])))
        saver.addDataRow(dict(zip(fields, ['four', 'five', 'six'])))
        saver.addDataRow(dict(zip(fields, ['seven', 'eight', 'nine'])))
        self.assertEqual(saver.itemsSaved(), 3)

        # saver.manage_deleteData(saver._storage.keys()[1])
        saver.delDataRow(saver.getSavedFormInputItems()[1][0])
        self.assertEqual(saver.itemsSaved(), 2)
        items = saver.getSavedFormInputItems()
        self.assertEqual(
            items[0][1],
            dict(zip(['id'] + fields, [items[0][0], 'one', 'two', 'three'])))
        self.assertEqual(
            items[1][1],
            dict(zip(['id'] + fields,
                     [items[1][0], 'seven', 'eight', 'nine'])))
Example #9
0
    def testSaverColumnNames(self):
        """ test save data adapter's getColumnNames function """

        self.createSaver()

        self.assertTrue("saver" in get_actions(self.ff1))
        saver = get_actions(self.ff1)["saver"]

        cn = saver.getColumnNames()
        self.assertTrue(len(cn) == 3)
        self.assertTrue(cn[0] == "replyto")
        self.assertTrue(cn[1] == "topic")
        self.assertTrue(cn[2] == "comments")

        # Use selective field saving
        saver.showFields = ("topic", "comments")
        cn = saver.getColumnNames()
        self.assertTrue(len(cn) == 2)
        self.assertTrue(cn[0] == "topic")
        self.assertTrue(cn[1] == "comments")
        saver.showFields = tuple()

        # Add an extra column
        saver.ExtraData = ("dt", )
        cn = saver.getColumnNames()
        self.assertTrue(len(cn) == 4)
        self.assertTrue(cn[3] == "dt")
    def testSaverSavedFormInput(self):
        """ test save data adapter action and direct access to
        SavedFormInput """

        self.createSaver()

        self.assertTrue('saver' in get_actions(self.ff1))
        saver = get_actions(self.ff1)['saver']

        request = FakeRequest(
            add_auth=True, method='POST', topic='test subject',
            replyto='*****@*****.**',
            comments='test comments')
        saver.onSuccess(request.form, request)

        self.assertEqual(saver.itemsSaved(), 1)
        row = iter(saver.getSavedFormInput()).next()
        self.assertEqual(len(row), 4)

        request = FakeRequest(
            add_auth=True, method='POST', topic='test subject',
            replyto='*****@*****.**',
            comments='test comments')
        saver.onSuccess(request.form, request)
        self.assertEqual(saver.itemsSaved(), 2)

        saver.clearSavedFormInput()
        self.assertEqual(saver.itemsSaved(), 0)
    def testSaverDataFormShowFields(self):
        ''' test saver data form show fields '''

        self.createSaver()

        self.assertTrue('saver' in get_actions(self.ff1))
        saver = get_actions(self.ff1)['saver']
        self.assertEqual(saver.itemsSaved(), 0)
        request = FakeRequest(
            topic='test subject',
            replyto='*****@*****.**',
            comments='test comments')
        saver.showFields = ('topic', 'comments')
        saver.onSuccess(request.form, request)

        view = self.ff1.restrictedTraverse('@@actions')
        view = view.publishTraverse(view.request, 'saver')
        view = view.publishTraverse(view.request, 'data')
        view.update()
        form = view.form_instance
        message = form.description()
        self.assertEqual(message.mapping, {'items': 1})
        item = form.get_items()[0]
        self.assertEqual(item[1]['id'], item[0])
        self.assertEqual(item[1]['topic'], 'test subject')
        self.assertEqual(item[1]['comments'], 'test comments')
        self.assertTrue('replyto' not in item[1])
Example #12
0
    def testDeleteSavedFormInput(self):
        """ test manage_deleteData functionality """

        # set up saver
        self.createSaver()
        self.assertTrue("saver" in get_actions(self.ff1))
        saver = get_actions(self.ff1)["saver"]

        # save a few rows
        fields = list(get_schema(self.ff1))
        saver.addDataRow(dict(list(zip(fields, ["one", "two", "three"]))))
        saver.addDataRow(dict(list(zip(fields, ["four", "five", "six"]))))
        saver.addDataRow(dict(list(zip(fields, ["seven", "eight", "nine"]))))
        self.assertEqual(saver.itemsSaved(), 3)

        # saver.manage_deleteData(saver._storage.keys()[1])
        saver.delDataRow(saver.getSavedFormInputItems()[1][0])
        self.assertEqual(saver.itemsSaved(), 2)
        items = saver.getSavedFormInputItems()
        self.assertEqual(
            items[0][1],
            dict(
                list(zip(["id"] + fields,
                         [items[0][0], "one", "two", "three"]))),
        )
        self.assertEqual(
            items[1][1],
            dict(
                list(
                    zip(["id"] + fields,
                        [items[1][0], "seven", "eight", "nine"]))),
        )
    def testSaverColumnNames(self):
        ''' test save data adapter's getColumnNames function '''

        self.createSaver()

        self.assertTrue('saver' in get_actions(self.ff1))
        saver = get_actions(self.ff1)['saver']

        cn = saver.getColumnNames()
        self.assertTrue(len(cn) == 3)
        self.assertTrue(cn[0] == 'replyto')
        self.assertTrue(cn[1] == 'topic')
        self.assertTrue(cn[2] == 'comments')

        # Use selective field saving
        saver.showFields = ('topic', 'comments')
        cn = saver.getColumnNames()
        self.assertTrue(len(cn) == 2)
        self.assertTrue(cn[0] == 'topic')
        self.assertTrue(cn[1] == 'comments')
        saver.showFields = tuple()

        # Add an extra column
        saver.ExtraData = ('dt',)
        cn = saver.getColumnNames()
        self.assertTrue(len(cn) == 4)
        self.assertTrue(cn[3] == 'dt')
Example #14
0
    def testSaverInputAsDictionaries(self):
        """ test save data adapter's InputAsDictionaries """

        self.createSaver()

        self.assertTrue("saver" in get_actions(self.ff1))
        saver = get_actions(self.ff1)["saver"]

        # self.ff1.setActionAdapter(('saver',))

        # self.assertEqual(saver.inputAsDictionaries,
        # saver.InputAsDictionaries)

        self.assertEqual(saver.itemsSaved(), 0)

        request = FakeRequest(
            add_auth=True,
            method="POST",
            topic="test subject",
            replyto="*****@*****.**",
            comments="test comments",
        )
        saver.onSuccess(request.form, request)
        # errors = self.ff1.fgvalidate(REQUEST=request)
        # self.assertEqual(errors, {})

        self.assertEqual(saver.itemsSaved(), 1)

        iad = saver.getSavedFormInput()
        row = next(iter(iad))
        self.assertEqual(len(row), 4)
        self.assertEqual(row["topic"], "test subject")
    def testDeleteSavedFormInput(self):
        ''' test manage_deleteData functionality '''

        # set up saver
        self.createSaver()
        self.assertTrue('saver' in get_actions(self.ff1))
        saver = get_actions(self.ff1)['saver']

        # save a few rows
        fields = list(get_schema(self.ff1))
        saver.addDataRow(dict(zip(fields, ['one', 'two', 'three'])))
        saver.addDataRow(dict(zip(fields, ['four', 'five', 'six'])))
        saver.addDataRow(dict(zip(fields, ['seven', 'eight', 'nine'])))
        self.assertEqual(saver.itemsSaved(), 3)

        # saver.manage_deleteData(saver._storage.keys()[1])
        saver.delDataRow(saver.getSavedFormInputItems()[1][0])
        self.assertEqual(saver.itemsSaved(), 2)
        items = saver.getSavedFormInputItems()
        self.assertEqual(
            items[0][1],
            dict(zip(['id'] + fields, [items[0][0], 'one', 'two', 'three']))
        )
        self.assertEqual(
            items[1][1],
            dict(zip(['id'] + fields, [items[1][0], 'seven', 'eight', 'nine']))
        )
    def testSaverInputAsDictionaries(self):
        ''' test save data adapter's InputAsDictionaries '''

        self.createSaver()

        self.assertTrue('saver' in get_actions(self.ff1))
        saver = get_actions(self.ff1)['saver']

        # self.ff1.setActionAdapter(('saver',))

        # self.assertEqual(saver.inputAsDictionaries,
        # saver.InputAsDictionaries)

        self.assertEqual(saver.itemsSaved(), 0)

        request = FakeRequest(
            add_auth=True, method='POST', topic='test subject',
            replyto='*****@*****.**',
            comments='test comments')
        saver.onSuccess(request.form, request)
        # errors = self.ff1.fgvalidate(REQUEST=request)
        # self.assertEqual(errors, {})

        self.assertEqual(saver.itemsSaved(), 1)

        iad = saver.getSavedFormInput()
        row = iter(iad).next()
        self.assertEqual(len(row), 4)
        self.assertEqual(row['topic'], 'test subject')
Example #17
0
    def testSaverSavedFormInput(self):
        """ test save data adapter action and direct access to
        SavedFormInput """

        self.createSaver()

        self.assertTrue("saver" in get_actions(self.ff1))
        saver = get_actions(self.ff1)["saver"]

        request = FakeRequest(
            add_auth=True,
            method="POST",
            topic="test subject",
            replyto="*****@*****.**",
            comments="test comments",
        )
        saver.onSuccess(request.form, request)

        self.assertEqual(saver.itemsSaved(), 1)
        row = next(iter(saver.getSavedFormInput()))
        self.assertEqual(len(row), 4)

        request = FakeRequest(
            add_auth=True,
            method="POST",
            topic="test subject",
            replyto="*****@*****.**",
            comments="test comments",
        )
        saver.onSuccess(request.form, request)
        self.assertEqual(saver.itemsSaved(), 2)

        saver.clearSavedFormInput()
        self.assertEqual(saver.itemsSaved(), 0)
Example #18
0
    def testSaverSavedFormInput(self):
        """ test save data adapter action and direct access to
        SavedFormInput """

        self.createSaver()

        self.assertTrue('saver' in get_actions(self.ff1))
        saver = get_actions(self.ff1)['saver']

        request = FakeRequest(add_auth=True,
                              method='POST',
                              topic='test subject',
                              replyto='*****@*****.**',
                              comments='test comments')
        saver.onSuccess(request.form, request)

        self.assertEqual(saver.itemsSaved(), 1)
        row = iter(saver.getSavedFormInput()).next()
        self.assertEqual(len(row), 4)

        request = FakeRequest(add_auth=True,
                              method='POST',
                              topic='test subject',
                              replyto='*****@*****.**',
                              comments='test comments')
        saver.onSuccess(request.form, request)
        self.assertEqual(saver.itemsSaved(), 2)

        saver.clearSavedFormInput()
        self.assertEqual(saver.itemsSaved(), 0)
Example #19
0
    def testSaverDownloadExtraData(self):
        """ test save data """

        self.createSaver()

        self.assertTrue("saver" in get_actions(self.ff1))
        saver = get_actions(self.ff1)["saver"]
        self.assertEqual(saver.itemsSaved(), 0)

        request = FakeRequest(
            add_auth=True,
            method="POST",
            topic="test subject",
            replyto="*****@*****.**",
            comments="test comments",
        )
        saver.ExtraData = ("dt", "HTTP_USER_AGENT")
        saver.onSuccess(request.form, request)

        self.assertEqual(saver.itemsSaved(), 1)
        saver.download(request.response)
        res = request.response.stdout.getvalue().decode("utf-8")
        self.assertTrue("Content-Type: text/comma-separated-values" in res)
        self.assertTrue(
            'Content-Disposition: attachment; filename="saver.csv"' in res)
        self.assertTrue(saver.getSavedFormInputForEdit() in res)
Example #20
0
    def testSaver(self):
        ''' test save data adapter action '''

        self.createSaver()

        self.assertTrue('saver' in get_actions(self.ff1))
        saver = get_actions(self.ff1)['saver']

        self.assertEqual(saver.itemsSaved(), 0)

        res = saver.getSavedFormInputForEdit()
        self.assertEqual(res, '')

        request = FakeRequest(add_auth=True,
                              method='POST',
                              topic='test subject',
                              replyto='*****@*****.**',
                              comments='test comments')
        saver.onSuccess(request.form, request)

        self.assertEqual(saver.itemsSaved(), 1)

        res = saver.getSavedFormInputForEdit()
        self.assertEqual(res.strip(),
                         '[email protected],test subject,test comments')
    def test_SubjectDollarReplacement(self):
        """
        Simple subject lines should do ${identifier} replacement from
        request.form -- but only for a basic override.
        """

        mailer = get_actions(self.ff1)['mailer']
        mailer.msg_subject = 'This is my ${topic} now'

        # baseline unchanged
        request = self.LoadRequestForm(
            topic='test subject',
            replyto='*****@*****.**',
            comments='test comments'
        )
        self.messageText = ''
        mailer.onSuccess(request.form, request)
        self.assertTrue(self.messageText.find(
            'Subject: =?utf-8?q?test_subject?=') > 0)

        # no substitution on field replacement (default situation)
        request = self.LoadRequestForm(
            topic='test ${subject}',
            replyto='*****@*****.**',
            comments='test comments'
        )
        self.messageText = ''
        mailer.onSuccess(request.form, request)
        self.assertTrue(self.messageText.find(
            'Subject: =?utf-8?q?test_=24=7Bsubject=7D?=') > 0)

        # we should get substitution in a basic override
        mailer.subject_field = ''
        request = self.LoadRequestForm(
            topic='test subject',
            replyto='*****@*****.**',
            comments='test comments'
        )
        self.messageText = ''
        mailer.onSuccess(request.form, request)
        self.assertTrue(self.messageText.find(
            'Subject: =?utf-8?q?This_is_my_test_subject_now?=') > 0)

        # we should get substitution in a basic override
        mailer.msg_subject = 'This is my ${untopic} now'
        self.messageText = ''
        mailer.onSuccess(request.form, request)
        self.assertTrue(self.messageText.find(
            'Subject: =?utf-8?q?This_is_my_=3F=3F=3F_now?=') > 0)

        # we don't want substitution on user input
        request = self.LoadRequestForm(
            topic='test ${subject}',
            replyto='*****@*****.**',
            comments='test comments'
        )
        self.messageText = ''
        mailer.onSuccess(request.form, request)
        self.assertTrue(self.messageText.find(
            'Subject: =?utf-8?q?This_is_my_=3F=3F=3F_now?=') > 0)
Example #22
0
    def testEditSavedFormInput(self):
        ''' test manage_saveData functionality '''

        # set up saver
        self.createSaver()
        self.assertTrue('saver' in get_actions(self.ff1))
        saver = get_actions(self.ff1)['saver']

        # save a row
        fields = list(get_fields(self.ff1))
        #saver.savedFormInput = 'one,two,three'
        saver.addDataRow(dict(zip(fields, ['one', 'two', 'three'])))
        self.assertEqual(saver.itemsSaved(), 1)
        items = saver.getSavedFormInputItems()
        self.assertEqual(
            items[0][1], dict(zip(['id'] + fields, [items[0][0], 'one', 'two', 'three'])))
Example #23
0
    def testSaverExtraData(self):
        ''' test save data adapter action '''

        self.createSaver()

        self.assertTrue('saver' in get_actions(self.ff1))
        saver = get_actions(self.ff1)['saver']
        self.assertEqual(saver.itemsSaved(), 0)

        request = FakeRequest(
            add_auth=True, method='POST', topic='test subject', replyto='*****@*****.**', comments='test comments')
        saver.ExtraData = ('dt',)
        saver.onSuccess(request.form, request)

        self.assertEqual(saver.itemsSaved(), 1)
        self.assertTrue('dt' in saver.getSavedFormInput()[0])
Example #24
0
    def test_set_actions_updates_modified(self):
        # https://github.com/collective/collective.easyform/issues/8
        # Calling set_actions should update the modification date,
        # also in the catalog.
        from collective.easyform.api import get_actions
        from collective.easyform.api import set_actions

        # Gather the original data.
        catalog = api.portal.get_tool("portal_catalog")
        path = "/".join(self.ff1.getPhysicalPath())
        orig_modified = self.ff1.modified()
        brain = catalog.unrestrictedSearchResults(path=path)[0]
        orig_counter = catalog.getCounter()
        self.assertEqual(brain.modified, orig_modified)

        # Set the actions.
        actions = get_actions(self.ff1)
        set_actions(self.ff1, actions)

        # The modification date on the form should have been updated.
        new_modified = self.ff1.modified()
        self.assertGreater(new_modified, orig_modified)

        # The catalog brain should have the new date
        brain = catalog.unrestrictedSearchResults(path=path)[0]
        self.assertEqual(brain.modified, new_modified)
        self.assertGreater(self.ff1.modified(), orig_modified)

        # The catalog counter should have been increased.
        # This helps invalidate caches because the catalogCounter ETag changes.
        self.assertEqual(catalog.getCounter(), orig_counter + 1)
    def testReturnError(self):
        """ Succesful script execution with return error
        """
        self.createScript()

        actions = get_actions(self.ff1)
        actions["adapter"].ScriptBody = return_error_script
        set_actions(self.ff1, actions)

        self.portal.REQUEST["form.widgets.test_field"] = u"Test field"
        self.portal.REQUEST["form.widgets.topic"] = u"subject"
        self.portal.REQUEST["form.widgets.comments"] = u"some comments"
        self.portal.REQUEST["form.widgets.replyto"] = u"*****@*****.**"
        self.portal.REQUEST["form.buttons.submit"] = u"Submit"

        view = self.ff1.restrictedTraverse("view")
        form = view.form_instance
        form.update()

        errors = form.widgets.errors
        self.assertEqual(len(errors), 1)
        self.assertEqual(errors[0].message, "Please enter more text")

        data, errors = form.extractData()
        self.assertEqual(len(errors), 0)

        errors = form.processActions(data)
        self.assertEqual(errors, {"comments": "Please enter more text"})
Example #26
0
    def testReturnError(self):
        ''' Succesful script execution with return error
        '''
        self.createScript()

        actions = get_actions(self.ff1)
        actions['adapter'].ScriptBody = return_error_script
        set_actions(self.ff1, actions)

        self.portal.REQUEST['form.widgets.test_field'] = u'Test field'
        self.portal.REQUEST['form.widgets.topic'] = u'subject'
        self.portal.REQUEST['form.widgets.comments'] = u'some comments'
        self.portal.REQUEST['form.widgets.replyto'] = u'*****@*****.**'
        self.portal.REQUEST['form.buttons.submit'] = u'Submit'

        view = self.ff1.restrictedTraverse('view')
        form = view.form_instance
        form.update()

        errors = form.widgets.errors
        self.assertEqual(len(errors), 1)
        self.assertEqual(errors[0].message, 'Please enter more text')

        data, errors = form.extractData()
        self.assertEqual(len(errors), 0)

        errors = form.processActions(data)
        self.assertEqual(errors, {'comments': 'Please enter more text'})
Example #27
0
def create_registration_form(container):
    current_lang = api.portal.get_current_language()
    reg_text = translate(_(u"Registration to"), target_language=current_lang)

    # Create & configure form
    form = api.content.create(
        type="EasyForm",
        title=u"{0} : {1}".format(reg_text, container.Title()),
        container=container,
    )

    form.exclude_from_nav = True

    set_fields(form, IRegistrationForm)
    form.submitLabel = translate(_(u"Register"), target_language=current_lang)
    form.thankstitle = translate(_(u"Thank you"), target_language=current_lang)
    form.thanksdescription = translate(
        _(u"Thank you for your subscription"),
        target_language=current_lang,
    )
    form.includeEmpties = False

    # Configure actions
    IRegistrationActions.setTaggedValue(CONTEXT_KEY, form)
    set_actions(form, IRegistrationActions)

    actions = get_actions(form)
    mailer = actions.get("mailer")
    mailer.msg_subject = reg_text

    form.reindexObject()
Example #28
0
 def processActions(self, fields):
     # get a list of adapters with no duplicates, retaining order
     actions = getFieldsInOrder(get_actions(self.context))
     for name, action in actions:
         if not action.required:
             continue
         # Now, see if we should execute it.
         # Check to see if execCondition exists and has contents
         execCondition = IActionExtender(action).execCondition
         if execCondition:
             doit = get_expression(self.context, execCondition)
         else:
             doit = True
         if doit and hasattr(action, "onSuccess"):
             if IRegistrantData.providedBy(action):
                 result = action.onSuccess(
                     fields,
                     self.request,
                     max_attendees=getattr(self.context, "max_attendees", 0),
                     waiting_list_size=getattr(self.context, "waiting_list_size", 0),
                 )
             else:
                 result = action.onSuccess(fields, self.request)
             if isinstance(result, dict) and len(result):
                 return result
Example #29
0
def migrate_saved_data(ploneformgen, easyform):
    for data_adapter in ploneformgen.objectValues('FormSaveDataAdapter'):
        actions = get_actions(easyform)
        action = actions.get(data_adapter.getId())
        schema = get_schema(easyform)
        if ISaveData.providedBy(action):
            cols = data_adapter.getColumnNames()
            for idx, row in enumerate(data_adapter.getSavedFormInput()):
                if len(row) != len(cols):
                    logger.warning(
                        'Number of columns does not match. Skipping row %s in '
                        'data adapter %s/%s', idx,
                        '/'.join(easyform.getPhysicalPath()),
                        data_adapter.getId())
                    continue
                data = {}
                for key, value in zip(cols, row):
                    field = schema.get(key)
                    value = value.decode('utf8')
                    if IFromUnicode.providedBy(field):
                        value = field.fromUnicode(value)
                    elif IDatetime.providedBy(field) and value:
                        value = DateTime(value).asdatetime()
                    elif IDate.providedBy(field) and value:
                        value = DateTime(value).asdatetime().date()
                    elif ISet.providedBy(field):
                        try:
                            value = set(literal_eval(value))
                        except ValueError:
                            pass
                    elif INamedBlobFileField.providedBy(field):
                        value = None
                    data[key] = value
                action.addDataRow(data)
    def testProxyRole(self):
        ''' Test seeing how setting proxy role affects unauthorized exception '''

        # TODO: Zope security system kills me
        self.createScript()

        actions = get_actions(self.ff1)
        adapter = actions['adapter']

        # 4. Set script data
        adapter.ScriptBody = proxied_script

        req = SecureFakeRequest(test_field='123')

        # errors = adapter.validate()
        # assert len(errors) == 0, 'Had errors:' + str(errors)

        # Execute script
        throwed = False
        try:
            adapter.onSuccess({}, req)
        except Unauthorized:
            throwed = True

        assert throwed, 'No Unauthorized was raised'
    def test_bccOverride(self):
        """ Test override for BCC field """

        mailer = get_actions(self.ff1)['mailer']
        request = self.LoadRequestForm(
            topic='test subject', replyto='*****@*****.**', comments='test comments')

        mailer.bcc_recipients = '*****@*****.**'
        self.messageText = ''
        mailer.onSuccess(request.form, request)
        self.assertTrue(
            '*****@*****.**' in self.mto
        )

        # simple override
        mailer.bccOverride = 'string:[email protected]'
        self.messageText = ''
        mailer.onSuccess(request.form, request)
        self.assertTrue(
            '*****@*****.**' in self.mto
        )

        # list override
        mailer.bccOverride = "python:['*****@*****.**', '*****@*****.**']"
        self.messageText = ''
        mailer.onSuccess(request.form, request)
        self.assertTrue(
            '*****@*****.**' in self.mto and
            '*****@*****.**' in self.mto
        )
Example #32
0
 def __init__(self, context, request):
     self.schema = get_actions(context)
     super(EasyFormActionsView, self).__init__(
         self.schema,
         request,
         name='actions'
     )
    def testProxyRole(self):
        """ Test seeing how setting proxy role affects unauthorized
        Exception
        """

        # TODO: Zope security system kills me
        self.createScript()

        actions = get_actions(self.ff1)
        adapter = actions['adapter']

        # 4. Set script data
        adapter.ScriptBody = proxied_script

        req = SecureFakeRequest(test_field='123')

        # errors = adapter.validate()
        # assert len(errors) == 0, 'Had errors:' + str(errors)

        # Execute script
        throwed = False
        try:
            adapter.onSuccess({}, req)
        except Unauthorized:
            throwed = True

        assert throwed, 'No Unauthorized was raised'
    def testSyntaxError(self):
        ''' Script has syntax errors

        TODO: Syntax errors are not returned in validation?
        '''

        # Note: this test logs an error message; it does not indicate test
        # failure

        self.createScript()

        actions = get_actions(self.ff1)
        adapter = actions['adapter']

        # 4. Set script data
        adapter.ScriptBody = syntax_error_script

        # Execute script
        throwed = False
        try:
            adapter.onSuccess({}, FakeRequest())
        except ValueError:
            throwed = True

        assert throwed, "Bad script didn't throw run-time exception"
    def testSyntaxError(self):
        ''' Script has syntax errors

        TODO: Syntax errors are not returned in validation?
        '''

        # Note: this test logs an error message; it does not indicate test
        # failure

        self.createScript()

        actions = get_actions(self.ff1)
        adapter = actions['adapter']

        # 4. Set script data
        adapter.ScriptBody = syntax_error_script

        # Execute script
        throwed = False
        try:
            adapter.onSuccess({}, FakeRequest())
        except ValueError:
            throwed = True

        assert throwed, "Bad script didn't throw run-time exception"
    def test_ccOverride(self):
        """ Test override for CC field """

        mailer = get_actions(self.ff1)["mailer"]
        fields = dict(topic="test subject",
                      replyto="*****@*****.**",
                      comments="test comments")
        request = self.LoadRequestForm(**fields)
        mailer.cc_recipients = "*****@*****.**"
        self.messageText = ""
        mailer.onSuccess(fields, request)
        self.assertIn("*****@*****.**", self.mto)

        # simple override
        mailer.ccOverride = "string:[email protected]"
        self.messageText = ""
        mailer.onSuccess(fields, request)
        self.assertIn("*****@*****.**", self.mto)

        # list override
        mailer.ccOverride = "python:['*****@*****.**', '*****@*****.**']"
        self.messageText = ""
        mailer.onSuccess(fields, request)
        self.assertTrue("*****@*****.**" in self.mto
                        and "*****@*****.**" in self.mto)
    def testReturnError(self):
        ''' Succesful script execution with return error
        '''
        self.createScript()

        actions = get_actions(self.ff1)
        actions['adapter'].ScriptBody = return_error_script
        set_actions(self.ff1, actions)

        self.portal.REQUEST['form.widgets.test_field'] = u'Test field'
        self.portal.REQUEST['form.widgets.topic'] = u'subject'
        self.portal.REQUEST['form.widgets.comments'] = u'some comments'
        self.portal.REQUEST['form.widgets.replyto'] = u'*****@*****.**'
        self.portal.REQUEST['form.buttons.submit'] = u'Submit'

        view = self.ff1.restrictedTraverse('view')
        form = view.form_instance
        form.update()

        errors = form.widgets.errors
        self.assertEqual(len(errors), 1)
        self.assertEqual(errors[0].message, 'Please enter more text')

        data, errors = form.extractData()
        self.assertEqual(len(errors), 0)

        errors = form.processActions(data)
        self.assertEqual(errors, {'comments': 'Please enter more text'})
    def test_selectiveFieldMailing(self):
        """ Test selective inclusion of fields in the mailing """

        mailer = get_actions(self.ff1)['mailer']
        fields = dict(topic='test subject',
                      replyto='*****@*****.**',
                      comments='test comments')
        request = self.LoadRequestForm(**fields)

        # make sure all fields are sent unless otherwise specified
        self.messageText = ''
        mailer.onSuccess(fields, request)
        self.assertTrue('te=\nst subject' in self.messageBody
                        and '*****@*****.**' in self.messageBody
                        and 'test comments' in self.messageBody)

        # setting some show fields shouldn't change that
        mailer.showFields = (
            'topic',
            'comments',
        )
        self.messageText = ''
        mailer.onSuccess(fields, request)
        self.assertTrue('te=\nst subject' in self.messageBody
                        and '*****@*****.**' in self.messageBody
                        and 'test comments' in self.messageBody)

        # until we turn off the showAll flag
        mailer.showAll = False
        self.messageText = ''
        mailer.onSuccess(fields, request)
        self.assertTrue('te=\nst subject' in self.messageBody
                        and '*****@*****.**' not in self.messageBody
                        and 'test comments' in self.messageBody)

        # check includeEmpties
        mailer.includeEmpties = False

        # first see if everything's still included
        mailer.showAll = True
        self.messageText = ''
        mailer.onSuccess(fields, request)
        # look for labels
        self.assertTrue(
            self.messageBody.find('Subject') > 0
            and self.messageBody.find('Your E-Mail Address') > 0
            and self.messageBody.find('Comments') > 0)

        # now, turn off required for a field and leave it empty
        fields = get_schema(self.ff1)
        fields['comments'].required = False
        set_fields(self.ff1, fields)
        fields = {'topic': 'test subject', 'replyto': '*****@*****.**'}
        request = self.LoadRequestForm(**fields)
        self.messageText = ''
        mailer.onSuccess(fields, request)
        self.assertIn('Subject', self.messageBody)
        self.assertIn('Your E-Mail Address', self.messageBody)
        self.assertNotIn('Comments', self.messageBody)
Example #39
0
    def testSetSavedFormInput(self):
        """ test setSavedFormInput functionality """

        # set up saver
        self.createSaver()
        self.assertTrue("saver" in get_actions(self.ff1))
        saver = get_actions(self.ff1)["saver"]
        self.assertEqual(saver.getSavedFormInputForEdit(), "")

        # save a row
        fields = list(get_schema(self.ff1))
        saver.addDataRow(dict(list(zip(fields, ["one", "two", "three"]))))
        self.assertEqual(saver.itemsSaved(), 1)
        items = saver.getSavedFormInputItems()
        self.assertEqual(
            items[0][1],
            dict(
                list(zip(["id"] + fields,
                         [items[0][0], "one", "two", "three"]))),
        )
        self.assertEqual(saver.getSavedFormInputForEdit(), "one,two,three\r\n")

        # save a couple of \n-delimited rows - \n eol
        saver.addDataRow(dict(list(zip(fields, ["four", "five", "six"]))))
        self.assertEqual(saver.itemsSaved(), 2)
        items = saver.getSavedFormInputItems()
        self.assertEqual(
            items[0][1],
            dict(
                list(zip(["id"] + fields,
                         [items[0][0], "one", "two", "three"]))),
        )
        self.assertEqual(
            items[1][1],
            dict(
                list(zip(["id"] + fields,
                         [items[1][0], "four", "five", "six"]))),
        )
        self.assertEqual(saver.getSavedFormInputForEdit(),
                         "one,two,three\r\nfour,five,six\r\n")

        # save empty string
        saver.clearSavedFormInput()
        self.assertEqual(saver.itemsSaved(), 0)
        self.assertEqual(saver.getSavedFormInputForEdit(), "")
Example #40
0
    def testSaverSelectiveFieldSaving(self):
        ''' Test selective inclusion of fields in the data'''

        self.createSaver()

        self.assertTrue('saver' in get_actions(self.ff1))
        saver = get_actions(self.ff1)['saver']
        saver.showFields = ('topic', 'comments')

        request = FakeRequest(add_auth=True, method='POST',
                              topic='test subject', replyto='*****@*****.**', comments='test comments')
        saver.onSuccess(request.form, request)

        self.assertEqual(saver.itemsSaved(), 1)
        row = iter(saver.getSavedFormInput()).next()
        self.assertEqual(len(row), 3)
        self.assertEqual(row['topic'], 'test subject')
        self.assertEqual(row['comments'], 'test comments')
 def testActiveAdaptersNotDuplicatedOnFormCopy(self):
     # self.loginAsPortalOwner()
     copy = self.folder.manage_copyObjects('ff1')
     new_id = self.folder.manage_pasteObjects(copy)[0]['new_id']
     ff2 = getattr(self.folder, new_id)
     active_adapters = tuple(get_actions(ff2))
     self.assertEqual(active_adapters, ('mailer',))
     active_fields = tuple(get_schema(ff2))
     self.assertEqual(active_fields, ('replyto', 'topic', 'comments'))
Example #42
0
    def test_custom_email_template(self):
        """ Test mailer with custom template """
        default_fields = api.content.create(
            self.portal, 'File', id='easyform_mail_body_default.pt')
        default_fields.file = NamedFile('Custom e-mail template!')

        mailer = get_actions(self.ff1)['mailer']
        mailer.onSuccess({}, self.layer['request'])
        self.assertIn(u'Custom e-mail template!', self.messageText)
    def download_csv(self):
        brain = api.content.find(context=self.context,
                                 portal_type="EasyForm")[0]
        subscription = brain.getObject()

        savedata = get_actions(subscription).get("save")
        if not savedata:
            return
        return savedata.download_csv(self.request.response)
Example #44
0
    def test_MailerOverridesWithFieldValues(self):
        mailer = get_actions(self.ff1)['mailer']
        mailer.subjectOverride = 'fields/topic'
        mailer.recipientOverride = 'fields/replyto'
        data = {'topic': 'eggs and spam', 'replyto': u'*****@*****.**'}
        request = self.LoadRequestForm(**data)
        mailer.onSuccess(data, request)

        self.assertIn('Subject: =?utf-8?q?eggs_and_spam?=', self.messageText)
        self.assertIn('To: [email protected]', self.messageText)
    def testSaverColumnTitles(self):
        ''' test save data adapter's getColumnTitles function '''

        self.createSaver()

        self.assertTrue('saver' in get_actions(self.ff1))
        saver = get_actions(self.ff1)['saver']

        cn = saver.getColumnTitles()
        self.assertTrue(len(cn) == 3)
        self.assertTrue(cn[0] == 'Your E-Mail Address')
        self.assertTrue(cn[1] == 'Subject')
        self.assertTrue(cn[2] == 'Comments')

        # Add an extra column
        saver.ExtraData = ('dt',)
        cn = saver.getColumnTitles()
        self.assertTrue(len(cn) == 4)
        self.assertTrue(cn[3] == 'Posting Date/Time')
 def afterSetUp(self):
     super(TestFunctions, self).afterSetUp()
     self.folder.invokeFactory('EasyForm', 'ff1')
     self.ff1 = getattr(self.folder, 'ff1')
     self.ff1.CSRFProtection = False  # no csrf protection
     self.mailhost = self.folder.MailHost
     self.mailhost._send = self.dummy_send
     actions = get_actions(self.ff1)
     actions['mailer'].recipient_email = u'*****@*****.**'
     set_actions(self.ff1, actions)
Example #47
0
    def testMultiRecipientOverrideByTuple(self):
        """ try multiple recipients in recipient override """

        mailer = get_actions(self.ff1)['mailer']
        mailer.recipientOverride = "python: ('*****@*****.**', 'spam.spam.com')"

        data = {'topic': 'test subject'}
        request = self.LoadRequestForm(**data)
        mailer.onSuccess(data, request)

        self.assertIn('To: [email protected], spam.spam.com', self.messageText)
Example #48
0
    def testSaverDownload(self):
        ''' test save data '''

        self.createSaver()

        self.assertTrue('saver' in get_actions(self.ff1))
        saver = get_actions(self.ff1)['saver']
        self.assertEqual(saver.itemsSaved(), 0)

        request = FakeRequest(
            add_auth=True, method='POST', topic='test subject', replyto='*****@*****.**', comments='test comments')
        saver.onSuccess(request.form, request)

        self.assertEqual(saver.itemsSaved(), 1)
        saver.download(request.response)
        res = request.response.stdout.getvalue()
        self.assertTrue('Content-Type: text/comma-separated-values' in res)
        self.assertTrue(
            'Content-Disposition: attachment; filename="saver.csv"' in res)
        self.assertTrue(saver.getSavedFormInputForEdit() in res)
 def afterSetUp(self):
     base.EasyFormTestCase.afterSetUp(self)
     self.folder.invokeFactory('EasyForm', 'ff1')
     self.ff1 = getattr(self.folder, 'ff1')
     self.ff1.title = u'ff1'
     self.ff1.CSRFProtection = False  # no csrf protection
     actions = get_actions(self.ff1)
     actions['mailer'].recipient_email = u'*****@*****.**'
     set_actions(self.ff1, actions)
     self.mailhost = self.folder.MailHost
     self.mailhost._send = self.dummy_send
     classImplements(BaseRequest, IFormLayer)
Example #50
0
    def testSaver(self):
        ''' test save data adapter action '''

        self.createSaver()

        self.assertTrue('saver' in get_actions(self.ff1))
        saver = get_actions(self.ff1)['saver']

        self.assertEqual(saver.itemsSaved(), 0)

        res = saver.getSavedFormInputForEdit()
        self.assertEqual(res, '')

        request = FakeRequest(
            add_auth=True, method='POST', topic='test subject', replyto='*****@*****.**', comments='test comments')
        saver.onSuccess(request.form, request)

        self.assertEqual(saver.itemsSaved(), 1)

        res = saver.getSavedFormInputForEdit()
        self.assertEqual(
            res.strip(), '[email protected],test subject,test comments')
Example #51
0
    def test_MailerOverrides(self):
        """ Test mailer override functions """

        mailer = get_actions(self.ff1)['mailer']
        mailer.subjectOverride = "python: '{0} and {1}'.format('eggs', 'spam')"
        mailer.senderOverride = 'string: [email protected]'
        mailer.recipientOverride = 'string: [email protected]'
        data = {'topic': 'test subject'}
        request = self.LoadRequestForm(**data)

        mailer.onSuccess(data, request)
        self.assertIn('Subject: =?utf-8?q?eggs_and_spam?=', self.messageText)
        self.assertIn('From: [email protected]', self.messageText)
        self.assertIn('To: [email protected]', self.messageText)
    def test_MailerOverridesWithFieldValues(self):
        mailer = get_actions(self.ff1)['mailer']
        mailer.subjectOverride = 'fields/topic'
        mailer.recipientOverride = 'fields/replyto'

        request = self.LoadRequestForm(
            topic='eggs and spam',
            replyto=u'*****@*****.**'
        )
        mailer.onSuccess(request.form, request)

        self.assertTrue(self.messageText.find(
            'Subject: =?utf-8?q?eggs_and_spam?=') > 0)
        self.assertTrue(self.messageText.find('To: <*****@*****.**>') > 0)
    def testMultiRecipientOverrideByTuple(self):
        """ try multiple recipients in recipient override """

        mailer = get_actions(self.ff1)['mailer']
        mailer.recipientOverride = "python: ('*****@*****.**', 'spam.spam.com')"

        # fields = self.ff1._getFieldObjects()

        request = self.LoadRequestForm(topic='test subject')

        mailer.onSuccess(request.form, request)

        self.assertTrue(self.messageText.find(
            'To: <*****@*****.**>, <spam.spam.com>') > 0)
    def testMultiRecipientOverrideByString(self):
        """ try multiple recipients in recipient override """

        mailer = get_actions(self.ff1)['mailer']
        mailer.recipientOverride = 'string: [email protected], [email protected]'

        # fields = self.ff1._getFieldObjects()

        request = self.LoadRequestForm(topic='test subject')

        mailer.onSuccess(request.form, request)

        self.assertTrue(self.messageText.find(
            'To: [email protected], [email protected]') > 0)
    def testDefaultParameters(self):
        """ Test to make sure the documented parameters are available """

        self.createScript()

        actions = get_actions(self.ff1)
        adapter = actions["adapter"]

        # 4. Set script data
        adapter.ScriptBody = default_params_script

        request = FakeRequest(topic="test subject", replyto="*****@*****.**", comments="test comments")

        errors = adapter.onSuccess({}, request)
        self.assertEqual(errors, None)