def setUp(self):
        super(TestHandleStatusMixin, self).setUp()
        self.factory = LaunchpadObjectFactory()
        self.build = self.makeBuild()
        # For the moment, we require a builder for the build so that
        # handleStatus_OK can get a reference to the slave.
        self.builder = self.factory.makeBuilder()
        self.build.buildqueue_record.markAsBuilding(self.builder)
        self.slave = WaitingSlave('BuildStatus.OK')
        self.slave.valid_file_hashes.append('test_file_hash')
        self.interactor = BuilderInteractor()
        self.behaviour = self.interactor.getBuildBehaviour(
            self.build.buildqueue_record, self.builder, self.slave)

        # We overwrite the buildmaster root to use a temp directory.
        tempdir = tempfile.mkdtemp()
        self.addCleanup(shutil.rmtree, tempdir)
        self.upload_root = tempdir
        tmp_builddmaster_root = """
        [builddmaster]
        root: %s
        """ % self.upload_root
        config.push('tmp_builddmaster_root', tmp_builddmaster_root)

        # We stub out our builds getUploaderCommand() method so
        # we can check whether it was called as well as
        # verifySuccessfulUpload().
        removeSecurityProxy(
            self.build).verifySuccessfulUpload = FakeMethod(result=True)
示例#2
0
 def setUp(self):
     login(ANONYMOUS)
     self._original_launch_bag = getUtility(ILaunchBag)
     self.factory = LaunchpadObjectFactory()
     self.launch_bag = self.installLaunchBag(
         user=self.factory.makePerson(), product=self.factory.makeProduct())
     self.popup = self.makeBranchPopup()
    def setUp(self):
        super(TestRemoveTranslations, self).setUp()
        # Acquire privileges to delete TranslationMessages.  That's not
        # something we normally do.  Actually we should test under
        # rosettaadmin, but that user does not have all the privileges
        # needed to set up this test.  A separate doctest
        # remove-translations-by.txt tests a realistic run of the
        # remove-translations-by.py script under the actual rosettaadmin
        # db user.
        switch_dbuser('postgres')

        # Set up a template with Dutch and German translations.  The
        # messages we set up here are invariant; they remain untouched
        # by deletions done in the test case.
        self.factory = LaunchpadObjectFactory()
        self.nl_pofile = self.factory.makePOFile('nl')
        self.potemplate = self.nl_pofile.potemplate
        self.de_pofile = self.factory.makePOFile('de',
                                                 potemplate=self.potemplate)

        self.nl_message, self.de_message = self._makeMessages(
            "This message is not to be deleted.",
            "Dit bericht mag niet worden verwijderd.",
            "Diese Nachricht soll nicht erloescht werden.")

        self.untranslated_message = self.factory.makePOTMsgSet(
            self.potemplate, 'This message is untranslated.', sequence=0)

        self._checkInvariant()
示例#4
0
def setGlobs(test, future=False):
    """Add the common globals for testing system documentation."""
    test.globs['ANONYMOUS'] = ANONYMOUS
    test.globs['login'] = login
    test.globs['login_person'] = login_person
    test.globs['logout'] = logout
    test.globs['ILaunchBag'] = ILaunchBag
    test.globs['getUtility'] = getUtility
    test.globs['transaction'] = transaction
    test.globs['flush_database_updates'] = flush_database_updates
    test.globs['create_view'] = create_view
    test.globs['create_initialized_view'] = create_initialized_view
    test.globs['factory'] = LaunchpadObjectFactory()
    test.globs['ordered_dict_as_string'] = ordered_dict_as_string
    test.globs['verifyObject'] = verifyObject
    test.globs['pretty'] = pprint.PrettyPrinter(width=1).pformat
    test.globs['stop'] = stop
    test.globs['launchpadlib_for'] = launchpadlib_for
    test.globs['launchpadlib_credentials_for'] = launchpadlib_credentials_for
    test.globs['oauth_access_token_for'] = oauth_access_token_for

    if future:
        import __future__
        for future_item in ('absolute_import', 'print_function',
                            'unicode_literals'):
            test.globs[future_item] = getattr(__future__, future_item)
 def test_checkForNewBuilders_detects_builder_only_once(self):
     # checkForNewBuilders() only detects a new builder once.
     builder_scanner = self._getScanner()
     self.assertEqual([], builder_scanner.checkForNewBuilders())
     LaunchpadObjectFactory().makeBuilder(name="sammy")
     self.assertEqual(["sammy"], builder_scanner.checkForNewBuilders())
     self.assertEqual([], builder_scanner.checkForNewBuilders())
