Exemplo n.º 1
0
    def test_az_image_tag_details(self):
        expected_url = f"https://{self.dummy_acr}.azurecr.io/acr/v1/{self.dummy_img}/_tags/{self.dummy_tag}"
        expected_credentials = (self.dummy_acr, self.dummy_passwd)
        dummy_response = self._tag_details_dummy_response()
        full_image_name = f"{self.dummy_acr}.azurecr.io/{self.dummy_img}:{self.dummy_tag}"

        response = mock({
            "status_code": 200,
            "text": dummy_response
        },
                        spec=requests.Response)

        when(os).getenv(f"ACR_PASSWD_{self.dummy_acr}").thenReturn(
            self.dummy_passwd)
        when(requests).get(ANY(), headers=ANY(),
                           auth=ANY()).thenReturn(response)

        did = azure_rest.DockerImageDetails.from_FQDIN(full_image_name)
        result = did.az_image_tag_details()

        self.assertIsNotNone(result)
        self.assertEqual(self.dummy_tag, result["name"])
        self.assertEqual("2020-05-05T10:11:44.1997799Z",
                         result["lastUpdateTime"])

        verify(requests, times=1).get(expected_url,
                                      headers=self.expected_headers,
                                      auth=expected_credentials)
        verify(os, times=1).getenv(f"ACR_PASSWD_{self.dummy_acr}")
    def test_validate_pipeline_for_valid_name(self):
        expected_url = conf.azure_org + self.dummy_project + \
                       "/_apis/build/definitions?api-version=5.1&name=" + self.dummy_pipeline_name
        with open(
                os.path.dirname(__file__) +
                "/../resources/pipeline_details.json", 'r') as f:
            dummy_response = f.read()

        response = mock({
            "status_code": 200,
            "text": dummy_response
        },
                        spec=requests.Response)
        when(requests).get(ANY(), headers=ANY(),
                           auth=ANY()).thenReturn(response)

        result = self.sut.validate()
        self.assertIsNotNone(result)
        self.assertEqual(91, result["id"])
        self.assertEqual("infra-docker-dummy", result["name"])

        verify(requests, times=1).get(expected_url,
                                      headers=self.expected_headers,
                                      auth=self.expected_credentials)
        verify(os, times=1).getenv("DEVOPS_PAT")
    def test_trigger_build_pipeline(self):
        dummy_pipeline_id = 42
        expected_url = conf.azure_org + self.dummy_project + "/_apis/build/builds?api-version=5.1"
        expected_data = "{\"definition\": {\"id\": " + str(
            dummy_pipeline_id) + "}}"

        with open(
                os.path.dirname(__file__) +
                "/../resources/pipeline_queue_result.json", 'r') as f:
            dummy_response = f.read()

        response = mock({
            "status_code": 200,
            "text": dummy_response
        },
                        spec=requests.Response)
        when(requests).post(ANY(), data=ANY(), headers=ANY(),
                            auth=ANY()).thenReturn(response)

        result = self.sut.trigger_build(dummy_pipeline_id)
        self.assertIsNotNone(result)
        self.assertEqual(26624, result["id"])
        self.assertEqual("notStarted", result["status"])
        self.assertEqual("20200512.1", result["buildNumber"])

        verify(requests, times=1).post(expected_url,
                                       data=expected_data,
                                       headers=self.expected_headers,
                                       auth=self.expected_credentials)
        verify(os, times=1).getenv("DEVOPS_PAT")
