Ejemplo n.º 1
0
    def cleanUp(self):
        """See `IBuildFarmJob`.

        Classes that derive from BuildFarmJobOld need to clean up
        after themselves correctly.
        """
        Store.of(self).remove(self)
Ejemplo n.º 2
0
    def test_BranchJobPruner(self):
        # Garbo should remove jobs completed over 30 days ago.
        switch_dbuser('testadmin')
        store = IMasterStore(Job)

        db_branch = self.factory.makeAnyBranch()
        db_branch.branch_format = BranchFormat.BZR_BRANCH_5
        db_branch.repository_format = RepositoryFormat.BZR_KNIT_1
        Store.of(db_branch).flush()
        branch_job = BranchUpgradeJob.create(
            db_branch, self.factory.makePerson())
        branch_job.job.date_finished = THIRTY_DAYS_AGO

        self.assertEqual(
            store.find(
                BranchJob,
                BranchJob.branch == db_branch.id).count(),
                1)

        self.runDaily()

        switch_dbuser('testadmin')
        self.assertEqual(
            store.find(
                BranchJob,
                BranchJob.branch == db_branch.id).count(),
                0)
Ejemplo n.º 3
0
 def add_lap(self):
     lap = RacerLap()
     lap.racer = self
     lap.race = self.race
     lap.event_time = datetime.datetime.now()
     Store.of(self).add(lap)
     return lap
Ejemplo n.º 4
0
 def _createPreviewDiff(self, line_count=0, added=None, removed=None, conflicts=None, diffstat=None):
     # Login an admin to avoid the launchpad.Edit requirements.
     login("*****@*****.**")
     # Create a dummy preview diff, and make sure the branches have the
     # correct last scanned ids to ensure that the new diff is not stale.
     bmp = self.factory.makeBranchMergeProposal()
     if line_count:
         content = "".join(unified_diff("", "random content"))
     else:
         content = ""
     preview = bmp.updatePreviewDiff(content, u"rev-a", u"rev-b", conflicts=conflicts)
     bmp.source_branch.last_scanned_id = preview.source_revision_id
     bmp.target_branch.last_scanned_id = preview.target_revision_id
     # Update the values directly sidestepping the security.
     naked_diff = removeSecurityProxy(preview)
     naked_diff.diff_lines_count = line_count
     naked_diff.added_lines_count = added
     naked_diff.removed_lines_count = removed
     naked_diff.diffstat = diffstat
     # In order to get the canonical url of the librarian file, we need to
     # commit.
     # transaction.commit()
     # Make sure that the preview diff is in the db for the test.
     # Storm bug: 324724
     Store.of(bmp).flush()
     return preview
    def test_preloads_irc_nicks_and_preferredemail(self):
        """Test that IRC nicks and preferred email addresses are preloaded."""
        # Create three people with IRC nicks, and one without.
        people = []
        for num in range(3):
            person = self.factory.makePerson(displayname='foobar %d' % num)
            getUtility(IIrcIDSet).new(person, 'launchpad', person.name)
            people.append(person)
        people.append(self.factory.makePerson(displayname='foobar 4'))

        # Remember the current values for checking later, and throw out
        # the cache.
        expected_nicks = dict(
            (person.id, list(person.ircnicknames)) for person in people)
        expected_emails = dict(
            (person.id, person.preferredemail) for person in people)
        Store.of(people[0]).invalidate()

        results = list(self.searchVocabulary(None, u'foobar'))
        with StormStatementRecorder() as recorder:
            self.assertEquals(4, len(results))
            for person in results:
                self.assertEqual(
                    expected_nicks[person.id], person.ircnicknames)
                self.assertEqual(
                    expected_emails[person.id], person.preferredemail)
        self.assertThat(recorder, HasQueryCount(Equals(0)))
Ejemplo n.º 6
0
 def _remove_permission(permission):
     if permission is None:
         # The permission has already been removed, so there's nothing more
         # to do here.
         return
     else:
         Store.of(permission).remove(permission)
    def test_implements_interface(self):
        # The implementation implements the interface correctly.
        dsd_comment = self.factory.makeDistroSeriesDifferenceComment()
        # Flush the store to ensure db constraints are triggered.
        Store.of(dsd_comment).flush()

        verifyObject(IDistroSeriesDifferenceComment, dsd_comment)
