def test_fixes_base_versions(self):
        # Test that the script sets base_version on the DSDs.

        # Create a package in parent and child that has some history in
        # its changelog.
        dsp = self.makeDerivedDistroSeries()
        distroseries = dsp.derived_series
        package = self.factory.makeSourcePackageName()
        spph = self._makePublication(distroseries, package, '1.2')
        parent_spph = self._makePublication(dsp.parent_series, package, '1.1')
        naked_spr = removeSecurityProxy(spph.sourcepackagerelease)
        naked_spr.changelog = self.factory.makeChangelog(
            package.name, ['1.2', '1.1'])
        naked_parent_spr = removeSecurityProxy(
            parent_spph.sourcepackagerelease)
        naked_parent_spr.changelog = self.factory.makeChangelog(
            package.name, ['1.1'])
        # Commit so the librarian gets the changelogs.
        transaction.commit()

        script = self.makeScript([
            '--distribution', distroseries.distribution.name,
            '--series', distroseries.name,
            ])
        script.main()
        dsd = self.getDistroSeriesDiff(distroseries)[0]
        self.assertEqual('1.1', dsd.base_version)
示例#2
0
 def addObject(self,id_obs_value, what_is_that=None):
     try:
         flatten = getUtility(IQreatureUtility, name="Flatten")
         id_obs_value_list = [i for i in flatten(id_obs_value)]
         if len(id_obs_value_list) == 3:
             value = id_obs_value_list[2]
         elif len(id_obs_value_list) == 6:
             value = [id_obs_value_list[2],id_obs_value_list[5]]
         else:
             return -1
         answer_id = int(id_obs_value_list[0])
         ob = id_obs_value_list[1]
         quiz = removeSecurityProxy(self.context)
         sm = quiz.getSiteManager()
         answer = removeSecurityProxy(sm['intids'].getObject(int(answer_id)))
         notify(CachedObjectChangedEvent([answer]))
         TYPE_OBJECT_MAP = {'lead':AnswerLeads,'depend':AnswerDepends, 'value':AnswerValue}
         if type(value) == type([]):
             ob = TYPE_OBJECT_MAP[ob](int(value[0]),int(value[1]))
         elif ob == 'value' or ob ==u'value':
             ob = TYPE_OBJECT_MAP[ob](unicode(value))
         else:
             ob = TYPE_OBJECT_MAP[ob](int(value))
         notify(ObjectCreatedEvent(ob))
         chooser = INameChooser(answer)
         name = chooser.chooseName(None, ob)
         
         if chooser.checkName(name, ob):
             answer[name] = ob
         else:
             return (0-1)
         return IAsyncDataManager(answer[name]).addSelf()
     except:
         return (0-1)
    def __init__(self, context):
        self._context = context
        self.__parent__ = context

        self.context = removeSecurityProxy(context)
        self._permissions = removeSecurityProxy(
            IPrincipalPermissionManager(context))
示例#4
0
 def __call__(self):
     self.request.response.setHeader('Content-type', 'application/pdf')
     self.request.response.setHeader('Content-disposition', 'inline;filename="'
                         + removeSecurityProxy(self.report.report_type) + "_"
                         + removeSecurityProxy(self.report.start_date).strftime('%Y-%m-%d') + '.pdf"')
     
     
     session = Session()
     report = session.query(domain.Report).get(self.report.report_id)
     d = dict([(f.file_title, f.file_data) for f in report.attached_files])
     if "pdf" not in d.keys():
         params = {}
         params['body_text'] = self.cleanupText()
         openofficepath = getUtility(IOpenOfficeConfig).getPath()
         renderer = Renderer(self.odt_file, params, self.tempFileName, pythonWithUnoPath=openofficepath)
         renderer.run()
         f = open(self.tempFileName, 'rb')
         doc = f.read()
         f.close()
         os.remove(self.tempFileName)
         attached_file = domain.AttachedFile()
         attached_file.file_title = "pdf"
         attached_file.file_data = doc
         attached_file.language = report.language
         report.attached_files.append(attached_file)
         notify(ObjectCreatedEvent(attached_file))
         session.add(report)
         session.commit()
         return doc
     else:
         return d["pdf"].__str__()
示例#5
0
 def fields(self):
     self.context = removeSecurityProxy(self.context)
     int_ids = getUtility(IQreatureIntIds, context = self.context)
     annotations = IAnnotations(removeSecurityProxy(self.context))
     graf = annotations.get(GRAF_KEY)
     
     #this means it is not first question
     if 'form.buttons.proceed' in self.request:
         answers = extract_answers(self.request)
         #actually it is only one answer
         received_answer = int_ids.getObject(int(answers[0]))
         question_id = received_answer['lead'].question_id
         
         if question_id in graf.keys()and graf[question_id] == LAST_QUESTION_KEY:
             self.gimmeAction = absoluteURL(self.context, self.request) + '/result.html'
                  
     #first question
     else:
         for i in graf.items():
             if i[1] == FIRST_QUESTION_KEY:
                 question_id = i[0]
         #it need to install idle answer
         answers = []
                 
     fields = field.Fields(IMultiPageQuizUnit, prefix = str(question_id))
     return install_widget_factories(fields, answers)