Exemplo n.º 4
0
    def test_call_wp_api(self):
        with open(
                os.path.dirname(__file__) +
                "/../resources/plugin_request.json", 'r') as f:
            dummy_request_body = f.read()
        with open(
                os.path.dirname(__file__) +
                "/../resources/plugin_request_encoded.txt", 'r') as f:
            dummy_request_body_enc = f.read()
        with open(
                os.path.dirname(__file__) +
                "/../resources/plugin_response.json", 'r') as f:
            dummy_response_body = f.read()
        response = mock({
            "status_code": 200,
            "text": dummy_response_body
        },
                        spec=requests.Response)
        dummy_request_json = json.loads(dummy_request_body)
        expected_url = "https://api.wordpress.org/plugins/update-check/1.1/"
        expected_data = f"plugins={dummy_request_body_enc}"
        expected_response = json.loads(dummy_response_body)
        when(requests).post(ANY(str), data=ANY(),
                            headers=ANY()).thenReturn(response)

        result = sut.call_wp_api(dummy_request_json)
        self.assertEqual(expected_response, result)

        verify(requests, times=1).post(expected_url,
                                       data=expected_data,
                                       headers={
                                           "content-type":
                                           "application/x-www-form-urlencoded",
                                           "user-agent": "curl/7.71.1"
                                       })
    def test_send_report(self):
        smtp_mock = mock(spec=smtplib.SMTP)
        when(smtplib).SMTP(ANY(), ANY()).thenReturn(smtp_mock)

        msg_captor = captor(ANY(EmailMessage))

        when(smtp_mock).login(ANY(), ANY())
        when(smtp_mock).send_message(msg_captor)
        when(smtp_mock).quit()

        with TemporaryDirectory("dummy-repo") as td:
            when(os).getenv(report_sender.ENV_MAIL_PASSWD).thenReturn(
                self.dummy_password)
            conf.report_target_dir = td + "/"
            copyfile(
                os.path.dirname(__file__) +
                "/../resources/report.html.expected", td + "/report.html")
            report_sender.send_report()

        verify(smtplib, times=1).SMTP(conf.report_smtp_server,
                                      conf.report_smtp_port)
        verify(smtp_mock, times=1).login(conf.report_smtp_user,
                                         self.dummy_password)
        verify(smtp_mock, times=1).send_message(...)
        verify(smtp_mock, times=1).quit()

        self.assertEqual(conf.report_sender, msg_captor.value["From"])
        self.assertEqual(conf.report_recipient, msg_captor.value["To"])
        self.assertIsNotNone(msg_captor.value.get_body())
    def test_catches_exceptions_to_not_break_other_listeners(self):
        when(logger).error(ANY()).thenReturn(None)
        listener = MailboxIndexerListener('INBOX', self.mail_store, mock())

        yield listener.notify_new()

        verify(logger).error(ANY())
Exemplo n.º 7
0
    def test_create_user_with_non_existing_referral(self):
        request = testing.DummyRequest()
        request.params['email'] = '*****@*****.**'
        test_uuid = str(uuid.uuid4())
        request.params['referral'] = test_uuid

        mock_referral = mock(Referral)
        mock_referral.num_referrals = 0
        mock_referral.user_id = 1
        request.dbsession = mock(sqlalchemy.orm.session.Session)
        mock_user = mock(User)
        mock_user.id = 1
        # TODO: take another look at mocking this constructor
        when(referral_program.models.user).User(
            email=ANY(str)).thenReturn(mock_user)
        when(request.dbsession).add(ANY(User))
        mock_referral_query = query.Query([])
        when(request.dbsession).query(Referral).thenReturn(mock_referral_query)
        err = IntegrityError('', params=None, orig=None)
        err.args = [
            '''(psycopg2.errors.ForeignKeyViolation) insert or update on table "referral" violates foreign key constraint "fk_referral_user_id_user"\nDETAIL:  Key (user_id)=(360) is not present in table "user".\n
        '''
        ]
        when(mock_referral_query).filter_by(id=ANY).thenRaise(err)

        view_being_tested = ReferralView(request)
        response = view_being_tested.create_user()
        self.assertEqual(response.status_code, 400)
    def _create_price_provider_mock(cls, tickers, fields,
                                    result) -> DataProvider:
        price_provider_mock = mock(strict=True)
        when(price_provider_mock).get_price(tickers, fields, ANY(datetime),
                                            ANY(datetime)).thenReturn(result)

        return price_provider_mock