Ejemplo n.º 8
0
	def as_subsonic_child(self, user):
		info = {
			'id': str(self.id),
			'isDir': True,
			'title': self.name,
			'album': self.name,
			'created': self.created.isoformat()
		}
		if not self.root:
			info['parent'] = str(self.parent_id)
			info['artist'] = self.parent.name
		if self.has_cover_art:
			info['coverArt'] = str(self.id)

		starred = Store.of(self).get(StarredFolder, (user.id, self.id))
		if starred:
			info['starred'] = starred.date.isoformat()

		rating = Store.of(self).get(RatingFolder, (user.id, self.id))
		if rating:
			info['userRating'] = rating.rating
		avgRating = Store.of(self).find(RatingFolder, RatingFolder.rated_id == self.id).avg(RatingFolder.rating)
		if avgRating:
			info['averageRating'] = avgRating

		return info
Ejemplo n.º 9
0
    def _test_AnswerContactPruner(self, status, interval, expected_count=0):
        # Garbo should remove answer contacts for accounts with given 'status'
        # which was set more than 'interval' days ago.
        switch_dbuser('testadmin')
        store = IMasterStore(AnswerContact)

        person = self.factory.makePerson()
        person.addLanguage(getUtility(ILanguageSet)['en'])
        question = self.factory.makeQuestion()
        with person_logged_in(question.owner):
            question.target.addAnswerContact(person, person)
        Store.of(question).flush()
        self.assertEqual(
            store.find(
                AnswerContact,
                AnswerContact.person == person.id).count(),
                1)

        account = person.account
        account.status = status
        # We flush because a trigger sets the date_status_set and we need to
        # modify it ourselves.
        Store.of(account).flush()
        if interval is not None:
            account.date_status_set = interval

        self.runDaily()

        switch_dbuser('testadmin')
        self.assertEqual(
            store.find(
                AnswerContact,
                AnswerContact.person == person.id).count(),
                expected_count)
 def cleanUp(self):
     """See `IBuildFarmJob`."""
     # This class is not itself database-backed.  But it delegates to
     # one that is.  We can't call its SQLObject destroySelf method
     # though, because then the BuildQueue and the BranchJob would
     # both try to delete the attached Job.
     Store.of(self.context).remove(self.context)
 def test_unmask_right_message(self):
     # Unmasking picks the right message, and doesn't try to violate
     # the unique constraint on is_current_upstream.
     inactive = self.factory.makeSuggestion(self.pofile, self.potmsgset)
     remove_translations(ids=[self.ubuntu.id])
     Store.of(self.upstream).autoreload()
     self.assertTrue(self.upstream.is_current_ubuntu)
     self.assertFalse(inactive.is_current_ubuntu)
    def test_getForDifference(self):
        # The utility can get comments by id.
        dsd_comment = self.factory.makeDistroSeriesDifferenceComment()
        Store.of(dsd_comment).flush()

        self.assertEqual(
            dsd_comment, get_comment_source().getForDifference(
                dsd_comment.distro_series_difference, dsd_comment.id))
 def test_search_query_count(self):
     # Verify query count.
     Store.of(self.milestone).flush()
     with StormStatementRecorder() as recorder:
         list(self.bugtask_set.search(self.params))
     # 1 query for the tasks, 1 query for the product (target) eager
     # loading.
     self.assertThat(recorder, HasQueryCount(Equals(4)))
Ejemplo n.º 14
0
 def test_acquireRevisionAuthors(self):
     # AcquireRevisionAuthors creates new authors only if none exists with
     # that name.
     author1 = self.revision_set.acquireRevisionAuthors(['name1'])['name1']
     self.assertEqual(author1.name, 'name1')
     Store.of(author1).flush()
     author2 = self.revision_set.acquireRevisionAuthors(['name1'])['name1']
     self.assertEqual(
         removeSecurityProxy(author1).id, removeSecurityProxy(author2).id)