示例#6
0
def set_service_usage(pillar_name, **kw):
    factory = LaunchpadObjectFactory()
    with celebrity_logged_in('admin'):
        pillar = getUtility(IPillarNameSet)[pillar_name]
        for attr, service_usage_name in kw.items():
            service_usage = getattr(ServiceUsage, service_usage_name)
            if attr == 'bug_tracking_usage':
                pillar.official_malone = (
                    service_usage == ServiceUsage.LAUNCHPAD)
                if service_usage == ServiceUsage.EXTERNAL:
                    pillar.bugtracker = factory.makeBugTracker()

            # if we're setting codehosting on product things get trickier.
            elif attr == 'codehosting_usage' and IProduct.providedBy(pillar):
                if service_usage == ServiceUsage.LAUNCHPAD:
                    branch = factory.makeProductBranch(product=pillar)
                    product_series = factory.makeProductSeries(product=pillar,
                                                               branch=branch)
                    pillar.development_focus = product_series
                elif service_usage == ServiceUsage.EXTERNAL:
                    branch = factory.makeProductBranch(
                        product=pillar, branch_type=BranchType.MIRRORED)
                    product_series = factory.makeProductSeries(product=pillar,
                                                               branch=branch)
                    pillar.development_focus = product_series
                elif service_usage == ServiceUsage.UNKNOWN:
                    branch = factory.makeProductBranch(product=pillar)
                    product_series = factory.makeProductSeries(product=pillar)
                    pillar.development_focus = product_series
            else:
                setattr(pillar, attr, service_usage)
示例#7
0
def example(request, data):
    # This is a test fixture.  You will want to write your own, and
    # delete this one.  See the parallel
    # standard_yuixhr_test_template.js to see how to call fixtures
    # from your Javascript tests.
    #
    # A test fixture prepares the application for your test.  You can
    # do whatever you need here, including creating objects with an
    # object factory and logging the browser in as a given user.
    # You'll see an example below.
    #
    # Test fixtures can also return information back to your test.
    # Simply stuff the information you want into the "data" dict.  It
    # will be converted into JSON and sent back to the Javascript
    # caller.  Even Launchpad objects are converted, using the
    # standard lazr.restful mechanism.  This can be useful in several
    # ways.  Here are three examples.
    #
    # First, you can communicate information about the objects you
    # have created in the setup so that the Javascript knows what URLs
    # to use.  The code in this function has an example of this,
    # below.
    #
    # Second, you can return information about verifying some aspect
    # of the database state, so your Javascript test can easily assert
    # some fact that is not usually easily exposed to it.
    #
    # Finally, you can stash information that your teardown might
    # need.  You shouldn't usually need to clean anything up, because
    # the database and librarian are reset after every test, but if
    # you do set something up that needs an explicit teardown, you can
    # stash JSON-serializable information in "data" that the teardown
    # can use to know what to clean up.
    #
    # You can compose these setups and teardowns as well, using .extend.
    # There is a small example of this as well, below.
    #
    # As a full example, we will create an administrator and another
    # person; we will have the administrator create an object; we will
    # log the browser in as the other person; and we will stash
    # information about the object and the two people in the data
    # object.
    #
    # Again, this is a semi-random example.  Rip this whole fixture
    # out, and write the ones that you need.
    factory = LaunchpadObjectFactory()
    data['admin'] = factory.makeAdministrator()
    data['user'] = factory.makePerson()
    with person_logged_in(data['admin']):
        data['product'] = factory.makeProduct(owner=data['admin'])
    # This logs the browser in as a given person.  You need to use
    # this function for that purpose--the standard lp.testing login
    # functions are insufficient.
    login_as_person(data['user'])
    # Now we've done everything we said we would.  Let's imagine that
    # we had to also write some file to disk that would need to be
    # cleaned up at the end of the test.  We might stash information
    # about that in "data" too.
    data['some random data we might need for cleaning up'] = 'rutebega'