示例#6
0
    def handleSend(self, action):
        request = self.request
        data, errors = self.extractData()

        if errors:
            IStatusMessage(request).add(self.formErrorsMessage, 'error')
        else:
            message = data['message']
            members = self.context.members
            getPrincipal = getUtility(IAuthentication).getPrincipal
            invitations = getUtility(IInvitations)
            group = removeAllProxies(self.context)

            for pid in request.get('principal.users', ()):
                try:
                    principal = getPrincipal(pid)
                except PrincipalLookupError:
                    continue

                if not invitations.catalog.search(
                    group, type = {'any_of': ('invitation.member',)},
                    principal = {'any_of': (pid,)}):
                    removeSecurityProxy(members).invite(pid, message)

            IStatusMessage(request).add(_(u'Invitations have been sent.'))
            self.redirect('.')
示例#7
0
 def createAndAdd(self, data):
     ob = super(AddForm, self).createAndAdd(data)
     self.created_object = ob # !+ used by calendar/browser sitting
     # execute domain.Entity on create hook
     removeSecurityProxy(ob).on_create()
     # cascade_modifications(ob)
     return ob
示例#8
0
 def constructQuery(self, context):
     session= Session()
     trusted=removeSecurityProxy(context)
     parliament_id = self._get_parliament_id(context)
     item_id = getattr(context, self.value_field, None)
     trusted = removeSecurityProxy(context)
     existing_item_ids = [assn.item_id for assn in trusted.values()]
     if item_id:
         query = session.query(domain.ParliamentaryItem).filter(
             domain.ParliamentaryItem.parliamentary_item_id ==
             item_id)
     else:
         query = session.query(domain.ParliamentaryItem).filter(
                 sql.and_(
                     sql.not_(domain.ParliamentaryItem.status.in_(
                             _assignable_state_ids
                         )
                     ),
                     sql.not_(
                         domain.ParliamentaryItem.parliamentary_item_id.in_(
                             existing_item_ids
                         )
                     ),
                     domain.ParliamentaryItem.parliament_id == parliament_id
                 )
             )
     return query
    def test_findBuildCandidate_supersedes_builds(self):
        # IBuilder._findBuildCandidate identifies if there are builds
        # for superseded source package releases in the queue and marks
        # the corresponding build record as SUPERSEDED.
        archive = self.factory.makeArchive()
        self.publisher.getPubSource(
            sourcename="gedit", status=PackagePublishingStatus.PUBLISHED,
            archive=archive).createMissingBuilds()
        old_candidate = removeSecurityProxy(
            self.frog_builder)._findBuildCandidate()

        # The candidate starts off as NEEDSBUILD:
        build = getUtility(IBinaryPackageBuildSet).getByQueueEntry(
            old_candidate)
        self.assertEqual(BuildStatus.NEEDSBUILD, build.status)

        # Now supersede the source package:
        publication = build.current_source_publication
        publication.status = PackagePublishingStatus.SUPERSEDED

        # The candidate returned is now a different one:
        new_candidate = removeSecurityProxy(
            self.frog_builder)._findBuildCandidate()
        self.assertNotEqual(new_candidate, old_candidate)

        # And the old_candidate is superseded:
        self.assertEqual(BuildStatus.SUPERSEDED, build.status)
示例#10
0
    def test_inplace(self):
        # TODO: should test all inplace operators...
        P = self.c.proxy

        pa = P(1)
        pa += 2
        self.assertEqual(removeSecurityProxy(pa), 3)

        a = [1, 2, 3]
        pa = qa = P(a)
        pa += [4, 5, 6]
        self.failUnless(pa is qa)
        self.assertEqual(a, [1, 2, 3, 4, 5, 6])

        def doit():
            pa = P(1)
            pa += 2
        self.shouldFail(doit)

        pa = P(2)
        pa **= 2
        self.assertEqual(removeSecurityProxy(pa), 4)

        def doit():
            pa = P(2)
            pa **= 2
        self.shouldFail(doit)