Ejemplo n.º 15
0
 def test_derivatives_email(self):
     # Make sure the package_derivatives_email column stores data
     # correctly.
     email = "*****@*****.**"
     distro = self.factory.makeDistribution()
     with person_logged_in(distro.owner):
         distro.package_derivatives_email = email
     Store.of(distro).flush()
     self.assertEqual(email, distro.package_derivatives_email)
 def test_search_query_count(self):
     # Verify query count.
     # 1. Query all the distroseries to determine the distro's
     #    currentseries.
     # 2. Query the bugtasks.
     Store.of(self.milestone).flush()
     with StormStatementRecorder() as recorder:
         list(self.bugtask_set.search(self.params))
     self.assertThat(recorder, HasQueryCount(Equals(4)))
 def test_product_affiliation_query_count(self):
     # Only 2 queries are expected, selects from:
     # - Product, Person
     person = self.factory.makePerson()
     product = self.factory.makeProduct(owner=person, name='pting')
     Store.of(product).invalidate()
     with StormStatementRecorder() as recorder:
         IHasAffiliation(product).getAffiliationBadges([person])
     self.assertThat(recorder, HasQueryCount(Equals(4)))
Ejemplo n.º 18
0
 def new(self, bug, datechanged, person, whatchanged,
         oldvalue=None, newvalue=None, message=None):
     """See IBugActivitySet."""
     activity = BugActivity(
         bug=bug, datechanged=datechanged, person=person,
         whatchanged=whatchanged, oldvalue=oldvalue, newvalue=newvalue,
         message=message)
     Store.of(activity).flush()
     return activity
Ejemplo n.º 19
0
 def test_deleteIncludesResult(self):
     """Ensure deleting CodeImport objects deletes associated results."""
     code_import_result = self.factory.makeCodeImportResult()
     code_import_result_id = code_import_result.id
     CodeImportSet().delete(code_import_result.code_import)
     # CodeImportResult.get should not raise anything.
     # But since it populates the object cache, we must invalidate it.
     Store.of(code_import_result).invalidate(code_import_result)
     self.assertRaises(
         SQLObjectNotFound, CodeImportResult.get, code_import_result_id)
 def createProductMilestone(
     self, milestone_name, product_name, date_expected):
     """Create a milestone in the trunk series of a product."""
     product_set = getUtility(IProductSet)
     product = product_set[product_name]
     series = product.getSeries('trunk')
     milestone = series.newMilestone(
         name=milestone_name, dateexpected=date_expected)
     Store.of(milestone).flush()
     return milestone
Ejemplo n.º 21
0
 def test_upload_log_url(self):
     # The url of the upload log file is determined by the PackageBuild.
     Store.of(self.package_build).flush()
     self.package_build.storeUploadLog("Some content")
     log_url = self.package_build.upload_log_url
     self.failUnlessEqual(
         'http://launchpad.dev/~joe/'
         '+archive/ppa/+recipebuild/%d/+files/upload_%d_log.txt' % (
             self.package_build.id, self.package_build.id),
         log_url)
 def test_distro_affiliation_query_count(self):
     # Only 2 business queries are expected, selects from:
     # - Distribution, Person
     # plus an additional query to create a PublisherConfig record.
     person = self.factory.makePerson()
     distro = self.factory.makeDistribution(owner=person, name='pting')
     Store.of(distro).invalidate()
     with StormStatementRecorder() as recorder:
         IHasAffiliation(distro).getAffiliationBadges([person])
     self.assertThat(recorder, HasQueryCount(Equals(3)))
Ejemplo n.º 23
0
 def linkBranch(self, branch, registrant):
     branch_link = self.getBranchLink(branch)
     if branch_link is not None:
         return branch_link
     branch_link = SpecificationBranch(
         specification=self, branch=branch, registrant=registrant)
     Store.of(self).flush()
     del get_property_cache(self).linked_branches
     notify(ObjectCreatedEvent(branch_link))
     return branch_link
Ejemplo n.º 24
0
    def __eq__(self, other):
        if type(self) is not type(other):
            return False

        from stoqlib.lib.environment import is_developer_mode
        if is_developer_mode():
            # Check this only in develper mode to get as many potential errors
            # as possible.
            assert Store.of(self) is Store.of(other)
        return self.id == other.id
    def test_permissions(self):
        # The branch scanner creates TranslationTemplatesBuilds.  It has
        # the database privileges it needs for that.
        branch = self.factory.makeBranch()
        switch_dbuser("branchscanner")
        build = getUtility(ITranslationTemplatesBuildSource).create(branch)

        # Writing the new objects to the database violates no access
        # restrictions.
        Store.of(build).flush()
 def test_new(self):
     # DistributionSourcePackageInDatabase.new() creates a new DSP, adds it
     # to the store, and updates the mapping cache.
     distribution = self.factory.makeDistribution()
     sourcepackagename = self.factory.makeSourcePackageName()
     dsp = DistributionSourcePackageInDatabase.new(
         distribution, sourcepackagename)
     self.assertIs(Store.of(distribution), Store.of(dsp))
     self.assertEqual(
         {(distribution.id, sourcepackagename.id): dsp.id},
         DistributionSourcePackageInDatabase._cache.items())