Exemplo n.º 9
0
    def test_az_latest_tag(self):
        expected_url = f"https://{self.dummy_acr}.azurecr.io/acr/v1/{self.dummy_img}/_tags"
        expected_credentials = (self.dummy_acr, self.dummy_passwd)
        with open(
                os.path.dirname(__file__) + "/../resources/acr_tags.json",
                'r') as f:
            dummy_response = f.read()

        response = mock({
            "status_code": 200,
            "text": dummy_response
        },
                        spec=requests.Response)

        when(os).getenv(f"ACR_PASSWD_{self.dummy_acr}").thenReturn(
            self.dummy_passwd)
        when(requests).get(ANY(), headers=ANY(),
                           auth=ANY()).thenReturn(response)

        did = azure_rest.DockerImageDetails(self.dummy_acr, self.dummy_img)
        result = did.az_latest_tag()

        self.assertIsNotNone(result)
        self.assertEqual("20200505.4", result["name"])
        self.assertEqual("2020-05-05T10:11:44.1997799Z",
                         result["lastUpdateTime"])

        verify(requests, times=1).get(expected_url,
                                      headers=self.expected_headers,
                                      auth=expected_credentials)
        verify(os, times=1).getenv(f"ACR_PASSWD_{self.dummy_acr}")
Exemplo n.º 10
0
    def test_main(self):
        repos.to_check = self._dummy_repos()
        dummy_latest_version = "5.4.2"
        when(app).determine_latest_version().thenReturn(dummy_latest_version)
        when(app).process_repository(ANY(), ANY(), ANY()).thenReturn(0)

        app.main()

        verify(app, times=1).determine_latest_version()
        verify(app, times=3).process_repository(ANY(), ANY(), dummy_latest_version)
Exemplo n.º 11
0
    def test_update_wp_version(self):
        dummy_repo_writer = mock(repow.RepoWriter)
        when(repow).RepoWriter(ANY()).thenReturn(dummy_repo_writer)
        when(dummy_repo_writer).update_wp_version(ANY())

        sut.update_wp_version(self.dummy_repo_path, self.dummy_latest_version)

        verify(repow, times=1).RepoWriter(self.dummy_repo_path)
        verify(dummy_repo_writer,
               times=1).update_wp_version(self.dummy_latest_version)
Exemplo n.º 12
0
    def test_compare_and_update_no_update(self):
        when(sut).check_and_update_wp(ANY(), ANY()).thenReturn(False)
        when(sut).check_and_update_plugins(ANY()).thenReturn(False)
        when(repush).RepositoryPusher(ANY())

        self.assertFalse(sut.compare_and_update(self.dummy_repo_path, "42"))

        verify(sut, times=1).check_and_update_wp(self.dummy_repo_path,
                                                 self.dummy_latest_version)
        verify(sut, times=1).check_and_update_plugins(self.dummy_repo_path)
        verifyZeroInteractions(repush)