示例#11
0
    def testNamedViewPageViewsNoDefault(self):
        self.assertEqual(zapi.queryMultiAdapter((ob, request), name='test'),
                         None)
        test3 = os.path.join(tests_path, 'testfiles', 'test3.pt')

        xmlconfig(StringIO(template %
            '''
            <browser:view
                name="test"
                class="zope.app.component.tests.views.V1"
                for="zope.app.component.tests.views.IC"
                permission="zope.Public"
                >

              <browser:page name="index.html" attribute="index" />
              <browser:page name="action.html" attribute="action" />
              <browser:page name="test.html" template="%s" />
            </browser:view>
            ''' % test3
            ))

        view = zapi.getMultiAdapter((ob, request), name='test')
        view = removeSecurityProxy(view)
        self.assertEqual(view.browserDefault(request)[1], (u'index.html', ))


        v = view.publishTraverse(request, 'index.html')
        v = removeSecurityProxy(v)
        self.assertEqual(v(), 'V1 here')
        v = view.publishTraverse(request, 'action.html')
        v = removeSecurityProxy(v)
        self.assertEqual(v(), 'done')
        v = view.publishTraverse(request, 'test.html')
        v = removeSecurityProxy(v)
        self.assertEqual(str(v()), '<html><body><p>done</p></body></html>\n')
示例#12
0
    def testNamedViewPageViewsCustomTraversr(self):
        self.assertEqual(zapi.queryMultiAdapter((ob, request), name='test'),
                         None)

        xmlconfig(StringIO(template %
            '''
            <browser:view
                name="test"
                class="zope.app.publisher.browser.tests.test_directives.V1"
                for="zope.app.component.tests.views.IC"
                permission="zope.Public"
                >

              <browser:page name="index.html" attribute="index" />
              <browser:page name="action.html" attribute="action" />
            </browser:view>
            '''
            ))

        view = zapi.getMultiAdapter((ob, request), name='test')
        view = removeSecurityProxy(view)
        self.assertEqual(view.browserDefault(request)[1], (u'index.html', ))


        v = view.publishTraverse(request, 'index.html')
        v = removeSecurityProxy(v)
        self.assertEqual(v(), 'V1 here')
        v = view.publishTraverse(request, 'action.html')
        v = removeSecurityProxy(v)
        self.assertEqual(v(), 'done')
示例#13
0
    def calculate_for_scale(self, received_answers):
        answers = self.getAnswers(received_answers)
        values = 0
        for answer in answers:
            if answer.has_key('value'):
                values += int(answer['value'].value)
        self.values = values
        results = [result for result in self.context.values() if IQuizResult.providedBy(result)]
        results.sort(key=lambda x: IAnnotations(removeSecurityProxy(x)).get(INTERVAL_KEY))
        
        if values == 0:
            self.result = results[0]
            return
        
        if values >= IAnnotations(removeSecurityProxy(results[-1])).get(INTERVAL_KEY):
            self.result = results[-1]
            return

        for i,v in enumerate(results):
            if i == 0:bottom_border = 0
            else: bottom_border = IAnnotations(removeSecurityProxy(results[i-1])).get(INTERVAL_KEY)
            top_border = IAnnotations(removeSecurityProxy(v)).get(INTERVAL_KEY)
            if bottom_border <= values <= top_border:
                self.result = v
                return
def merge_pofiletranslators(from_template, to_template):
    """Merge POFileTranslator entries from one template into another.
    """
    # Import here to avoid circular import.
    from lp.translations.interfaces.pofiletranslator import (
        IPOFileTranslatorSet)

    pofiletranslatorset = getUtility(IPOFileTranslatorSet)
    affected_rows = pofiletranslatorset.getForTemplate(from_template)
    for pofiletranslator in affected_rows:
        person = pofiletranslator.person
        from_pofile = pofiletranslator.pofile
        to_pofile = to_template.getPOFileByLang(from_pofile.language.code)

        pofiletranslator = removeSecurityProxy(pofiletranslator)
        if to_pofile is None:
            # There's no POFile to move this to.  We could create one,
            # but it's probably not worth the trouble.
            pofiletranslator.destroySelf()
        else:
            existing_row = pofiletranslatorset.getForPersonPOFile(
                person, to_pofile)
            date_last_touched = pofiletranslator.date_last_touched
            if existing_row is None:
                # Move POFileTranslator over to representative POFile.
                pofiletranslator.pofile = to_pofile
            elif existing_row.date_last_touched < date_last_touched:
                removeSecurityProxy(existing_row).destroySelf()
            else:
                pofiletranslator.destroySelf()
    def test_unsubscribe_pillar_artifacts_specific_info_types(self):
        # Only remove subscriptions for bugs of the specified info type.

        person_grantee = self.factory.makePerson(name='grantee')

        owner = self.factory.makePerson(name='pillarowner')
        pillar = self.factory.makeProduct(owner=owner)

        # Make bugs the person_grantee is subscribed to.
        bug1, ignored = self._make_subscribed_bug(
            person_grantee, pillar,
            information_type=InformationType.USERDATA)

        bug2, ignored = self._make_subscribed_bug(
            person_grantee, pillar,
            information_type=InformationType.PRIVATESECURITY)

        # Now run the job, removing access to userdata artifacts.
        getUtility(IRemoveArtifactSubscriptionsJobSource).create(
            pillar.owner, pillar=pillar,
            information_types=[InformationType.USERDATA])
        with block_on_job(self):
            transaction.commit()

        self.assertNotIn(
            person_grantee, removeSecurityProxy(bug1).getDirectSubscribers())
        self.assertIn(
            person_grantee, removeSecurityProxy(bug2).getDirectSubscribers())