Ejemplo n.º 27
0
    def updateRevisionCacheForBranch(branch):
        """See `IRevisionSet`."""
        # Hand crafting the sql insert statement as storm doesn't handle the
        # INSERT INTO ... SELECT ... syntax.  Also there is no public api yet
        # for storm to get the select statement.

        # Remove the security proxy to get access to the ID columns.
        naked_branch = removeSecurityProxy(branch)

        insert_columns = ['Revision.id', 'revision_author', 'revision_date']
        subselect_clauses = []
        if branch.product is None:
            insert_columns.append('NULL')
            subselect_clauses.append('product IS NULL')
        else:
            insert_columns.append(str(naked_branch.productID))
            subselect_clauses.append('product = %s' % naked_branch.productID)

        if branch.distroseries is None:
            insert_columns.extend(['NULL', 'NULL'])
            subselect_clauses.extend(
                ['distroseries IS NULL', 'sourcepackagename IS NULL'])
        else:
            insert_columns.extend(
                [str(naked_branch.distroseriesID),
                 str(naked_branch.sourcepackagenameID)])
            subselect_clauses.extend(
                ['distroseries = %s' % naked_branch.distroseriesID,
                 'sourcepackagename = %s' % naked_branch.sourcepackagenameID])

        insert_columns.append(str(branch.private))
        if branch.private:
            subselect_clauses.append('private IS TRUE')
        else:
            subselect_clauses.append('private IS FALSE')

        insert_statement = """
            INSERT INTO RevisionCache
            (revision, revision_author, revision_date,
             product, distroseries, sourcepackagename, private)
            SELECT %(columns)s FROM Revision
            JOIN BranchRevision ON BranchRevision.revision = Revision.id
            WHERE Revision.revision_date > (
                CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - interval '30 days')
            AND BranchRevision.branch = %(branch_id)s
            AND Revision.id NOT IN (
                SELECT revision FROM RevisionCache
                WHERE %(subselect_where)s)
            """ % {
            'columns': ', '.join(insert_columns),
            'branch_id': branch.id,
            'subselect_where': ' AND '.join(subselect_clauses),
            }
        Store.of(branch).execute(insert_statement)
Ejemplo n.º 28
0
 def _remove_series_bugs_and_specifications(self, series):
     """Untarget the associated bugs and specifications."""
     for spec in series.all_specifications:
         # The logged in user may have no permission to see the spec, so
         # make use of removeSecurityProxy to force it.
         removeSecurityProxy(spec).proposeGoal(None, self.user)
     for bugtask in self._getBugtasks(series):
         # Bugtasks cannot be deleted directly. In this case, the bugtask
         # is already reported on the product, so the series bugtask has
         # no purpose without a series.
         Store.of(bugtask).remove(bugtask)
 def addNotificationRecipient(self, notification, person):
     # Manually insert BugNotificationRecipient for
     # construct_email_notifications to work.
     # Not sure why using SQLObject constructor doesn't work (it
     # tries to insert a row with only the ID which fails).
     Store.of(notification).execute("""
         INSERT INTO BugNotificationRecipient
           (bug_notification, person, reason_header, reason_body)
           VALUES (%s, %s, %s, %s)""" % sqlvalues(
                       notification, person,
                       u'reason header', u'reason body'))
Ejemplo n.º 30
0
    def get_where_for_remote(self, local):
        """Generate a column comparison expression for reference properties.

        The returned expression may be used to find objects of the I{remote}
        type referring to C{local}.
        """
        local_variables = self.get_local_variables(local)
        for variable in local_variables:
            if not variable.is_defined():
                Store.of(local).flush()
                break
        return compare_columns(self.remote_key, local_variables)
