def test_user_location_view_service_host_with_port():
    client = UserLocationViewServiceClient(
        credentials=ga_credentials.AnonymousCredentials(),
        client_options=client_options.ClientOptions(api_endpoint='googleads.googleapis.com:8000'),
    )
    assert client.transport._host == 'googleads.googleapis.com:8000'
def test_service_controller_client_client_options(client_class,
                                                  transport_class,
                                                  transport_name):
    # Check that if channel is provided we won't create a new one.
    with mock.patch.object(ServiceControllerClient,
                           'get_transport_class') as gtc:
        transport = transport_class(
            credentials=ga_credentials.AnonymousCredentials())
        client = client_class(transport=transport)
        gtc.assert_not_called()

    # Check that if channel is provided via str we will create a new one.
    with mock.patch.object(ServiceControllerClient,
                           'get_transport_class') as gtc:
        client = client_class(transport=transport_name)
        gtc.assert_called()

    # Check the case api_endpoint is provided.
    options = client_options.ClientOptions(api_endpoint="squid.clam.whelk")
    with mock.patch.object(transport_class, '__init__') as patched:
        patched.return_value = None
        client = client_class(client_options=options)
        patched.assert_called_once_with(
            credentials=None,
            credentials_file=None,
            host="squid.clam.whelk",
            scopes=None,
            client_cert_source_for_mtls=None,
            quota_project_id=None,
            client_info=transports.base.DEFAULT_CLIENT_INFO,
        )

    # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is
    # "never".
    with mock.patch.dict(os.environ,
                         {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
        with mock.patch.object(transport_class, '__init__') as patched:
            patched.return_value = None
            client = client_class()
            patched.assert_called_once_with(
                credentials=None,
                credentials_file=None,
                host=client.DEFAULT_ENDPOINT,
                scopes=None,
                client_cert_source_for_mtls=None,
                quota_project_id=None,
                client_info=transports.base.DEFAULT_CLIENT_INFO,
            )

    # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is
    # "always".
    with mock.patch.dict(os.environ,
                         {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
        with mock.patch.object(transport_class, '__init__') as patched:
            patched.return_value = None
            client = client_class()
            patched.assert_called_once_with(
                credentials=None,
                credentials_file=None,
                host=client.DEFAULT_MTLS_ENDPOINT,
                scopes=None,
                client_cert_source_for_mtls=None,
                quota_project_id=None,
                client_info=transports.base.DEFAULT_CLIENT_INFO,
            )

    # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has
    # unsupported value.
    with mock.patch.dict(os.environ,
                         {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}):
        with pytest.raises(MutualTLSChannelError):
            client = client_class()

    # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value.
    with mock.patch.dict(os.environ,
                         {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}):
        with pytest.raises(ValueError):
            client = client_class()

    # Check the case quota_project_id is provided
    options = client_options.ClientOptions(quota_project_id="octopus")
    with mock.patch.object(transport_class, '__init__') as patched:
        patched.return_value = None
        client = client_class(client_options=options)
        patched.assert_called_once_with(
            credentials=None,
            credentials_file=None,
            host=client.DEFAULT_ENDPOINT,
            scopes=None,
            client_cert_source_for_mtls=None,
            quota_project_id="octopus",
            client_info=transports.base.DEFAULT_CLIENT_INFO,
        )
def test_transport_adc(transport_class):
    # Test default credentials are used if not provided.
    with mock.patch.object(google.auth, 'default') as adc:
        adc.return_value = (ga_credentials.AnonymousCredentials(), None)
        transport_class()
        adc.assert_called_once()
def test_feed_item_set_link_service_host_with_port():
    client = FeedItemSetLinkServiceClient(
        credentials=ga_credentials.AnonymousCredentials(),
        client_options=client_options.ClientOptions(api_endpoint='googleads.googleapis.com:8000'),
    )
    assert client.transport._host == 'googleads.googleapis.com:8000'
Ejemplo n.º 5
0
def test_reach_plan_service_client_client_options():
    # Check that if channel is provided we won't create a new one.
    with mock.patch(
            'google.ads.googleads.v5.services.services.reach_plan_service.ReachPlanServiceClient.get_transport_class'
    ) as gtc:
        transport = transports.ReachPlanServiceGrpcTransport(
            credentials=ga_credentials.AnonymousCredentials())
        client = ReachPlanServiceClient(transport=transport)
        gtc.assert_not_called()

    # Check that if channel is provided via str we will create a new one.
    with mock.patch(
            'google.ads.googleads.v5.services.services.reach_plan_service.ReachPlanServiceClient.get_transport_class'
    ) as gtc:
        client = ReachPlanServiceClient(transport="grpc")
        gtc.assert_called()

    # Check the case api_endpoint is provided.
    options = client_options.ClientOptions(api_endpoint="squid.clam.whelk")
    with mock.patch(
            'google.ads.googleads.v5.services.services.reach_plan_service.transports.ReachPlanServiceGrpcTransport.__init__'
    ) as grpc_transport:
        grpc_transport.return_value = None
        client = ReachPlanServiceClient(client_options=options)
        grpc_transport.assert_called_once_with(
            ssl_channel_credentials=None,
            credentials=None,
            host="squid.clam.whelk",
            client_info=transports.base.DEFAULT_CLIENT_INFO,
        )

    # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT
    # is "never".
    with mock.patch.dict(os.environ,
                         {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
        with mock.patch(
                'google.ads.googleads.v5.services.services.reach_plan_service.transports.ReachPlanServiceGrpcTransport.__init__'
        ) as grpc_transport:
            grpc_transport.return_value = None
            client = ReachPlanServiceClient()
            grpc_transport.assert_called_once_with(
                ssl_channel_credentials=None,
                credentials=None,
                host=client.DEFAULT_ENDPOINT,
                client_info=transports.base.DEFAULT_CLIENT_INFO,
            )

    # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is
    # "always".
    with mock.patch.dict(os.environ,
                         {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
        with mock.patch(
                'google.ads.googleads.v5.services.services.reach_plan_service.transports.ReachPlanServiceGrpcTransport.__init__'
        ) as grpc_transport:
            grpc_transport.return_value = None
            client = ReachPlanServiceClient()
            grpc_transport.assert_called_once_with(
                ssl_channel_credentials=None,
                credentials=None,
                host=client.DEFAULT_MTLS_ENDPOINT,
                client_info=transports.base.DEFAULT_CLIENT_INFO,
            )

    # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has
    # unsupported value.
    with mock.patch.dict(os.environ,
                         {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}):
        with pytest.raises(MutualTLSChannelError):
            client = ReachPlanServiceClient()

    # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value.
    with mock.patch.dict(os.environ,
                         {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}):
        with pytest.raises(ValueError):
            client = ReachPlanServiceClient()
def test_expanded_landing_page_view_service_host_with_port():
    client = ExpandedLandingPageViewServiceClient(
        credentials=ga_credentials.AnonymousCredentials(),
        client_options=client_options.ClientOptions(api_endpoint='googleads.googleapis.com:8000'),
    )
    assert client.transport._host == 'googleads.googleapis.com:8000'
def test_transport_grpc_default():
    # A client should use the gRPC transport by default.
    client = PublisherServiceClient(credentials=credentials.AnonymousCredentials(),)
    assert isinstance(client.transport, transports.PublisherServiceGrpcTransport,)
Ejemplo n.º 8
0
def test_transport_instance():
    # A client may be instantiated with a custom transport instance.
    transport = transports.GlobalOrganizationOperationsRestTransport(
        credentials=ga_credentials.AnonymousCredentials(), )
    client = GlobalOrganizationOperationsClient(transport=transport)
    assert client.transport is transport
Ejemplo n.º 9
0
 def test_init_tensorboard_with_id_only_without_project_or_location(self):
     with pytest.raises(GoogleAuthError):
         tensorboard.Tensorboard(
             tensorboard_name=_TEST_ID,
             credentials=auth_credentials.AnonymousCredentials(),
         )
def test_transport_instance():
    # A client may be instantiated with a custom transport instance.
    transport = transports.AdGroupCriterionSimulationServiceGrpcTransport(
        credentials=ga_credentials.AnonymousCredentials(), )
    client = AdGroupCriterionSimulationServiceClient(transport=transport)
    assert client.transport is transport
Ejemplo n.º 11
0
def test_get_rest(transport: str = "rest",
                  request_type=compute.GetGlobalOrganizationOperationRequest):
    client = GlobalOrganizationOperationsClient(
        credentials=ga_credentials.AnonymousCredentials(),
        transport=transport,
    )

    # Everything is optional in proto3 as far as the runtime is concerned,
    # and we are mocking out the actual API, so just send an empty request.
    request = request_type()

    # Mock the http request call within the method and fake a response.
    with mock.patch.object(Session, "request") as req:
        # Designate an appropriate value for the returned response.
        return_value = compute.Operation(
            client_operation_id="client_operation_id_value",
            creation_timestamp="creation_timestamp_value",
            description="description_value",
            end_time="end_time_value",
            error=compute.Error(errors=[compute.Errors(code="code_value")]),
            http_error_message="http_error_message_value",
            http_error_status_code=2374,
            id="id_value",
            insert_time="insert_time_value",
            kind="kind_value",
            name="name_value",
            operation_group_id="operation_group_id_value",
            operation_type="operation_type_value",
            progress=885,
            region="region_value",
            self_link="self_link_value",
            start_time="start_time_value",
            status=compute.Operation.Status.DONE,
            status_message="status_message_value",
            target_id="target_id_value",
            target_link="target_link_value",
            user="******",
            warnings=[
                compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)
            ],
            zone="zone_value",
        )

        # Wrap the value into a proper Response obj
        json_return_value = compute.Operation.to_json(return_value)
        response_value = Response()
        response_value.status_code = 200
        response_value._content = json_return_value.encode("UTF-8")
        req.return_value = response_value
        response = client.get(request)

    # Establish that the response is the type that we expect.
    assert isinstance(response, compute.Operation)
    assert response.client_operation_id == "client_operation_id_value"
    assert response.creation_timestamp == "creation_timestamp_value"
    assert response.description == "description_value"
    assert response.end_time == "end_time_value"
    assert response.error == compute.Error(
        errors=[compute.Errors(code="code_value")])
    assert response.http_error_message == "http_error_message_value"
    assert response.http_error_status_code == 2374
    assert response.id == "id_value"
    assert response.insert_time == "insert_time_value"
    assert response.kind == "kind_value"
    assert response.name == "name_value"
    assert response.operation_group_id == "operation_group_id_value"
    assert response.operation_type == "operation_type_value"
    assert response.progress == 885
    assert response.region == "region_value"
    assert response.self_link == "self_link_value"
    assert response.start_time == "start_time_value"
    assert response.status == compute.Operation.Status.DONE
    assert response.status_message == "status_message_value"
    assert response.target_id == "target_id_value"
    assert response.target_link == "target_link_value"
    assert response.user == "user_value"
    assert response.warnings == [
        compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)
    ]
    assert response.zone == "zone_value"
def test_transport_get_channel():
    # A client may be instantiated with a custom transport instance.
    transport = transports.ThirdPartyAppAnalyticsLinkServiceGrpcTransport(
        credentials=ga_credentials.AnonymousCredentials(), )
    channel = transport.grpc_channel
    assert channel
def test_transport_instance():
    # A client may be instantiated with a custom transport instance.
    transport = transports.ThirdPartyAppAnalyticsLinkServiceGrpcTransport(
        credentials=ga_credentials.AnonymousCredentials(), )
    client = ThirdPartyAppAnalyticsLinkServiceClient(transport=transport)
    assert client.transport is transport
def test_transport_instance():
    # A client may be instantiated with a custom transport instance.
    transport = transports.RegionDiskTypesRestTransport(
        credentials=ga_credentials.AnonymousCredentials(), )
    client = RegionDiskTypesClient(transport=transport)
    assert client.transport is transport
Ejemplo n.º 15
0
]
_TEST_BATCH_PREDICTION_GCS_DEST_PREFIX = "gs://example-bucket/folder/output"
_TEST_BATCH_PREDICTION_BQ_PREFIX = "ucaip-sample-tests"
_TEST_BATCH_PREDICTION_BQ_DEST_PREFIX_WITH_PROTOCOL = (
    f"bq://{_TEST_BATCH_PREDICTION_BQ_PREFIX}"
)
_TEST_BATCH_PREDICTION_DISPLAY_NAME = "test-batch-prediction-job"
_TEST_BATCH_PREDICTION_JOB_NAME = job_service_client.JobServiceClient.batch_prediction_job_path(
    project=_TEST_PROJECT, location=_TEST_LOCATION, batch_prediction_job=_TEST_ID
)

_TEST_INSTANCE_SCHEMA_URI = "gs://test/schema/instance.yaml"
_TEST_PARAMETERS_SCHEMA_URI = "gs://test/schema/parameters.yaml"
_TEST_PREDICTION_SCHEMA_URI = "gs://test/schema/predictions.yaml"

_TEST_CREDENTIALS = mock.Mock(spec=auth_credentials.AnonymousCredentials())

_TEST_EXPLANATION_METADATA = aiplatform.explain.ExplanationMetadata(
    inputs={
        "features": {
            "input_tensor_name": "dense_input",
            "encoding": "BAG_OF_FEATURES",
            "modality": "numeric",
            "index_feature_mapping": ["abc", "def", "ghj"],
        }
    },
    outputs={"medv": {"output_tensor_name": "dense_2"}},
)
_TEST_EXPLANATION_PARAMETERS = aiplatform.explain.ExplanationParameters(
    {"sampled_shapley_attribution": {"path_count": 10}}
)
def test_transport_instance():
    # A client may be instantiated with a custom transport instance.
    transport = transports.SpeechTranslationServiceGrpcTransport(
        credentials=credentials.AnonymousCredentials())
    client = SpeechTranslationServiceClient(transport=transport)
    assert client._transport is transport
Ejemplo n.º 17
0
    def test_batch_predict_with_all_args(
        self, create_batch_prediction_job_with_explanations_mock, sync
    ):
        aiplatform.init(project=_TEST_PROJECT, location=_TEST_LOCATION)
        test_model = models.Model(_TEST_ID)
        creds = auth_credentials.AnonymousCredentials()

        # Make SDK batch_predict method call passing all arguments
        batch_prediction_job = test_model.batch_predict(
            job_display_name=_TEST_BATCH_PREDICTION_DISPLAY_NAME,
            gcs_source=_TEST_BATCH_PREDICTION_GCS_SOURCE,
            gcs_destination_prefix=_TEST_BATCH_PREDICTION_GCS_DEST_PREFIX,
            predictions_format="csv",
            model_parameters={},
            machine_type=_TEST_MACHINE_TYPE,
            accelerator_type=_TEST_ACCELERATOR_TYPE,
            accelerator_count=_TEST_ACCELERATOR_COUNT,
            starting_replica_count=_TEST_STARTING_REPLICA_COUNT,
            max_replica_count=_TEST_MAX_REPLICA_COUNT,
            generate_explanation=True,
            explanation_metadata=_TEST_EXPLANATION_METADATA,
            explanation_parameters=_TEST_EXPLANATION_PARAMETERS,
            labels=_TEST_LABEL,
            credentials=creds,
            encryption_spec_key_name=_TEST_ENCRYPTION_KEY_NAME,
            sync=sync,
        )

        if not sync:
            batch_prediction_job.wait()

        # Construct expected request
        expected_gapic_batch_prediction_job = gca_batch_prediction_job_v1beta1.BatchPredictionJob(
            display_name=_TEST_BATCH_PREDICTION_DISPLAY_NAME,
            model=model_service_client_v1beta1.ModelServiceClient.model_path(
                _TEST_PROJECT, _TEST_LOCATION, _TEST_ID
            ),
            input_config=gca_batch_prediction_job_v1beta1.BatchPredictionJob.InputConfig(
                instances_format="jsonl",
                gcs_source=gca_io_v1beta1.GcsSource(
                    uris=[_TEST_BATCH_PREDICTION_GCS_SOURCE]
                ),
            ),
            output_config=gca_batch_prediction_job_v1beta1.BatchPredictionJob.OutputConfig(
                gcs_destination=gca_io_v1beta1.GcsDestination(
                    output_uri_prefix=_TEST_BATCH_PREDICTION_GCS_DEST_PREFIX
                ),
                predictions_format="csv",
            ),
            dedicated_resources=gca_machine_resources_v1beta1.BatchDedicatedResources(
                machine_spec=gca_machine_resources_v1beta1.MachineSpec(
                    machine_type=_TEST_MACHINE_TYPE,
                    accelerator_type=_TEST_ACCELERATOR_TYPE,
                    accelerator_count=_TEST_ACCELERATOR_COUNT,
                ),
                starting_replica_count=_TEST_STARTING_REPLICA_COUNT,
                max_replica_count=_TEST_MAX_REPLICA_COUNT,
            ),
            generate_explanation=True,
            explanation_spec=gca_explanation_v1beta1.ExplanationSpec(
                metadata=_TEST_EXPLANATION_METADATA,
                parameters=_TEST_EXPLANATION_PARAMETERS,
            ),
            labels=_TEST_LABEL,
            encryption_spec=_TEST_ENCRYPTION_SPEC_V1BETA1,
        )

        create_batch_prediction_job_with_explanations_mock.assert_called_once_with(
            parent=f"projects/{_TEST_PROJECT}/locations/{_TEST_LOCATION}",
            batch_prediction_job=expected_gapic_batch_prediction_job,
        )
def test_transport_grpc_default():
    # A client should use the gRPC transport by default.
    client = SpeechTranslationServiceClient(
        credentials=credentials.AnonymousCredentials())
    assert isinstance(client._transport,
                      transports.SpeechTranslationServiceGrpcTransport)
Ejemplo n.º 19
0
def test_transport_instance():
    # A client may be instantiated with a custom transport instance.
    transport = transports.DetailPlacementViewServiceGrpcTransport(
        credentials=ga_credentials.AnonymousCredentials(), )
    client = DetailPlacementViewServiceClient(transport=transport)
    assert client.transport is transport
Ejemplo n.º 20
0
def test_customer_feed_service_host_with_port():
    client = CustomerFeedServiceClient(
        credentials=ga_credentials.AnonymousCredentials(),
        client_options=client_options.ClientOptions(api_endpoint='googleads.googleapis.com:8000'),
    )
    assert client.transport._host == 'googleads.googleapis.com:8000'
def test_transport_instance():
    # A client may be instantiated with a custom transport instance.
    transport = transports.OfflineUserDataJobServiceGrpcTransport(
        credentials=ga_credentials.AnonymousCredentials(), )
    client = OfflineUserDataJobServiceClient(transport=transport)
    assert client.transport is transport
Ejemplo n.º 22
0
 def testListSubscriptions(self):
     app = service.CreateApp({
         'environ': {
             'GOOGLE_CLOUD_PROJECT': 'chromeperf',
             'GAE_SERVICE': 'sheriff-config',
         },
         'datastore_client':
         datastore.Client(credentials=credentials.AnonymousCredentials(),
                          project='chromeperf'),
         'http':
         HttpMockSequenceWithDiscovery([({
             'status': '200'
         }, self.sample_config), ({
             'status': '200'
         }, '{ "is_member": true }'),
                                        ({
                                            'status': '200'
                                        }, '{ "is_member": false }')]),
     })
     client = app.test_client()
     response = client.get('/configs/update',
                           headers={'X-Forwarded-Proto': 'https'})
     self.assertEqual(response.status_code, 200)
     response = client.post('/subscriptions/list',
                            json={'identity_email': '*****@*****.**'},
                            headers={'X-Forwarded-Proto': 'https'})
     self.assertEqual(response.status_code, 200)
     self.assertDictEqual(
         response.get_json(), {
             'subscriptions': [{
                 'config_set': 'projects/project',
                 'revision': '0123456789abcdef',
                 'subscription': {
                     'name': 'Config 1',
                     'contact_email': '*****@*****.**',
                     'bug_labels': ['Some-Label'],
                     'bug_components': ['Some>Component'],
                     'auto_triage': {
                         'enable': False
                     },
                     'auto_bisection': {
                         'enable': False
                     },
                     'rules': {},
                 }
             }, {
                 'config_set': 'projects/project',
                 'revision': '0123456789abcdef',
                 'subscription': {
                     'name': 'Config 2',
                     'contact_email': '*****@*****.**',
                     'bug_labels': ['Some-Label'],
                     'bug_components': ['Some>Component'],
                     'auto_triage': {
                         'enable': False
                     },
                     'auto_bisection': {
                         'enable': False
                     },
                     'rules': {},
                 }
             }, {
                 'config_set': 'projects/other_project',
                 'revision': '0123456789abcdff',
                 'subscription': {
                     'name': 'Expected 1',
                     'monorail_project_id': 'non-chromium',
                     'contact_email': '*****@*****.**',
                     'bug_labels': ['Some-Label'],
                     'bug_components': ['Some>Component'],
                     'auto_triage': {
                         'enable': False
                     },
                     'auto_bisection': {
                         'enable': False
                     },
                     'rules': {},
                 }
             }]
         })
     response = client.post('/subscriptions/list',
                            json={'identity_email': '*****@*****.**'},
                            headers={'X-Forwarded-Proto': 'https'})
     self.assertEqual(response.status_code, 200)
     self.assertDictEqual(response.get_json(), {})
def test_campaign_asset_service_host_with_port():
    client = CampaignAssetServiceClient(
        credentials=ga_credentials.AnonymousCredentials(),
        client_options=client_options.ClientOptions(api_endpoint='googleads.googleapis.com:8000'),
    )
    assert client.transport._host == 'googleads.googleapis.com:8000'
Ejemplo n.º 24
0
def test_get_campaign(transport: str = 'grpc',
                      request_type=campaign_service.GetCampaignRequest):
    client = CampaignServiceClient(
        credentials=ga_credentials.AnonymousCredentials(),
        transport=transport,
    )

    # Everything is optional in proto3 as far as the runtime is concerned,
    # and we are mocking out the actual API, so just send an empty request.
    request = request_type()

    # Mock the actual call within the gRPC stub, and fake the request.
    with mock.patch.object(type(client.transport.get_campaign),
                           '__call__') as call:
        # Designate an appropriate return value for the call.
        call.return_value = campaign.Campaign(
            resource_name='resource_name_value',
            id=205,
            name='name_value',
            status=campaign_status.CampaignStatusEnum.CampaignStatus.UNKNOWN,
            serving_status=campaign_serving_status.CampaignServingStatusEnum.
            CampaignServingStatus.UNKNOWN,
            ad_serving_optimization_status=ad_serving_optimization_status.
            AdServingOptimizationStatusEnum.AdServingOptimizationStatus.
            UNKNOWN,
            advertising_channel_type=advertising_channel_type.
            AdvertisingChannelTypeEnum.AdvertisingChannelType.UNKNOWN,
            advertising_channel_sub_type=advertising_channel_sub_type.
            AdvertisingChannelSubTypeEnum.AdvertisingChannelSubType.UNKNOWN,
            tracking_url_template='tracking_url_template_value',
            labels=['labels_value'],
            experiment_type=campaign_experiment_type.
            CampaignExperimentTypeEnum.CampaignExperimentType.UNKNOWN,
            base_campaign='base_campaign_value',
            campaign_budget='campaign_budget_value',
            bidding_strategy_type=bidding_strategy_type.
            BiddingStrategyTypeEnum.BiddingStrategyType.UNKNOWN,
            start_date='start_date_value',
            end_date='end_date_value',
            final_url_suffix='final_url_suffix_value',
            video_brand_safety_suitability=brand_safety_suitability.
            BrandSafetySuitabilityEnum.BrandSafetySuitability.UNKNOWN,
            payment_mode=payment_mode.PaymentModeEnum.PaymentMode.UNKNOWN,
            optimization_score=0.1954,
            excluded_parent_asset_field_types=[
                asset_field_type.AssetFieldTypeEnum.AssetFieldType.UNKNOWN
            ],
            bidding_strategy='bidding_strategy_value',
        )
        response = client.get_campaign(request)

        # Establish that the underlying gRPC stub method was called.
        assert len(call.mock_calls) == 1
        _, args, _ = call.mock_calls[0]
        assert args[0] == campaign_service.GetCampaignRequest()

    # Establish that the response is the type that we expect.
    assert isinstance(response, campaign.Campaign)
    assert response.resource_name == 'resource_name_value'
    assert response.id == 205
    assert response.name == 'name_value'
    assert response.status == campaign_status.CampaignStatusEnum.CampaignStatus.UNKNOWN
    assert response.serving_status == campaign_serving_status.CampaignServingStatusEnum.CampaignServingStatus.UNKNOWN
    assert response.ad_serving_optimization_status == ad_serving_optimization_status.AdServingOptimizationStatusEnum.AdServingOptimizationStatus.UNKNOWN
    assert response.advertising_channel_type == advertising_channel_type.AdvertisingChannelTypeEnum.AdvertisingChannelType.UNKNOWN
    assert response.advertising_channel_sub_type == advertising_channel_sub_type.AdvertisingChannelSubTypeEnum.AdvertisingChannelSubType.UNKNOWN
    assert response.tracking_url_template == 'tracking_url_template_value'
    assert response.labels == ['labels_value']
    assert response.experiment_type == campaign_experiment_type.CampaignExperimentTypeEnum.CampaignExperimentType.UNKNOWN
    assert response.base_campaign == 'base_campaign_value'
    assert response.campaign_budget == 'campaign_budget_value'
    assert response.bidding_strategy_type == bidding_strategy_type.BiddingStrategyTypeEnum.BiddingStrategyType.UNKNOWN
    assert response.start_date == 'start_date_value'
    assert response.end_date == 'end_date_value'
    assert response.final_url_suffix == 'final_url_suffix_value'
    assert response.video_brand_safety_suitability == brand_safety_suitability.BrandSafetySuitabilityEnum.BrandSafetySuitability.UNKNOWN
    assert response.payment_mode == payment_mode.PaymentModeEnum.PaymentMode.UNKNOWN
    assert math.isclose(response.optimization_score, 0.1954, rel_tol=1e-6)
    assert response.excluded_parent_asset_field_types == [
        asset_field_type.AssetFieldTypeEnum.AssetFieldType.UNKNOWN
    ]
Ejemplo n.º 25
0
def test_transport_get_channel():
    # A client may be instantiated with a custom transport instance.
    transport = transports.ReachPlanServiceGrpcTransport(
        credentials=ga_credentials.AnonymousCredentials(), )
    channel = transport.grpc_channel
    assert channel
def test_bidding_strategy_service_host_with_port():
    client = BiddingStrategyServiceClient(
        credentials=ga_credentials.AnonymousCredentials(),
        client_options=client_options.ClientOptions(api_endpoint='googleads.googleapis.com:8000'),
    )
    assert client.transport._host == 'googleads.googleapis.com:8000'
def test_transport_instance():
    # A client may be instantiated with a custom transport instance.
    transport = transports.ServiceControllerGrpcTransport(
        credentials=ga_credentials.AnonymousCredentials(), )
    client = ServiceControllerClient(transport=transport)
    assert client.transport is transport
Ejemplo n.º 28
0
def test_transport_instance():
    # A client may be instantiated with a custom transport instance.
    transport = transports.CampaignFeedServiceGrpcTransport(
        credentials=ga_credentials.AnonymousCredentials(), )
    client = CampaignFeedServiceClient(transport=transport)
    assert client.transport is transport
def test_service_controller_base_transport_error():
    # Passing both a credentials object and credentials_file should raise an error
    with pytest.raises(core_exceptions.DuplicateCredentialArgs):
        transport = transports.ServiceControllerTransport(
            credentials=ga_credentials.AnonymousCredentials(),
            credentials_file="credentials.json")
Ejemplo n.º 30
0
 def test_init_metadata_store_with_id_without_project_or_location(self):
     with pytest.raises(GoogleAuthError):
         metadata_store._MetadataStore(
             metadata_store_name=_TEST_ID,
             credentials=auth_credentials.AnonymousCredentials(),
         )