def test_user_deleted(self): request = self.portal.REQUEST # protected user self.assertRaises(Redirect, api.user.delete, username='******') smi = IStatusMessage(request) msgs = smi.show() self.assertEqual(msgs[0].message, u"You cannot delete the user name 'scanner'.") # having group self.assertRaises(Redirect, api.user.delete, 'lecteur') msgs = smi.show() self.assertEqual( msgs[0].message, u"You cannot delete the user name 'lecteur', used in following groups." ) # is used in content self.assertRaises(Redirect, api.user.delete, username=TEST_USER_ID) msgs = smi.show() self.assertEqual( msgs[0].message, u"You cannot delete the user name 'test_user_1_', used in 'Creator' index." ) # is used as person user_id api.user.create('*****@*****.**', 'testuser', 'Password#1') agent = self.portal.contacts['personnel-folder']['agent'] agent.userid = 'testuser' agent.reindexObject() self.assertRaises(Redirect, api.user.delete, username='******') msgs = smi.show() self.assertEqual( msgs[0].message, u"You cannot delete the user name 'testuser', used in 'Mail type' index." )
def extractData(self, setErrors=True): data = super(EditForm, self).extractData(setErrors) # If there is a validation error on the form, consume all status messages, # so that they don't appear in the form. We only want to show validation # messages directly on the respective field(s) in that case. if data[1]: status = IStatusMessage(self.request) status.show() return data
def test_show_message(self): from Products.statusmessages.interfaces import IStatusMessage request = self.layer['request'] portal.show_message(message='Blueberries!', request=request) messages = IStatusMessage(request) show = messages.show() self.assertEquals(len(show), 1) self.assertTrue('Blueberries!' in show[0].message) portal.show_message(message='One', request=request) portal.show_message(message='Two', request=request) messages = IStatusMessage(request) show = messages.show() self.assertEqual(len(show), 2) self.assertEqual(show[0].message, 'One') self.assertEqual(show[1].message, 'Two')
def test_no_message(self): """If no interface gets removed, no portal message is shown.""" discard_view = api.content.get_view(name="discard-alert", context=self.document, request=self.request) discard_view() messages = IStatusMessage(self.request) show = messages.show() self.assertEqual(len(show), 0)
def test_canNotSendIfInNoPMCreatorGroup(self): """ If the user that wants to send the item in PloneMeeting is not a creator in PM, aka is not in a _creators suffixed group, a message is displayed to him. """ # remove pmCreator2 from the vendors_creators group # first check that the user is actually in a _creators group pmCreator2 = self.portal.portal_membership.getMemberById('pmCreator2') self.assertTrue([ group for group in self.portal.acl_users.source_groups. getGroupsForPrincipal(pmCreator2) if group.endswith('_creators') ]) self.portal.portal_groups.removePrincipalFromGroup( 'pmCreator2', self.vendors_creators) # pmCreator2 is no more in a _creators group self.assertFalse([ group for group in self.portal.acl_users.source_groups. getGroupsForPrincipal(pmCreator2) if group.endswith('_creators') ]) # try to send the item setCorrectSettingsConfig(self.portal) self.changeUser('pmCreator2') self.tool.getPloneMeetingFolder('plonemeeting-assembly', 'pmCreator2') transaction.commit() # create an element to send... document = createDocument(self.portal.Members.pmCreator2) messages = IStatusMessage(self.request) # if no item is created, _sendToPloneMeeting returns None self.assertFalse( self._sendToPloneMeeting(document, user='******', proposingGroup=self.vendors_uid)) msg = _(NO_PROPOSING_GROUP_ERROR, mapping={'userId': 'pmCreator2'}) self.assertEqual(messages.show()[-3].message, translate(msg))
def test_show_message(self): """Test to see if message appears.""" from Products.statusmessages.interfaces import IStatusMessage request = self.layer['request'] portal.show_message(message='Blueberries!', request=request) messages = IStatusMessage(request) show = messages.show() self.assertEqual(len(show), 1) self.assertIn('Blueberries!', show[0].message) portal.show_message(message='One', request=request) portal.show_message(message='Two', request=request) messages = IStatusMessage(request) show = messages.show() self.assertEqual(len(show), 2) self.assertEqual(show[0].message, 'One') self.assertEqual(show[1].message, 'Two')
def status_messages(self): """ Returns status messages if any """ messages = IStatusMessage(self.request) m = messages.show() for item in m: item.id = idnormalizer.normalize(item.message) return m
def test_soap_createItem(self): """Check item creation. Item creation will automatically use currently connected user to create the item regarding the _getUserIdToUseInTheNameOfWith.""" cfg2 = self.meetingConfig2 cfg2Id = cfg2.getId() ws4pmSettings = getMultiAdapter((self.portal, self.request), name='ws4pmclient-settings') setCorrectSettingsConfig(self.portal, minimal=True) self.changeUser('pmManager') self.setMeetingConfig(cfg2Id) test_meeting = self.create('Meeting') self.freezeMeeting(test_meeting) self.changeUser('pmCreator1') # create the 'pmCreator1' member area to be able to create an item pmFolder = self.tool.getPloneMeetingFolder(cfg2Id) # we have to commit() here or portal used behing the SOAP call # does not have the freshly created item... transaction.commit() # create an item for 'pmCreator1' data = {'title': u'My sample item', 'category': u'deployment', 'description': u'<p>My description</p>', # also use accents, this was failing with suds-jurko 0.5 'decision': u'<p>My d\xe9cision</p>', 'preferredMeeting': test_meeting.UID(), 'externalIdentifier': u'my-external-identifier', 'extraAttrs': [{'key': 'internalNotes', 'value': '<p>Internal notes</p>'}]} result = ws4pmSettings._soap_createItem(cfg2Id, 'developers', data) # commit again so the item is really created transaction.commit() # the item is created and his UID is returned # check that the item is actually created inTheNameOf 'pmCreator1' itemUID = result[0] item = self.portal.uid_catalog(UID=itemUID)[0].getObject() # created in the 'pmCreator1' member area self.assertTrue(item.aq_inner.aq_parent.UID(), pmFolder.UID()) self.assertTrue(item.owner_info()['id'] == 'pmCreator1') self.assertEqual(item.Title(), data['title']) self.assertEqual(item.getCategory(), data['category']) self.assertEqual(item.Description(), data['description']) self.assertEqual(item.getDecision(), data['decision'].encode('utf-8')) self.assertEqual(item.getPreferredMeeting(), test_meeting.UID(), data['preferredMeeting']) self.assertEqual(item.externalIdentifier, data['externalIdentifier']) # extraAttrs self.assertEqual(item.getInternalNotes(), data['extraAttrs'][0]['value']) # if we try to create with wrong data, the SOAP ws returns a response # that is displayed to the user creating the item data['category'] = 'unexisting-category-id' result = ws4pmSettings._soap_createItem('plonegov-assembly', 'developers', data) self.assertIsNone(result) messages = IStatusMessage(self.request) # a message is displayed self.assertEqual(messages.show()[-1].message, u"An error occured during the item creation in PloneMeeting! " "The error message was : Server raised fault: ''unexisting-category-id' " "is not available for the 'developers' group!'")
def test_group_deleted(self): request = self.portal.REQUEST # protected group self.assertRaises(Redirect, api.group.delete, groupname='expedition') smi = IStatusMessage(request) msgs = smi.show() self.assertEqual(msgs[0].message, u"You cannot delete the group 'expedition'.") # is used in content group = '%s_editeur' % get_registry_organizations()[0] # we remove this organization to escape plonegroup subscriber set_registry_organizations(get_registry_organizations()[1:]) self.assertRaises(Redirect, api.group.delete, groupname=group) msgs = smi.show() self.assertEqual( msgs[0].message, u"You cannot delete the group '%s', used in 'Assigned group' index." % group)
def status_messages(self): """ Returns status messages if any """ messages = IStatusMessage(self.request) m = messages.show() for item in m: item.id = idnormalizer.normalize(item.message) return m
def test_message(self): """If the interface gets removed, a portal message is shown.""" alsoProvides(self.document, IHasStopWords) discard_view = api.content.get_view(name="discard-alert", context=self.document, request=self.request) discard_view() messages = IStatusMessage(self.request) show = messages.show() self.assertEqual(len(show), 1) self.assertIn("The object no longer ", show[0].message)
def test_available(self): """ """ self.changeUser('admin') document = createDocument(self.portal) # by default, no viewlet_display_condition TAL expression viewlet = PloneMeetingInfosViewlet(document, self.request, None, None) viewlet.update() settings = viewlet.ws4pmSettings.settings() settings.viewlet_display_condition = u'' # no items created/linked, so the viewlet is not displayed self.assertFalse(viewlet.available()) # viewlet is displayed depending on : # by default, the fact that it is linked to an item # or if a TAL expression is defined in the config and returns True # test with a defined TAL expression in the configuration settings.viewlet_display_condition = u'python: True' # if a TAL expression is defined, it take precedence # available is memoized so it is still False... self.assertFalse(viewlet.available()) # remove memoized informations cleanMemoize(self.request, viewlet) self.assertTrue(viewlet.available()) cleanMemoize(self.request, viewlet) # now remove the TAL expression and send the object to PloneMeeting settings.viewlet_display_condition = u'' self.assertFalse(viewlet.available()) cleanMemoize(self.request, viewlet) item = self._sendToPloneMeeting(document) # now that the element has been sent, the viewlet is available self.assertTrue(viewlet.available()) cleanMemoize(self.request, viewlet) # define a TAL expression taking care of the 'isLinked' settings.viewlet_display_condition = u'python: isLinked and object.portal_type == "wrong_value"' self.assertFalse(viewlet.available()) cleanMemoize(self.request, viewlet) settings.viewlet_display_condition = u'python: isLinked and object.portal_type == "Document"' self.assertTrue(viewlet.available()) cleanMemoize(self.request, viewlet) # if the TAL expression has errors, available is False and a message is displayed messages = IStatusMessage(self.request) # by default, 2 messages already exist, these are item creation related messages shownMessages = messages.show() self.assertTrue(len(shownMessages) == 1) self.assertTrue(shownMessages[0].message, CORRECTLY_SENT_TO_PM_INFO) settings.viewlet_display_condition = u'python: object.getUnexistingAttribute()' # in case there is a problem, a message is displayed in a tuple (msg, error_level) self.assertTrue(isinstance(viewlet.available(), tuple)) cleanMemoize(self.request, viewlet) # now check when the linked item is removed settings.viewlet_display_condition = u'' self.assertTrue(viewlet.available()) cleanMemoize(self.request, viewlet) item.aq_inner.aq_parent.manage_delObjects(ids=[ item.getId(), ]) transaction.commit() self.assertFalse(viewlet.available())
def at_post_create_script(self): """ Esse método é chamado no momento da criação de um objeto da classe. Ele preenche o campo subject (tags) com visit type no edit. """ patient = self.getPatient() patient.create_event(Event.CREATION, self.startDate, self) # make scheduled the initial state. This code needs to be here, not in at_post_edit self.portal_workflow.doActionFor(self, 'schedule') self.setTitle(patient.Title()) # limpa a pilha de messagens e evita que apareça a mensagem "Suas alteraçoes # foram salvas." fora de contexto (já que Visit é salva utilizando Ajax) messages = IStatusMessage(self.REQUEST) messages.show() self.at_post_edit_script()
def test_show_message(self): """Test to see if message appears.""" from Products.statusmessages.interfaces import IStatusMessage request = self.layer["request"] portal.show_message(message="Blueberries!", request=request) messages = IStatusMessage(request) show = messages.show() self.assertEqual(len(show), 1) self.assertIn("Blueberries!", show[0].message) portal.show_message(message="One", request=request) portal.show_message(message="Two", request=request) messages = IStatusMessage(request) show = messages.show() self.assertEqual(len(show), 2) self.assertEqual(show[0].message, "One") self.assertEqual(show[1].message, "Two")
class GlobalStatusMessage(ViewletBase): """Display messages to the current user""" index = ViewPageTemplateFile('globalstatusmessage.pt') def update(self): super(GlobalStatusMessage, self).update() self.status = IStatusMessage(self.request) self.messages = self.status.show()
def test_canNotConnectToPloneMeeting(self): """If no valid parameters are defined in the settings, the view is not accessible and a relevant message if displayed to the member in portal_messages.""" # set base params to avoid extra status messages like 'no field_mappings defined' setCorrectSettingsConfig(self.portal, setConnectionParams=False, withValidation=False) # only available to connected users self.changeUser('pmCreator1') self._configureRequestForView(self.portal) view = self.portal.restrictedTraverse( SEND_TO_PM_VIEW_NAME).form_instance # when we can not connect, a message is displayed to the user messages = IStatusMessage(self.request) self.assertTrue(len(messages.show()) == 0) # call the view view() self.assertTrue(len(messages.show()) == 1) self.assertEquals(messages.show()[0].message, UNABLE_TO_CONNECT_ERROR)
def testLockoutPolicy(self): sector = createSector(self.portal) mbtool = api.portal.get_tool(TOOLNAME) member = mbtool.getUserObject(login=sector.login) auth = user_ifaces.IMembraneUserAuth(member, None) status = IStatusMessage(auth.context.REQUEST) auth.applyLockoutPolicy(0) self.assertEqual(len(status.show()), 0) self.assertFalse(sector.locked) auth.applyLockoutPolicy(2) self.assertEqual(len(status.show()), 1) self.assertEqual(auth.context._v_login_attempts, 1) self.assertFalse(sector.locked) auth.applyLockoutPolicy(2) self.assertEqual(len(status.show()), 1) self.assertEqual(auth.context._v_login_attempts, 2) self.assertTrue(sector.locked)
def test_cart_limit(self): """Test if cart limit is honored when adding an item to cart.""" # Set a lower limit, since it's 100 by default' api.portal.set_registry_record('slc.cart.limit', 1) cart = self.portal.restrictedTraverse('cart').cart self.assertEqual(len(cart), 0) # add a new item self.item1.restrictedTraverse("add-to-cart").render() self.assertEqual(len(cart), 1) messages = IStatusMessage(self.portal.REQUEST) self.assertEqual(len(messages.show()), 0) # add another item, error message should be displayed self.item2.restrictedTraverse("add-to-cart").render() messages = IStatusMessage(self.portal.REQUEST) message = messages.show()[0].message self.assertIn('Cart full (limit is 1 item(s))', message) self.assertEqual(len(cart), 1)
def testLockoutPolicy(self): sector = createSector(self.portal) mbtool = api.portal.get_tool(TOOLNAME) member = mbtool.getUserObject(login=sector.login) auth = user_ifaces.IMembraneUserAuth(member, None) status = IStatusMessage(auth.context.REQUEST) auth.applyLockoutPolicy(0) self.assertEqual(len(status.show()), 0) self.assertFalse(sector.locked) auth.applyLockoutPolicy(2) self.assertEqual(len(status.show()), 1) self.assertEqual(auth.context._v_login_attempts, 1) self.assertFalse(sector.locked) auth.applyLockoutPolicy(2) self.assertEqual(len(status.show()), 1) self.assertEqual(auth.context._v_login_attempts, 2) self.assertTrue(sector.locked)
def test_cart_limit(self): """Test if cart limit is honored when adding an item to cart.""" # Set a lower limit, since it's 100 by default' api.portal.set_registry_record('slc.cart.limit', 1) cart = self.portal.restrictedTraverse('cart').cart self.assertEqual(len(cart), 0) # add a new item self.item1.restrictedTraverse("add-to-cart").render() self.assertEqual(len(cart), 1) messages = IStatusMessage(self.portal.REQUEST) self.assertEqual(len(messages.show()), 0) # add another item, error message should be displayed self.item2.restrictedTraverse("add-to-cart").render() messages = IStatusMessage(self.portal.REQUEST) message = messages.show()[0].message self.assertIn('Cart full (limit is 1 item(s))', message) self.assertEqual(len(cart), 1)
class GlobalStatusMessage(ViewletBase): """ Displays messages to the current user. The markup is changed to rely on pat-notification. """ index = ViewPageTemplateFile('globalstatusmessage.pt') def update(self): super(GlobalStatusMessage, self).update() self.status = IStatusMessage(self.request) messages = self.status.show() for m in messages: m.id = idnormalizer.normalize(m.message) self.messages = messages
def test_DownloadAnnexFromItemView_without_annex_id(self): """ Test the BrowserView that return the annex of an item """ messages = IStatusMessage(self.request) self.changeUser('admin') download_annex = self.portal.restrictedTraverse( '@@download_annex_from_plonemeeting') # mock connexion to PloneMeeting download_annex.ws4pmSettings._soap_connectToPloneMeeting = Mock( return_value=True) download_annex() self.assertEqual(messages.show()[-1].message, ANNEXID_MANDATORY_ERROR)
class GlobalStatusMessageTile(Tile): """Display messages to the current user""" def __call__(self): self.update() return self.index() def update(self): if not self.request.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest': self.status = IStatusMessage(self.request) self.messages = self.status.show() else: return u'<html></html>'
def _doDelete(self): wf = self.context.restrictedTraverse('folder_publish') ##parameters=workflow_action=None, paths=[], comment='No comment', ##expiration_date=None, effective_date=None, include_children=False wf(workflow_action="delete", comment="RCSE Delete action", include_children=True, paths=['/'.join(self.context.getPhysicalPath())]) status = IStatusMessage(self.request) # lets replace the message from folder_publish by ours. status.show() self.request.cookies[STATUSMESSAGEKEY] = None self.request.response.expireCookie(STATUSMESSAGEKEY, path='/') annotations = IAnnotations(self.request) annotations[STATUSMESSAGEKEY] = None status.add(_(u"Item and it's content has been deleted")) # avoid getting the context itself if it's a group group = get_group(aq_inner(self.context).__parent__) if group is None: url = getToolByName(self.context, 'portal_url')() else: url = group.absolute_url() self.request.response.redirect(url)
def _doDelete(self): wf = self.context.restrictedTraverse('folder_publish') ##parameters=workflow_action=None, paths=[], comment='No comment', ##expiration_date=None, effective_date=None, include_children=False wf(workflow_action="delete", comment="RCSE Delete action", include_children=True, paths=['/'.join(self.context.getPhysicalPath())]) status = IStatusMessage(self.request) # lets replace the message from folder_publish by ours. status.show() self.request.cookies[STATUSMESSAGEKEY] = None self.request.response.expireCookie(STATUSMESSAGEKEY, path='/') annotations = IAnnotations(self.request) annotations[STATUSMESSAGEKEY] = None status.add(_(u"Item and it's content has been deleted")) # avoid getting the context itself if it's a group group = get_group(aq_inner(self.context).__parent__) if group is None: url = getToolByName(self.context, 'portal_url')() else: url = group.absolute_url() self.request.response.redirect(url)
def test_group_deleted(self): class Dummy(object): def __init__(self, name): self.principal = name self.assertIsNone(group_deleted(Dummy('no-underscore'))) request = self.portal.REQUEST smi = IStatusMessage(request) uid = self.contacts[0].UID() self.assertRaises(Redirect, api.group.delete, groupname='%s_director' % uid) msgs = smi.show() self.assertEqual(msgs[0].message, u"You cannot delete the group '%s_director', linked to used organization " "'Department 1'." % uid) api.group.create(groupname='%s_other' % uid) api.group.create(groupname='12345_director') api.group.delete(groupname='%s_other' % uid) api.group.delete(groupname='12345_director')
def test_process(self): view = CSVImportView(self.profiles, self.request) file_loc = self._get_fixture_location('missing_first_name.csv') with open(file_loc) as bf: filedata = bf.read() view.process(filedata) messages = IStatusMessage(self.request) m = messages.show() self.assertEqual(m[0].message, u'Missing required field first_name on row 1') user_fields_file_loc = self._get_fixture_location('basic_users.csv') with open(user_fields_file_loc) as bf: filedata = bf.read() view.process(filedata)
def test_DownloadAnnexFromItemView_with_no_result(self, _soap_getItemInfos): """ Test the BrowserView that return the annex of an item """ # return no annex _soap_getItemInfos.return_value = None messages = IStatusMessage(self.request) self.changeUser('admin') document = createDocument(self.portal) self.request.set('annex_id', 'my_annex') download_annex = document.restrictedTraverse( '@@download_annex_from_plonemeeting') # mock connexion to PloneMeeting download_annex.ws4pmSettings._soap_connectToPloneMeeting = Mock( return_value=True) download_annex() self.assertEqual(messages.show()[-1].message, MISSING_FILE_ERROR)
def test_leave_owner(self): ws = self.traverse(WS_PUBLIC) self.assertTrue(ws.userIsMember(testing.WS_OWNER)) self.assertFalse(ws.userCanJoin(testing.WS_OWNER)) self.assertFalse(ws.userCanLeave(testing.WS_OWNER)) self.assertFalse(ws.userIsInvited(testing.WS_OWNER)) login(self.portal, testing.WS_OWNER) self.traverse(WS_PUBLIC + '/leave').update() msgs = IStatusMessage(self.request) self.assertEquals(msgs.show()[-1].message, workspace.CANT_LEAVE_BECAUSE_NO_MEMBER_MESSAGE) self.assertTrue(ws.userIsMember(testing.WS_OWNER)) self.assertFalse(ws.userCanJoin(testing.WS_OWNER)) self.assertFalse(ws.userCanLeave(testing.WS_OWNER)) self.assertFalse(ws.userIsInvited(testing.WS_OWNER))
def test_join_owner(self): ws = self.traverse(WS_PUBLIC) ws.autoAcceptNewMembers = False self.assertTrue(ws.userIsMember(testing.WS_OWNER)) self.assertFalse(ws.userIsInvited(testing.WS_OWNER)) self.assertFalse(ws.userCanJoin(testing.WS_OWNER)) self.assertFalse(ws.userCanLeave(testing.WS_OWNER)) login(self.portal, testing.WS_OWNER) self.traverse(WS_PUBLIC + '/join').update() msgs = IStatusMessage(self.request) self.assertEquals(msgs.show()[-1].message, workspace.ALREADY_MEMBER_MESSAGE) self.assertTrue(ws.userIsMember(testing.WS_OWNER)) self.assertFalse(ws.userIsInvited(testing.WS_OWNER)) self.assertFalse(ws.userCanJoin(testing.WS_OWNER)) self.assertFalse(ws.userCanLeave(testing.WS_OWNER))
def test_join_closed_ws(self): ws = self.traverse(WS_PUBLIC) ws.autoAcceptNewMembers = False self.assertFalse(ws.userIsMember(testing.SITE_MEMBER)) self.assertFalse(ws.userIsInvited(testing.SITE_MEMBER)) self.assertFalse(ws.userCanJoin(testing.SITE_MEMBER)) self.assertFalse(ws.userCanLeave(testing.SITE_MEMBER)) login(self.portal, testing.SITE_MEMBER) self.traverse(WS_PUBLIC + '/join').update() msgs = IStatusMessage(self.request) self.assertEquals(msgs.show()[-1].message, workspace.WORKSPACE_CLOSED_MESSAGE) self.assertFalse(ws.userIsMember(testing.SITE_MEMBER)) self.assertFalse(ws.userIsInvited(testing.SITE_MEMBER)) self.assertFalse(ws.userCanJoin(testing.SITE_MEMBER)) self.assertFalse(ws.userCanLeave(testing.SITE_MEMBER))
def test_process(self): view = CSVImportView(self.profiles, self.request) file_loc = self._get_fixture_location( 'missing_first_name.csv') with open(file_loc) as bf: filedata = bf.read() view.process(filedata) messages = IStatusMessage(self.request) m = messages.show() self.assertEqual( m[0].message, u'Missing required field first_name on row 1' ) user_fields_file_loc = self._get_fixture_location( 'basic_users.csv') with open(user_fields_file_loc) as bf: filedata = bf.read() view.process(filedata)
def test_group_deleted(self): class Dummy(object): def __init__(self, name): self.principal = name self.assertIsNone(group_deleted(Dummy('no-underscore'))) request = self.portal.REQUEST smi = IStatusMessage(request) uid = self.contacts[0].UID() self.assertRaises(Redirect, api.group.delete, groupname='%s_director' % uid) msgs = smi.show() self.assertEqual( msgs[0].message, u"You cannot delete the group '%s_director', " "linked to used organization 'Department 1'." % uid) api.group.create(groupname='%s_other' % uid) api.group.create(groupname='12345_director') api.group.delete(groupname='%s_other' % uid) api.group.delete(groupname='12345_director')
def test_join_uninvited(self): p = self.project self.assertFalse(p.userIsMember(testing.MEMBER)) self.assertFalse(p.userIsManager(testing.MEMBER)) self.assertFalse(p.userIsInvited(testing.MEMBER)) self.assertFalse(p.userCanJoin(testing.MEMBER)) self.assertFalse(p.userCanLeave(testing.MEMBER)) login(self.portal, testing.MEMBER) p.restrictedTraverse('@@join').update() msgs = IStatusMessage(self.request) self.assertEquals(msgs.show()[-1].message, workspace.WORKSPACE_CLOSED_MESSAGE) self.assertFalse(p.userIsMember(testing.MEMBER)) self.assertFalse(p.userIsManager(testing.MEMBER)) self.assertFalse(p.userIsInvited(testing.MEMBER)) self.assertFalse(p.userCanJoin(testing.MEMBER)) self.assertFalse(p.userCanLeave(testing.MEMBER))
def test_leave_success(self): ws = self.traverse(WS_PUBLIC) self.assertTrue(ws.userIsMember(testing.WS_MEMBER)) self.assertFalse(ws.userCanJoin(testing.WS_MEMBER)) self.assertTrue(ws.userCanLeave(testing.WS_MEMBER)) self.assertFalse(ws.userIsInvited(testing.WS_MEMBER)) login(self.portal, testing.WS_MEMBER) self.request['form.button.Leave'] = True self.traverse(WS_PUBLIC + '/leave').update() msgs = IStatusMessage(self.request) self.assertEquals(msgs.show()[-1].message, workspace.LEFT_WORKSPACE_MESSAGE) self.assertFalse(ws.userIsMember(testing.WS_MEMBER)) self.assertTrue(ws.userCanJoin(testing.WS_MEMBER)) self.assertFalse(ws.userCanLeave(testing.WS_MEMBER)) self.assertFalse(ws.userIsInvited(testing.WS_MEMBER))
def handleSaveAndPublish(self, action): """ The additional button to send to a "ftw.publisher.receiver" instance. """ self.handleSave(self, action) self.send_to_receiver() # Consume Plone messages set by `handleSave` so we can set our own message. messages = IStatusMessage(self.request) if messages.show(): self.request.response.cookies.pop(STATUSMESSAGEKEY) IAnnotations(self.request)[STATUSMESSAGEKEY] = None # Set a new Plone message. api.portal.show_message( message=_(u'Changes saved and published.'), request=self.request, type='info' )
def __call__(self, auth=None): if auth is None: raise Unauthorized("Missing authentication token.") registry = getUtility(IRegistry) settings = registry.forInterface(ISettings) if auth != settings.update_token: raise Unauthorized("Bad authentication token.") # as unrestricted user ... old = security.loginAsUnrestrictedUser() try: super(ControlPanelPublicRequest, self).update() finally: security.loginAsUser(old) self.request.response.setHeader('Content-Type', 'text/plain') status = IStatusMessage(self.request) return "\n".join( "%s: %s" % (message.type.upper(), message.message) for message in status.show() )
def drop_login_failed_msg(request): """ Drop an eventual "Login failed..." status message from the request, but keep all other messages by re-adding them. Because what ends up in the request is the message translated in the user's language, we have to first translate the "Login failed" message using the same request(i.e. language), and then filter out the status message based on that. :param ZPublisher.HTTPRequest request: """ login_failed = ("Login failed. Both login name and password are case " "sensitive, check that caps lock is not enabled.") login_failed_translated = translate( login_failed, domain='plone', context=request) status_messages = IStatusMessage(request) msgs = status_messages.show() for msg in msgs: if msg.message == login_failed_translated: # Drop the "Login failed" message continue status_messages.add(msg.message, msg.type)
class EmbeddedPFGView(BrowserView): """ Browser view that can update and render a PFG form in some other context """ # Prefix to ensure that we don't try to process other forms that might # be on the same page prefix = u'' # optional form action override action = None # enable form unload warning if it has been edited? enable_unload_protection = False # auto-focus the form on page load? enable_auto_focus = False def setPrefix(self, prefix): self.prefix = prefix def setAction(self, action): self.action = action def __call__(self): if self.prefix: form_marker = self.prefix + '.' + DEFAULT_SUBMISSION_MARKER else: form_marker = DEFAULT_SUBMISSION_MARKER # CMFFormController form processing is based on the presence of a 'form.submitted' # key in the request. We need to translate our prefixed version. if DEFAULT_SUBMISSION_MARKER in self.request.form: fiddled_submission_marker = self.request.form[DEFAULT_SUBMISSION_MARKER] else: fiddled_submission_marker = None # the form.submitted marker gets removed by CMFFormController, but we # need to be able to test for it from our own template as well self.request.other['pfg_form_submitted'] = False if self.request.environ.get('X_PFG_RETRY', False): # We check for the absence of the X_PFG_RETRY flag in the request, # to avoid processing the form in the edge case where the form already completed # and is using a Retry exception to traverse to the thank you page, but the thank # you page also has the same embedded form on it somewhere if DEFAULT_SUBMISSION_MARKER in self.request.form: del self.request.form[DEFAULT_SUBMISSION_MARKER] elif form_marker in self.request.form: self.request.form[DEFAULT_SUBMISSION_MARKER] = True self.request.other['pfg_form_submitted'] = True elif self.prefix and DEFAULT_SUBMISSION_MARKER in self.request.form: # not our form; temporarily remove the form.submitted key to avoid a false positive del self.request.form[DEFAULT_SUBMISSION_MARKER] # And we need to pass the form marker in the request so it can be inserted # into the form (we can't just use it as an argument to the controller template, # b/c then it won't survive validation) self.request.form['pfg_form_marker'] = form_marker # temporarily clear out the controller_state from the request in case we're embedded in # another controller page template fiddled_controller_state = self.request.get('controller_state', None) self.request.set('controller_state', None) # pass the form action override # (we do this in the request instead of passing it in when calling the .cpt, because # the .cpt might end up getting called again after validation or something) if self.action is not None: self.request.set('pfg_form_action', self.action) else: self.request.set('pfg_form_action', self.request['URL']) self.status = IStatusMessage(self.request) self.request.set('messages', self.status.show()) # Delegate to CMFFormController page template so we can share logic with the standalone form try: context = aq_inner(self.context) self.request.view = self return context.fg_embedded_view_p3( enable_unload_protection=self.enable_unload_protection, enable_auto_focus=self.enable_auto_focus ) finally: # Clean up if fiddled_submission_marker is not None: self.request.form['form.submitted'] = fiddled_submission_marker elif fiddled_submission_marker is None and 'form.submitted' in self.request.form: del self.request.form['form.submitted'] if fiddled_controller_state is not None: self.request.set('controller_state', fiddled_controller_state) try: del self.request.other['pfg_form_action'] del self.request.other['pfg_form_submitted'] del self.request.form['pfg_form_marker'] except KeyError: pass
def remove_from_portal_messages(self, *messages_to_remove): status_message = IStatusMessage(self.request) # noqa: P001 messages = status_message.show() # clears messages for msg in messages: if msg.message not in messages_to_remove: status_message.add(msg.message, msg.type)
class EmbeddedPFGView(BrowserView): """ Browser view that can update and render a PFG form in some other context """ # Prefix to ensure that we don't try to process other forms that might # be on the same page prefix = '' # optional form action override action = None # enable form unload warning if it has been edited? enable_unload_protection = False # auto-focus the form on page load? enable_auto_focus = False def setPrefix(self, prefix): self.prefix = prefix def setAction(self, action): self.action = action def __call__(self): if self.prefix: form_marker = self.prefix + '.' + DEFAULT_SUBMISSION_MARKER else: form_marker = DEFAULT_SUBMISSION_MARKER # CMFFormController form processing is based on the presence of a 'form.submitted' # key in the request. We need to translate our prefixed version. if DEFAULT_SUBMISSION_MARKER in self.request.form: fiddled_submission_marker = self.request.form[ DEFAULT_SUBMISSION_MARKER] else: fiddled_submission_marker = None # the form.submitted marker gets removed by CMFFormController, but we # need to be able to test for it from our own template as well self.request.other['pfg_form_submitted'] = False if self.request.environ.get('X_PFG_RETRY', False): # We check for the absence of the X_PFG_RETRY flag in the request, # to avoid processing the form in the edge case where the form already completed # and is using a Retry exception to traverse to the thank you page, but the thank # you page also has the same embedded form on it somewhere if DEFAULT_SUBMISSION_MARKER in self.request.form: del self.request.form[DEFAULT_SUBMISSION_MARKER] elif form_marker in self.request.form: self.request.form[DEFAULT_SUBMISSION_MARKER] = True self.request.other['pfg_form_submitted'] = True elif self.prefix and DEFAULT_SUBMISSION_MARKER in self.request.form: # not our form; temporarily remove the form.submitted key to avoid a false positive del self.request.form[DEFAULT_SUBMISSION_MARKER] # And we need to pass the form marker in the request so it can be inserted # into the form (we can't just use it as an argument to the controller template, # b/c then it won't survive validation) self.request.form['pfg_form_marker'] = form_marker # temporarily clear out the controller_state from the request in case we're embedded in # another controller page template fiddled_controller_state = self.request.get('controller_state', None) self.request.set('controller_state', None) # pass the form action override # (we do this in the request instead of passing it in when calling the .cpt, because # the .cpt might end up getting called again after validation or something) if self.action is not None: self.request.set('pfg_form_action', self.action) else: actionOverride = getattr(self.context, 'formActionOverride', None) if actionOverride: self.request.set('pfg_form_action', actionOverride) else: self.request.set('pfg_form_action', self.request['URL']) self.status = IStatusMessage(self.request) self.request.set('messages', self.status.show()) # Delegate to CMFFormController page template so we can share logic with the standalone form try: context = aq_inner(self.context) self.request.view = self return context.fg_embedded_view_p3( enable_unload_protection=self.enable_unload_protection, enable_auto_focus=self.enable_auto_focus) finally: # Clean up if fiddled_submission_marker is not None: self.request.form['form.submitted'] = fiddled_submission_marker elif fiddled_submission_marker is None and 'form.submitted' in self.request.form: del self.request.form['form.submitted'] if fiddled_controller_state is not None: self.request.set('controller_state', fiddled_controller_state) try: del self.request.other['pfg_form_action'] del self.request.other['pfg_form_submitted'] del self.request.form['pfg_form_marker'] except KeyError: pass
def test_pm_ChangeItemOrderMoveAtGivenNumber(self): '''Test the ChangeItemOrderView : - we can change an item to a given p_moveNumber.''' # create a meetingWithItems and play self.changeUser('pmManager') meeting, item1, item2, item3, item4, item5, item6, item7 = self._setupOrderedItems( ) self.assertEquals(item1.getItemNumber(), 100) self.assertEquals(item2.getItemNumber(), 200) self.assertEquals(item3.getItemNumber(), 300) self.assertEquals(item4.getItemNumber(), 400) self.assertEquals(item5.getItemNumber(), 500) view = item2.restrictedTraverse('@@change-item-order') # move the item2 to position 3 view('number', '3') self.assertEquals(item2.getItemNumber(), 300) # and other items position are adapted self.assertEquals(item1.getItemNumber(), 100) self.assertEquals(item3.getItemNumber(), 200) self.assertEquals(item4.getItemNumber(), 400) self.assertEquals(item5.getItemNumber(), 500) # put the item2 back to position 2 view('up') self.assertEquals(item2.getItemNumber(), 200) # and other items position are adapted self.assertEquals(item1.getItemNumber(), 100) self.assertEquals(item3.getItemNumber(), 300) self.assertEquals(item4.getItemNumber(), 400) self.assertEquals(item5.getItemNumber(), 500) # no valid number does not cause crash view('number', '0') # nothing changed self.assertEquals(item2.getItemNumber(), 200) view('number', '-4') # nothing changed self.assertEquals(item2.getItemNumber(), 200) view('number', '99') # nothing changed self.assertEquals(item2.getItemNumber(), 200) view('number', None) # nothing changed self.assertEquals(item2.getItemNumber(), 200) # move 2 positions to far self.assertEqual(len(meeting.get_items()), 7) view('number', '9') # nothing changed self.assertEquals(item2.getItemNumber(), 200) # move one of the last items upper view = item4.restrictedTraverse('@@change-item-order') view('number', '1') self.assertEquals(item4.getItemNumber(), 100) # and other items position are adapted self.assertEquals(item1.getItemNumber(), 200) self.assertEquals(item2.getItemNumber(), 300) self.assertEquals(item3.getItemNumber(), 400) self.assertEquals(item5.getItemNumber(), 500) # change the item to the same place, a message is displayed messages = IStatusMessage(self.request) view('number', _storedItemNumber_to_itemNumber(item4.getItemNumber())) self.assertEquals(messages.show()[-1].message, translate('item_did_not_move', 'PloneMeeting'))
def status(self): messages = IStatusMessage(self.request) return messages.show()
class UcBaseView: def uc_update(self): self.users = SessionUsers(self.context) self.current_user = self.users.current() self.admin = AdminUtil(self.context) self.util = getUtility(IUserManagerUtil) self._status = IStatusMessage(self.request) def has_permission(self): if not self.current_user: return True return self.admin.has_permission(self.current_user) if self.current_user and \ not self.admin.has_permission(self.current_user): self.set_status( u'Usted no tiene permisos para actuar sobre este usuario.', u'error') else: self.clear_status() def clear_status(self): return self._status.show() def add_status(self, msg, kind): self._status.add(msg, kind) def set_status(self, msg, kind=u''): self.clear_status() self.add_status(msg, kind) def entry_from_user(self, dct): entry = dict(**dct) for k, v in entry.items(): if 'date' in k: entry[k] = self._string_from_date(v) continue entry[k] = entry[k].encode('ascii') if entry[k] else '' # Consolidamos givenName2 y surname2 en givenname y surname self._attributes_to_list(entry, 'givenName') self._attributes_to_list(entry, 'sn') if 'uid' in entry: entry['uid'] = entry['uid'].lower() return entry def _attributes_to_list(self, dct, k): '''Convierte {k='a', k2='b'} en {k=['a', 'b']}''' k2 = k + '2' if not k2 in dct: return if not dct[k2]: del (dct[k2]) return dct[k] = [dct[k], dct[k2]] del (dct[k2]) def _date_or_empty_from_entry(self, entry, key): date_string = entry.first(key, '') if not date_string: return '' return self._date_from_string(date_string) def user_from_entry(self, entry): entry['dateCreation'] = self._date_or_empty_from_entry( entry, 'dateCreation') entry['dateExpiration'] = self._date_or_empty_from_entry( entry, 'dateExpiration') self._list_to_attributes(entry, 'givenName') self._list_to_attributes(entry, 'sn') return entry def _list_to_attributes(self, dct, k): '''Convierte {k=['a', 'b']} en {k='a', k2='b'}''' k2 = k + '2' if type(dct[k]) <> list: return elif len(dct[k]) == 1: dct[k2] = '' dct[k] = dct[k][0] else: dct[k2] = dct[k][1] dct[k] = dct[k][0] def _date_from_string(self, strdate): try: return datetime.strptime(strdate, '%Y%m%d') except ValueError, e: raise ValueError('Error in dateformat "{0}"'.format(strdate))
def test_checkAlreadySentToPloneMeeting(self): """Test in case we sent the element again to PloneMeeting, that should not happen... It check also that relevant annotation wipe out works correctly.""" ws4pmSettings = getMultiAdapter((self.portal, self.request), name='ws4pmclient-settings') setCorrectSettingsConfig(self.portal) settings = ws4pmSettings.settings() self.changeUser('pmCreator1') # create an element to send... document = createDocument(self.portal.Members.pmCreator1) self._configureRequestForView(document) view = document.restrictedTraverse(SEND_TO_PM_VIEW_NAME).form_instance view.proposingGroupId = 'developers' # create the 'pmCreator1' member area to be able to create an item self.tool.getPloneMeetingFolder('plonemeeting-assembly', 'pmCreator1') self.tool.getPloneMeetingFolder('plonegov-assembly', 'pmCreator1') # we have to commit() here or portal used behing the SOAP call # does not have the freshly created member area... transaction.commit() # before sending, the element is not linked annotations = IAnnotations(document) self.assertFalse(WS4PMCLIENT_ANNOTATION_KEY in annotations) self.assertFalse( view.ws4pmSettings.checkAlreadySentToPloneMeeting( document, self.request.get('meetingConfigId'))) # send the document self.assertTrue(view._doSendToPloneMeeting()) # is linked to one item self.assertTrue(annotations[WS4PMCLIENT_ANNOTATION_KEY] == [ self.request.get('meetingConfigId'), ]) self.assertTrue( view.ws4pmSettings.checkAlreadySentToPloneMeeting( document, (self.request.get('meetingConfigId'), ))) self.assertTrue( len( ws4pmSettings._soap_searchItems( {'externalIdentifier': document.UID()})) == 1) messages = IStatusMessage(self.request) # there is one message saying that the item was correctly sent shownMessages = messages.show() self.assertEquals(shownMessages[-1].message, CORRECTLY_SENT_TO_PM_INFO) # call form again, it will display relevant status messages # the rendered form is u'' self.assertTrue(settings.only_one_sending) self.assertTrue(view() == u'') # the item is not created again # is still linked to one item self.assertTrue(annotations[WS4PMCLIENT_ANNOTATION_KEY] == [ self.request.get('meetingConfigId'), ]) self.assertTrue( len( ws4pmSettings._soap_searchItems( {'externalIdentifier': document.UID()})) == 1) # a warning is displayed to the user self.request.response.status = 200 # if status in 300, messages are not deleted with show self.assertEquals(messages.show()[-1].message, ALREADY_SENT_TO_PM_ERROR) settings.only_one_sending = False self.assertFalse(settings.only_one_sending) view._finishedSent = False self.request.response.status = 200 # if status in 300, render is not called by z3cform self.assertIn('Send to PloneMeeting Assembly', view()) self.assertEqual(len(messages.show()), 0) # if we remove the item in PloneMeeting, the view is aware of it itemUID = str( ws4pmSettings._soap_searchItems( {'externalIdentifier': document.UID()})[0]['UID']) # avoid weird ConflictError while committing because of # self.portal._volatile_cache_keys PersistentMapping self.portal._volatile_cache_keys._p_changed = False transaction.commit() item = self.portal.uid_catalog(UID=itemUID)[0].getObject() # remove the item item.aq_inner.aq_parent.manage_delObjects(ids=[ item.getId(), ]) transaction.commit() # checkAlreadySentToPloneMeeting will wipe out inconsistent annotations # for now, annotations are inconsistent self.assertTrue(annotations[WS4PMCLIENT_ANNOTATION_KEY] == [ self.request.get('meetingConfigId'), ]) self.assertFalse( view.ws4pmSettings.checkAlreadySentToPloneMeeting( document, (self.request.get('meetingConfigId'), ))) # now it is consistent self.assertFalse(WS4PMCLIENT_ANNOTATION_KEY in annotations) self.assertTrue( len( ws4pmSettings._soap_searchItems( {'externalIdentifier': document.UID()})) == 0) # the item can be sent again and will be linked to a new created item self.assertTrue(view._doSendToPloneMeeting()) self.assertTrue( view.ws4pmSettings.checkAlreadySentToPloneMeeting( document, (self.request.get('meetingConfigId'), ))) self.assertTrue( len( ws4pmSettings._soap_searchItems( {'externalIdentifier': document.UID()})) == 1) # the item can also been send to another meetingConfig self.request.set('meetingConfigId', 'plonegov-assembly') view = document.restrictedTraverse(SEND_TO_PM_VIEW_NAME).form_instance view.proposingGroupId = 'developers' self.assertFalse( view.ws4pmSettings.checkAlreadySentToPloneMeeting( document, (self.request.get('meetingConfigId'), ))) self.request.form['form.widgets.category'] = [ u'deployment', ] self.assertTrue(view._doSendToPloneMeeting()) self.assertTrue( view.ws4pmSettings.checkAlreadySentToPloneMeeting( document, (self.request.get('meetingConfigId'), ))) self.assertTrue(annotations[WS4PMCLIENT_ANNOTATION_KEY] == [ 'plonemeeting-assembly', self.request.get('meetingConfigId'), ]) # if we remove the 2 items, a call to checkAlreadySentToPloneMeeting # without meetingConfigs will wipeout the annotations transaction.commit() itemUIDs = [ str(elt['UID']) for elt in ws4pmSettings._soap_searchItems( {'externalIdentifier': document.UID()}) ] item1 = self.portal.uid_catalog(UID=itemUIDs[0])[0].getObject() item2 = self.portal.uid_catalog(UID=itemUIDs[1])[0].getObject() item1.aq_inner.aq_parent.manage_delObjects(ids=[ item1.getId(), ]) item2.aq_inner.aq_parent.manage_delObjects(ids=[ item2.getId(), ]) transaction.commit() # annotations are still messed up self.assertTrue(annotations[WS4PMCLIENT_ANNOTATION_KEY] == [ 'plonemeeting-assembly', self.request.get('meetingConfigId'), ]) # wipe out annotations view.ws4pmSettings.checkAlreadySentToPloneMeeting(document) self.assertFalse(WS4PMCLIENT_ANNOTATION_KEY in annotations)
def testAdapter(self): """ Test status messages First some boilerplate. """ request = self.request = TestRequest() directlyProvides(request, NuPloneSkin) # Now lets make sure we can actually adapt the request. status = IStatusMessage(self.request) self.assertEquals(IStatusMessage.providedBy(status), True) assert (hasattr(status, 'addHTMLStatusMessage')) # We also need the request to be annotatable: directlyProvides(self.request, IAttributeAnnotatable) # Make sure there's no stored message. self.assertEquals(len(status.show()), 0) # Add one message status.add('test', type='info') # Now check the results messages = status.show() self.assertEquals(len(messages), 1) self.assertEquals(messages[0].message, 'test') self.assertEquals(messages[0].type, 'info') # Make sure messages are removed self.assertEquals(len(status.show()), 0) # Since we accessed the message prior to publishing the page, we must # ensure that the messages have been removed from the cookies self.assertEquals(len(status.show()), 0) # Now we repeat the test, only this time we publish the page prior to # retrieving the messages # Add one message status.add('test', type='info') # Now check the results messages = status.show() self.assertEqual(len(messages), 1) self.assertEquals(messages[0].message, 'test') self.assertEquals(messages[0].type, 'info') # Make sure messages are removed self.assertEquals(len(status.show()), 0) # Add two messages status.add('test', type='info') status.add('test1', 'warn') # And check the results again messages = status.show() self.assertEquals(len(messages), 2) test = messages[1] self.assertEquals(test.message, 'test1') self.assertEquals(test.type, 'warn') # Make sure messages are removed again self.assertEquals(len(status.show()), 0) # Add two identical messages status.add('test', type='info') status.add('test', type='info') # And check the results again messages = status.show() self.assertEquals(len(messages), 1) test = messages[0] self.assertEquals(test.message, 'test') self.assertEquals(test.type, 'info') # Make sure messages are removed again self.assertEquals(len(status.show()), 0) # Test incredibly long messages: status.add('m' * 0x400, type='t' * 0x20) # And check the results again messages = status.show() self.assertEquals(len(messages), 1) test = messages[0] assert (test.message == 'm' * 0x3FF) assert (test.type == 't' * 0x1F) # Add one HTML messages status.addHTML('test', type='success') # And check the results again messages = status.show() self.assertEquals(len(messages), 1) test = messages[0] self.assertEquals(test.type, 'success') self.assertEquals(test.message, 'test') self.assertEquals(type(test.message), literal) # Add two HTML messages status.addHTML('test', type='info') status.addHTML('test1', 'warn') # And check the results again messages = status.show() self.assertEquals(len(messages), 2) test = messages[1] self.assertEquals(test.message, 'test1') self.assertEquals(type(test.message), literal) self.assertEquals(test.type, 'warn') # add two identical messages status.addHTML('test', type='info') status.addHTML('test', type='info') # And check the results again messages = status.show() self.assertEquals(len(messages), 1) test = messages[0] self.assertEquals(test.message, 'test') self.assertEquals(type(test.message), literal) self.assertEquals(test.type, 'info') # Make sure messages are removed again self.assertEquals(len(status.show()), 0) # Test incredibly long messages: status.addHTML('m' * 0x400, type='t' * 0x20) # And check the results again messages = status.show() self.assertEquals(len(messages), 1) test = messages[0] self.assertEquals(type(test.message), literal) assert (test.message == '%s' % ('m' * 0x3FF)) assert (test.type == 't' * 0x1F) # Add two mixed messages status.add('test', type='info') status.addHTML('test1', 'warn') # And check the results again messages = status.show() self.assertEquals(len(messages), 2) test = messages[0] self.assertEquals(test.message, 'test') self.assertNotEquals(type(test.message), literal) self.assertEquals(test.type, 'info') test = messages[1] self.assertEquals(test.message, 'test1') self.assertEquals(type(test.message), literal) self.assertEquals(test.type, 'warn') # Add a more complicated html message status.addHTML('You can go <a href="http://plone.org">here</a>.', type='success') messages = status.show() self.assertEquals(len(messages), 1) test = messages[0] self.assertEquals(test.type, 'success') self.assertEquals( test.message, 'You can go <a href="http://plone.org" rel="nofollow" target="_blank">here</a>.' ) self.assertEquals(type(test.message), literal) # Add html message with disallowed tags status.addHTML( '<p>You can go <a href="http://plone.org">here</a>.</p>', type='success') messages = status.show() self.assertEquals(len(messages), 1) test = messages[0] self.assertEquals(test.type, 'success') self.assertEquals( test.message, 'You can go <a href="http://plone.org" rel="nofollow" target="_blank">here</a>.' ) self.assertEquals(type(test.message), literal) status.addHTML("<script type=\"javascript\">alert('hello')</script>", type='success') messages = status.show() self.assertEquals(len(messages), 1) test = messages[0] self.assertEquals(test.type, 'success') self.assertEquals(test.message, '') self.assertEquals(type(test.message), literal) status.addHTML( '<a href="data:text/html;base64,PHNjcmlwdD5hbGVydCgidGVzdCIpOzwvc2NyaXB0Pg==">click me</a>', type='success') messages = status.show() self.assertEquals(len(messages), 1) test = messages[0] self.assertEquals(test.type, 'success') self.assertEquals(test.message, '<a href="">click me</a>') self.assertEquals(type(test.message), literal)
def test_generateItemTemplateView(self): """ Test the BrowserView that generates a given template of an item """ self.changeUser('admin') messages = IStatusMessage(self.request) document = createDocument(self.portal) DOCUMENT_ABSOLUTE_URL = document.absolute_url() # we must obviously be connected to PM... view = document.restrictedTraverse( '@@generate_document_from_plonemeeting') # nothing is generated, just redirected to the context self.assertFalse(view() != DOCUMENT_ABSOLUTE_URL) self.assertTrue(len(messages.show()) == 1) self.assertTrue(messages.show()[0].message == UNABLE_TO_CONNECT_ERROR) # _soap_connectToPloneMeeting is memoized... cleanMemoize(self.request) item = self._sendToPloneMeeting(document) # a statusmessage for having created the item successfully self.assertEqual(messages.show()[-1].message, CORRECTLY_SENT_TO_PM_INFO) view = document.restrictedTraverse( '@@generate_document_from_plonemeeting') # with no templateFormat defined, the mimetype can not be determined # an error statusmessage is displayed # last added statusmessage # nothing is generated, just redirected to the context self.assertFalse(view() != DOCUMENT_ABSOLUTE_URL) self.assertEqual(messages.show()[-1].message, UNABLE_TO_DETECT_MIMETYPE_ERROR) self.request.set('templateFormat', 'odt') # if no templateFilename, an error is displayed, nothing is generated view = document.restrictedTraverse( '@@generate_document_from_plonemeeting') # nothing is generated, just redirected to the context self.assertFalse(view() != DOCUMENT_ABSOLUTE_URL) self.assertEqual(messages.show()[-1].message, FILENAME_MANDATORY_ERROR) # if not valid itemUID defined, the item can not be found and so accessed self.request.set('templateFilename', 'filename') view = document.restrictedTraverse( '@@generate_document_from_plonemeeting') # nothing is generated, just redirected to the context self.assertFalse(view() != DOCUMENT_ABSOLUTE_URL) self.assertEqual( messages.show()[-1].message, u"An error occured while generating the document in " "PloneMeeting! The error message was : Server raised fault: 'You can not access this item!'" ) # now with a valid itemUID but no valid templateId self.request.set('itemUID', item.UID()) view = document.restrictedTraverse( '@@generate_document_from_plonemeeting') # nothing is generated, just redirected to the context self.assertFalse(view() != DOCUMENT_ABSOLUTE_URL) self.assertEqual( messages.show()[-1].message, u"An error occured while generating the document in " "PloneMeeting! The error message was : Server raised fault: 'You can not access this template!'" ) # now with all valid infos self.request.set('templateId', POD_TEMPLATE_ID_PATTERN.format('itemTemplate', 'odt')) view = document.restrictedTraverse( '@@generate_document_from_plonemeeting') res = view() # with have a real result, aka not redirected to the context, a file self.assertTrue(view() != DOCUMENT_ABSOLUTE_URL) self.assertTrue(len(res) > 10000) self.assertEquals( self.request.response.headers, { 'content-type': 'application/vnd.oasis.opendocument.text', 'location': '{0}/document'.format(self.portal.absolute_url()), 'content-disposition': 'inline;filename="filename.odt"' })
def messages(self): status = IStatusMessage(self.request) messages = status.show() for m in messages: m.id = idnormalizer.normalize(m.message) return messages
def testAdapter(self): """ Test status messages First some boilerplate. """ request = self.request = TestRequest() directlyProvides(request, NuPloneSkin) # Now lets make sure we can actually adapt the request. status = IStatusMessage(self.request) self.assertEquals(IStatusMessage.providedBy(status), True) assert hasattr(status, "addHTMLStatusMessage") # We also need the request to be annotatable: directlyProvides(self.request, IAttributeAnnotatable) # Make sure there's no stored message. self.assertEquals(len(status.show()), 0) # Add one message status.add(u"test", type=u"info") # Now check the results messages = status.show() self.assertEquals(len(messages), 1) self.assertEquals(messages[0].message, u"test") self.assertEquals(messages[0].type, u"info") # Make sure messages are removed self.assertEquals(len(status.show()), 0) # Since we accessed the message prior to publishing the page, we must # ensure that the messages have been removed from the cookies self.assertEquals(len(status.show()), 0) # Now we repeat the test, only this time we publish the page prior to # retrieving the messages # Add one message status.add(u"test", type=u"info") # Now check the results messages = status.show() self.assertEqual(len(messages), 1) self.assertEquals(messages[0].message, u"test") self.assertEquals(messages[0].type, u"info") # Make sure messages are removed self.assertEquals(len(status.show()), 0) # Add two messages status.add(u"test", type=u"info") status.add(u"test1", u"warn") # And check the results again messages = status.show() self.assertEquals(len(messages), 2) test = messages[1] self.assertEquals(test.message, u"test1") self.assertEquals(test.type, u"warn") # Make sure messages are removed again self.assertEquals(len(status.show()), 0) # Add two identical messages status.add(u"test", type=u"info") status.add(u"test", type=u"info") # And check the results again messages = status.show() self.assertEquals(len(messages), 1) test = messages[0] self.assertEquals(test.message, u"test") self.assertEquals(test.type, u"info") # Make sure messages are removed again self.assertEquals(len(status.show()), 0) # Test incredibly long messages: status.add(u"m" * 0x400, type=u"t" * 0x20) # And check the results again messages = status.show() self.assertEquals(len(messages), 1) test = messages[0] assert test.message == u"m" * 0x3FF assert test.type == u"t" * 0x1F # Add one HTML messages status.addHTML(u"test", type=u"success") # And check the results again messages = status.show() self.assertEquals(len(messages), 1) test = messages[0] self.assertEquals(test.type, u"success") self.assertEquals(test.message, u"test") self.assertEquals(type(test.message), literal) # Add two HTML messages status.addHTML(u"test", type=u"info") status.addHTML(u"test1", u"warn") # And check the results again messages = status.show() self.assertEquals(len(messages), 2) test = messages[1] self.assertEquals(test.message, u"test1") self.assertEquals(type(test.message), literal) self.assertEquals(test.type, u"warn") # add two identical messages status.addHTML(u"test", type=u"info") status.addHTML(u"test", type=u"info") # And check the results again messages = status.show() self.assertEquals(len(messages), 1) test = messages[0] self.assertEquals(test.message, u"test") self.assertEquals(type(test.message), literal) self.assertEquals(test.type, u"info") # Make sure messages are removed again self.assertEquals(len(status.show()), 0) # Test incredibly long messages: status.addHTML(u"m" * 0x400, type=u"t" * 0x20) # And check the results again messages = status.show() self.assertEquals(len(messages), 1) test = messages[0] self.assertEquals(type(test.message), literal) assert test.message == "%s" % (u"m" * 0x3FF) assert test.type == u"t" * 0x1F # Add two mixed messages status.add(u"test", type=u"info") status.addHTML(u"test1", u"warn") # And check the results again messages = status.show() self.assertEquals(len(messages), 2) test = messages[0] self.assertEquals(test.message, u"test") self.assertNotEquals(type(test.message), literal) self.assertEquals(test.type, u"info") test = messages[1] self.assertEquals(test.message, u"test1") self.assertEquals(type(test.message), literal) self.assertEquals(test.type, u"warn") # Add a more complicated html message status.addHTML(u'You can go <a href="http://plone.org">here</a>.', type=u"success") messages = status.show() self.assertEquals(len(messages), 1) test = messages[0] self.assertEquals(test.type, u"success") self.assertEquals( test.message, u'You can go <a href="http://plone.org" rel="nofollow" target="_blank">here</a>.' ) self.assertEquals(type(test.message), literal) # Add html message with disallowed tags status.addHTML(u'<p>You can go <a href="http://plone.org">here</a>.</p>', type=u"success") messages = status.show() self.assertEquals(len(messages), 1) test = messages[0] self.assertEquals(test.type, u"success") self.assertEquals( test.message, u'You can go <a href="http://plone.org" rel="nofollow" target="_blank">here</a>.' ) self.assertEquals(type(test.message), literal) status.addHTML(u"<script type=\"javascript\">alert('hello')</script>", type=u"success") messages = status.show() self.assertEquals(len(messages), 1) test = messages[0] self.assertEquals(test.type, u"success") self.assertEquals(test.message, "") self.assertEquals(type(test.message), literal) status.addHTML( u'<a href="data:text/html;base64,PHNjcmlwdD5hbGVydCgidGVzdCIpOzwvc2NyaXB0Pg==">click me</a>', type=u"success", ) messages = status.show() self.assertEquals(len(messages), 1) test = messages[0] self.assertEquals(test.type, u"success") self.assertEquals(test.message, '<a href="">click me</a>') self.assertEquals(type(test.message), literal)
def status(self): messages = IStatusMessage(self.request) return messages.show()
class UcBaseView: def uc_update(self): self.users = SessionUsers(self.context) self.current_user = self.users.current() self.admin = AdminUtil(self.context) self.util = getUtility(IUserManagerUtil) self._status = IStatusMessage(self.request) def has_permission(self): if not self.current_user: return True return self.admin.has_permission(self.current_user) if self.current_user and \ not self.admin.has_permission(self.current_user): self.set_status(u'Usted no tiene permisos para actuar sobre este usuario.', u'error') else: self.clear_status() def clear_status(self): return self._status.show() def add_status(self, msg, kind): self._status.add(msg, kind) def set_status(self, msg, kind=u''): self.clear_status() self.add_status(msg, kind) def entry_from_user(self, dct): entry = dict(**dct) for k, v in entry.items(): if 'date' in k : entry[k] = self._string_from_date(v) continue entry[k] = entry[k].encode('ascii') if entry[k] else '' # Consolidamos givenName2 y surname2 en givenname y surname self._attributes_to_list(entry, 'givenName') self._attributes_to_list(entry, 'sn') if 'uid' in entry: entry['uid'] = entry['uid'].lower() return entry def _attributes_to_list(self, dct, k): '''Convierte {k='a', k2='b'} en {k=['a', 'b']}''' k2 = k + '2' if not k2 in dct: return if not dct[k2]: del(dct[k2]) return dct[k] = [dct[k], dct[k2]] del(dct[k2]) def _date_or_empty_from_entry(self, entry, key): date_string = entry.first(key, '') if not date_string: return '' return self._date_from_string(date_string) def user_from_entry(self, entry): entry['dateCreation'] = self._date_or_empty_from_entry(entry, 'dateCreation') entry['dateExpiration'] = self._date_or_empty_from_entry(entry, 'dateExpiration') self._list_to_attributes(entry, 'givenName') self._list_to_attributes(entry, 'sn') return entry def _list_to_attributes(self, dct, k): '''Convierte {k=['a', 'b']} en {k='a', k2='b'}''' k2 = k + '2' if type(dct[k]) <> list: return elif len(dct[k]) == 1: dct[k2] = '' dct[k] = dct[k][0] else: dct[k2] = dct[k][1] dct[k] = dct[k][0] def _date_from_string(self, strdate): try: return datetime.strptime(strdate, '%Y%m%d') except ValueError, e: raise ValueError('Error in dateformat "{0}"'.format(strdate))
def testAdapter(self): """Test status messages First some boilerplate. """ request = self.layer["request"].clone() # Now lets make sure we can actually adapt the request. status = IStatusMessage(request) self.assertTrue(IStatusMessage.providedBy(status)) # Make sure there's no stored message. self.assertEqual(len(status.show()), 0) # Add one message status.add("test", type="info") # Now check the results messages = status.show() self.assertEqual(len(messages), 1) self.assertEqual(messages[0].message, "test") self.assertEqual(messages[0].type, "info") # Make sure messages are removed self.assertEqual(len(status.show()), 0) # Since we accessed the message prior to publishing the page, we must # ensure that the messages have been removed from the cookies self.assertEqual(len(status.show()), 0) # Now we repeat the test, only this time we publish the page prior to # retrieving the messages # Add one message status.add("test", type="info") # Now check the results messages = status.show() self.assertEqual(len(messages), 1) self.assertEqual(messages[0].message, "test") self.assertEqual(messages[0].type, "info") # Make sure messages are removed self.assertEqual(len(status.show()), 0) # Add two messages status.add("test", type="info") status.add("test1", "warn") # And check the results again messages = status.show() self.assertEqual(len(messages), 2) test = messages[1] self.assertEqual(test.message, "test1") self.assertEqual(test.type, "warn") # Make sure messages are removed again self.assertEqual(len(status.show()), 0) # Add two identical messages status.add("test", type="info") status.add("test", type="info") # And check the results again messages = status.show() self.assertEqual(len(messages), 1) test = messages[0] self.assertEqual(test.message, "test") self.assertEqual(test.type, "info") # Make sure messages are removed again self.assertEqual(len(status.show()), 0) # Test incredibly long messages: status.add("m" * 0x400, type="t" * 0x20) # And check the results again messages = status.show() self.assertEqual(len(messages), 1) test = messages[0] assert test.message == "m" * 0x3FF assert test.type == "t" * 0x1F # Add one HTML messages status.add("test", type="success") # And check the results again messages = status.show() self.assertEqual(len(messages), 1) test = messages[0] self.assertEqual(test.type, "success") self.assertEqual(test.message, "test") self.assertIsInstance(test.message, six.text_type) # Add two HTML messages status.add("test", type="info") status.add("test1", "warn") # And check the results again messages = status.show() self.assertEqual(len(messages), 2) test = messages[1] self.assertEqual(test.message, "test1") self.assertIsInstance(test.message, six.text_type) self.assertEqual(test.type, "warn") # add two identical messages status.add("test", type="info") status.add("test", type="info") # And check the results again messages = status.show() self.assertEqual(len(messages), 1) test = messages[0] self.assertEqual(test.message, "test") self.assertIsInstance(test.message, six.text_type) self.assertEqual(test.type, "info") # Make sure messages are removed again self.assertEqual(len(status.show()), 0) # Test incredibly long messages: status.add("m" * 0x400, type="t" * 0x20) # And check the results again messages = status.show() self.assertEqual(len(messages), 1) test = messages[0] self.assertIsInstance(test.message, six.text_type) assert test.message == "%s" % ("m" * 0x3FF) assert test.type == "t" * 0x1F # Add two mixed messages status.add("test", type="info") status.add("test1", "warn") # And check the results again messages = status.show() self.assertEqual(len(messages), 2) test = messages[0] self.assertEqual(test.message, "test") self.assertIsInstance(test.message, six.text_type) self.assertEqual(test.type, "info") test = messages[1] self.assertEqual(test.message, "test1") self.assertIsInstance(test.message, six.text_type) self.assertEqual(test.type, "warn") # Add a more complicated html message status.add('You can go <a href="http://plone.org">here</a>.', type="success") messages = status.show() self.assertEqual(len(messages), 1) test = messages[0] self.assertEqual(test.type, "success") self.assertEqual( test.message, 'You can go <a href="http://plone.org">here</a>.', # noqa: E501 ) self.assertIsInstance(test.message, six.text_type)
def messages(self): status = IStatusMessage(self.request) messages = status.show() for m in messages: m.id = idnormalizer.normalize(m.message) return messages