Ejemplo n.º 31
0
 def test_bug_activity_query_count(self):
     # Bug:+activity doesn't make O(n) queries based on the amount of
     # activity.
     bug = self.factory.makeBug()
     ten_minutes_ago = datetime.now(pytz.UTC) - timedelta(minutes=10)
     with person_logged_in(bug.owner):
         attachment = self.factory.makeBugAttachment(bug=bug)
         for i in range(10):
             bug.addChange(
                 BugAttachmentChange(ten_minutes_ago,
                                     self.factory.makePerson(),
                                     'attachment', None, attachment))
     Store.of(bug).invalidate()
     with StormStatementRecorder() as recorder:
         view = create_initialized_view(bug.default_bugtask,
                                        name='+activity')
         view.render()
     self.assertThat(recorder, HasQueryCount(Equals(7)))
Ejemplo n.º 32
0
    def get_remote(self, local):
        """Return the remote object for this relation, using the local cache.

        If the object in the cache is invalidated, we validate it again to
        check if it's still in the database.
        """
        local_info = get_obj_info(local)
        try:
            obj = local_info[self]["remote"]
        except KeyError:
            return None
        remote_info = get_obj_info(obj)
        if remote_info.get("invalidated"):
            try:
                Store.of(obj)._validate_alive(remote_info)
            except LostObjectError:
                return None
        return obj
Ejemplo n.º 33
0
 def __get__(self, local, cls=None):
     """
     Wrapper around C{Reference.__get__}.
     """
     store = Store.of(local)
     if store is None:
         return None
     _thread = store._deferredStore.thread
     return _thread.defer_to_thread(Reference.__get__, self, local, cls)
 def test_prejoins(self):
     # The properties BinaryPackageRelease.build and
     # and BinaryPackageRelease.binarypackagename of the
     # the result objects are preloaded in the query
     # issued in DistroSeriesSourcePackageRelease.binaries.
     self.makeBinaryPackageRelease()
     # Both properties we want to check have been created
     # in makeBinaryPackageRelease() and are thus already
     # in Storm's cache. We must empty the cache, otherwise
     # accessing bp_release.build and
     # bp_release.binarypackagename will never cause an
     # SQL query to be issued.
     Store.of(self.distroarchseries).invalidate()
     [bp_release] = list(self.dssp_release.binaries)
     with StormStatementRecorder() as recorder:
         bp_release.build
         bp_release.binarypackagename
     self.assertThat(recorder, HasQueryCount(Equals(0)))
Ejemplo n.º 35
0
 def test_does_not_find_publication_outside_release_pocket(self):
     distroseries = self.factory.makeDistroSeries()
     spphs = dict(
         (pocket, self.makeSPPH(distroseries=distroseries, pocket=pocket))
         for pocket in PackagePublishingPocket.items)
     release_spph = spphs[PackagePublishingPocket.RELEASE]
     query = compose_sql_find_latest_source_package_releases(distroseries)
     self.assertContentEqual([self.getExpectedResultFor(release_spph)],
                             Store.of(distroseries).execute(query))
Ejemplo n.º 36
0
 def remove(self, submission, bug):
     """See `IHWSubmissionBugSet`."""
     store = Store.of(bug)
     link = store.find(
         HWSubmissionBug,
         And(HWSubmissionBug.bug == bug,
             HWSubmissionBug.submission == submission.id)).one()
     if link is not None:
         store.remove(link)
Ejemplo n.º 37
0
 def _deleteMilestone(self, milestone):
     """Delete a milestone and unlink related objects."""
     self._unsubscribe_structure(milestone)
     # We need to remove the milestone from every bug, even those the
     # current user can't see/change, otherwise we can't delete the
     # milestone, since it's still referenced.
     for bugtask in self._getBugtasks(milestone, ignore_privacy=True):
         nb = removeSecurityProxy(bugtask)
         if nb.conjoined_master is not None:
             Store.of(bugtask).remove(nb.conjoined_master)
         else:
             nb.milestone = None
     removeSecurityProxy(milestone.all_specifications).set(milestoneID=None)
     Store.of(milestone).find(
         SpecificationWorkItem,
         milestone_id=milestone.id).set(milestone_id=None)
     self._deleteRelease(milestone.product_release)
     milestone.destroySelf()