示例#16
0
 def validate_unique(self, action, data):
     """Validate unique.
     
     Since this class always adds a single object, we can safely
     return an empty list of errors.
     """
     errors = []
     dm = removeSecurityProxy(self.domain_model)
     
     # find unique columns in data model.. TODO do this statically
     mapper = sa.orm.class_mapper(dm)
     ucols = list(unique_columns(mapper))
     
     # query out any existing values with the same unique values,
     session = Session()
     # find data matching unique columns
     ctx = removeSecurityProxy(self.context)
     ctx_is_dm_instance = isinstance(ctx, dm) # !+when is this not true?
     for key, col in ucols:
         if key in data:
             # on edit ignore new value if its the same as the previous value
             if ctx_is_dm_instance and data[key] == getattr(ctx, key, None):
                 continue
             value = session.query(dm).filter(col == data[key]).count()
             if not value:
                 continue
             errors.append(self.set_widget_error(key,
                     _(u"A record with this value already exists")))
     return errors
示例#17
0
    def delete_subobjects(self):
        """Delete subobjects.

        1) For category maintenance, move the scheduling to the bottom
        of the container.

        2) Delete any discussion items that have been associated to
        this scheduling.
        """
        field = self.request.form['field']
        reorder_form = ItemScheduleReorderForm(self.context, self.request)
        container = copy.copy(removeSecurityProxy(self.context.__parent__))
        subset_query = container.subset_query
        container.subset_query = sql.and_(
            subset_query,
            container.domain_model.planned_order > self.context.planned_order)
        for i in range(len(container) * 2):
            reorder_form.handle_move.success({'mode': 'down', 'field': field})
        container.subset_query = subset_query

        count = 0
        session = Session()
        unproxied = removeSecurityProxy(self.context)
        for key, discussion in unproxied.discussions.items():
            del unproxied.discussions[key]
            session.delete(discussion)
            count += 1
        #session.close()
        return count
示例#18
0
 def constructQuery(self, context):
     session= Session()
     trusted=removeSecurityProxy(context)
     parliament_id = self._get_parliament_id(context)
     trusted = removeSecurityProxy(context)
     assigned_committee_ids = []
     if IGroupGroupItemAssignment.providedBy(trusted):
         committee_id = getattr(trusted, "group_id", None)
         if committee_id:
             query = session.query(domain.Committee).filter(
                 sql.and_(
                     domain.Committee.parent_group_id == parliament_id,
                     domain.Committee.group_id == committee_id
                 )
             )
             return query
         else:
             assigned_committee_ids = \
                 [ comm.group_id for comm in trusted.__parent__.values() ]
     else:
         assigned_committee_ids = \
             [ comm.group_id for comm in trusted.values() ]
     query = session.query(domain.Committee).filter(
         sql.and_(
             domain.Committee.status == 'active',
             domain.Committee.parent_group_id == parliament_id,
             sql.not_(
                 domain.Committee.group_id.in_(assigned_committee_ids)
             )
         )
     )
     return query
    def mergeTranslationMessages(self):
        """Share `TranslationMessage`s between templates where possible."""
        order_check = OrderingCheck(
            key=methodcaller('sharingKey'), reverse=True)
        for template_number, template in enumerate(self.potemplates):
            log.info("Merging template %d/%d." % (
                template_number + 1, len(self.potemplates)))
            deletions = 0
            order_check.check(template)
            potmsgset_ids = self._getPOTMsgSetIds(template)
            for potmsgset_id in potmsgset_ids:
                potmsgset = POTMsgSet.get(potmsgset_id)

                tm_ids = self._partitionTranslationMessageIds(potmsgset)
                before = sum([len(sublist) for sublist in tm_ids], 0)

                for ids in tm_ids:
                    for id in ids:
                        message = TranslationMessage.get(id)
                        removeSecurityProxy(message).shareIfPossible()

                self.tm.endTransaction(intermediate=True)

                after = potmsgset.getAllTranslationMessages().count()
                deletions += max(0, before - after)

            report = "Deleted TranslationMessages: %d." % deletions
            if deletions > 0:
                log.info(report)
            else:
                log.log(DEBUG2, report)