示例#8
0
def create_ppa(distribution, person, name):
    """Create a PPA for `person`."""
    ppa = LaunchpadObjectFactory().makeArchive(
        distribution=distribution, owner=person, name=name, virtualized=False,
        description="Automatically created test PPA.")
    ppa.external_dependencies = (
        "deb http://archive.ubuntu.com/ubuntu %(series)s "
        "main restricted universe multiverse\n")
 def setUp(self):
     """Set up context to test in."""
     super(TestGetGuessedPOFile, self).setUp()
     self.queue = getUtility(ITranslationImportQueue)
     self.factory = LaunchpadObjectFactory()
     self.distribution = self.factory.makeDistribution('boohoo')
     self.distroseries = self.factory.makeDistroSeries(self.distribution)
     self.uploaderperson = self.factory.makePerson()
示例#10
0
 def test_scan_with_nothing_to_dispatch(self):
     factory = LaunchpadObjectFactory()
     builder = factory.makeBuilder()
     self.patch(BuilderSlave, 'makeBuilderSlave', FakeMethod(OkSlave()))
     transaction.commit()
     scanner = self._getScanner(builder_name=builder.name)
     d = scanner.scan()
     return d.addCallback(self._checkNoDispatch, builder)
示例#11
0
 def setUp(self):
     BzrTestCase.setUp(self)
     login('*****@*****.**')
     self.factory = LaunchpadObjectFactory()
     nuke_codeimport_sample_data()
     self.repo_path = tempfile.mkdtemp()
     self.disable_directory_isolation()
     self.addCleanup(shutil.rmtree, self.repo_path)
     self.foreign_commit_count = 0
示例#12
0
    def create_test_product(self):
        """Create a test product with `LaunchpadObjectFactory`.

        Returns the new object's name.
        """
        factory = LaunchpadObjectFactory()
        product = factory.makeProduct(official_malone=True)
        transaction.commit()
        return product.name
示例#13
0
def setUpGlobs(test):
    test.globs['transaction'] = transaction
    test.globs['http'] = UnstickyCookieHTTPCaller()
    test.globs['webservice'] = LaunchpadWebServiceCaller(
        'launchpad-library', 'salgado-change-anything')
    test.globs['public_webservice'] = LaunchpadWebServiceCaller(
        'foobar123451432', 'salgado-read-nonprivate')
    test.globs['user_webservice'] = LaunchpadWebServiceCaller(
        'launchpad-library', 'nopriv-read-nonprivate')
    test.globs['anon_webservice'] = LaunchpadWebServiceCaller(
        'launchpad-library', '')
    test.globs['setupBrowser'] = setupBrowser
    test.globs['setupDTCBrowser'] = setupDTCBrowser
    test.globs['setupRosettaExpertBrowser'] = setupRosettaExpertBrowser
    test.globs['browser'] = setupBrowser()
    test.globs['anon_browser'] = setupBrowser()
    test.globs['user_browser'] = setupBrowser(
        auth="Basic [email protected]:test")
    test.globs['admin_browser'] = setupBrowser(
        auth="Basic [email protected]:test")

    test.globs['ANONYMOUS'] = ANONYMOUS
    # If a unicode URL is opened by the test browswer, later navigation
    # raises ValueError exceptions in /usr/lib/python2.4/Cookie.py
    test.globs['canonical_url'] = safe_canonical_url
    test.globs['factory'] = LaunchpadObjectFactory()
    test.globs['find_tag_by_id'] = find_tag_by_id
    test.globs['first_tag_by_class'] = first_tag_by_class
    test.globs['find_tags_by_class'] = find_tags_by_class
    test.globs['find_portlet'] = find_portlet
    test.globs['find_main_content'] = find_main_content
    test.globs['print_feedback_messages'] = print_feedback_messages
    test.globs['print_table'] = print_table
    test.globs['extract_link_from_tag'] = extract_link_from_tag
    test.globs['extract_text'] = extract_text
    test.globs['launchpadlib_for'] = launchpadlib_for
    test.globs['login'] = login
    test.globs['login_person'] = login_person
    test.globs['logout'] = logout
    test.globs['parse_relationship_section'] = parse_relationship_section
    test.globs['pretty'] = pprint.PrettyPrinter(width=1).pformat
    test.globs['print_action_links'] = print_action_links
    test.globs['print_errors'] = print_errors
    test.globs['print_location'] = print_location
    test.globs['print_location_apps'] = print_location_apps
    test.globs['print_navigation_links'] = print_navigation_links
    test.globs['print_portlet_links'] = print_portlet_links
    test.globs['print_comments'] = print_comments
    test.globs['print_submit_buttons'] = print_submit_buttons
    test.globs['print_radio_button_field'] = print_radio_button_field
    test.globs['print_batch_header'] = print_batch_header
    test.globs['print_ppa_packages'] = print_ppa_packages
    test.globs['print_self_link_of_entries'] = print_self_link_of_entries
    test.globs['print_tag_with_id'] = print_tag_with_id
    test.globs['PageTestLayer'] = PageTestLayer
    test.globs['stop'] = stop