Ejemplo n.º 38
0
 def submissionsForBug(self, bug, user=None):
     """See `IHWSubmissionBugSet`."""
     store = Store.of(bug)
     result = store.find(
         HWSubmission, And(HWSubmissionBug.bug == bug,
                           HWSubmissionBug.submission == HWSubmission.id,
                           _userCanAccessSubmissionStormClause(user)))
     result.order_by(HWSubmission.submission_key)
     return result
    def _checkInvariant(self):
        """Check that our translations are in their original state.

        Tests in this test case don't work in the usual way, by making
        changes and then testing for them.  Instead they make changes by
        creating new messages, and then using `remove_translations` to
        undo those changes.

        We see that a removal worked correctly by verifying that the
        invariant is restored.
        """
        # First make sure we're not reading out of cache.
        Store.of(self.nl_pofile).flush()

        self.assertEqual(self._getContents(self.nl_pofile),
                         ["Dit bericht mag niet worden verwijderd."])
        self.assertEqual(self._getContents(self.de_pofile),
                         ["Diese Nachricht soll nicht erloescht werden."])
Ejemplo n.º 40
0
 def new(self,
         bug,
         datechanged,
         person,
         whatchanged,
         oldvalue=None,
         newvalue=None,
         message=None):
     """See IBugActivitySet."""
     activity = BugActivity(bug=bug,
                            datechanged=datechanged,
                            person=person,
                            whatchanged=whatchanged,
                            oldvalue=oldvalue,
                            newvalue=newvalue,
                            message=message)
     Store.of(activity).flush()
     return activity
Ejemplo n.º 41
0
 def _unqueueBuild(self):
     """Remove the build's queue and job."""
     store = Store.of(self)
     if self.buildqueue_record is not None:
         job = self.buildqueue_record.job
         store.remove(self.buildqueue_record)
         store.find(SourcePackageRecipeBuildJob,
                    SourcePackageRecipeBuildJob.build == self.id).remove()
         store.remove(job)
 def copyright(self, content):
     """See `ISourcePackageRelease`."""
     store = Store.of(self)
     store.flush()
     if content is not None:
         content = unicode(content)
     store.execute(
         "UPDATE sourcepackagerelease SET copyright=%s WHERE id=%s",
         (content, self.id))
Ejemplo n.º 43
0
 def _fetch_children_or_parents(self, join_cond, cond, user):
     from lp.blueprints.model.specificationsearch import (
         get_specification_privacy_filter)
     return list(Store.of(self).using(
         Specification,
         Join(SpecificationDependency, join_cond == self.id)).find(
         Specification,
         cond == Specification.id, *get_specification_privacy_filter(user)
         ).order_by(Specification.title))
Ejemplo n.º 44
0
 def test_finds_active_publication(self):
     distroseries = self.factory.makeDistroSeries()
     spphs = dict(
         (status, self.makeSPPH(distroseries=distroseries, status=status))
         for status in active_publishing_status)
     query = compose_sql_find_latest_source_package_releases(distroseries)
     self.assertContentEqual(
         [self.getExpectedResultFor(spph) for spph in spphs.itervalues()],
         Store.of(distroseries).execute(query))
Ejemplo n.º 45
0
 def find(self, *args, **kwargs):
     store = Store.of(self._local)
     if store is None:
         raise NoStoreError("Can't perform operation without a store")
     where = self._get_where_clause()
     result = store.find(self._target_cls, where, *args, **kwargs)
     if self._order_by is not None:
         result.order_by(*self._order_by)
     return result
Ejemplo n.º 46
0
 def test_does_not_find_grandparents_packages(self):
     dsp = self.makeDerivedDistroSeries()
     grandparent = self.factory.makeDistroSeriesParent(
         derived_series=dsp.parent_series)
     self.makeSPPH(distroseries=grandparent.parent_series)
     query = compose_sql_find_differences(dsp.derived_series,
                                          dsp.parent_series)
     self.assertContentEqual([],
                             Store.of(dsp.derived_series).execute(query))
Ejemplo n.º 47
0
 def clear(self, *args, **kwargs):
     set_kwargs = {}
     for remote_column in self._relation.remote_key:
         set_kwargs[remote_column.name] = None
     store = Store.of(self._local)
     if store is None:
         raise NoStoreError("Can't perform operation without a store")
     where = self._relation.get_where_for_remote(self._local)
     store.find(self._target_cls, where, *args, **kwargs).set(**set_kwargs)