示例#20
0
 def createAndAdd(self, data):
     ob = super(AddForm, self).createAndAdd(data)
     self.created_object = ob
     # execute domain.Entity on create hook
     removeSecurityProxy(ob).on_create()
     cascade_modifications(ob)
     return ob
 def test_job_notifications_display_failed(self):
     job = self.makeJob('package_1', failed=True)
     # Manually poke an error message.
     removeSecurityProxy(job).extendMetadata(
         {'error_message': 'Job failed!'})
     with person_logged_in(self.archive.owner):
         view = create_initialized_view(
             self.archive, "+packages", principal=self.archive.owner)
         html = view.render()
     packages_matches = soupmatchers.HTMLContains(
         # Check the main title.
         soupmatchers.Tag(
             'job summary', 'a',
             text=re.compile('Copying.*'),
             attrs={'class': re.compile('job-summary')}),
         # Check the link to the source archive.
         soupmatchers.Tag(
             'copied from', 'a',
             text=job.source_archive.displayname,
             attrs={'class': re.compile('copied-from')}),
         # Check the presence of the link to remove the notification.
         soupmatchers.Tag(
             'no remove notification link', 'a',
             text=re.compile('\s*Remove notification\s*'),
             attrs={'class': re.compile('remove-notification')}),
         # Check the presence of the error message.
         soupmatchers.Tag(
             'job error msg', 'div',
             text='Job failed!',
             attrs={'class': re.compile('job-failed-error-msg')}),
         )
     self.assertThat(html, packages_matches)
示例#22
0
 def saveDiscussions(self):
     session = Session()
     new_record_keys = []
     domain_model = removeSecurityProxy(self.context.domain_model)
     for record in self.data:
         discussion_text = record.get("body", "")
         object_id = record.get("object_id", None)
         if object_id:
             current_record = removeSecurityProxy(self.context.get(getItemKey(object_id)))
             current_record.body = discussion_text
             session.add(current_record)
             session.flush()
             notify(ObjectModifiedEvent(current_record))
             new_record_keys.append(stringKey(current_record))
         else:
             new_record = domain_model(body=discussion_text, language=get_default_language())
             new_record.scheduled_item = removeSecurityProxy(self.context.__parent__)
             session.add(new_record)
             session.flush()
             notify(ObjectCreatedEvent(new_record))
             new_record_keys.append(stringKey(new_record))
     records_to_delete = [
         removeSecurityProxy(self.context.get(key)) for key in self.context.keys() if key not in new_record_keys
     ]
     map(session.delete, records_to_delete)
     map(lambda deleted: notify(ObjectRemovedEvent(deleted)), records_to_delete)
示例#23
0
 def add_container_menu_items(self, context, container):
     request = self.request
     
     _url = url.absoluteURL(container, request)
     
     if IReadContainer.providedBy(container):
         #XXX should be the same in all containers ?
         container=proxy.removeSecurityProxy(container)
         for name, item in container.items():
             if context is None:
                 selected = False
             else:
                 selected = url.same_path_names(context.__name__, name)
             item = proxy.removeSecurityProxy(item)
             if IDCDescriptiveProperties.providedBy(item):
                 title = item.title
             else:
                 props = IDCDescriptiveProperties(item)
                 title = props.title
             # only items with valid title
             if title is not None:
                 self.items.append(url.get_menu_item_descriptor(
                         title, selected, _url, name))
     default_view_name = queryDefaultViewName(container, self.request)
     default_view = component.queryMultiAdapter(
         (container, self.request), name=default_view_name)
     if hasattr(default_view, "title") and default_view.title is not None:
         self.items.insert(0, url.get_menu_item_descriptor(
                 default_view.title, 
                 sameProxiedObjects(container, self.context), 
                 _url))
    def setupPPA(self):
        """Create pending removal publications in cprov PPA.

        Firstly, transform the cprov & mark PPAs in a ubuntutest PPA,
        since ubuntu publish configuration is broken in the sampledata.

        Also create one respective file in disk, so it can be removed and
        verified.
        """
        ubuntutest = getUtility(IDistributionSet)['ubuntutest']

        cprov = getUtility(IPersonSet).getByName('cprov')
        removeSecurityProxy(cprov.archive).distribution = ubuntutest
        ppa_pubrecs = cprov.archive.getPublishedSources(u'iceweasel')
        self.ppa_pubrec_ids = self.markPublishingForRemoval(ppa_pubrecs)

        mark = getUtility(IPersonSet).getByName('mark')
        removeSecurityProxy(mark.archive).distribution = ubuntutest
        ppa_pubrecs = mark.archive.getPublishedSources(u'iceweasel')
        self.ppa_pubrec_ids.extend(self.markPublishingForRemoval(ppa_pubrecs))

        # Fill one of the files in cprov PPA just to ensure that deathrow
        # will be able to remove it. The other files can remain missing
        # in order to test if deathrow can cope with not-found files.
        self.ppa_test_folder = os.path.join(
            config.personalpackagearchive.root, "cprov", cprov.archive.name)
        package_folder = os.path.join(
            self.ppa_test_folder, "ubuntutest/pool/main/i/iceweasel")
        os.makedirs(package_folder)
        self.ppa_package_path = os.path.join(
            package_folder, "iceweasel-1.0.dsc")
        self.writeContent(self.ppa_package_path)