示例#14
0
def login_team(team, participation=None):
    """Login as a member of 'team'."""
    # Prevent import loop.
    from lp.testing.factory import LaunchpadObjectFactory
    if not team.is_team:
        raise ValueError("Got person, expected team: %r" % (team, ))
    login(ADMIN_EMAIL)
    person = LaunchpadObjectFactory().makePerson()
    team.addMember(person, person)
    login_person(person, participation=participation)
    return person
示例#15
0
def setupDTCBrowser():
    """Testbrowser configured for Distribution Translations Coordinators.

    Ubuntu is the configured distribution.
    """
    login('*****@*****.**')
    try:
        dtg_member = LaunchpadObjectFactory().makePerson(
            name='ubuntu-translations-coordinator', email="*****@*****.**")
    except NameAlreadyTaken:
        # We have already created the translations coordinator
        pass
    else:
        dtg = LaunchpadObjectFactory().makeTranslationGroup(
            name="ubuntu-translators",
            title="Ubuntu Translators",
            owner=dtg_member)
        ubuntu = getUtility(ILaunchpadCelebrities).ubuntu
        ubuntu.translationgroup = dtg
    logout()
    return setupBrowser(auth='Basic [email protected]:test')
示例#16
0
    def setUp(self):
        login('*****@*****.**')

        factory = LaunchpadObjectFactory()
        branches = [factory.makeAnyBranch() for count in range(5)]
        branch_ids = [branch.id for branch in branches]
        for branch in branches:
            factory.makeRevisionsForBranch(branch)
        # Retrieve the updated branches (due to transaction boundaries).
        branch_set = getUtility(IBranchLookup)
        self.branches = [branch_set.get(id) for id in branch_ids]
        self.revision_set = getUtility(IRevisionSet)
示例#17
0
def _get_locals():
    if len(sys.argv) > 1:
        dbuser = sys.argv[1]
    else:
        dbuser = None
    dbconfig.override(dbuser=dbuser)
    execute_zcml_for_scripts()
    readline.parse_and_bind('tab: complete')
    # Mimic the real interactive interpreter's loading of any
    # $PYTHONSTARTUP file.
    startup = os.environ.get('PYTHONSTARTUP')
    if startup:
        execfile(startup)
    store = IMasterStore(Person)

    if dbuser == 'launchpad':
        # Create a few variables "in case they come in handy."
        # Do we really use these?  Are they worth carrying around?
        d = Distribution.get(1)
        p = Person.get(1)
        ds = DistroSeries.get(1)
        prod = Product.get(1)
        proj = ProjectGroup.get(1)
        b2 = Bug.get(2)
        b1 = Bug.get(1)
        s = Specification.get(1)
        q = Question.get(1)
        # Silence unused name warnings
        d, p, ds, prod, proj, b2, b1, s, q

    # Having a factory instance is handy.
    factory = LaunchpadObjectFactory()

    def browser_open(obj, *args, **kwargs):
        """Open a (possibly newly-created) object's view in a web browser.

        Accepts the same parameters as canonical_url.

        Performs a commit before invoking the browser, so
        "browser_open(factory.makeFoo())" works.
        """
        transaction.commit()
        webbrowser.open(canonical_url(obj, *args, **kwargs))

    # Silence unused name warnings
    factory, store

    res = {}
    res.update(locals())
    res.update(globals())
    del res['_get_locals']
    return res