Ejemplo n.º 48
0
 def getArchive(self, distribution, purpose):
     """Get an existing `Archive`, or create one."""
     archive = Store.of(distribution).find(
         Archive, Archive.distribution == distribution,
         Archive.purpose == purpose).any()
     if archive is not None:
         return archive
     return self.factory.makeArchive(distribution=distribution,
                                     purpose=purpose)
Ejemplo n.º 49
0
 def remove(self, remote):
     store = Store.of(self._local)
     if store is None:
         raise NoStoreError("Can't perform operation without a store")
     # Don't use remote here, as it might be security proxied or something.
     remote = get_obj_info(remote).get_obj()
     where = (self._relation1.get_where_for_remote(self._local)
              & self._relation2.get_where_for_remote(remote))
     store.find(self._link_cls, where).remove()
Ejemplo n.º 50
0
 def all_blocked(self, user=None):
     """See `ISpecification`."""
     return list(
         Store.of(self).with_(
             SQL(recursive_blocked_query(user), params=(self.id, ))).find(
                 Specification,
                 Specification.id != self.id,
                 Specification.id.is_in(SQL('select id from blocked')),
             ).order_by(Specification.name, Specification.id))
Ejemplo n.º 51
0
    def last_lap(self):
        if hasattr(self, '_last_lap') and self._last_lap != -1:
            return self._last_lap

        store = Store.of(self)
        query = (RacerLap.racer_id == self.id)
        self._last_lap = store.find(RacerLap, query).order_by(
            RacerLap.event_time).last()
        return self._last_lap
Ejemplo n.º 52
0
    def updateWorkItems(self, new_work_items):
        """See ISpecification."""
        # First mark work items with titles that are no longer present as
        # deleted.
        self._deleteWorkItemsNotMatching(
            [wi['title'] for wi in new_work_items])
        work_items = self._work_items
        # At this point the list of new_work_items is necessarily the same
        # size (or longer) than the list of existing ones, so we can just
        # iterate over it updating the existing items and creating any new
        # ones.
        to_insert = []
        existing_titles = [wi.title for wi in work_items]
        existing_title_count = self._list_to_dict_of_frequency(existing_titles)

        for i, new_wi in enumerate(new_work_items):
            if (new_wi['title'] not in existing_titles or
                existing_title_count[new_wi['title']] == 0):
                to_insert.append((i, new_wi))
            else:
                existing_title_count[new_wi['title']] -= 1
                # Get an existing work item with the same title and update
                # it to match what we have now.
                existing_wi_index = existing_titles.index(new_wi['title'])
                existing_wi = work_items[existing_wi_index]
                # Mark a work item as dirty - don't use it again this update.
                existing_titles[existing_wi_index] = None
                # Update the sequence to match its current position on the
                # list entered by the user.
                existing_wi.sequence = i
                existing_wi.status = new_wi['status']
                existing_wi.assignee = new_wi['assignee']
                milestone = new_wi['milestone']
                if milestone is not None:
                    assert milestone.target == self.target, (
                        "%s does not belong to this spec's target (%s)" %
                            (milestone.displayname, self.target.name))
                existing_wi.milestone = milestone

        for sequence, item in to_insert:
            self.newWorkItem(item['title'], sequence, item['status'],
                             item['assignee'], item['milestone'])
        Store.of(self).flush()
        del get_property_cache(self).work_items
Ejemplo n.º 53
0
 def getNotifiedPersons(self, include_all=False):
     notified_persons = Store.of(self.bug).find(
         Person,
         BugNotification.id == BugNotificationRecipient.bug_notificationID,
         BugNotificationRecipient.personID == Person.id,
         BugNotification.bugID == self.bug.id)
     if include_all:
         return list(notified_persons)
     else:
         return set(notified_persons) - self.old_persons
Ejemplo n.º 54
0
 def test_does_not_find_publication_outside_primary_archive(self):
     distroseries = self.factory.makeDistroSeries()
     spphs = dict(
         (purpose,
          self.makeSPPH(distroseries=distroseries, archive_purpose=purpose))
         for purpose in ArchivePurpose.items)
     query = compose_sql_find_latest_source_package_releases(distroseries)
     self.assertContentEqual(
         [self.getExpectedResultFor(spphs[ArchivePurpose.PRIMARY])],
         Store.of(distroseries).execute(query))