示例#25
0
    def traverse(self, obj):
        'See IPublisherRequest'

        publication = self.publication

        traversal_stack = self._traversal_stack
        traversed_names = self._traversed_names

        prev_object = None
        while True:

            self._last_obj_traversed = obj

            if removeSecurityProxy(obj) is not removeSecurityProxy(prev_object):
                # Invoke hooks (but not more than once).
                publication.callTraversalHooks(self, obj)

            if not traversal_stack:
                # Finished traversal.
                break

            prev_object = obj

            # Traverse to the next step.
            entry_name = traversal_stack.pop()
            traversed_names.append(entry_name)
            obj = publication.traverseName(self, obj, entry_name)

        return obj
    def test_recent_translation_activity(self):
        # the recent_activity property lists the most recent translation
        # targets the person has worked on, for active projects only.
        self._makeReviewer()

        # make a translation record for an inactive project (will be excluded)
        [pofile] = self._makePOFiles(1, previously_worked_on=True)
        removeSecurityProxy(pofile.potemplate.product).active = False

        # and make one which has not been worked on (will be excluded)
        self._makePOFiles(1, previously_worked_on=False)

        # and make one which has a product no longer using translations (will
        # be excluded)
        [pofile] = self._makePOFiles(1, previously_worked_on=True)
        naked_product = removeSecurityProxy(pofile.potemplate.product)
        naked_product.translations_usage = ServiceUsage.NOT_APPLICABLE

        pofiles_worked_on = self._makePOFiles(11, previously_worked_on=True)

        # the expected results
        person_name = urllib.urlencode({'person': self.view.context.name})
        expected_links = [
            (pofile.potemplate.translationtarget.title,
            canonical_url(pofile, view_name="+filter") + "?%s" % person_name)
            for pofile in pofiles_worked_on[:10]]

        recent_activity = self.view.recent_activity
        self.assertContentEqual(
            expected_links,
            ((item.title, item.url) for item in recent_activity))
示例#27
0
def make_erics_fooix_project(factory):
    """Make Eric, the Fooix project, and some branches.

    :return: a dict of objects to put into local scope.
    """
    eric = factory.makePerson(name="eric", displayname="Eric the Viking", email="*****@*****.**")
    fooix = factory.makeProduct(name="fooix", displayname="Fooix", owner=eric)
    trunk = factory.makeProductBranch(owner=eric, product=fooix, name="trunk")
    removeSecurityProxy(fooix.development_focus).branch = trunk
    # Development is done by Fred.
    fred = factory.makePerson(name="fred", displayname="Fred Flintstone", email="*****@*****.**")
    feature = factory.makeProductBranch(owner=fred, product=fooix, name="feature")
    proposed = factory.makeProductBranch(owner=fred, product=fooix, name="proposed")
    bmp = proposed.addLandingTarget(
        registrant=fred, target_branch=trunk, needs_review=True, review_requests=[(eric, "code")]
    )
    # And fake a diff.
    naked_bmp = removeSecurityProxy(bmp)
    preview = removeSecurityProxy(
        naked_bmp.updatePreviewDiff("".join(unified_diff("", "random content")), u"rev-a", u"rev-b")
    )
    naked_bmp.source_branch.last_scanned_id = preview.source_revision_id
    naked_bmp.target_branch.last_scanned_id = preview.target_revision_id
    preview.diff_lines_count = 47
    preview.added_lines_count = 7
    preview.remvoed_lines_count = 13
    preview.diffstat = {"file1": (3, 8), "file2": (4, 5)}
    return {"eric": eric, "fooix": fooix, "trunk": trunk, "feature": feature, "proposed": proposed, "fred": fred}
示例#28
0
def set_sitting_parent_ids(ob, event):
    """We add the group ID/sesssion id if adding a sitting in contexts
    not bound to groups in traversal hierarchy
    """
    scheduling_context = ISchedulingContext(ob.__parent__, None)
    if ob.group_id is None:
        if scheduling_context is not None:
            ob.group_id = removeSecurityProxy(scheduling_context).group_id
    if ob.session_id is None or IObjectModifiedEvent.providedBy(event):
        if scheduling_context is not None:
            group = scheduling_context.get_group()
            if interfaces.IParliament.providedBy(group):
                container = removeSecurityProxy(group).sessions
            else:
                return
        else:
            try:
                container = ob.group.sessions
            except AttributeError:
                return
        try:
            session_id = container._query.filter(
                sql.and_(
                    domain.Session.start_date < ob.start_date,
                    domain.Session.end_date > ob.end_date
                )
            ).one().session_id
            ob.session_id = session_id
        except (orm.exc.NoResultFound, orm.exc.MultipleResultsFound):
            log.error("Could not determine session for sitting %s", ob)
 def _makeProductSeries(self, branch):
     """Create a `ProductSeries` that imports templates from `branch`."""
     productseries = self.factory.makeProductSeries()
     removeSecurityProxy(productseries).branch = branch
     removeSecurityProxy(productseries).translations_autoimport_mode = (
         TranslationsBranchImportMode.IMPORT_TEMPLATES)
     return productseries