Exemplo n.º 13
0
    def test_process_repository(self):
        when(RepositoryFetcher).clone_or_update_repo().thenReturn(self.dummy_img_repo_path)
        when(RepositoryFetcher).cleanup()
        when(app).process_img_repo(ANY(), ANY(), ANY())

        result = app.process_repository(self.dummy_repo, "dummy_repo", self.dummy_latest_version)
        self.assertEqual(0, result)

        verify(RepositoryFetcher, times=1).clone_or_update_repo()
        verify(RepositoryFetcher, times=1).cleanup()
        verify(app, times=1).process_img_repo(self.dummy_repo, self.dummy_img_repo_path, self.dummy_latest_version)
    def test_validate_pipeline_for_invalid_name(self):
        expected_url = f"{conf.azure_org}{self.dummy_project}/_apis/build/definitions?api-version=5.1&name={self.dummy_pipeline_name}"
        dummy_result = "{\"count\":0,\"value\":[]}"
        response = mock({"status_code": 200, "text": dummy_result}, spec=requests.Response)
        when(requests).get(ANY(), headers=ANY(), auth=ANY()).thenReturn(response)

        result = self.sut.validate()
        self.assertIsNone(result)

        verify(requests, times=1).get(expected_url, headers=self.expected_headers, auth=self.expected_credentials)
        verify(os, times=1).getenv("DEVOPS_PAT")
    def test_send_mail(self):
        when(InputMail).from_dict(ANY()).thenReturn('inputmail')
        when(self.mail_sender).sendmail(ANY()).thenReturn(defer.Deferred())

        sent_deferred = self.mail_service.send_mail(mail_dict())

        verify(self.mail_sender).sendmail("inputmail")

        sent_deferred.callback('Assume sending mail succeeded')

        return sent_deferred
    def test_fetch_build_status_for_error(self):
        dummy_build_id = 36
        expected_request_invocations = 3
        expected_url = f"{conf.azure_org}{self.dummy_project}/_apis/build/builds/{dummy_build_id}?api-version=5.1"

        response = mock({"status_code": 500, "text": "TEST ERROR"}, spec=requests.Response)
        when(requests).get(ANY(), headers=ANY(), auth=ANY()).thenReturn(response)

        result = self.sut.fetch_build_status(dummy_build_id)
        self.assertIsNone(result)

        verify(requests, times=expected_request_invocations).get(expected_url, headers=self.expected_headers, auth=self.expected_credentials)
    def test_fetch_most_recent_build_for_connection_error(self):
        dummy_pipeline_id = 21
        expected_request_invocations = 3
        expected_url = f"{conf.azure_org}{self.dummy_project}/_apis/build/builds?api-version=5.1" \
                       f"&definitions={dummy_pipeline_id}&$top=1&queryOrder=queueTimeDescending"
        when(requests).get(ANY(), headers=ANY(), auth=ANY()).thenRaise(requests.exceptions.ConnectionError("TEST ERROR"))

        result = self.sut.fetch_most_recent_build(dummy_pipeline_id)
        self.assertIsNone(result)

        verify(requests, times=expected_request_invocations).get(expected_url, headers=self.expected_headers,
                                                                 auth=self.expected_credentials)
    def test_send_mail_does_not_delete_draft_on_error(self):
        when(InputMail).from_dict(ANY()).thenReturn('inputmail')

        deferred_failure = defer.fail(Exception("Assume sending mail failed"))
        when(self.mail_sender).sendmail(ANY()).thenReturn(deferred_failure)

        try:
            yield self.mail_service.send_mail({'ident': '12'})
            self.fail(
                "send_mail is expected to raise if underlying call fails")
        except:
            verify(self.mail_sender).sendmail("inputmail")
            verifyNoMoreInteractions(self.drafts)
    def test_validate(self):
        expected_url = f"{conf.azure_org_vs}{self.dummy_project}/_apis/release/definitions?api-version=5.1&searchText=Setup%20Wordpress%20DB"
        with open(os.path.dirname(__file__) + "/../resources/release_pipeline_list.json", 'r') as f:
            dummy_response = f.read()
        response = mock({"status_code": 200, "text": dummy_response}, spec=requests.Response)
        when(requests).get(ANY(), headers=ANY(), auth=ANY()).thenReturn(response)

        result = self.sut.validate()
        self.assertIsNotNone(result)
        self.assertEqual(68, result["id"])
        self.assertEqual(self.dummy_pipeline_name, result["name"])

        verify(requests, times=1).get(expected_url, headers=self.expected_headers, auth=self.expected_credentials)
        verify(os, times=1).getenv("DEVOPS_PAT")