Ejemplo n.º 55
0
 def test_finds_only_latest_publication_for_release(self):
     distroseries = self.factory.makeDistroSeries()
     spr = self.factory.makeSourcePackageRelease(distroseries=distroseries)
     spphs = [
         self.makeSPPH(distroseries=distroseries, sourcepackagerelease=spr)
         for counter in xrange(5)
     ]
     query = compose_sql_find_latest_source_package_releases(distroseries)
     self.assertContentEqual([self.getExpectedResultFor(spphs[-1])],
                             Store.of(distroseries).execute(query))
Ejemplo n.º 56
0
 def test_query_count(self):
     subscriber = self.factory.makePerson()
     for x in range(10):
         archive = self.factory.makeArchive(private=True)
         with person_logged_in(archive.owner):
             if x >= 5:
                 team = self.factory.makeTeam(members=[subscriber])
                 archive.newSubscription(team, archive.owner)
             else:
                 archive.newSubscription(subscriber, archive.owner)
     Store.of(subscriber).flush()
     Store.of(subscriber).invalidate()
     with person_logged_in(subscriber):
         with StormStatementRecorder() as recorder:
             view = create_initialized_view(subscriber,
                                            '+archivesubscriptions',
                                            principal=subscriber)
             view.render()
     self.assertThat(recorder, HasQueryCount(Equals(12)))
    def test_private_build_log_storage(self):
        # Builds in private archives should have their log uploaded to
        # the restricted librarian.

        # Go behind Storm's back since the field validator on
        # Archive.private prevents us from setting it to True with
        # existing published sources.
        Store.of(self.build).execute("""
            UPDATE archive SET private=True,buildd_secret='foo'
            WHERE archive.id = %s""" % self.build.archive.id)
        Store.of(self.build).invalidate()

        def got_update(ignored):
            # Librarian needs a commit.  :(
            self.layer.txn.commit()
            self.assertTrue(self.build.log.restricted)

        d = self.updateBuild(self.candidate, WaitingSlave('BuildStatus.OK'))
        return d.addCallback(got_update)
Ejemplo n.º 58
0
 def test_unmute_is_idempotent(self):
     # Unmuting works even if the user is not muted
     store = Store.of(self.filter)
     mutes = store.find(
         BugSubscriptionFilterMute,
         BugSubscriptionFilterMute.filter == self.filter.id,
         BugSubscriptionFilterMute.person == self.team_member.id)
     self.assertTrue(mutes.is_empty())
     self.filter.unmute(self.team_member)
     self.assertTrue(mutes.is_empty())
Ejemplo n.º 59
0
    def setUp(self):
        super(TestSourcePackageRecipeBuildUploads, self).setUp()

        self.setupBreezy()

        self.switchToAdmin()
        self.recipe = self.factory.makeSourcePackageRecipe()
        self.build = getUtility(ISourcePackageRecipeBuildSource).new(
            distroseries=self.breezy,
            recipe=self.recipe,
            archive=self.factory.makeArchive(distribution=self.ubuntu,
                                             owner=self.recipe.owner),
            requester=self.recipe.owner)
        Store.of(self.build).flush()
        self.switchToUploader()
        self.options.context = 'buildd'

        self.uploadprocessor = self.getUploadProcessor(self.layer.txn,
                                                       builds=True)
Ejemplo n.º 60
0
 def test_does_not_conflate_releases_of_different_packages(self):
     dsp = self.makeDerivedDistroSeries()
     distroseries = dsp.derived_series
     parent_spph = self.makeSPPH(distroseries=dsp.parent_series)
     derived_spph = self.makeSPPH(distroseries=distroseries)
     query = compose_sql_find_differences(distroseries, dsp.parent_series)
     self.assertEqual(2, Store.of(distroseries).execute(query).rowcount)
     self.assertContentEqual(
         [(
             parent_spph.sourcepackagerelease.sourcepackagenameID,
             None,
             parent_spph.sourcepackagerelease.version,
         ),
          (
              derived_spph.sourcepackagerelease.sourcepackagenameID,
              derived_spph.sourcepackagerelease.version,
              None,
          )],
         Store.of(distroseries).execute(query))