示例#30
0
 def update(self):
     if removeSecurityProxy(self.context).has_key('lead'):
         #returns LeadEditForm
         lead = getMultiAdapter((self.context['lead'], self.request, self),IContentProvider, name=u'qreature.QreatureGeneralVM')
         lead.update()
         self.viewlets = [lead]
         #handle delete
         if not removeSecurityProxy(self.context).has_key('lead'):
             #self.cleanTermsStorage()
             if self.first_widget:
                 self.something_happened_with_da_first = True
             no_lead = getMultiAdapter((self.context, self.request, self),IContentProvider, name=u'qreature.QreatureGeneralVM')
             no_lead.update()
             no_lead.viewlets = [viewlet for viewlet in no_lead.viewlets if IInlineAddForm.providedBy(viewlet)]
             self.viewlets = [no_lead]
     else:
         no_lead = getMultiAdapter((self.context, self.request, self),IContentProvider, name=u'qreature.QreatureGeneralVM')
         no_lead.update()
         no_lead.viewlets = [viewlet for viewlet in no_lead.viewlets if IInlineAddForm.providedBy(viewlet)]
         self.viewlets = [no_lead]
         #handle add
         if removeSecurityProxy(self.context).has_key('lead'):
             #self.cleanTermsStorage()
             if self.first_widget:
                 self.something_happened_with_da_first = True
             lead = getMultiAdapter((self.context['lead'], self.request, self),IContentProvider, name=u'qreature.QreatureGeneralVM')
             lead.update()
             self.viewlets = [lead]
 def test_been_mirrored(self):
     # `check_default_stacked_on` returns the branch if it has revisions.
     branch = self.factory.makeAnyBranch()
     removeSecurityProxy(branch).branchChanged(
         '', self.factory.getUniqueString(), None, None, None)
     self.assertEqual(branch, check_default_stacked_on(branch))
示例#32
0
 def title(self):
     session = Session()
     context = session.merge(removeSecurityProxy(self.context))
     return "%s %s %s" % (context.titles,
             context.first_name,
             context.last_name)
 def _setDevelopmentFocus(self, product, branch):
     removeSecurityProxy(product).development_focus.branch = branch
 def test_retargetBranch_personalBranch(self):
     # Retarget an existing personal branch to this target.
     branch = self.factory.makePersonalBranch()
     self.target._retargetBranch(removeSecurityProxy(branch))
     self.assertEqual(self.target, branch.target)
示例#35
0
 def __init__(self, context):
     self.context = removeSecurityProxy(context)
示例#36
0
 def __call__(self):
     need("yui-datatable")
     self.context = removeSecurityProxy(self.context)
     return self.render()
示例#37
0
 def getDefaultTraversal(self, request, ob):
     obj, path = super(GrokBrowserPublication,
                       self).getDefaultTraversal(request, ob)
     return removeSecurityProxy(obj), path
示例#38
0
 def getApplication(self, request):
     result = super(ZopePublicationSansProxy, self).getApplication(request)
     return removeSecurityProxy(result)
示例#39
0
 def handleApply(self, action):
     container = ITimetableContainer(self.context)
     container.default = removeSecurityProxy(self.context)
     self.ajax_settings['dialog'] = 'close'
示例#40
0
def publish_to_xml(context):
    """Generates XML for object and saves it to the file. If object contains
    attachments - XML is saved in zip archive with all attached files. 
    """
    include = []

    context = removeSecurityProxy(context)

    if IVersionable.implementedBy(context.__class__):
        include.append("versions")
    if IAuditable.implementedBy(context.__class__):
        include.append("event")

    data = obj2dict(context,
                    1,
                    parent=None,
                    include=include,
                    exclude=[
                        "file_data", "image", "logo_data", "event",
                        "attached_files", "changes"
                    ])

    type = IWorkflow(context).name

    tags = IStateController(context).get_state().tags
    if tags:
        data["tags"] = tags

    permissions = get_object_state_rpm(context).permissions
    data["permissions"] = get_permissions_dict(permissions)

    data["changes"] = []
    for change in getattr(context, "changes", []):
        change_dict = obj2dict(change, 0, parent=context)
        change_permissions = get_head_object_state_rpm(change).permissions
        change_dict["permissions"] = get_permissions_dict(change_permissions)
        data["changes"].append(change_dict)

    # list of files to zip
    files = []
    # setup path to save serialized data
    path = os.path.join(setupStorageDirectory(), type)
    if not os.path.exists(path):
        os.makedirs(path)

    # xml file path
    file_path = os.path.join(path, stringKey(context))

    has_attachments = False
    if IAttachmentable.implementedBy(context.__class__):
        attached_files = getattr(context, "attached_files", None)
        if attached_files:
            has_attachments = True
            # add xml file to list of files to zip
            files.append("%s.xml" % (file_path))
            data["attached_files"] = []
            for attachment in attached_files:
                # serializing attachment
                attachment_dict = obj2dict(
                    attachment,
                    1,
                    parent=context,
                    exclude=["file_data", "event", "versions", "changes"])
                permissions = get_object_state_rpm(attachment).permissions
                attachment_dict["permissions"] = \
                    get_permissions_dict(permissions)
                # saving attachment to tmp
                with tmp(delete=False) as f:
                    f.write(attachment.file_data)
                    files.append(f.name)
                    attachment_dict["saved_file"] = \
                        os.path.split(f.name)[-1]
                data["attached_files"].append(attachment_dict)

    # saving xml file
    with open("%s.xml" % (file_path), "w") as file:
        file.write(serialize(data, name=type))

    # zipping xml and attached files
    # unzipped files are removed
    if has_attachments:
        zip = ZipFile("%s.zip" % (file_path), "w")
        for f in files:
            zip.write(f, os.path.split(f)[-1])
            os.remove(f)
        zip.close()
