def test_insert_rest_flattened(): client = RoutesClient(credentials=ga_credentials.AnonymousCredentials(),) # 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() # 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 # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. route_resource = compute.Route(creation_timestamp="creation_timestamp_value") client.insert( project="project_value", route_resource=route_resource, ) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, http_call, http_params = req.mock_calls[0] body = http_params.get("data") assert "project_value" in http_call[1] + str(body) assert compute.Route.to_json( route_resource, including_default_value_fields=False, use_integers_for_enums=False, ) in http_call[1] + str(body)
def test_list_rest(transport: str = "rest", request_type=compute.ListRoutesRequest): client = RoutesClient( 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.RouteList( id="id_value", items=[ compute.Route(creation_timestamp="creation_timestamp_value") ], kind="kind_value", next_page_token="next_page_token_value", self_link="self_link_value", warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED), ) # Wrap the value into a proper Response obj json_return_value = compute.RouteList.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.list(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListPager) assert response.id == "id_value" assert response.items == [ compute.Route(creation_timestamp="creation_timestamp_value") ] assert response.kind == "kind_value" assert response.next_page_token == "next_page_token_value" assert response.self_link == "self_link_value" assert response.warning == compute.Warning( code=compute.Warning.Code.CLEANUP_FAILED)
def test_insert_rest_flattened_error(): client = RoutesClient(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.insert( compute.InsertRouteRequest(), project="project_value", route_resource=compute.Route(creation_timestamp="creation_timestamp_value"), )
def test_list_pager(): client = RoutesClient(credentials=ga_credentials.AnonymousCredentials(), ) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # Set the response as a series of pages response = ( compute.RouteList( items=[ compute.Route(), compute.Route(), compute.Route(), ], next_page_token="abc", ), compute.RouteList( items=[], next_page_token="def", ), compute.RouteList( items=[ compute.Route(), ], next_page_token="ghi", ), compute.RouteList(items=[ compute.Route(), compute.Route(), ], ), ) # Two responses for two calls response = response + response # Wrap the values into proper Response objs response = tuple(compute.RouteList.to_json(x) for x in response) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): return_val._content = response_val.encode("UTF-8") return_val.status_code = 200 req.side_effect = return_values metadata = () pager = client.list(request={}) assert pager._metadata == metadata results = list(pager) assert len(results) == 6 assert all(isinstance(i, compute.Route) for i in results) pages = list(client.list(request={}).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token
def __call__( self, request: compute.InsertRouteRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Call the insert method over HTTP. Args: request (~.compute.InsertRouteRequest): The request object. A request message for Routes.Insert. See the method description for details. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: ~.compute.Operation: Represents an Operation resource. Google Compute Engine has three Operation resources: \* `Global </compute/docs/reference/rest/v1/globalOperations>`__ \* `Regional </compute/docs/reference/rest/v1/regionOperations>`__ \* `Zonal </compute/docs/reference/rest/v1/zoneOperations>`__ You can use an operation resource to manage asynchronous API requests. For more information, read Handling API responses. Operations can be global, regional or zonal. - For global operations, use the ``globalOperations`` resource. - For regional operations, use the ``regionOperations`` resource. - For zonal operations, use the ``zonalOperations`` resource. For more information, read Global, Regional, and Zonal Resources. """ http_options = [ { "method": "post", "uri": "/compute/v1/projects/{project}/global/routes", "body": "route_resource", }, ] request_kwargs = compute.InsertRouteRequest.to_dict(request) transcoded_request = path_template.transcode( http_options, **request_kwargs) # Jsonify the request body body = compute.Route.to_json( compute.Route(transcoded_request["body"]), including_default_value_fields=False, use_integers_for_enums=False, ) uri = transcoded_request["uri"] method = transcoded_request["method"] # Jsonify the query params query_params = json.loads( compute.InsertRouteRequest.to_json( compute.InsertRouteRequest( transcoded_request["query_params"]), including_default_value_fields=False, use_integers_for_enums=False, )) query_params.update(self._get_unset_required_fields(query_params)) # Send the request headers = dict(metadata) headers["Content-Type"] = "application/json" response = getattr(self._session, method)( # Replace with proper schema configuration (http/https) logic "https://{host}{uri}".format(host=self._host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params), data=body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. if response.status_code >= 400: raise core_exceptions.from_http_response(response) # Return the response return compute.Operation.from_json(response.content, ignore_unknown_fields=True)
def test_get_rest(transport: str = "rest", request_type=compute.GetRouteRequest): client = RoutesClient( 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.Route( creation_timestamp="creation_timestamp_value", description="description_value", dest_range="dest_range_value", id="id_value", kind="kind_value", name="name_value", network="network_value", next_hop_gateway="next_hop_gateway_value", next_hop_ilb="next_hop_ilb_value", next_hop_instance="next_hop_instance_value", next_hop_ip="next_hop_ip_value", next_hop_network="next_hop_network_value", next_hop_peering="next_hop_peering_value", next_hop_vpn_tunnel="next_hop_vpn_tunnel_value", priority=898, self_link="self_link_value", tags=["tags_value"], warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)], ) # Wrap the value into a proper Response obj json_return_value = compute.Route.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.Route) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" assert response.dest_range == "dest_range_value" assert response.id == "id_value" assert response.kind == "kind_value" assert response.name == "name_value" assert response.network == "network_value" assert response.next_hop_gateway == "next_hop_gateway_value" assert response.next_hop_ilb == "next_hop_ilb_value" assert response.next_hop_instance == "next_hop_instance_value" assert response.next_hop_ip == "next_hop_ip_value" assert response.next_hop_network == "next_hop_network_value" assert response.next_hop_peering == "next_hop_peering_value" assert response.next_hop_vpn_tunnel == "next_hop_vpn_tunnel_value" assert response.priority == 898 assert response.self_link == "self_link_value" assert response.tags == ["tags_value"] assert response.warnings == [ compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED) ]