def test_generate_product_mix_ideas_flattened(): client = ReachPlanServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.generate_product_mix_ideas), '__call__') as call: # Designate an appropriate return value for the call. call.return_value = reach_plan_service.GenerateProductMixIdeasResponse( ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.generate_product_mix_ideas( customer_id='customer_id_value', plannable_location_id=wrappers_pb2.StringValue( value='value_value'), currency_code=wrappers_pb2.StringValue(value='value_value'), budget_micros=wrappers_pb2.Int64Value(value=541), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0].customer_id == 'customer_id_value' assert args[0].plannable_location_id == wrappers_pb2.StringValue( value='value_value') assert args[0].currency_code == wrappers_pb2.StringValue( value='value_value') assert args[0].budget_micros == wrappers_pb2.Int64Value(value=541)
def wrap_value(value): if isinstance(value, bool): message = wrapper.BoolValue() message.value = value elif isinstance(value, int): message = wrapper.Int64Value() message.value = value elif isinstance(value, float): message = wrapper.DoubleValue() message.value = value else: raise Exception("Unsupported type {}".format(type(value))) return message
def test_get_account_budget( transport: str = 'grpc', request_type=account_budget_service.GetAccountBudgetRequest): client = AccountBudgetServiceClient( 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_account_budget), '__call__') as call: # Designate an appropriate return value for the call. call.return_value = account_budget.AccountBudget( resource_name='resource_name_value', status=account_budget_status.AccountBudgetStatusEnum. AccountBudgetStatus.UNKNOWN, proposed_end_date_time=wrappers_pb2.StringValue( value='value_value'), approved_end_date_time=wrappers_pb2.StringValue( value='value_value'), proposed_spending_limit_micros=wrappers_pb2.Int64Value(value=541), approved_spending_limit_micros=wrappers_pb2.Int64Value(value=541), adjusted_spending_limit_micros=wrappers_pb2.Int64Value(value=541), ) response = client.get_account_budget(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == account_budget_service.GetAccountBudgetRequest() # Establish that the response is the type that we expect. assert isinstance(response, account_budget.AccountBudget) assert response.resource_name == 'resource_name_value' assert response.status == account_budget_status.AccountBudgetStatusEnum.AccountBudgetStatus.UNKNOWN
def pod_to_pb_any(value): if value is None: v = sqlflow_pb2.Row.Null() elif isinstance(value, bool): v = wrappers_pb2.BoolValue(value=value) elif isinstance(value, int): v = wrappers_pb2.Int64Value(value=value) elif isinstance(value, float): v = wrappers_pb2.FloatValue(value=value) elif isinstance(value, str): v = wrappers_pb2.StringValue(value=value) else: raise ValueError("not supported cell data type: %s" % type(value)) return v
def test_generate_product_mix_ideas_flattened_error(): client = ReachPlanServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.generate_product_mix_ideas( reach_plan_service.GenerateProductMixIdeasRequest(), customer_id='customer_id_value', plannable_location_id=wrappers_pb2.StringValue( value='value_value'), currency_code=wrappers_pb2.StringValue(value='value_value'), budget_micros=wrappers_pb2.Int64Value(value=541), )
def _unpack_values(values): """Unpack protobuf values.""" unpacked = {} for key, packed_value in six.iteritems(values): if packed_value.Is(wrappers_pb2.DoubleValue.DESCRIPTOR): value = wrappers_pb2.DoubleValue() elif packed_value.Is(wrappers_pb2.Int64Value.DESCRIPTOR): value = wrappers_pb2.Int64Value() elif packed_value.Is(wrappers_pb2.StringValue.DESCRIPTOR): value = wrappers_pb2.StringValue() else: raise ValueError('Unknown stat type for ' + key) packed_value.Unpack(value) unpacked[key] = value.value return unpacked
def test_translation_of_search_hit_with_primitives(self): """Verify that well-known types get translated into their values rather than into dicts.""" values_and_serializations = ( (wrappers_pb2.BoolValue(value=True), True), (wrappers_pb2.Int32Value(value=1), 1), (wrappers_pb2.UInt32Value(value=2), 2), # int64 is expected to be converted to a string because of JSON!! (wrappers_pb2.Int64Value(value=3), "3"), (wrappers_pb2.StringValue(value="abc"), "abc"), ) for value, expected in values_and_serializations: any_proto = any_pb2.Any() any_proto.Pack(value) self.assertEqual( expected, response_translation.translate_message_to_dict(any_proto))
def test_get_ad_group_criterion_simulation( transport: str = 'grpc', request_type=ad_group_criterion_simulation_service. GetAdGroupCriterionSimulationRequest): client = AdGroupCriterionSimulationServiceClient( 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_ad_group_criterion_simulation), '__call__') as call: # Designate an appropriate return value for the call. call.return_value = ad_group_criterion_simulation.AdGroupCriterionSimulation( resource_name='resource_name_value', type_=simulation_type.SimulationTypeEnum.SimulationType.UNKNOWN, modification_method=simulation_modification_method. SimulationModificationMethodEnum.SimulationModificationMethod. UNKNOWN, cpc_bid_point_list=simulation.CpcBidSimulationPointList(points=[ simulation.CpcBidSimulationPoint( cpc_bid_micros=wrappers_pb2.Int64Value(value=541)) ]), ) response = client.get_ad_group_criterion_simulation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[ 0] == ad_group_criterion_simulation_service.GetAdGroupCriterionSimulationRequest( ) # Establish that the response is the type that we expect. assert isinstance(response, ad_group_criterion_simulation.AdGroupCriterionSimulation) assert response.resource_name == 'resource_name_value' assert response.type_ == simulation_type.SimulationTypeEnum.SimulationType.UNKNOWN assert response.modification_method == simulation_modification_method.SimulationModificationMethodEnum.SimulationModificationMethod.UNKNOWN
def _pack_values(values): """Pack protobuf values.""" packed = {} if values is None: return packed for key, value in six.iteritems(values): packed_value = Any() if isinstance(value, float): packed_value.Pack(wrappers_pb2.DoubleValue(value=value)) elif isinstance(value, six.integer_types): packed_value.Pack(wrappers_pb2.Int64Value(value=value)) elif isinstance(value, six.string_types): packed_value.Pack(wrappers_pb2.StringValue(value=value)) else: raise ValueError('Unknown stat type for ' + key) packed[key] = packed_value return packed
def test_get_account_link( transport: str = 'grpc', request_type=account_link_service.GetAccountLinkRequest): client = AccountLinkServiceClient( 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_account_link), '__call__') as call: # Designate an appropriate return value for the call. call.return_value = account_link.AccountLink( resource_name='resource_name_value', status=account_link_status.AccountLinkStatusEnum.AccountLinkStatus. UNKNOWN, type_=linked_account_type.LinkedAccountTypeEnum.LinkedAccountType. UNKNOWN, third_party_app_analytics=account_link. ThirdPartyAppAnalyticsLinkIdentifier( app_analytics_provider_id=wrappers_pb2.Int64Value(value=541)), ) response = client.get_account_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == account_link_service.GetAccountLinkRequest() # Establish that the response is the type that we expect. assert isinstance(response, account_link.AccountLink) assert response.resource_name == 'resource_name_value' assert response.status == account_link_status.AccountLinkStatusEnum.AccountLinkStatus.UNKNOWN assert response.type_ == linked_account_type.LinkedAccountTypeEnum.LinkedAccountType.UNKNOWN
def test_get_recommendation( transport: str = 'grpc', request_type=recommendation_service.GetRecommendationRequest): client = RecommendationServiceClient( 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_recommendation), '__call__') as call: # Designate an appropriate return value for the call. call.return_value = recommendation.Recommendation( resource_name='resource_name_value', type_=recommendation_type.RecommendationTypeEnum. RecommendationType.UNKNOWN, campaign_budget_recommendation=recommendation.Recommendation. CampaignBudgetRecommendation( current_budget_amount_micros=wrappers_pb2.Int64Value( value=541)), ) response = client.get_recommendation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == recommendation_service.GetRecommendationRequest() # Establish that the response is the type that we expect. assert isinstance(response, recommendation.Recommendation) assert response.resource_name == 'resource_name_value' assert response.type_ == recommendation_type.RecommendationTypeEnum.RecommendationType.UNKNOWN
def serialize_data_frame( df, project_cols: List[msg.ProjectColumn], chunk_size=100) -> Generator[msg.DataRecordsReply, None, None]: ''' Iterate a dataframe's rows as api.DataRecordsReply !!! time columns must be converted to int BEFORE this method is called !!! Immutable on df :param df: DataFrame - :param project_cols: ProjectColumn[] - columns and type order to keep things aligned :param chunk_size: Int - Optional chunking size for record arrays ''' string_names = [ x.name for x in project_cols if util.is_string_column_type(x.type) ] string_dict = { col_name: index for (index, col_name) in enumerate(string_names) } number_names = [ x.name for x in project_cols if util.is_number_column_type(x.type) ] number_dict = { col_name: index for (index, col_name) in enumerate(number_names) } time_names = [ x.name for x in project_cols if util.is_time_column_type(x.type) ] time_dict = { col_name: index for (index, col_name) in enumerate(time_names) } num_rows = df.shape[0] for chunk_df in list( filter(lambda x: not x.empty, np.array_split(df, math.ceil(num_rows / chunk_size)))): data_records = [] for _, row in chunk_df.iterrows(): strings = [ msg.OptionalString(value=proto.StringValue(value=None)) ] * len(string_names) numbers = [ msg.OptionalNumber(value=proto.DoubleValue(value=None)) ] * len(number_names) times = [msg.OptionalTime(value=proto.Int64Value(value=None)) ] * len(time_names) for col in project_cols: # Strings if util.is_string_column_type(col.type): if row[col.name] == None: strings[string_dict[col.name]] = msg.OptionalString( value=None) else: strings[string_dict[col.name]] = msg.OptionalString( value=proto.StringValue(value=row[col.name])) # Numbers elif util.is_number_column_type(col.type): if row[col.name] == None or math.isnan(row[col.name]): numbers[number_dict[col.name]] = msg.OptionalNumber( value=None) else: numbers[number_dict[col.name]] = msg.OptionalNumber( value=proto.DoubleValue(value=row[col.name])) # Times elif util.is_time_column_type(col.type): if row[col.name] == None or math.isnan( row[col.name].value): times[time_dict[col.name]] = msg.OptionalTime( value=None) else: times[time_dict[col.name]] = msg.OptionalTime( value=proto.Int64Value( value=ts_to_unix_epoch_seconds(row[col.name]))) data_records.append( msg.DataRecord(strings=strings, numbers=numbers, times=times)) yield msg.DataRecordsReply(records=data_records)