示例#41
0
 def get_note(self):
     """Return Notes if supplied by context.
     """
     context = removeSecurityProxy(self.context)
     if getattr(context, "note", False):
         return context.note
示例#42
0
 def retryErrorTypes(self, job):
     return removeSecurityProxy(job).retry_error_types
示例#43
0
 def assertVisible(self, distro, branch, person):
     self.assertTrue(  # Double-checking.
         removeSecurityProxy(branch).visibleByUser(person))
     self.assertEqual(1, len(distro.getBranchTips(user=person)))
示例#44
0
 def __init__(self, context, request):
     self.context = removeSecurityProxy(context)
     self.request = request
示例#45
0
 def __lt__(self, job):
     naked_job = removeSecurityProxy(job)
     if self.__class__ is naked_job.__class__:
         return self.__dict__ < naked_job.__dict__
     else:
         return NotImplemented
示例#46
0
 def _getUserIdentifiers(self, user):
     """Return the user's openid_identifier."""
     from zope.security.proxy import removeSecurityProxy
     return [
         identifier.identifier for identifier
             in removeSecurityProxy(user.account).openid_identifiers]
示例#47
0
 def __eq__(self, job):
     naked_job = removeSecurityProxy(job)
     return (self.__class__ is naked_job.__class__
             and self.__dict__ == naked_job.__dict__)
示例#48
0
 def userErrorTypes(self, job):
     return removeSecurityProxy(job).user_error_types
示例#49
0
 def get_feed_entries(self):
     return get_changes(removeSecurityProxy(self.context), "workflow")
示例#50
0
 def prefix(self):
     context = proxy.removeSecurityProxy(self.context)
     return "container_contents_%s" % (naming.as_identifier(
         context.__name__))
示例#51
0
 def __init__(self, context, request):
     super(KSSView, self).__init__(context, request)
     self.context = removeSecurityProxy(context)
 def _getBuildQueueItem(self, behavior):
     """Get `BuildQueue` for an `IBuildFarmJobBehavior`."""
     job = removeSecurityProxy(behavior.buildfarmjob.job)
     return IStore(BuildQueue).find(BuildQueue, job=job).one()
示例#53
0
def unset_group_local_role(context):
    role = _get_group_local_role(context)
    group = removeSecurityProxy(context)
    ctx = _get_group_context(context)
    IPrincipalRoleMap(ctx).unsetRoleForPrincipal(
            role, group.group_principal_id)
示例#54
0
def _get_group_context(context):
    if interfaces.IOffice.providedBy(context):
        return BungeniApp() #get_parliament(context)
    else:
        return removeSecurityProxy(context)
示例#55
0
def set_group_local_role(context):
    role = _get_group_local_role(context)
    group = removeSecurityProxy(context)
    ctx = _get_group_context(context) 
    IPrincipalRoleMap(ctx).assignRoleToPrincipal(
            role, group.group_principal_id)
 def fetchPolicies(self, specification):
     # We may be dealing with private specs, so just ignore security.
     return IStore(Specification).execute(
         "SELECT access_policy, access_grants FROM specification WHERE "
         "id = ?", (removeSecurityProxy(specification).id, )).get_one()
示例#57
0
 def __init__(self, object):
     try:
         self.is_private = removeSecurityProxy(object).private
     except AttributeError:
         self.is_private = False
示例#58
0
 def traverseName(self, request, ob, name, check_auth=1):
     # Fake the virtual host
     if name == "vh":
         return ProxyFactory(ob)
     return super(HookPublication, self).traverseName(
         request, removeSecurityProxy(ob), name, check_auth=1)
示例#59
0
 def domain_model(self):
     return type(removeSecurityProxy(self.context))
示例#60
0
def setParliamentId(info, context):
    instance = removeSecurityProxy(context)
    if not instance.parliament_id:
        parliamentId = prefs.getCurrentParliamentId()
        instance.parliament_id = parliamentId