def get_references(self, value, obj): portal = getToolByName(obj, 'portal_url').getPortalObject() paths = value["paths"] if isinstance(paths, list): relations = [] for path in paths: try: obj = portal.restrictedTraverse(str(path)) if obj: # create relation value intid = getUtility(IIntIds).getId(obj) relation = RelationValue(intid) relations.append(relation) except: continue return relations else: try: obj = portal.restrictedTraverse(str(paths)) except: obj = None if obj: # create relation value intid = getUtility(IIntIds).getId(obj) relation = RelationValue(intid) return relation return ""
def test_related_contacts_behavior_view_for_partners(self): add_behavior('Event', IRelatedContacts.__identifier__) timezone = 'Europe/Brussels' now = datetime.datetime.now() self.event = api.content.create(container=self.portal, type='Event', id='event') self.event.timezone = timezone eventbasic = IEventBasic(self.event) eventbasic.start = datetime.datetime(now.year, now.month, now.day, 18) eventbasic.end = datetime.datetime(now.year, now.month, now.day, 21) self.event.reindexObject() view = getMultiAdapter((self.event, self.request), name='event_summary') self.assertNotIn('partners', view()) person, organization1, organization2 = add_test_contents(self.portal) # set related contact intids = getUtility(IIntIds) to_id1 = intids.getId(person) to_id2 = intids.getId(organization2) rv1 = RelationValue(to_id1) rv2 = RelationValue(to_id2) self.event.partners = [rv1, rv2] self.assertIn('partners', view())
def set(self, instance, value, **kwargs): """ """ if value is None: ObjectField.set(self, instance, value, **kwargs) return if self.multiValued and not isinstance(value, (list, tuple)): value = value, elif not self.multiValued and isinstance(value, (list, tuple)): if len(value) > 1: raise ValueError( "Multiple values given for single valued field %r" % self) value = value[0] intid_tool = getUtility(IIntIds) #convert objects to intids if necessary if self.multiValued: result = [] for v in value: if isinstance(v, (basestring, int)): result.append(RelationValue(int(v))) else: result.append(RelationValue(intid_tool.getId(v))) else: if isinstance(value, (basestring, int)): result = RelationValue(int(value)) else: result = RelationValue(intid_tool.getId(value)) ObjectField.set(self, instance, result, **kwargs)
def test_document_fusion_with_merge_multiple(self): # data source is in a related content # we merge two files from two sources alsoProvides(self.portal.REQUEST, ICollectiveDocumentfusionLayer) intids = getUtility(IIntIds) source_1 = api.content.create(self.portal, type='contact_infos', id='desvenain_thomas', identity='M. Desvenain Thomas', address_1='24 rue des Trois Mollettes', address_2='C24', zipcode='59000', city='Lille') source_2 = api.content.create(self.portal, type='contact_infos', id='fretin_vincent', identity='M. Fretin Vincent', address_1='51 r Lac', address_2='', zipcode='59810', city='LESQUIN') content = api.content.create(self.portal, type='label_model', title=u"Modèle d'étiquette", file=NamedFile(data=open(TEST_LABEL_ODT).read(), filename=u'label.odt', contentType='application/vnd.oasis.opendocument.text'), relatedItems=[RelationValue(intids.getId(source_1)), RelationValue(intids.getId(source_2))], ) notify(ObjectModifiedEvent(content)) generated_stream = content.unrestrictedTraverse('@@getdocumentfusion')() self.assertTrue(generated_stream) self.assertEqual(self.portal.REQUEST.response['content-type'], 'application/pdf') generated_path = tempfile.mktemp(suffix='label.pdf') generated_file = open(generated_path, 'w') generated_file.write(generated_stream.read()) generated_file.close() txt_path = tempfile.mktemp(suffix='label.pdf') subprocess.call(['pdftotext', generated_path, txt_path]) txt = open(txt_path).read().replace(r'\xc2\xa0', ' ') # label 1 self.assertIn('M. DESVENAIN THOMAS', txt) self.assertIn('24 RUE DES TROIS MOLLETTES', txt) self.assertIn('C24', txt) self.assertIn(u'59000', txt) # label 2 self.assertIn('M. FRETIN VINCENT', txt) self.assertIn(u'59810', txt) self.assertIn(u'LESQUIN', txt) os.remove(txt_path) os.remove(generated_path)
def testRelations(self): rel_fti = DexterityFTI( 'RelationsType', schema= 'plone.app.versioningbehavior.tests.test_modifiers.IRelationsType') self.portal.portal_types._setObject('RelationsType', rel_fti) # Setup IIntIds utility which is required for relations to work from five.intid import site from zope.app.intid.interfaces import IIntIds site.add_intids(self.portal) intids = getUtility(IIntIds) source = createContentInContainer(self.portal, 'RelationsType') target = createContentInContainer(self.portal, 'RelationsType') # Test modifier when no relations are set modifier = SkipRelations('modifier', 'Modifier') pers_id, pers_load, empty1, empty2 = modifier.getOnCloneModifiers( source) self.assertTrue(pers_id(None) is None) self.assertTrue(pers_id(None) is None) self.assertTrue(pers_load(None) is None) self.assertTrue(pers_load(None) is None) self.assertTrue(empty1 == []) self.assertTrue(empty2 == []) repo_clone = createContent('RelationsType') modifier.afterRetrieveModifier(source, repo_clone) self.assertTrue(repo_clone.single is source.single) self.assertTrue(repo_clone.multiple is source.multiple) # Add some relations source.single = RelationValue(intids.getId(target)) source.multiple = [RelationValue(intids.getId(target))] # Update relations from zope.lifecycleevent import ObjectModifiedEvent from zope.event import notify notify(ObjectModifiedEvent(source)) modifier = SkipRelations('modifier', 'Modifier') pers_id, pers_load, empty1, empty2 = modifier.getOnCloneModifiers( source) self.assertTrue(pers_id(source.single)) self.assertTrue(pers_id(source.multiple)) self.assertTrue(pers_load(source.single) is None) self.assertTrue(pers_load(source.multiple) is None) self.assertTrue(empty1 == []) self.assertTrue(empty2 == []) repo_clone = createContent('RelationsType') modifier.afterRetrieveModifier(source, repo_clone) self.assertTrue(repo_clone.single is source.single) self.assertTrue(repo_clone.multiple is source.multiple)
def testRelationsInBehaviors(self): self.register_RelationsType() intids = getUtility(IIntIds) source = createContentInContainer(self.portal, 'RelationsType') target = createContentInContainer(self.portal, 'RelationsType') # Test modifier when no relations are set modifier = SkipRelations('modifier', 'Modifier') on_clone_modifiers = modifier.getOnCloneModifiers(source) pers_id, pers_load, empty1, empty2 = on_clone_modifiers self.assertTrue(pers_id(None) is None) self.assertTrue(pers_id(None) is None) self.assertTrue(pers_load(None) is None) self.assertTrue(pers_load(None) is None) self.assertTrue(empty1 == []) self.assertTrue(empty2 == []) repo_clone = createContent('RelationsType') modifier.afterRetrieveModifier(source, repo_clone) self.assertTrue(repo_clone.single is None) self.assertTrue(repo_clone.multiple is None) # Add some relations IRelationsBehavior(source).single = RelationValue(intids.getId(target)) IRelationsBehavior(source).multiple = [ RelationValue(intids.getId(target)) ] # Update relations from zope.lifecycleevent import ObjectModifiedEvent from zope.event import notify notify(ObjectModifiedEvent(source)) modifier = SkipRelations('modifier', 'Modifier') on_clone_modifiers = modifier.getOnCloneModifiers(source) pers_id, pers_load, empty1, empty2 = on_clone_modifiers self.assertTrue(pers_id(IRelationsBehavior(source).single)) self.assertTrue(pers_id(IRelationsBehavior(source).multiple)) self.assertTrue(pers_load(IRelationsBehavior(source).single) is None) self.assertTrue(pers_load(IRelationsBehavior(source).multiple) is None) self.assertTrue(empty1 == []) self.assertTrue(empty2 == []) repo_clone = createContent('RelationsType') modifier.afterRetrieveModifier(source, repo_clone) self.assertTrue( IRelationsBehavior(repo_clone).single is IRelationsBehavior( source).single) self.assertTrue( IRelationsBehavior(repo_clone).multiple is IRelationsBehavior( source).multiple)
def testRelations(self): rel_fti = DexterityFTI('RelationsType', schema=IRelationsType.__identifier__) self.portal.portal_types._setObject('RelationsType', rel_fti) intids = getUtility(IIntIds) source = createContentInContainer(self.portal, 'RelationsType') target = createContentInContainer(self.portal, 'RelationsType') # Test modifier when no relations are set modifier = SkipRelations('modifier', 'Modifier') on_clone_modifiers = modifier.getOnCloneModifiers(source) pers_id, pers_load, empty1, empty2 = on_clone_modifiers self.assertTrue(pers_id(None) is None) self.assertTrue(pers_id(None) is None) self.assertTrue(pers_load(None) is None) self.assertTrue(pers_load(None) is None) self.assertTrue(empty1 == []) self.assertTrue(empty2 == []) repo_clone = createContent('RelationsType') modifier.afterRetrieveModifier(source, repo_clone) self.assertTrue(repo_clone.single is source.single) self.assertTrue(repo_clone.multiple is source.multiple) # Add some relations source.single = RelationValue(intids.getId(target)) source.multiple = [RelationValue(intids.getId(target))] # Update relations from zope.lifecycleevent import ObjectModifiedEvent from zope.event import notify notify(ObjectModifiedEvent(source)) modifier = SkipRelations('modifier', 'Modifier') on_clone_modifiers = modifier.getOnCloneModifiers(source) pers_id, pers_load, empty1, empty2 = on_clone_modifiers self.assertTrue(pers_id(source.single)) self.assertTrue(pers_id(source.multiple)) self.assertTrue(pers_load(source.single) is None) self.assertTrue(pers_load(source.multiple) is None) self.assertTrue(empty1 == []) self.assertTrue(empty2 == []) repo_clone = createContent('RelationsType') modifier.afterRetrieveModifier(source, repo_clone) self.assertTrue(repo_clone.single is source.single) self.assertTrue(repo_clone.multiple is source.multiple)
def setUp(self): """ """ super(TestContactForm, self).setUp() self.typ1 = api.content.create(self.eea_folder, 'testtype', 'typ1') self.typ2 = api.content.create(self.eea_folder, 'testtype', 'typ2') org1 = self.portal['mydirectory']['armeedeterre'] org2 = org1['corpsa'] org3 = org1['corpsb'] self.intids = getUtility(IIntIds) self.orgs = [org1, org2, org3] self.rels = [RelationValue(self.intids.getId(org1)), RelationValue(self.intids.getId(org2)), RelationValue(self.intids.getId(org3))] # set 'uids' in form typ_uids = u"{0},{1}".format(self.typ1.UID(), self.typ2.UID()) self.request.form['form.widgets.uids'] = typ_uids
def test_should_provide_diff_for_related_fields(self): intids = getUtility(IIntIds) self.portal.invokeFactory( testing.TEST_CONTENT_TYPE_ID, 'obj1', title=u'Object 1', description=u'Desc 1', text=u'Text 1', ) obj1 = self.portal['obj1'] intid = intids.register(obj1) self.portal.invokeFactory( testing.TEST_CONTENT_TYPE_ID, 'obj2', title=u'Object 2', relatedItems=[RelationValue(intid)], ) obj2 = self.portal['obj2'] intid = intids.register(obj2) self.portal.invokeFactory( testing.TEST_CONTENT_TYPE_ID, 'obj3', title=u'Object 3', relatedItems=[RelationValue(intid)], ) obj3 = self.portal['obj3'] diffs = DexterityCompoundDiff(obj2, obj3, 'any') for d in diffs: if d.field == 'relatedItems': inline_diff = d.inline_diff() self.assertTrue(inline_diff) i_diff_sub = inline_diff.index('<div class="diff_sub">') i_obj1 = inline_diff.index('Object 1') i_diff_add = inline_diff.index('<div class="diff_add">') i_obj2 = inline_diff.index('Object 2') self.assertTrue(i_diff_sub < i_obj1 < i_diff_add < i_obj2) n_diff = d.ndiff() self.assertTrue(n_diff) i_rem = n_diff.index('-') i_obj1 = n_diff.index('obj1') i_add = n_diff.index('+') i_obj2 = n_diff.index('obj2') self.assertTrue(i_rem < i_obj1 < i_add < i_obj2)
def test_toc_can_be_downloaded(self, browser): templates = create(Builder('templatefolder')) sablon_template = create( Builder('sablontemplate').within(templates).with_asset_file( 'sablon_template.docx')) self.committee.toc_template = RelationValue( getUtility(IIntIds).getId(sablon_template)) transaction.commit() browser.login().open(self.committee, view='tabbedview_view-periods') browser.find(self.download_button_label).click() self.assertDictContainsSubset( { 'status': '200 Ok', 'content-disposition': 'attachment; ' 'filename="{}"'.format(self.toc_filename), 'x-frame-options': 'SAMEORIGIN', 'content-type': MIME_DOCX, 'x-theme-disabled': 'True' }, browser.headers) self.assertIsNotNone(browser.contents)
def __call__(self): relation_catalog = component.queryUtility(ICatalog) # First we make sure that templates are set on the committee query = {'object_provides': ICommittee.__identifier__} message = 'Make sure all meeting templates are set on the committee' intids = getUtility(IIntIds) for committee in self.objects(query, message): committee_container = committee.get_committee_container() for template_name in templates: if not getattr(committee, template_name, None) and getattr( committee_container, template_name, None): template_relation = getattr(committee_container, template_name) template = template_relation.to_object if template: setattr(committee, template_name, RelationValue(intids.getId(template))) committee.reindexObject() addRelations(committee, None) # Now we remove the relations to the templates on the ComitteeContainers # we can't use z3c.relationfield.eventremoveRelations because the fields # don't exist on the ICommitteeContainer schema anymore. # We also remove the attribute, as it will not be needed anymore query = {'object_provides': ICommitteeContainer.__identifier__} for committee_container in self.objects(query, message): for template_name in templates: if hasattr(committee_container, template_name): template = getattr(committee_container, template_name) if template: relation_catalog.unindex(template) delattr(committee_container, template_name)
def test_SenderColumn(self): column = SenderColumn(self.portal, self.portal.REQUEST, self.mail_table) brain = self.portal.portal_catalog(UID=self.im5.UID())[0] self.assertEqual(column.renderCell(brain), u"<a href='http://nohost/plone/contacts/jeancourant/agent-electrabel' target='_blank' " "class='pretty_link link-tooltip'><span class='pretty_link_icons'><img title='Held position' " "src='http://nohost/plone/held_position_icon.png' /></span><span class='pretty_link_content'" ">Monsieur Jean Courant, Agent (Electrabel)</span></a>") # multiple senders self.im5.sender.append(RelationValue(self.intids.getId(self.portal['contacts']['sergerobinet']))) self.im5.reindexObject(idxs=['sender_index']) brain = self.portal.portal_catalog(UID=self.im5.UID())[0] rendered = column.renderCell(brain) self.assertIn('<ul class="contacts_col"><li>', rendered) self.assertEqual(rendered.count('<a href'), 2) # no sender imail = sub_create(self.portal['incoming-mail'], 'dmsincomingmail', datetime.now(), 'my-id', **{'title': u'My title', 'description': u'Description'}) brain = self.portal.portal_catalog(UID=imail.UID())[0] self.assertEqual(column.renderCell(brain), '-') # sender not found: we delete it self.im5.sender = self.im5.sender[0:1] self.im5.reindexObject(idxs=['sender_index']) api.content.delete(obj=self.portal['contacts']['jeancourant']['agent-electrabel'], check_linkintegrity=False) brain = self.portal.portal_catalog(UID=self.im5.UID())[0] self.assertEqual(column.renderCell(brain), '-')
def _apply(self, **data): if ((data.get('removed_values', None) and data['action_choice'] in ('remove', 'replace')) or (data.get('added_values', None)) and data['action_choice'] in ('add', 'replace', 'overwrite')): intids = getUtility(IIntIds) for brain in self.brains: obj = brain.getObject() if data['action_choice'] in ('overwrite'): items = set(data['added_values']) else: # we get the linked objects items = set([ intids.getObject(rel.to_id) for rel in (getattr(obj, self.attribute) or []) if not rel.isBroken() ]) if data['action_choice'] in ('remove', 'replace'): items = items.difference(data['removed_values']) if data['action_choice'] in ('add', 'replace'): items = items.union(data['added_values']) # transform to relations rels = [RelationValue(intids.getId(ob)) for ob in items] setattr(obj, self.attribute, rels) modified(obj)
def append_excerpt(self, excerpt_document): """Add a relation to a new excerpt document. """ excerpts = getattr(self, 'excerpts', None) if not excerpts: # The missing_value attribute of a z3c-form field is used # as soon as an object has no default_value i.e. after creating # an object trough the command-line. # # Because the excerpts field needs a list as a missing_value, # we will fall into the "mutable keyword argument"-python gotcha. # The excerpts will be shared between the object-instances. # # Unfortunately the z3c-form field does not provide a # missing_value-factory (like the defaultFactory) which would be # necessary to fix this issue properly. # # As a workaround we reassign the field with a new list if the # excerpts-attribute has never been assigned before. excerpts = [] intid = getUtility(IIntIds).getId(excerpt_document) excerpts.append(RelationValue(intid)) self.excerpts = excerpts addRelations(self, None)
def _aliasTarget(self, value): if '_aliasTarget' in self.__dict__: raise AttributeError("Cannot set _aliasTarget more than once") if not IRelationValue.providedBy(value): raise AttributeError("_aliasTarget must be an IRelationValue") counter = 0 target = value.to_object while IAlias.providedBy( target) and counter < 1000: # avoid infinite loop target = aq_inner(target._target) counter += 1 if counter > 0: intids = queryUtility(IIntIds) if intids is None: raise LookupError("Cannot find intid utility") to_id = intids.getId(target) value = RelationValue(to_id) self.__dict__['_aliasTarget'] = value
def test_related_contacts_behavior_view_for_contact(self): add_behavior('Event', IRelatedContacts.__identifier__) timezone = 'Europe/Brussels' now = datetime.datetime.now() self.event = api.content.create(container=self.portal, type='Event', id='event') self.event.timezone = timezone eventbasic = IEventBasic(self.event) eventbasic.start = datetime.datetime(now.year, now.month, now.day, 18) eventbasic.end = datetime.datetime(now.year, now.month, now.day, 21) self.event.reindexObject() view = getMultiAdapter((self.event, self.request), name='event_summary') person, organization1, organization2 = add_test_contents(self.portal) # set related contact intids = getUtility(IIntIds) to_id = intids.getId(organization1) rv = RelationValue(to_id) self.event.contact = rv self.assertEqual(view.get_website(organization1), None) organization1.website = 'www.foo.bar' self.assertEqual( view.get_website(organization1), '<a class="event_website" href="http://www.foo.bar" target="_blank">www.foo.bar</a>' # noqa )
def test_revokes_permissions_on_proposal(self): self.login(self.dossier_responsible) intids = getUtility(IIntIds) relation = RelationValue(intids.getId(self.proposaldocument)) ITask(self.subtask).relatedItems.append(relation) notify(ObjectModifiedEvent(self.subtask)) self.set_workflow_state('task-state-tested-and-closed', self.subtask) expected_assignments = [{ 'cause': ASSIGNMENT_VIA_TASK, 'roles': ['Reader', 'Editor'], 'reference': Oguid.for_object(self.subtask), 'principal': self.regular_user.id }, { 'cause': ASSIGNMENT_VIA_TASK_AGENCY, 'roles': ['Reader', 'Editor'], 'reference': Oguid.for_object(self.subtask), 'principal': u'fa_inbox_users' }] document_storage = RoleAssignmentManager(self.proposaldocument).storage self.assertEqual(expected_assignments, document_storage._storage()) proposal_storage = RoleAssignmentManager(self.proposal).storage self.assertEqual(expected_assignments, proposal_storage._storage()) RevokePermissions(self.subtask, self.request)() self.assertEqual([], proposal_storage._storage()) self.assertEqual([], document_storage._storage())
def replace_contact_list(obj, fieldname): """ Replace ContactList in contact field """ value = getattr(obj, fieldname) if not value: return False newvalue = [] objs = [] changed = False for relation in value: if not relation.isBroken() and relation.to_object: to_obj = relation.to_object if to_obj.portal_type == 'contact_list': changed = True intids = getUtility(IIntIds) # contact_list.contacts is a ContactList field for rel in to_obj.contacts: if not rel.isBroken() and rel.to_object and rel.to_object not in objs: objs.append(rel.to_object) newvalue.append(RelationValue(intids.getId(rel.to_object))) elif to_obj not in objs: objs.append(to_obj) newvalue.append(relation) if changed: setattr(obj, fieldname, newvalue) orig_updateRelations(obj, None) return changed
def addPersonsAndHeldPositions(self, person_descriptors, source): '''Creates persons and eventual held_positions.''' own_org = get_own_organization() container = own_org.aq_inner.aq_parent intids = getUtility(IIntIds) for person_descr in person_descriptors: # create the person person = api.content.create(container=container, type='person', **person_descr.getData()) # person.photo is the name of the photo to use stored in /images if person.photo: photo_path = '%s/images/%s' % (source, person.photo) data = self.find_binary(photo_path) photo_file = NamedImage(data, filename=person.photo) person.photo = photo_file validate_fields(person, raise_on_errors=True) for held_pos_descr in person_descr.held_positions: # get the position data = held_pos_descr.getData() org = container.restrictedTraverse(data['position']) data['position'] = RelationValue(intids.getId(org)) held_position = api.content.create(container=person, type='held_position', **data) validate_fields(held_position, raise_on_errors=True)
def setup_excerpt_template(self): templates = create(Builder('templatefolder')) sablon_template = create( Builder('sablontemplate').within(templates).with_asset_file( 'sablon_template.docx')) self.container.excerpt_template = RelationValue( getUtility(IIntIds).getId(sablon_template))
def set(self, value): """Sets the relationship target""" value = value or [] new_relationships = [] intids = getUtility(IIntIds) for item in value: # otherwise create one to_id = intids.getId(item) new_relationships.append(RelationValue(to_id)) super(RelationListDictDataManager, self).set(new_relationships)
def relate_to(self, documents): if not isinstance(documents, list): documents = [ documents, ] intids = getUtility(IIntIds) self.arguments['relatedItems'] = [ RelationValue(intids.getId(doc)) for doc in documents ] return self
def setUp(self): self.portal = self.layer["portal"] self.catalog = getToolByName(self.portal, "portal_catalog") setRoles(self.portal, TEST_USER_ID, ["Manager"]) # creating test objects: folder, news, newsletter and subscriber self.portal.invokeFactory("Folder", "testfolder") self.folder = self.portal["testfolder"] self.folder.invokeFactory("News Item", "news01") self.folder.invokeFactory("Newsletter", "daily-news") self.newsletter = self.folder["daily-news"] self.newsletter.title = u"Daily News" # XXX check if we could ovaid this by using defaults from site settings self.newsletter.sender_email = u"*****@*****.**" self.newsletter.sender_name = u"ACME newsletter" self.newsletter.test_email = u"*****@*****.**" news_collection = api.content.create( type="Collection", id="news-collection", title=u"News Collection", container=self.folder, ) query = [{ "i": "portal_type", "o": "plone.app.querystring.operation.selection.is", "v": ["News Item"], }] news_collection.setQuery(query) news_collection.aggregation_template = "aggregation_generic_listing" transaction.commit() intids = getUtility(IIntIds) to_id = intids.getId(news_collection) self.newsletter.content_aggregation_sources = [RelationValue(to_id)] api.content.create( type="Newsletter Subscriber", id="subscriber01", container=self.newsletter, email=u"*****@*****.**", ) self.view = getMultiAdapter((self.newsletter, self.layer["request"]), name="daily-issue") self.mail_settings = get_portal_mail_settings() self.mail_settings.email_from_address = "*****@*****.**" # setting a Mock mailhost self.portal._original_MailHost = self.portal.MailHost self.portal.MailHost = mailhost = MockMailHost("MailHost") sm = getSiteManager(context=self.portal) sm.unregisterUtility(provided=IMailHost) sm.registerUtility(mailhost, provided=IMailHost)
def test_reply_to(self): catalog = getUtility(ICatalog) imail1 = get_object(oid='courrier1', ptype='dmsincomingmail') imail2 = get_object(oid='courrier2', ptype='dmsincomingmail') omail1 = get_object(oid='reponse1', ptype='dmsoutgoingmail') omail2 = get_object(oid='reponse2', ptype='dmsoutgoingmail') omail1.reply_to = [ RelationValue(self.intids.getId(imail1)), RelationValue(self.intids.getId(imail2)), RelationValue(self.intids.getId(omail2)), ] modified(omail1) self.assertEqual(len(omail1.reply_to), 3) omail_intid = self.intids.queryId(omail1) query = { 'from_id': omail_intid, 'from_attribute': 'reply_to' } linked = set([rel.to_object for rel in catalog.findRelations(query)]) self.assertSetEqual(set([imail1, imail2, omail2]), linked)
def test_person_held_positions(self): self.login(TEST_USER_NAME) degaulle = self.directory.degaulle intids = getUtility(IIntIds) # de gaulle in 1960... api.content.create(container=self.directory, type='organization', id='france', ) api.content.create(container=degaulle, type='held_position', id='president', start_date=datetime.date(1959, 1, 8), position=RelationValue(intids.getId(self.directory.france))) api.content.create(container=degaulle, type='held_position', id='lieutenant-colonel', position=RelationValue(intids.getId(self.directory.armeedeterre)), end_date=datetime.date(1940, 6, 1), start_date=datetime.date(1933, 12, 25)) api.content.create(container=degaulle, type='held_position', id='commandant', position=RelationValue(intids.getId(self.directory.armeedeterre)), start_date=datetime.date(1927, 10, 9), end_date=datetime.date(1933, 12, 25)) del self.degaulle.gadt.end_date self.degaulle.moveObjectsToTop(['president']) adapter = IPersonHeldPositions(degaulle) self.assertEqual(adapter.get_main_position(), self.degaulle.president) self.assertEqual(adapter.get_current_positions(), (self.degaulle.president, self.degaulle.gadt, )) self.assertEqual(adapter.get_sorted_positions(), (self.degaulle.president, self.degaulle.gadt, degaulle.adt, degaulle['lieutenant-colonel'], self.degaulle['commandant'], )) api.content.transition(degaulle.adt, 'deactivate') self.assertEqual(adapter.get_main_position(), self.degaulle.president) api.content.transition(degaulle.president, 'deactivate') self.assertEqual(adapter.get_main_position(), degaulle.gadt)
def test_are_grouped_by_repository_and_sorted(self, browser): self.login(self.records_manager, browser) repository_10 = create( Builder('repository').titled(u'Repository B').having( reference_number_prefix=u'10')) dossier_c = create( Builder('dossier').as_expired().titled(u'Dossier C').within( repository_10)) dossier_d = create( Builder('dossier').as_expired().titled(u'Dossier D').within( self.empty_repofolder)) # We change the former end state of the offered_dossier_to_destroy, # dossiers that were inactive are displayed separately. api.content.transition( self.offered_dossier_to_destroy, transition="dossier-transition-offered-to-resolved") api.content.transition(self.offered_dossier_to_destroy, transition="dossier-transition-offer") intids = getUtility(IIntIds) self.disposition.dossiers += [ RelationValue(intids.getId(dossier_c)), RelationValue(intids.getId(dossier_d)) ] browser.open(self.disposition, view='overview') repos = browser.css('.repository-list-item') self.assertEquals([ u'1.1. Vertr\xe4ge und Vereinbarungen', u'2. Rechnungspr\xfcfungskommission', '10. Repository B' ], repos.css('.repository_title h3').text) self.assertEquals( ['Hannah Baufrau', 'Hans Baumann', 'Dossier D', 'Dossier C'], repos.css('h3.title a').text)
def test_related_searchable_text(self): self.assertEqual( organization_searchable_text(self.divisionalpha)(), u"Armée de terre Corps A Division Alpha") intids = getUtility(IIntIds) alsoProvides(self.divisionalpha, IRelatedOrganizations) self.divisionalpha.related_organizations = [ RelationValue(intids.getId(self.divisionbeta)), ] self.assertEqual( organization_searchable_text(self.divisionalpha)(), u'Armée de terre Corps A Division Beta Armée de terre Corps A Division Alpha' )
def _create_task(self, context, with_docs=False, return_docs=False): # task task = create( Builder('task').having(title='Task1', responsible=TEST_USER_ID, issuer=TEST_USER_ID, task_type='correction')) if not with_docs: return task documents = [] # containing documents documents.append( set_defaults( createContentInContainer(task, 'opengever.document.document', title=u'Doc 1'))) documents.append( set_defaults( createContentInContainer(task, 'opengever.document.document', title=u'Doc 2'))) # related documents documents.append( set_defaults( createContentInContainer(context, 'opengever.document.document', title=u'Doc 3'))) documents.append( set_defaults( createContentInContainer(context, 'opengever.document.document', title=u'Doc 4'))) intids = getUtility(IIntIds) ITask(task).relatedItems = [RelationValue(intids.getId(documents[2]))] # commit any pending transaction in order to avoid # StorageTransactionError: Duplicate tpc_begin calls for same transaction # See https://github.com/4teamwork/opengever.core/pull/556 transaction.commit() if return_docs: return task, documents return task
def test_override_geo_with_related_contact(self): add_behavior( 'Event', 'cpskin.agenda.behaviors.related_contacts.IRelatedContacts' ) # noqa add_behavior('Event', ICoordinates.__identifier__) event = api.content.create(container=self.portal, type='Event', id='myevent') # add some contacts applyProfile(self.portal, 'collective.contact.core:default') add_behavior('organization', ICoordinates.__identifier__) directory = api.content.create(container=self.portal, type='directory', id='directory') organization = api.content.create(container=directory, type='organization', id='organization') organization.title = u'IMIO' organization.street = u'Rue Léon Morel' organization.number = u'1' organization.zip_code = u'5032' organization.city = u'Isnes' # set related contact intids = getUtility(IIntIds) to_id = intids.getId(organization) rv = RelationValue(to_id) event.location = rv notify(ObjectModifiedEvent(event)) # coord = ICoordinates(event) view = getMultiAdapter((event, event.REQUEST), name='geoview') coord = view.getCoordinates() self.assertEqual(coord, (None, None)) coordinates = ICoordinates(event).coordinates self.assertEqual(coordinates, u'') # check if event georeferenced is correct orga_geo = IGeoreferenced(organization) orga_geo.setGeoInterface('Point', (4.711178, 50.504827)) notify(ObjectModifiedEvent(event)) view = getMultiAdapter((event, event.REQUEST), name='geoview') coord = view.getCoordinates() self.assertEqual(coord, ('Point', (4.711178, 50.504827))) coordinates = ICoordinates(event).coordinates self.assertEqual(coordinates, 'POINT (4.711178 50.504827)')
def test_relation_value(self): portal = self.layer['portal'] doc1 = portal[portal.invokeFactory( 'DXTestDocument', id='doc1', title='Document 1', description='Description', )] intids = getUtility(IIntIds) self.assertEquals( {'@id': 'http://nohost/plone/doc1', '@type': 'DXTestDocument', 'title': 'Document 1', 'description': 'Description', 'review_state': 'private'}, json_compatible(RelationValue(intids.getId(doc1))))