Exemplo n.º 20
0
    def test_setup_job_handler(self, root_chain, child_chain):
        (when('plasma_cash.operator_cron_job.__main__.container').
         get_child_chain().thenReturn(child_chain))

        (when('plasma_cash.operator_cron_job.__main__.container').
         get_root_chain().thenReturn(root_chain))

        job_handler = spy(JobHandler())
        job_handler = setup_job_handler(job_handler)

        verify(job_handler).add_job(ANY(SubmitBlockJob),
                                    time_interval=SUBMIT_BLOCK_INTERVAL)
        verify(job_handler).add_job(ANY(ApplyDepositJob),
                                    time_interval=APPLY_DEPOSIT_INTERVAL)
    def test_should_not_process_login_if_already_logged_in(
            self, mock_logged_in, mock_redirect):
        mock_logged_in.return_value = True
        when(self.services_factory).is_logged_in(ANY()).thenReturn(True)
        mock_redirect.return_value = "mocked redirection"
        when(self.portal).login(ANY(), None, IResource).thenRaise(Exception())
        d = self.web.get(self.request)

        def assert_login_setup_service_for_user(_):
            verifyZeroInteractions(self.portal)
            mock_redirect.assert_called_once_with('/', self.request)

        d.addCallback(assert_login_setup_service_for_user)
        return d
Exemplo n.º 22
0
    def test_check_and_update_wp(self):
        dummy_repo_version = "21"
        when(RepoDetails).determine_imageversion(
            self.dummy_repo_path).thenReturn(dummy_repo_version)
        when(sut).update_wp_version(ANY(), ANY())

        result = sut.check_and_update_wp(self.dummy_repo_path,
                                         self.dummy_latest_version)
        self.assertTrue(result)

        verify(RepoDetails,
               times=1).determine_imageversion(self.dummy_repo_path)
        verify(sut, times=1).update_wp_version(self.dummy_repo_path,
                                               self.dummy_latest_version)
Exemplo n.º 23
0
    def test_check_and_update_plugins(self):
        dummy_plugin_json = {"plugin": "NARF"}
        dummy_request_body = {"request": "ZORT"}
        dummy_plugin_status = {"status": "POIT"}
        dummy_plugin_updated_json = {"plugin": "update"}
        when(wp_plugins).read_plugin_list(ANY()).thenReturn(dummy_plugin_json)
        when(wp_plugins).build_request_body(
            ANY()).thenReturn(dummy_request_body)
        when(wp_plugins).call_wp_api(ANY()).thenReturn(dummy_plugin_status)
        when(wp_plugins).is_update_plugins(ANY()).thenReturn(True)
        when(wp_plugins).update_plugin_list(
            ANY(), ANY()).thenReturn(dummy_plugin_updated_json)
        when(wp_plugins).write_plugin_list(ANY(), ANY())

        result = sut.check_and_update_plugins(self.dummy_repo_path)
        self.assertTrue(result)

        verify(wp_plugins, times=1).read_plugin_list(self.dummy_repo_path)
        verify(wp_plugins, times=1).build_request_body(dummy_plugin_json)
        verify(wp_plugins, times=1).call_wp_api(dummy_request_body)
        verify(wp_plugins, times=1).is_update_plugins(dummy_plugin_status)
        verify(wp_plugins, times=1).update_plugin_list(dummy_plugin_json,
                                                       dummy_plugin_status)
        verify(wp_plugins,
               times=1).write_plugin_list(self.dummy_repo_path,
                                          dummy_plugin_updated_json)
    def test_send_mail_removes_draft(self):
        mail = LeapMail('id', 'INBOX')
        when(mail).raw = 'raw mail'
        when(InputMail).from_dict(ANY()).thenReturn(mail)
        when(self.mail_store).delete_mail('12').thenReturn(defer.succeed(None))
        when(self.mail_store).add_mail('SENT', ANY()).thenReturn(mail)

        deferred_success = defer.succeed(None)
        when(self.mail_sender).sendmail(ANY()).thenReturn(deferred_success)

        yield self.mail_service.send_mail({'ident': '12'})

        verify(self.mail_sender).sendmail(mail)
        verify(self.mail_store).add_mail('SENT', mail.raw)
        verify(self.mail_store).delete_mail('12')