示例#18
0
    def test_checkForNewBuilders(self):
        # Test that checkForNewBuilders() detects a new builder

        # The basic case, where no builders are added.
        builder_scanner = self._getScanner()
        self.assertEqual([], builder_scanner.checkForNewBuilders())

        # Add two builders and ensure they're returned.
        new_builders = ["scooby", "lassie"]
        factory = LaunchpadObjectFactory()
        for builder_name in new_builders:
            factory.makeBuilder(name=builder_name)
        self.assertEqual(new_builders, builder_scanner.checkForNewBuilders())
示例#19
0
def sign_code_of_conduct(person, log):
    """Sign Ubuntu Code of Conduct for `person`, if necessary."""
    if person.is_ubuntu_coc_signer:
        # Already signed.
        return

    log.info("Signing Ubuntu code of conduct.")
    signedcocset = getUtility(ISignedCodeOfConductSet)
    person_id = person.id
    if signedcocset.searchByUser(person_id).count() == 0:
        fake_gpg_key = LaunchpadObjectFactory().makeGPGKey(person)
        Store.of(person).add(SignedCodeOfConduct(
            owner=person, signing_key_fingerprint=fake_gpg_key.fingerprint,
            signing_key_owner=fake_gpg_key.owner,
            signedcode="Normally a signed CoC would go here.", active=True))
示例#20
0
def setupRosettaExpertBrowser():
    """Testbrowser configured for Rosetta Experts."""

    login('*****@*****.**')
    try:
        rosetta_expert = LaunchpadObjectFactory().makePerson(
            name='rosetta-experts-member', email='*****@*****.**')
    except NameAlreadyTaken:
        # We have already created an Rosetta expert
        pass
    else:
        rosetta_experts_team = removeSecurityProxy(
            getUtility(ILaunchpadCelebrities).rosetta_experts)
        rosetta_experts_team.addMember(rosetta_expert,
                                       reviewer=rosetta_experts_team,
                                       status=TeamMembershipStatus.ADMIN)
    logout()
    return setupBrowser(auth='Basic [email protected]:test')
示例#21
0
def make_running_import(code_import=None,
                        machine=None,
                        date_started=None,
                        factory=None,
                        logtail=None):
    """Return a code import with a running job.

    :param code_import: The code import to create the job for.  If None, an
        anonymous CodeImport is created.
    :param machine: The `CodeImportMachine` to associate with the running
        job.  If None, an anonymous CodeImportMachine is created.
    :param date_started: If specified this overrides the UTC_NOW timestamp
        of the newly started job.
    :param factory: The LaunchpadObjectFactory to use for the creation of
        the objects.  If None, one is created.
    :param logtail: An optional string to put in the logtail field of the job.
    """
    if factory is None:
        factory = LaunchpadObjectFactory()
    if code_import is None:
        code_import = factory.makeCodeImport()
    if machine is None:
        machine = factory.makeCodeImportMachine(set_online=True)
    # The code import must be in a reviewed state.
    if code_import.review_status != CodeImportReviewStatus.REVIEWED:
        code_import.updateFromData(
            {'review_status': CodeImportReviewStatus.REVIEWED},
            code_import.registrant)

    CodeImportJobWorkflow().startJob(code_import.import_job, machine)
    if logtail:
        CodeImportJobWorkflow().updateHeartbeat(code_import.import_job,
                                                logtail)

    assert code_import.import_job.state == CodeImportJobState.RUNNING

    if date_started is not None:
        # Override the job date_started.
        naked_job = removeSecurityProxy(code_import.import_job)
        naked_job.date_started = date_started

    return code_import
