def testDrainContinuesOnFailure(self): my_region = 'us-central1' self.mocked_client.projects_locations_jobs.Update.Expect( request=self._DrainReq(JOB_1_ID, region=my_region), response=self.SampleJob(JOB_1_ID)) self.mocked_client.projects_locations_jobs.Update.Expect( request=self._DrainReq(JOB_2_ID, region=my_region), exception=http_error.MakeHttpError(404)) self.mocked_client.projects_locations_jobs.Update.Expect( request=self._DrainReq(JOB_3_ID, region=my_region), response=self.SampleJob(JOB_3_ID)) self.mocked_client.projects_locations_jobs.Update.Expect( request=self._DrainReq(JOB_4_ID, region=my_region), exception=http_error.MakeHttpError(403)) self.Run('beta dataflow jobs drain --region={0} {1} {2} {3} {4}'.format( my_region, JOB_1_ID, JOB_2_ID, JOB_3_ID, JOB_4_ID, normalize_space=True)) self.AssertErrEquals("""\ Started draining job [{0}] Failed to drain job [{1}]: Resource not found. Please ensure you have \ permission to access the job and the `--region` flag, {4}, matches the job\'s \ region. Started draining job [{2}] Failed to drain job [{3}]: Permission denied. Please ensure you have \ permission to access the job and the `--region` flag, {4}, matches the job\'s \ region. """.format( JOB_1_ID, JOB_2_ID, JOB_3_ID, JOB_4_ID, my_region, normalize_space=True))
def testRaisesErrorWhenAllUpdatesFailed(self): self.kms.projects_locations_keyRings_cryptoKeys.Get.Expect( self.messages. CloudkmsProjectsLocationsKeyRingsCryptoKeysGetRequest( name=self.key_name.RelativeName()), self.messages.CryptoKey(name=self.key_name.RelativeName())) self.kms.projects_locations_keyRings_cryptoKeys.UpdatePrimaryVersion.Expect( self.messages. CloudkmsProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersionRequest( name=self.key_name.RelativeName(), updateCryptoKeyPrimaryVersionRequest=( self.messages.UpdateCryptoKeyPrimaryVersionRequest( cryptoKeyVersionId='10'))), exception=http_error.MakeHttpError()) self.kms.projects_locations_keyRings_cryptoKeys.Patch.Expect( self.messages. CloudkmsProjectsLocationsKeyRingsCryptoKeysPatchRequest( name=self.key_name.RelativeName(), cryptoKey=self.messages.CryptoKey(rotationPeriod='864000s'), updateMask='rotationPeriod'), exception=http_error.MakeHttpError()) with self.AssertRaisesExceptionMatches( exceptions.ToolException, 'An Error occurred: Failed to update field \'primaryVersion\'. ' 'Failed to update field(s) \'rotationPeriod\'.'): self.Run( 'kms keys update --rotation-period=10d ' '--location={0} --keyring={1} {2} --primary-version=10'.format( self.version_name.location_id, self.version_name.key_ring_id, self.version_name.crypto_key_id))
def testBucketNotExist(self): self.client.objects.List.Expect( self.messages.StorageObjectsListRequest(bucket='bucket3'), exception=http_error.MakeHttpError(code=404)) self.assertEqual(self.expander.Exists('gs://bucket3'), False) self.client.objects.List.Expect( self.messages.StorageObjectsListRequest(bucket='bucket3'), exception=http_error.MakeHttpError(code=404)) self.assertEqual(self.expander.IsDir('gs://bucket3'), False)
def testBatch_SingleError(self): requests = [ (self.client.instances, 'Get', self.messages.ComputeInstancesGetRequest(instance='instance=X', zone='zone-X', project='project-X')) ] instance_ref = resources.REGISTRY.Create('compute.instances', project='mickey', zone='disney', instance='Super-Cheese') http_err = http_error.MakeHttpError(code=404, url=instance_ref.SelfLink()) errors_to_collect = [] responses = [ Payload(response='Some response', is_error=True, exception=http_err) ] with mock.patch.object(batch.BatchApiRequest, 'Execute', return_value=responses): result = self.adapter.BatchRequests(requests, errors_to_collect) self.assertEqual(['Some response'], result) self.assertEqual(len(requests), len(responses)) self.assertEqual([api_exceptions.HttpException(http_err)], errors_to_collect)
def testGetCmekSettingsNoPerms(self): self.mock_client_v2.organizations.GetCmekSettings.Expect( self.msgs.LoggingOrganizationsGetCmekSettingsRequest( name='organizations/123'), exception=http_error.MakeHttpError(403)) self.RunWithoutPerms( 'cmek-settings describe --organization=organizations/123')
def testGetNoPerms(self): self.mock_client_v2.projects_locations.Get.Expect( self.msgs.LoggingProjectsLocationsGetRequest( name='projects/my-project/locations/my-location'), exception=http_error.MakeHttpError(403)) self.RunWithoutPerms('locations describe my-location', calliope_base.ReleaseTrack.ALPHA)
def testHttpException400FormatAll(self): err = http_error.MakeHttpError(400) exc = exceptions.HttpException(err, self._ERROR_FORMAT_ALL) expected = """\ api_name: <> api_version: <> content: <debugInfo: mock-debug-info error: code: '400' errors: - domain: global message: Invalid request. reason: Invalid request API reason. message: Invalid request. location: mock-location status: INVALID_ARGUMENT> error_info: <code: '400' errors: - domain: global message: Invalid request. reason: Invalid request API reason. message: Invalid request.> instance_name: <> message: <Invalid request API reason: Invalid request.> resource_name: <> status_code: <400> status_description: <Invalid request API reason.> status_message: <Invalid request.> url: <> """ actual = str(exc) self.assertEqual(expected, actual)
def testHttpExceptionErrorFormatAttributesDebugVerbosityDefaultLine(self): log.SetVerbosity(logging.DEBUG) err = http_error.MakeHttpError( 400, url='https://mock.googleapis.com/v1/projects/your-stuff/junk/mine', content={ 'stuff': [ "We're in a tight spot.", "You're gonna need a bigger boat.", ], 'debugInfo': { 'stackTrace': [ 'file-1:line-1: call-1', 'file-2:line-2: call-2', ], 'message': [ 'Memory fault: core dumped', ], }, }, ) exc = exceptions.HttpException( err, 'Error [{status_code}] {status_message}{url?\n{?}}{.stuff?\n{?}}') self.assertEqual("""\ Error [400] Invalid request. https://mock.googleapis.com/v1/projects/your-stuff/junk/mine - We're in a tight spot. - You're gonna need a bigger boat.""", exc.message)
def testDeny_RemoveValues_NoExistingPolicy_ThrowsError(self): get_exception = http_error.MakeHttpError(code=404, message='Not found.') self.ExpectGetPolicyWithException(get_exception) with self.AssertRaisesHttpExceptionMatches('Not found.'): self.RunDenyCommand(self.VALUE_A, self.REMOVE_FLAG)
def testHttpException504(self): err = http_error.MakeHttpError(504) exc = exceptions.HttpException(err, self._ERROR_FORMAT_ALL) expected = """\ content: <debugInfo: mock-debug-info error: code: '504' errors: - domain: global message: Deadline exceeded. reason: Deadline exceeded API reason. message: Deadline exceeded. location: mock-location status: DEADLINE_EXCEEDED> error_info: <code: '504' errors: - domain: global message: Deadline exceeded. reason: Deadline exceeded API reason. message: Deadline exceeded.> instance_name: <> message: <Deadline exceeded API reason: Deadline exceeded.> resource_name: <> status_code: <504> status_description: <Deadline exceeded API reason.> status_message: <Deadline exceeded.> url: <> """ actual = str(exc) self.assertMultiLineEqual(expected, actual)
def testHttpException500(self): err = http_error.MakeHttpError(500) exc = exceptions.HttpException(err, self._ERROR_FORMAT_ALL) expected = """\ content: <debugInfo: mock-debug-info error: code: '500' errors: - domain: global message: Internal server error. reason: Internal server error API reason. message: Internal server error. location: mock-location status: INTERNAL_SERVER_ERROR> error_info: <code: '500' errors: - domain: global message: Internal server error. reason: Internal server error API reason. message: Internal server error.> instance_name: <> message: <Internal server error API reason: Internal server error.> resource_name: <> status_code: <500> status_description: <Internal server error API reason.> status_message: <Internal server error.> url: <> """ actual = str(exc) self.assertMultiLineEqual(expected, actual)
def testHttpException409(self): err = http_error.MakeHttpError(409) exc = exceptions.HttpException(err, self._ERROR_FORMAT_ALL) expected = """\ content: <debugInfo: mock-debug-info error: code: '409' errors: - domain: global message: Resource already exists. reason: Resource already exists API reason. message: Resource already exists. location: mock-location status: ALREADY_EXISTS> error_info: <code: '409' errors: - domain: global message: Resource already exists. reason: Resource already exists API reason. message: Resource already exists.> instance_name: <> message: <Resource already exists API reason: Resource already exists.> resource_name: <> status_code: <409> status_description: <Resource already exists API reason.> status_message: <Resource already exists.> url: <> """ actual = str(exc) self.assertMultiLineEqual(expected, actual)
def testHttpException404(self): err = http_error.MakeHttpError(404) exc = exceptions.HttpException(err, self._ERROR_FORMAT_ALL) expected = """\ content: <debugInfo: mock-debug-info error: code: '404' errors: - domain: global message: Resource not found. reason: Resource not found API reason. message: Resource not found. location: mock-location status: NOT_FOUND> error_info: <code: '404' errors: - domain: global message: Resource not found. reason: Resource not found API reason. message: Resource not found.> instance_name: <> message: <Resource not found API reason: Resource not found.> resource_name: <> status_code: <404> status_description: <Resource not found API reason.> status_message: <Resource not found.> url: <> """ actual = str(exc) self.assertMultiLineEqual(expected, actual)
def testDeploy_createAllArguments(self): full_service_account = 'projects/-/serviceAccounts/' + NEW_SERVICE_ACCOUNT workflow = self.messages.Workflow(sourceContents=NEW_SOURCE, description=NEW_DESCRIPTION, serviceAccount=full_service_account) source_path = self.Touch(self.temp_path, name='workflow.yaml', contents=NEW_SOURCE) workflow_name = self.GetWorkflowName(WORKFLOW_ID) self.ExpectGet(workflow_name, exception=http_error.MakeHttpError(code=404)) self.ExpectCreate(self.GetLocationName(), WORKFLOW_ID, workflow) self.MockOperationWait() self.ExpectGet(workflow_name, result=workflow) result = self.Run('workflows deploy {id} ' '--source={source} ' '--description={desc} ' '--service-account={sa}'.format( id=WORKFLOW_ID, source=source_path, desc=NEW_DESCRIPTION, sa=full_service_account)) self.assertEqual(result, workflow)
def testCreate_withNoApp_withRegion(self): # Set it up so that the app doesn't exist: err = http_error.MakeHttpError(code=404) self.ExpectGetApplicationRequest(self.Project(), exception=err) with self.assertRaises(create_util.AppEngineAppDoesNotExist): self.Run('datastore databases create --region=foo')
def testHttpException403(self): err = http_error.MakeHttpError(403) exc = exceptions.HttpException(err, self._ERROR_FORMAT_ALL) expected = """\ content: <debugInfo: mock-debug-info error: code: '403' errors: - domain: global message: Permission denied. reason: Permission denied API reason. message: Permission denied. location: mock-location status: PERMISSION_DENIED> error_info: <code: '403' errors: - domain: global message: Permission denied. reason: Permission denied API reason. message: Permission denied.> instance_name: <> message: <Permission denied API reason: Permission denied.> resource_name: <> status_code: <403> status_description: <Permission denied API reason.> status_message: <Permission denied.> url: <> """ actual = str(exc) self.assertMultiLineEqual(expected, actual)
def testGetIamPolicyFailure(self): with mock.patch.object(sourcerepo.Source, 'GetIamPolicy', autospec=True) as source_mock: source_mock.side_effect = http_error.MakeHttpError(code=400) with self.assertRaises(c_exc.HttpException): self.RunSourceRepos(['get-iam-policy', 'some_name'])
def testHttpException666(self): err = http_error.MakeHttpError(666) exc = exceptions.HttpException(err, self._ERROR_FORMAT_ALL) expected = """\ content: <debugInfo: mock-debug-info error: code: '666' errors: - domain: global message: '' reason: '' message: '' location: mock-location status: ''> error_info: <code: '666' errors: - domain: global message: '' reason: '' message: ''> instance_name: <> message: <HTTPError 666> resource_name: <> status_code: <666> status_description: <> status_message: <> url: <> """ actual = str(exc) self.assertMultiLineEqual(expected, actual)
def SetUp(self): self.cloud_scheduler_client.projects_locations.List.Expect( self.cloud_scheduler_messages. CloudschedulerProjectsLocationsListRequest( name=self.project_resource_name, pageSize=2), exception=http_error.MakeHttpError(code=404)) self.StartObjectPatch(console_io, 'CanPrompt', return_value=True)
def testHttpException400WithMessageAndUrl(self): err = http_error.MakeHttpError( 400, 'Your bad.', url='https://www.mock.googleapis.com/mock/v1/projects/your-stuff') exc = exceptions.HttpException(err, self._ERROR_FORMAT_ALL) expected = """\ content: <debugInfo: mock-debug-info error: code: '400' errors: - domain: global message: Your bad. reason: Invalid request API reason. message: Your bad. location: mock-location status: INVALID_ARGUMENT> error_info: <code: '400' errors: - domain: global message: Your bad. reason: Invalid request API reason. message: Your bad.> instance_name: <your-stuff> message: <Invalid request API reason: Your bad.> resource_name: <projects> status_code: <400> status_description: <Invalid request API reason.> status_message: <Your bad.> url: <https://www.mock.googleapis.com/mock/v1/projects/your-stuff> """ actual = str(exc) self.assertMultiLineEqual(expected, actual)
def testHttpExceptionErrorFormatAttributesValueUnicode(self): err = http_error.MakeHttpError( 400, url='https://mock.googleapis.com/v1/projects/your-stuff/junk/mine', content={ 'stuff': [ 'Ṳᾔḯ¢◎ⅾℯ', ], 'debugInfo': { 'stackTrace': [ 'file-1:line-1: call-1', 'file-2:line-2: call-2', ], 'message': [ 'Memory fault: core dumped', ], }, }, ) exc = exceptions.HttpException( err, 'Error [{status_code}] {status_message}{url?\n{?}}{.stuff?\n{?}}') self.assertEqual('''\ Error [400] Invalid request. https://mock.googleapis.com/v1/projects/your-stuff/junk/mine - Ṳᾔḯ¢◎ⅾℯ''', exc.message)
def testHttpException403WithMessageAndUrl(self): err = http_error.MakeHttpError( 403, 'Your bad.', url='https://www-mock.googleapis.com/mock/v1/projects/your-stuff') exc = exceptions.HttpException(err, self._ERROR_FORMAT_ALL) expected = """\ content: <debugInfo: mock-debug-info error: code: '403' errors: - domain: global message: Your bad. reason: Permission denied API reason. message: Your bad. location: mock-location status: PERMISSION_DENIED> error_info: <code: '403' errors: - domain: global message: Your bad. reason: Permission denied API reason. message: Your bad.> instance_name: <your-stuff> message: <User [[email protected]] does not have permission to access projects instance [your-stuff] (or it may not exist): Your bad.> resource_name: <projects> status_code: <403> status_description: <Permission denied API reason.> status_message: <Your bad.> url: <https://www-mock.googleapis.com/mock/v1/projects/your-stuff> """ actual = str(exc) self.assertMultiLineEqual(expected, actual)
def testHttpExceptionDefaultErrorFormatDebugVerbosity(self): log.SetVerbosity(logging.DEBUG) err = http_error.MakeHttpError( 400, url='https://mock.googleapis.com/v1/projects/your-stuff/junk/mine', content={ 'stuff': [ "We're in a tight spot.", "You're gonna need a bigger boat.", ], 'debugInfo': { 'stackTrace': [ 'file-1:line-1: call-1', 'file-2:line-2: call-2', ], 'message': [ 'Memory fault: core dumped', ], }, }, ) exc = exceptions.HttpException(err) self.assertEqual("""\ Invalid request API reason: Invalid request. message: - 'Memory fault: core dumped' stackTrace: - 'file-1:line-1: call-1' - 'file-2:line-2: call-2'""", exc.message)
def testHttpException404WithMessageAndUrl(self): err = http_error.MakeHttpError( 404, 'Your bad.', url='https://www+mock.googleapis.com/v1/projects/your-stuff') exc = exceptions.HttpException(err, self._ERROR_FORMAT_ALL) expected = """\ content: <debugInfo: mock-debug-info error: code: '404' errors: - domain: global message: Your bad. reason: Resource not found API reason. message: Your bad. location: mock-location status: NOT_FOUND> error_info: <code: '404' errors: - domain: global message: Your bad. reason: Resource not found API reason. message: Your bad.> instance_name: <your-stuff> message: <Projects instance [your-stuff] not found: Your bad.> resource_name: <projects> status_code: <404> status_description: <Resource not found API reason.> status_message: <Your bad.> url: <https://www+mock.googleapis.com/v1/projects/your-stuff> """ actual = str(exc) self.assertMultiLineEqual(expected, actual)
def testMultipleTopicsDeletionWithOutput(self): topic_to_succeed = util.ParseTopic('topic1', self.Project()) self.svc.Expect( request=self.msgs.PubsubProjectsTopicsDeleteRequest( topic=topic_to_succeed.RelativeName()), response='') topic_to_fail = util.ParseTopic('not_there', self.Project()) self.svc.Expect( request=self.msgs.PubsubProjectsTopicsDeleteRequest( topic=topic_to_fail.RelativeName()), response='', exception=http_error.MakeHttpError(message='Topic does not exist.')) with self.AssertRaisesExceptionMatches( util.RequestsFailedError, 'Failed to delete the following: [not_there].'): self.Run('pubsub topics delete topic1 not_there' ' --format=csv[no-heading](name)') self.AssertErrContains( 'Deleted topic [{}].'.format(topic_to_succeed.RelativeName())) self.AssertErrContains( 'Failed to delete topic [{}]: Topic does not exist.' .format(topic_to_fail.RelativeName())) self.AssertErrContains( 'Failed to delete the following: [{}].'.format(topic_to_fail.Name()))
def testHttpException409WithMessageAndUrl(self): err = http_error.MakeHttpError( 409, 'Your bad.', url='https://mock.googleapis.com/v1/projects/your-stuff') exc = exceptions.HttpException(err, self._ERROR_FORMAT_ALL) expected = """\ content: <debugInfo: mock-debug-info error: code: '409' errors: - domain: global message: Your bad. reason: Resource already exists API reason. message: Your bad. location: mock-location status: ALREADY_EXISTS> error_info: <code: '409' errors: - domain: global message: Your bad. reason: Resource already exists API reason. message: Your bad.> instance_name: <your-stuff> message: <Resource in projects [your-stuff] is the subject of a conflict: Your bad.> resource_name: <projects> status_code: <409> status_description: <Resource already exists API reason.> status_message: <Your bad.> url: <https://mock.googleapis.com/v1/projects/your-stuff> """ actual = str(exc) self.assertMultiLineEqual(expected, actual)
def testUneleteNoPerms(self): self.mock_client_v2.projects_locations_buckets.Undelete.Expect( self.msgs.LoggingProjectsLocationsBucketsUndeleteRequest( name='projects/my-project/locations/global/buckets/porkpie'), exception=http_error.MakeHttpError(403)) self.RunWithoutPerms('buckets undelete porkpie --location=global -q', calliope_base.ReleaseTrack.ALPHA)
def testHttpException504WithMessageAndUrl(self): err = http_error.MakeHttpError( 504, 'Your bad.', url='https://mock.com/mocks/v1/projects/your-stuff') exc = exceptions.HttpException(err, self._ERROR_FORMAT_ALL) expected = """\ content: <debugInfo: mock-debug-info error: code: '504' errors: - domain: global message: Your bad. reason: Deadline exceeded API reason. message: Your bad. location: mock-location status: DEADLINE_EXCEEDED> error_info: <code: '504' errors: - domain: global message: Your bad. reason: Deadline exceeded API reason. message: Your bad.> instance_name: <your-stuff> message: <Deadline exceeded API reason: Your bad.> resource_name: <projects> status_code: <504> status_description: <Deadline exceeded API reason.> status_message: <Your bad.> url: <https://mock.com/mocks/v1/projects/your-stuff> """ actual = str(exc) self.assertMultiLineEqual(expected, actual)
def testSuccessfulDeleteMultipleWithSingleFastFailure_synchronous(self): self.WriteInput('y\n') deletions = [ _Deletion(self.TEST_PROJECT, self.TEST_LOCATION, self.TEST_ENVIRONMENT_ID, self.TEST_OPERATION_UUID, deletion_exception=http_error.MakeHttpError( code=404, message='NOT_FOUND')), _Deletion(self.TEST_PROJECT, self.TEST_LOCATION, self.TEST_ENVIRONMENT_ID2, self.TEST_OPERATION_UUID2) ] self._ExpectMultipleDeletionCalls(deletions) with self.AssertRaisesExceptionMatches( command_util.Error, 'Some requested deletions did not succeed.'): self.RunEnvironments('delete', '--project', self.TEST_PROJECT, '--location', self.TEST_LOCATION, self.TEST_ENVIRONMENT_ID, self.TEST_ENVIRONMENT_ID2) self.AssertErrMatches(r'Failed to delete environment \[{}\]'.format( self.TEST_ENVIRONMENT_NAME)) self.AssertErrMatches( r'^{{"ux": "PROGRESS_TRACKER", "message": "Waiting for \[{}] to ' r'be deleted'.format(self.TEST_ENVIRONMENT_NAME2))
def testHttpException666WithMessageAndUrl(self): err = http_error.MakeHttpError( 666, 'Your bad.', url='https://mock.com/mocks/v1/projects/your-stuff') exc = exceptions.HttpException(err, self._ERROR_FORMAT_ALL) expected = """\ content: <debugInfo: mock-debug-info error: code: '666' errors: - domain: global message: Your bad. reason: '' message: Your bad. location: mock-location status: ''> error_info: <code: '666' errors: - domain: global message: Your bad. reason: '' message: Your bad.> instance_name: <your-stuff> message: <HTTPError 666: Your bad.> resource_name: <projects> status_code: <666> status_description: <> status_message: <Your bad.> url: <https://mock.com/mocks/v1/projects/your-stuff> """ actual = str(exc) self.assertMultiLineEqual(expected, actual)