Exemplo n.º 25
0
    def test_call_wp_api_for_bad_response(self):
        dummy_request_body = {"dummy": "body"}
        response = mock(
            {
                "status_code": 500,
                "text": "TEST Error",
                "content": "TEST Error 500",
                "reason": "Internal Server Error"
            },
            spec=requests.Response)
        when(requests).post(ANY(str), data=ANY(),
                            headers=ANY()).thenReturn(response)

        with self.assertRaises(RuntimeError):
            sut.call_wp_api(dummy_request_body)
Exemplo n.º 26
0
    def test_compare_and_update_full_update(self):
        when(sut).check_and_update_wp(ANY(), ANY()).thenReturn(True)
        when(sut).check_and_update_plugins(ANY()).thenReturn(True)
        when(repush).RepositoryPusher(ANY()).thenReturn(self.dummy_repo_pusher)
        when(self.dummy_repo_pusher).commit_and_push(ANY())
        expected_commit_msg = f"auto-update wordpress: wp-version={True} | plugins={True}"

        self.assertTrue(sut.compare_and_update(self.dummy_repo_path, "42"))

        verify(sut, times=1).check_and_update_wp(self.dummy_repo_path,
                                                 self.dummy_latest_version)
        verify(sut, times=1).check_and_update_plugins(self.dummy_repo_path)
        verify(repush, times=1).RepositoryPusher(self.dummy_repo_path)
        verify(self.dummy_repo_pusher,
               times=1).commit_and_push(expected_commit_msg)
    def test_trigger_build_and_wait(self):
        dummy_pipeline_id = 42
        dummy_pipeline_details = {"id": dummy_pipeline_id}
        dummy_build_status = {"id": 36}
        dummy_result_status = "succeeded"
        when(self.sut).validate().thenReturn(dummy_pipeline_details)
        when(self.sut).trigger_build(ANY()).thenReturn(dummy_build_status)
        when(self.sut).wait_for_build_with_id(ANY(), ANY()).thenReturn(dummy_result_status)

        result = self.sut.trigger_build_and_wait()
        self.assertEqual(dummy_result_status, result)

        verify(self.sut, times=1).validate()
        verify(self.sut, times=1).trigger_build(dummy_pipeline_id)
        verify(self.sut, times=1).wait_for_build_with_id(36, {})
    def test_send_mail_marks_as_read(self):
        mail = InputMail()
        when(mail).raw = 'raw mail'
        when(InputMail).from_dict(ANY(), ANY()).thenReturn(mail)
        when(self.mail_store).delete_mail('12').thenReturn(defer.succeed(None))
        when(self.mail_sender).sendmail(mail).thenReturn(defer.succeed(None))

        sent_mail = LeapMail('id', 'INBOX')
        add_mail_deferral = defer.succeed(sent_mail)
        when(self.mail_store).add_mail('SENT', ANY()).thenReturn(add_mail_deferral)

        yield self.mail_service.send_mail({'ident': '12'})

        self.assertIn(Status.SEEN, sent_mail.flags)
        verify(self.mail_store).update_mail(sent_mail)
    def test_cleanup(self):
        expected_target_path = conf.workdir + self.dummy_name
        when(shutil).rmtree(ANY())

        self.sut.cleanup()

        verify(shutil, times=1).rmtree(expected_target_path)
Exemplo n.º 30
0
    def test_simpletextmsg_correctresponse(self):
        KNOWN_RESPONSE = "You'll get halp!"
        KNOWN_CHANNEL = "a_channel"
        # mock entire class

        bot = SupportBot()

        when(bot).post_message(channel=ANY(str), text=ANY(str))

        bot.try_support_response(KNOWN_CHANNEL, "halp")

        verify(bot, times=1).post_message(channel=KNOWN_CHANNEL,
                                          text=KNOWN_RESPONSE)

        # clean up
        unstub()