def testWorkflowMenuWithNoTransitionsDisabled(self): logout() items = self.menu.getMenuItems(self.folder, self.request) workflowMenuItem = [ i for i in items if i['extra']['id'] == 'plone-contentmenu-workflow'][0] self.assertEqual(workflowMenuItem['action'], '')
def test_not_available(self): # Use a non-opened poll poll_uid = IUUID(self.p1) logout() r = self.renderer(assignment=voteportlet.Assignment(header='Polls', poll=poll_uid)) self.assertEqual(False, r.available)
def test_percentage_vote_report(self): poll = self.p3 # Vote as logged user options = 2 voted = poll.setVote(options, self.request) self.assertTrue(voted) total = poll.total_votes self.assertEqual(total, 1) results = poll.getResults() # One vote self.assertEqual(results[options][1], 1) # 100% self.assertEqual(results[options][2], 1.0) logout() options = 1 voted = poll.setVote(options, self.request) self.assertTrue(voted) total = poll.total_votes self.assertEqual(total, 2) results = poll.getResults() # One vote self.assertEqual(results[options][1], 1) # 50% self.assertEqual(results[options][2], 0.5)
def setUpContent(self): login(self.portal, testing.SITE_ADMIN) self.project = helpers.create_project( self.workspaces, 'project', title=u"Project") self.project_admin = helpers.add_activated_student( self.people, u"Hörbert M@ier") self.project.addManager(self.project_admin.id) self.project_admin2 = helpers.add_activated_student( self.people, u"Administanator") self.project.addManager(self.project_admin2.id) self.ws = ws_helpers.create_workspace(self.workspaces, "project_workspace_1", title=u"Project-Workspace") self.ws_member = helpers.add_activated_student( self.people, u"Workspace Member") self.ws.addMember(self.ws_member.id) self.project.add_workspace(self.ws) self.ws2 = ws_helpers.create_workspace(self.workspaces, "project_workspace_2", title=u"Project-Workspace") self.ws_member2 = helpers.add_activated_student( self.people, u"Another Workspace Member") self.ws2.addMember(self.ws_member2.id) self.project.add_workspace(self.ws2) logout()
def test_available_anonymous(self): # Use a opened poll poll_uid = IUUID(self.p3) r = self.renderer(assignment=voteportlet.Assignment(header='Polls', poll=poll_uid)) logout() self.assertEqual(True, r.available)
def testSourcePermissionDenied(self): from z3c.form.browser.text import TextWidget from zope.interface import implementer from zope.interface import Interface from zope.schema import Choice from zope.schema.interfaces import ISource @implementer(ISource) class DummyCatalogSource(object): def search_catalog(self, query): querytext = query['SearchableText']['query'] return [Mock(id=querytext)] widget = TextWidget(self.request) widget.context = self.portal widget.field = Choice(source=DummyCatalogSource()) widget.field.interface = Interface from plone.app.content.browser.vocabulary import SourceView view = SourceView(widget, self.request) query = { 'criteria': [ { 'i': 'SearchableText', 'o': 'plone.app.querystring.operation.string.is', 'v': 'foo' } ] } self.request.form.update({ 'query': json.dumps(query), }) logout() data = json.loads(view()) self.assertEquals(data['error'], 'Vocabulary lookup not allowed.')
def test_anonymous_can_not_add_comments_if_discussion_is_not_allowed(self): """Make sure that anonymous users can't post comments if anonymous comments are disabled. """ # Anonymous comments are disabled by default logout() def make_request(form={}): request = TestRequest() request.form.update(form) alsoProvides(request, IFormLayer) alsoProvides(request, IAttributeAnnotatable) return request provideAdapter(adapts=(Interface, IBrowserRequest), provides=Interface, factory=CommentForm, name=u"comment-form") request = make_request(form={'form.widgets.text': u'bar'}) commentForm = getMultiAdapter((self.context, request), name=u"comment-form") commentForm.update() data, errors = commentForm.extractData() # pylint: disable-msg=W0612 self.assertEqual(len(errors), 0) self.assertRaises( Unauthorized, commentForm.handleComment, commentForm, "foo" )
def tearDown(self): for s in self.services: s.setAllowManualUncertainty(False) s.setUncertainties([]) s.setPrecisionFromUncertainty(False) logout() super(TestManualUncertainty, self).tearDown()
def createMembers(portal, userdefs, log_in=True): """Create example members in testing environment example_userdefs = [ {'user': '******', 'roles': ('Member', 'Manager'), 'groups': ()}, {'user': '******', 'roles': ('Member', ), 'groups': ()}, {'user': '******', 'roles': (), 'groups': ('contributeurs',)}, {'user': '******', 'roles': (), 'groups': ('animateurs',)}, ] """ if log_in: setRoles(portal, TEST_USER_ID, ["Manager"]) login(portal, TEST_USER_NAME) pas = portal.acl_users gtool = portal.portal_groups for userinfo in userdefs: username = userinfo["user"] addMember(pas, username, roles=userinfo["roles"]) member = portal.portal_membership.getMemberById(username) member.setMemberProperties({"email": "*****@*****.**" % username, "fullname": username.title()}) for groupname in userinfo["groups"]: group = gtool.getGroupById(groupname) group.addMember(username) if log_in: setRoles(portal, TEST_USER_ID, ["Member"]) logout()
def setUp(self): portal = self.layer['portal'] self.tp_catalog = portal.tablepage_catalog login(portal, TEST_USER_NAME) portal.invokeFactory(type_name='TablePage', id='table_page', title="The Table Document") tp = portal.table_page tp.edit(pageColumns=[{'id': 'foo_field', 'label': 'Foo field', 'description': '', 'type': 'String', 'vocabulary': '', 'options': []}, ], batchSize=10) tp.edit(searchConfig=[{'id': 'foo_field', 'label': '', 'description': '', 'additionalConfiguration': ['SearchableText']}]) self.tp = tp self.storage = IDataStorage(tp) self._addRows(35) # now adding another tablepage: this must be always ignored by searches portal.invokeFactory(type_name='TablePage', id='table_page2', title="Another Table Document") portal.table_page2.edit(pageColumns=[{'id': 'foo_field', 'label': 'Foo field', 'description': '', 'type': 'String', 'vocabulary': '', 'options': []}, ], batchSize=10) storage2 = IDataStorage(portal.table_page2) storage2.add({'__label__': 'A Label', '__uuid__': 'l2l2l2'}) storage2.add({'foo_field': 'aa001', '__uuid__': '010'}) portal.portal_workflow.doActionFor(tp, 'publish') self.tp_catalog.clearFindAndRebuild() logout()
def test_file_type(self): self.link.remoteUrl = 'file:///some/file/on/your/system' view = self._get_link_redirect_view(self.link) self._publish(self.link) logout() self.assertTrue(view()) self._assert_redirect(self.link.remoteUrl)
def test_anonymous_allowed_to_view(self): ''' Anonymous can view a opened poll ''' logout() utility = queryUtility(IPolls, name='collective.polls') # Opened Poll, member can view poll = self.subfolder['p5'] self.assertTrue(utility.allowed_to_view(poll))
def test_anonymous_not_allowed_to_view(self): ''' Anonymous cannot view a private poll ''' logout() utility = queryUtility(IPolls, name='collective.polls') # Opened Poll, member can view poll = self.subfolder['p6'] self.assertFalse(utility.allowed_to_view(poll))
def test_delete_confirmation_if_locked(self): folder = self.portal['f1'] lockable = ILockable.providedBy(folder) form = getMultiAdapter( (folder, self.request), name='delete_confirmation') form.update() self.assertFalse(form.is_locked) if lockable: lockable.lock() form = getMultiAdapter( (folder, self.request), name='delete_confirmation') form.update() self.assertFalse(form.is_locked) # After switching the user it should not be possible to delete the # object. Of course this is only possible if our context provides # ILockable interface. if lockable: logout() login(self.portal, 'editor') form = getMultiAdapter( (folder, self.request), name='delete_confirmation') form.update() self.assertTrue(form.is_locked) logout() login(self.portal, TEST_USER_NAME) ILockable(folder).unlock()
def test_project_info_navigation_anonymous(self): pat.logout() open(self.driver, self.project.absolute_url()) nav_links = self.find_elements(By.CSS_SELECTOR, ".content-views>li>a") nav_link_texts = [x.text for x in nav_links] self.assertListEqual(nav_link_texts, [u'Information', u'Conversation'])
def test_results(self): # set standard workflow for News Items wt = self.portal['portal_workflow'] wt.setChainForPortalTypes(['News Item'], 'simple_publication_workflow') # create some testing content and add it to the tile with api.env.adopt_roles(['Manager']): folder = api.content.create(self.portal, 'Folder', id='test') for i in range(1, 10): obj = api.content.create(folder, 'News Item', id=str(i)) self.tile.populate_with_object(obj) # tile should list the first 5 objects results = self.tile.results() self.assertEqual(len(results), 5) for i in range(1, 6): self.assertIn(folder[str(i)], results) # for an anonymous user, no content is returned logout() results = self.tile.results() self.assertEqual(len(results), 0) # for the test user, the first 5 objects should be still there login(self.portal, TEST_USER_NAME) results = self.tile.results() self.assertEqual(len(results), 5) for i in range(1, 6): self.assertIn(folder[str(i)], results) # delete one object; it should be removed from the tile also api.content.delete(folder['1']) results = self.tile.results() self.assertEqual(len(results), 5) for i in range(2, 7): self.assertIn(folder[str(i)], results)
def setUpPloneSite(self, portal): login(portal.aq_parent, SITE_OWNER_NAME) wf = getToolByName(portal, 'portal_workflow') wf.setDefaultChain('plone_workflow') setupPortalContent(portal) # make sure we have folder_listing as a template portal.getTypeInfo().manage_changeProperties( view_methods=['folder_listing'], default_view='folder_listing') applyProfile(portal, 'bika.lims:default') # Add some test users for role in ('LabManager', 'LabClerk', 'Analyst', 'Verifier', 'Sampler', 'Preserver', 'Publisher', 'Member', 'Reviewer', 'RegulatoryInspector'): for user_nr in range(2): if user_nr == 0: username = "******" % (role.lower()) else: username = "******" % (role.lower(), user_nr) try: member = portal.portal_registration.addMember( username, username, properties={ 'username': username, 'email': username + "@example.com", 'fullname': username} ) # Add user to all specified groups group_id = role + "s" group = portal.portal_groups.getGroupById(group_id) if group: group.addMember(username) # Add user to all specified roles member._addRole(role) # If user is in LabManagers, add Owner local role on clients folder if role == 'LabManager': portal.clients.manage_setLocalRoles(username, ['Owner', ]) except ValueError: pass # user exists # Force the test browser to show the site always in 'en' ltool = portal.portal_languages ltool.manage_setLanguageSettings('en', ['en'], setUseCombinedLanguageCodes=False, startNeutral=True) logout()
def test_collection_templates(self): data = getData('image.png') # add an image that will be listed by the collection self.portal.invokeFactory("Image", "image", title="Image example", image=data) # Search for images query = [{ 'i': 'Type', 'o': 'plone.app.querystring.operation.string.is', 'v': 'Image', }] # set the query and publish the collection self.collection.setQuery(query) commit() logout() # open a browser to see if our image is in the results browser = Browser(self.layer['app']) browser.handleErrors = False browser.open(self.collection.absolute_url()) self.assertTrue("Image example" in browser.contents) # open summary_view template browser.open('%s/summary_view' % self.collection.absolute_url()) self.assertTrue("Image example" in browser.contents) # open folder_summary_view template browser.open('%s/folder_summary_view' % self.collection.absolute_url()) self.assertTrue("Image example" in browser.contents) # open thumbnail_view template browser.open('%s/thumbnail_view' % self.collection.absolute_url()) self.assertTrue("Image example" in browser.contents)
def test_pub_date(self): # configure our portal to enable publication date on pages globally on # the site registry = getUtility(IRegistry) settings = registry.forInterface( ISiteSchema, prefix='plone') settings.display_publication_date_in_byline = True logout() viewlet = self._get_viewlet() # publication date should be None as there is not Effective date set # for our document yet self.assertEqual(viewlet.pub_date(), None) # now set effective date for our document effective = DateTime() self.context.setEffectiveDate(effective) self.assertEqual(viewlet.pub_date(), DateTime(effective.ISO8601())) # now switch off publication date globally on the site and see if # viewlet returns None for publication date settings.display_publication_date_in_byline = False self.assertEqual(viewlet.pub_date(), None)
def export(portal, context, request, url): environ_orig = request.environ form_orig = request.form.copy() other_orig = request.other.copy() stdout_orig = request.response.stdout stdout = StringIO.StringIO() getattr(request, '__annotations__', {}).clear() try: request.environ['QUERY_STRING'] = urlparse.urlsplit( url).query request.response.stdout = stdout request.processInputs() testing.login(portal, testing.TEST_USER_NAME) export_view = context.restrictedTraverse('export') export_view() finally: request.response.stdout = stdout_orig request.environ.clear() request.environ.update(environ_orig) request.form.clear() request.form.update(form_orig) request.other.clear() request.other.update(other_orig) testing.logout() return stdout.getvalue()
def testAnonymous(self): logout() ctx = IPortletContext(self.folder) g = ctx.globalPortletCategories() self.assertEqual(len(g), 2) self.assertEqual(g[0], ('content_type', 'Folder')) self.assertEqual(g[1], ('user', 'Anonymous User'))
def test_view_protected(self): # view can not be accessed by anonymous users from AccessControl import Unauthorized logout() self.assertRaises(Unauthorized, self.portal.restrictedTraverse, '@@quickupload-controlpanel')
def test_draft_state(self): """ draft content can only be viewed by a team manager and owner """ admin_permissions = api.user.get_permissions( username='******', obj=self.document, ) self.assertTrue(admin_permissions[VIEW], 'Admin cannot view draft content') member_permissions = api.user.get_permissions( username='******', obj=self.document, ) self.assertFalse(member_permissions[VIEW], 'Member can view draft content') nonmember_permissions = api.user.get_permissions( username='******', obj=self.document, ) self.assertFalse(nonmember_permissions[VIEW], 'Non-member can view draft content') logout() anon_permissions = api.user.get_permissions( obj=self.document, ) self.assertFalse(anon_permissions[VIEW], 'Anonymous can view draft content')
def test_pending_state(self): """ team managers should be able to view pending items, team members should not """ api.content.transition(self.document, 'submit') admin_permissions = api.user.get_permissions( username='******', obj=self.document, ) self.assertTrue(admin_permissions[VIEW], 'Admin cannot view pending content') member_permissions = api.user.get_permissions( username='******', obj=self.document, ) self.assertFalse(member_permissions[VIEW], 'member can view pending content') nonmember_permissions = api.user.get_permissions( username='******', obj=self.document, ) self.assertFalse(nonmember_permissions[VIEW], 'nonmember can view pending content') logout() anon_permissions = api.user.get_permissions( obj=self.document, ) self.assertFalse(anon_permissions[VIEW], 'Anonymous can view pending content')
def test_published_state(self): """ all team members should be able to see published content, regular plone users should also """ api.content.transition(self.document, 'submit') api.content.transition(self.document, 'publish') admin_permissions = api.user.get_permissions( username='******', obj=self.document, ) self.assertTrue(admin_permissions[VIEW], 'Admin cannot view published content') member_permissions = api.user.get_permissions( username='******', obj=self.document, ) self.assertTrue(member_permissions[VIEW], 'member cannot view published content') nonmember_permissions = api.user.get_permissions( username='******', obj=self.document, ) self.assertTrue(nonmember_permissions[VIEW], 'user cannot view workspace content') logout() anon_permissions = api.user.get_permissions( obj=self.document, ) self.assertFalse(anon_permissions[VIEW], 'Anonymous can view draft content')
def test_user_activation(self): login(self.portal, testing.SITE_ADMIN) members = self.portal['people'] # create a user: member = utilities.add_member_object(members, member_id='member', fullname=u"Hörbert M@ier", email="*****@*****.**") logout() password = '******' utilities.add_plone_member(member, password) utilities.activate_member_object(member) plone_member = self.portal.acl_users.authenticate(member.id, password, self.portal.REQUEST) self.assertNotEqual(plone_member, None) portal_membership = getToolByName(self.portal, 'portal_membership') plone_member = portal_membership.getMemberById(member.id) self.assertNotEqual(plone_member, None) self.assertEqual(unicode(plone_member.getProperty('fullname'), 'utf-8'), member.title) self.assertEqual(plone_member.getProperty('email'), member.emailAddress) login(self.portal, member.id)
def test_add_anonymous_comment(self): self.discussionTool.overrideDiscussionFor(self.portal.doc1, True) self.viewlet = CommentsViewlet(self.context, self.request, None, None) registry = queryUtility(IRegistry) settings = registry.forInterface(IDiscussionSettings, check=False) settings.anonymous_comments = True # Logout logout() def make_request(form={}): request = TestRequest() request.form.update(form) alsoProvides(request, IFormLayer) alsoProvides(request, IAttributeAnnotatable) return request provideAdapter(adapts=(Interface, IBrowserRequest), provides=Interface, factory=CommentForm, name=u"comment-form") # Post an anonymous comment and provide a name request = make_request(form={'form.widgets.name': u'john doe', 'form.widgets.text': u'bar'}) commentForm = getMultiAdapter((self.context, request), name=u"comment-form") commentForm.update() data, errors = commentForm.extractData() # pylint: disable-msg=W0612 self.assertEqual(len(errors), 0) self.assertFalse(commentForm.handleComment(commentForm, "action"))
def test_view_comments(self): """Make sure published comments can be viewed by everyone. """ # Owner is allowed # self.login(default_user) # self.assertTrue(checkPerm(View, self.doc)) # Member is allowed login(self.portal, TEST_USER_NAME) workflow = self.portal.portal_workflow workflow.doActionFor(self.doc, 'publish') login(self.portal, 'member') self.assertTrue(checkPerm(View, self.comment)) # Reviewer is allowed login(self.portal, 'reviewer') self.assertTrue(checkPerm(View, self.comment)) # Anonymous is allowed logout() self.assertTrue(checkPerm(View, self.comment)) # Editor is allowed login(self.portal, 'editor') self.assertTrue(checkPerm(View, self.comment)) # Reader is allowed login(self.portal, 'reader') self.assertTrue(checkPerm(View, self.comment))
def test_migrate_view_protected(self): """ test if the view is protected """ from AccessControl import Unauthorized logout() self.assertRaises(Unauthorized, self.portal.restrictedTraverse, '@@migrate-types')
def setUpContent(self): login(self.portal, testing.SITE_ADMIN) self.ws = ws_helpers.create_workspace(self.workspaces, "test-workspace", title=u"Test Workspace") self.links = [] self.links_by_group = {} for i in range(1, 4): group_label = u"Group {0}".format(i) group_handle = add_group(self.ws, group_label) link_id = "link-{0}".format(i) link_title = u"Link {0}".format(i) self.ws.invokeFactory('RichLink', link_id, title=link_title, url="www.ixds.com", rmGroup=group_handle) self.links.append(self.ws[link_id]) self.links_by_group[group_handle] = self.ws[link_id] link_id = "link-without-group" self.ws.invokeFactory('RichLink', link_id, title="Link without Group", url="www.ixds.com") self.misc_link = self.ws[link_id] self.links.append(self.misc_link) self.links_by_group['Miscellaneous'] = self.misc_link add_group(self.ws, u"Empty Group") logout()
def test_getUserId_anonymous(self): logout() self.assertEqual(None, getCurrentUserId())
def test_controlpanel_view_is_protected(self): from AccessControl import Unauthorized logout() with self.assertRaises(Unauthorized): self.portal.restrictedTraverse('@@global_statusmessage_config')
def logout(self): return logout()
def tearDown(self): logout() super(TestShowPartitions, self).tearDown()
def reject_poll(self, poll): login(self.portal, TEST_USER_NAME) setRoles(self.portal, TEST_USER_ID, ['Manager']) self.wt.doActionFor(poll, 'reject') setRoles(self.portal, TEST_USER_ID, ['Member']) logout()
def test_controlpanel_view_is_protected(self): from AccessControl import Unauthorized logout() with self.assertRaises(Unauthorized): self.portal.restrictedTraverse('@@texttospeech-settings')
def test__footer_controlpanel_view_protected(self): """The control panel view should be protected""" portal = self.layer['portal'] logout() self.assertRaises(Unauthorized, portal.restrictedTraverse, '@@footer-controlpanel')
def test_mls_controlpanel_view_protected(self): """Test that the MLS configuration view needs authentication.""" from AccessControl import Unauthorized logout() self.assertRaises(Unauthorized, self.portal.restrictedTraverse, '@@mls-controlpanel')
def setUpPloneSite(self, portal): """Setup the Plone site with some groups. Create some standard groups and subgroups, and same for content groups, so we can compare. Let the groups ids start with the same character, so that we can check that both types can be found. """ applyProfile(portal, "collective.contentgroups.tests:testing") # Create some standard groups. subcasual = api.group.create(groupname="subcasual", title="Sub Casual") casual = api.group.create(groupname="casual", title="Casual", roles=["Reader"], groups=["subcasual"]) # Create some content groups. We need to be logged in for this. # Take over some lines from plone.app.contenttypes.testing # for creating a site owner and logging in. I expected that the # site owner already existed, but apparently not. portal.acl_users.userFolderAddUser(SITE_OWNER_NAME, SITE_OWNER_PASSWORD, ["Manager"], []) login(portal, SITE_OWNER_NAME) content1 = api.content.create(container=portal, type="Group", id="content1", title="Content 1") content2 = api.content.create(container=portal, type="Group", id="content2", title="Content 2") # Create sub content groups. # Note that ids and title are different so that we can test the sort order. sub2a = api.content.create(container=portal, type="Group", id="sub2a", title="2A Sub Content") sub2b = api.content.create(container=portal, type="Group", id="sub2b", title="2B Sub Content") content_sub_of_standard = api.content.create( container=portal, type="Group", id="content_sub_of_standard", title="Content Sub of Standard", ) content_sub_of_standard.users = "" logout() # Add the sub groups to their parent groups. api.group.add_user(group=casual, user=subcasual) # Ah, yes, we don't support this for content groups, because you have to go # through the content UI content2.users = "sub2a\nsub2b" # Let's also create a standard sub group in a content group: standard_sub_of_content = api.group.create( groupname="standard_sub_of_content", title="Standard Sub of Content 1", roles=["Reader"], ) content1.users = "standard_sub_of_content" # and a content sub group in a standard group. api.group.add_user(group=casual, user=content_sub_of_standard) # Create some standard users and add them to groups. ann = api.user.create( email="*****@*****.**", username="******", password="******", properties={"title": "Ann Casual"}, ) api.group.add_user(group=casual, user=ann) bert = api.user.create( email="*****@*****.**", username="******", password="******", properties={"title": "Bert Sub Casual"}, ) api.group.add_user(group=subcasual, user=bert) corey = api.user.create( email="*****@*****.**", username="******", password="******", properties={"title": "Corey Content 1"}, ) content1.users += "\n{0}".format(corey.getUserId()) donna = api.user.create( email="*****@*****.**", username="******", password="******", properties={"title": "Donna Content 2"}, ) content2.users += "\n{0}".format(donna.getUserId()) eddy = api.user.create( email="*****@*****.**", username="******", password="******", properties={"title": "Eddy Sub 2A"}, ) sub2a.users = eddy.getUserId() fiona = api.user.create( email="*****@*****.**", username="******", password="******", properties={"title": "Fiona Sub 2B"}, ) sub2b.users = fiona.getUserId() # Add one user who is in all groups. general = api.user.create( email="*****@*****.**", username="******", password="******", properties={"title": "General"}, ) for group in (casual, subcasual, standard_sub_of_content): api.group.add_user(group=group, user=general) for group in (content1, content2, sub2a, sub2b, content_sub_of_standard): group.users += "\n{0}".format(general.getUserId()) # Add one user who is in all SUB groups. sub = api.user.create( email="*****@*****.**", username="******", password="******", properties={"title": "Sub"}, ) for group in (subcasual, standard_sub_of_content): api.group.add_user(group=group, user=sub) for group in (sub2a, sub2b, content_sub_of_standard): group.users += "\n{0}".format(sub.getUserId())
def anon_permissions(self, permission): logout() permissions = api.user.get_permissions(obj=self.document, ) return permissions[permission]
def test_controlpanel_view_is_protected(self): from AccessControl import Unauthorized logout() self.assertRaises(Unauthorized, self.portal.restrictedTraverse, '@@imagecropping-settings')
def test_permission_aware_search(self): """ """ items = self.load_contents() practitioner_user = api.user.get(username=PRACTITIONER_USER_NAME) org1_url = items[0] org_id = org1_url.split("/")[-1] brain = api.portal.get_tool("portal_catalog")( portal_type="Organization", id=[org_id] ) organization = brain[0].getObject() api.user.grant_roles( user=practitioner_user, obj=organization, roles=["Practitioner"] ) patient1_url = items[3] patient_id = patient1_url.split("/")[-1] brain = api.portal.get_tool("portal_catalog")( portal_type="Patient", id=[patient_id] ) patient = brain[0].getObject() patient_user = api.user.get(username=PATIENT_USER_NAME) api.user.grant_roles(user=patient_user, obj=patient, roles=["Patient"]) api.user.grant_roles( user=patient_user, obj=organization, roles=["OrganizationMember"] ) patient2_url = items[-1] patient_id = patient2_url.split("/")[-1] brain = api.portal.get_tool("portal_catalog")( portal_type="Patient", id=[patient_id] ) patient2 = brain[0].getObject() patient_user2 = api.user.get(username=PATIENT_USER2_NAME) api.user.grant_roles(user=patient_user2, obj=patient2, roles=["Patient"]) api.user.grant_roles( user=patient_user2, obj=organization, roles=["OrganizationMember"] ) # Update Index organization.reindexObjectSecurity() self.commit() time.sleep(1) logout() params = [("_lastUpdated", "2010-05-28T05:35:56+01:00")] search_factory = self.get_factory("Organization", unrestricted=False) with api.env.adopt_user(username=PATIENT_USER_NAME): bundle = search_factory(params) # patient one should have access on his own organization self.assertEqual(len(bundle.entry), 1) self.assertEqual(bundle.entry[0].resource.id, "f001") params = [("gender", "male")] search_factory = self.get_factory("Patient", unrestricted=False) bundle = search_factory(params) # Although First organization have to two patients, # but should access it's own. self.assertEqual(len(bundle.entry), 1) self.assertEqual( bundle.entry[0].resource.id, "19c5245f-89a8-49f8-b244-666b32adb92e" ) params = [("status", "ready")] search_factory = self.get_factory("Task", unrestricted=False) bundle = search_factory(params) self.assertEqual(len(bundle.entry), 2) with api.env.adopt_user(username=PRACTITIONER_USER_NAME): params = [("active", "true")] search_factory = self.get_factory("Organization", unrestricted=False) bundle = search_factory(params) # still single organization self.assertEqual(len(bundle.entry), 1) params = [("gender", "male")] search_factory = self.get_factory("Patient", unrestricted=False) bundle = search_factory(params) # First organization have to two patients, # should access both. self.assertEqual(len(bundle.entry), 2) params = [("status:not", "rejected")] search_factory = self.get_factory("Task", unrestricted=False) bundle = search_factory(params) self.assertEqual(len(bundle.entry), 3) with api.env.adopt_user(username=PATIENT_USER2_NAME): params = [("active", "true")] search_factory = self.get_factory("Organization", unrestricted=False) bundle = search_factory(params) # still single organization self.assertEqual(len(bundle.entry), 1) params = [("gender", "male")] search_factory = self.get_factory("Patient", unrestricted=False) bundle = search_factory(params) self.assertEqual(len(bundle.entry), 1) self.assertNotEqual( bundle.entry[0].resource.id, "19c5245f-89a8-49f8-b244-666b32adb92e" )
def test_audit_log_view_is_protected(self): from AccessControl import Unauthorized logout() with self.assertRaises(Unauthorized): self.portal.restrictedTraverse('@@fingerpointing-audit-log')
def tearDown(self): logout() super(Test_LIMS2001, self).tearDown()
def test_comment_on_private_content_not_visible_to_world(self): logout() self.assertFalse(checkPerm(View, self.comment))
def testLogin(self): logout() login(self.portal, IMembraneUserAuth(self.member).getUserId())
def test_can_reply(self): # Portal owner can reply self.assertTrue(self.viewlet.can_reply()) logout() # Anonymous users can not reply self.assertFalse(self.viewlet.can_reply())
def logout(self): """ helper method to avoid importing the p.a.testing logout method """ logout()
def test_controlpanel_view_is_protected(self): from AccessControl import Unauthorized logout() with self.assertRaises(Unauthorized): self.portal.restrictedTraverse('@@prefs_keywords_view')
def test_is_anonymous(self): self.assertFalse(self.viewlet.is_anonymous()) logout() self.assertTrue(self.viewlet.is_anonymous())
def test_controlpanel_view_is_protected(self): from AccessControl import Unauthorized from plone.app.testing import logout logout() with self.assertRaises(Unauthorized): self.portal.restrictedTraverse('@@amp-settings')
class SimpleTestLayer(PloneSandboxLayer): """Setup Plone with installed AddOn only """ defaultBases = ( BIKA_LIMS_FUNCTIONAL_TESTING, PLONE_FIXTURE, ) def setUpZope(self, app, configurationContext): super(SimpleTestLayer, self).setUpZope(app, configurationContext) # Load ZCML # import senaite.api import bika.lims # self.loadZCML(package=senaite.api) self.loadZCML(package=bika.lims) # Install product and call its initialize() function z2.installProduct(app, 'senaite.addon') def setUpPloneSite(self, portal): super(SimpleTestLayer, self).setUpPloneSite(portal) # Apply Setup Profile (portal_quickinstaller) applyProfile(portal, 'bika.lims:default') # applyProfile(portal, 'senaite.api:default') login(portal.aq_parent, SITE_OWNER_NAME) # Add some test users for role in ('LabManager', 'LabClerk', 'Analyst', 'Verifier', 'Sampler', 'Preserver', 'Publisher', 'Member', 'Reviewer', 'RegulatoryInspector'): for user_nr in range(2): if user_nr == 0: username = "******" % (role.lower()) else: username = "******" % (role.lower(), user_nr) try: member = portal.portal_registration.addMember( username, username, properties={ 'username': username, 'email': username + "@example.com", 'fullname': username }) # Add user to all specified groups group_id = role + "s" group = portal.portal_groups.getGroupById(group_id) if group: group.addMember(username) # Add user to all specified roles member._addRole(role) # If user is in LabManagers, add Owner local role on clients folder if role == 'LabManager': portal.clients.manage_setLocalRoles( username, [ 'Owner', ]) except ValueError: pass # user exists logout()
def test_get_restricted_translation_for_anonymous(self): logout() restricted_translations = \ ITranslationManager(self.a_ca).get_restricted_translations() self.assertEqual(restricted_translations, {})
def logout(self): """Log out, i.e. become anonymous.""" testing.logout()
def test_disallow_sendto(self): logout() portal = self.layer['portal'] self.assertFalse(checkPerm('Allow sendto', portal))
def setUp(self): self.portal = self.layer['portal'] logout()
def logout(self): logout()
def test_community_creation_closed(self): nom = u'community-test' description = 'Blabla' image = None community_type = 'Closed' twitter_hashtag = 'helou' login(self.portal, 'ulearn.testuser1') self.portal.invokeFactory('ulearn.community', 'community-test', title=nom, description=description, image=image, community_type=community_type, twitter_hashtag=twitter_hashtag) community = self.portal['community-test'] logout() # Test for the acl registry soup = get_soup('communities_acl', self.portal) # By the gwuuid records = [ r for r in soup.query(Eq('gwuuid', IGWUUID(community).get())) ] self.assertEqual(len(records), 1) self.assertEqual(records[0].attrs.get('gwuuid', ''), IGWUUID(community).get()) self.assertEqual(records[0].attrs.get('path', ''), '/'.join(community.getPhysicalPath())) self.assertEqual(records[0].attrs.get('hash', ''), sha1(community.absolute_url()).hexdigest()) self.assertEqual( records[0].attrs.get('acl', '').get('users', [])[0]['role'], u'owner') self.assertEqual( records[0].attrs.get('acl', '').get('users', [])[0]['id'], u'ulearn.testuser1') # Test for internal objects self.assertEqual(community.objectIds(), ['documents', 'events', 'discussion']) # Test for photo folder self.assertEqual(community['documents'].objectIds(), [ 'media', ]) # Test for subscribed users self.assertTrue( u'ulearn.testuser1' in self.get_max_subscribed_users(community)) # Test for Plone permissions/local roles self.assertTrue('Reader' not in community.get_local_roles_for_userid( userid='AuthenticatedUsers')) self.assertTrue('Editor' in community.get_local_roles_for_userid( userid='ulearn.testuser1')) self.assertTrue('Owner' in community.get_local_roles_for_userid( userid='ulearn.testuser1')) self.assertTrue('Reader' in community.get_local_roles_for_userid( userid='ulearn.testuser1')) # Test the initial MAX properties max_community_info = self.get_max_context_info(community) self.assertEqual('helou', max_community_info.get(u'twitterHashtag', '')) self.assertFalse(max_community_info.get(u'notifications', False)) self.assertTrue(u'[COMMUNITY]' in max_community_info.get('tags', [])) for key in CLOSED_PERMISSIONS: self.assertEqual(max_community_info['permissions'].get(key, ''), CLOSED_PERMISSIONS[key])
class SimpleTestLayer(PloneSandboxLayer): """Setup Plone with installed AddOn only """ defaultBases = ( BASE_LAYER_FIXTURE, PLONE_FIXTURE, ) def setUpZope(self, app, configurationContext): super(SimpleTestLayer, self).setUpZope(app, configurationContext) # Load ZCML import archetypes.schemaextender import bika.lims import senaite.lims import bhp.lims self.loadZCML(package=archetypes.schemaextender) self.loadZCML(package=bika.lims) self.loadZCML(package=senaite.lims) self.loadZCML(package=bhp.lims) # Install product and call its initialize() function z2.installProduct(app, "bhp.lims") def setUpPloneSite(self, portal): super(SimpleTestLayer, self).setUpPloneSite(portal) # Apply Setup Profile (portal_quickinstaller) applyProfile(portal, "bika.lims:default") applyProfile(portal, "senaite.lims:default") applyProfile(portal, "bhp.lims:default") login(portal.aq_parent, SITE_OWNER_NAME) # Add some test users for role in ("LabManager", "LabClerk", "Analyst", "Verifier", "Sampler", "Preserver", "Publisher", "Member", "Reviewer", "RegulatoryInspector"): for user_nr in range(2): if user_nr == 0: username = "******" % (role.lower()) else: username = "******" % (role.lower(), user_nr) try: member = portal.portal_registration.addMember( username, username, properties={ "username": username, "email": username + "@example.com", "fullname": username }) # Add user to all specified groups group_id = role + "s" group = portal.portal_groups.getGroupById(group_id) if group: group.addMember(username) # Add user to all specified roles member._addRole(role) # If user is in LabManagers, add Owner local role on # clients folder if role == "LabManager": portal.clients.manage_setLocalRoles( username, [ "Owner", ]) except ValueError: pass # user exists # Force the test browser to show the site always in 'en' ltool = portal.portal_languages ltool.manage_setLanguageSettings("en", ["en"], setUseCombinedLanguageCodes=False, startNeutral=True) logout()
def test_community_subscribe_post(self): username = '******' login(self.portal, username) community = self.create_test_community() gwuuid = IGWUUID(community).get() acl = dict(users=[ dict(id=u'janet.dura', displayName=u'Janet Durà', role=u'writer'), dict(id=u'victor.fernandez', displayName=u'Víctor Fernández de Alba', role=u'reader') ], groups=[ dict(id=u'PAS', displayName=u'PAS UPC', role=u'writer'), dict(id=u'UPCnet', displayName=u'UPCnet', role=u'reader') ]) subscriptions_view = self.request_API_endpoint( username, ['api', 'communities', gwuuid, 'subscriptions'], body=acl) httpretty.enable() http_mock_hub_syncacl(acl, self.settings.hub_server) response = subscriptions_view.POST() response = json.loads(response) self.assertEqual(subscriptions_view.request.response.getStatus(), 200) self.assertTrue('message' in response) self.assertEqual(ICommunityACL(community)().attrs['acl'], acl) self.assertEqual( ICommunityACL(community)().attrs['groups'], ['PAS', 'UPCnet']) logout() # Not allowed to change ACL username_not_allowed = 'ulearn.testuser2' login(self.portal, username_not_allowed) subscriptions_view = self.request_API_endpoint( username_not_allowed, ['api', 'communities', gwuuid, 'subscriptions'], body=acl) response = subscriptions_view.POST() response = json.loads(response) self.assertEqual(subscriptions_view.request.response.getStatus(), 404) logout() # Subscribed to community but not Owner login(self.portal, username) acl = dict(users=[ dict(id=username_not_allowed, displayName=u'Test', role=u'writer'), dict(id=u'victor.fernandez', displayName=u'Víctor Fernández de Alba', role=u'reader') ], groups=[ dict(id=u'PAS', displayName=u'PAS UPC', role=u'writer'), dict(id=u'UPCnet', displayName=u'UPCnet', role=u'reader') ]) subscriptions_view = self.request_API_endpoint( username, ['api', 'communities', gwuuid, 'subscriptions'], body=acl) response = subscriptions_view.POST() response = json.loads(response) logout() login(self.portal, username_not_allowed) subscriptions_view = self.request_API_endpoint( username_not_allowed, ['api', 'communities', gwuuid, 'subscriptions'], body=acl) response = subscriptions_view.POST() response = json.loads(response) self.assertEqual(subscriptions_view.request.response.getStatus(), 404) logout() httpretty.disable() httpretty.reset()