示例#22
0
def extended_example(request, data):
    # We have declared a new fixture named "extended_example", but
    # instead of using "setup" we used the "extend" method of the
    # "example" fixture.  You can think of "example" wrapping
    # "extended_example".  During test setup, the "example" setup will
    # be called first.  Then this function, in "extended_example,"
    # will be called.  During test teardown, the "extended_example"
    # cleanups will be called first, followed by the "example"
    # cleanups.
    #
    # The "data" dict is the same one that was passed to the wrapping
    # fixture.  You can look at it, mutate it, or do what you need.
    # You are also responsible for not overwriting or mangling the
    # dict so that the wrapping fixtures data and/or teardown is
    # compromised.
    #
    # For this example, we will log in as the user and make something.
    factory = LaunchpadObjectFactory()
    with person_logged_in(data['user']):
        data['another_product'] = factory.makeProduct(owner=data['user'])
示例#23
0
def make_finished_import(code_import=None,
                         status=None,
                         date_finished=None,
                         factory=None):
    """Return a code import with a new finished job.

    :param code_import: The code import to create the job for.  If None, an
        anonymous CodeImport is created.
    :param status: The result status.  If not specified it is set to
        SUCCESSFUL.
    :param date_finished: If specified this overrides the date_last_successful
        attribute of the code_import if the state is SUCCESSFUL.
    :param factory: The LaunchpadObjectFactory to use for the creation of
        the objects.  If None, one is created.
    """
    if factory is None:
        factory = LaunchpadObjectFactory()
    if code_import is None:
        code_import = factory.makeCodeImport()
    if status is None:
        status = CodeImportResultStatus.SUCCESS
    # The code import must be in a reviewed state.
    if code_import.review_status != CodeImportReviewStatus.REVIEWED:
        code_import.updateFromData(
            {'review_status': CodeImportReviewStatus.REVIEWED},
            code_import.registrant)

    # If the job isn't running, make it run.
    if code_import.import_job.state != CodeImportJobState.RUNNING:
        machine = factory.makeCodeImportMachine(set_online=True)
        CodeImportJobWorkflow().startJob(code_import.import_job, machine)

    CodeImportJobWorkflow().finishJob(code_import.import_job, status, None)

    if date_finished is not None and status == CodeImportResultStatus.SUCCESS:
        # Override the code import date last successful.
        naked_import = removeSecurityProxy(code_import)
        naked_import.date_last_successful = date_finished

    return code_import
 def _makeHarry(self, email_address_status=None):
     factory = LaunchpadObjectFactory()
     return factory.makePerson(email='*****@*****.**',
                               name='harry',
                               email_address_status=email_address_status)
def branchMergeProposalSetUp(test):
    setUp(test, future=True)
    factory = LaunchpadObjectFactory()
    test.globs['target'] = ProxyFactory(
        factory.makeBranchMergeProposalForGit())
 def setUp(self):
     super(TestVerifySuccessfulBuildMixin, self).setUp()
     self.factory = LaunchpadObjectFactory()
"""Support for the lp.registry.javascript.milestoneoverlay YUIXHR tests.
"""

__metaclass__ = type
__all__ = []

from lp.services.webapp.publisher import canonical_url
from lp.testing import person_logged_in
from lp.testing.factory import LaunchpadObjectFactory
from lp.testing.yuixhr import (
    login_as_person,
    make_suite,
    setup,
)

factory = LaunchpadObjectFactory()


@setup
def setup(request, data):
    owner = factory.makePerson()
    with person_logged_in(owner):
        product = factory.makeProduct(name="my-test-project", owner=owner)
        product_series = factory.makeProductSeries(name="new-series",
                                                   product=product)
        data['product'] = product
        data['series_uri'] = canonical_url(product_series,
                                           path_only_if_possible=True)
        data['milestone_form_uri'] = (canonical_url(product_series) +
                                      '/+addmilestone/++form++')
    login_as_person(owner)
示例#28
0
 def setUp(self):
     self._factory = LaunchpadObjectFactory()
示例#29
0
 def setUp(self):
     TestCase.setUp(self)
     login('*****@*****.**')
     self.factory = LaunchpadObjectFactory()
 def setUp(self):
     super(TestRemoveTranslationsOptionsHandling, self).setUp()
     self.factory = LaunchpadObjectFactory()