def test_get_rest_flattened():
    client = ZonesClient(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.Zone()

        # Wrap the value into a proper Response obj
        json_return_value = compute.Zone.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.
        client.get(
            project="project_value", zone="zone_value",
        )

        # 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")
        params = http_params.get("params")
        assert "project_value" in http_call[1] + str(body) + str(params)
        assert "zone_value" in http_call[1] + str(body) + str(params)
def test_list_rest(transport: str = "rest",
                   request_type=compute.ListZonesRequest):
    client = ZonesClient(
        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.ZoneList(
            id="id_value",
            items=[
                compute.Zone(
                    available_cpu_platforms=["available_cpu_platforms_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.ZoneList.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.Zone(available_cpu_platforms=["available_cpu_platforms_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_get_rest(transport: str = "rest",
                  request_type=compute.GetZoneRequest):
    client = ZonesClient(
        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.Zone(
            available_cpu_platforms=["available_cpu_platforms_value"],
            creation_timestamp="creation_timestamp_value",
            deprecated=compute.DeprecationStatus(deleted="deleted_value"),
            description="description_value",
            id="id_value",
            kind="kind_value",
            name="name_value",
            region="region_value",
            self_link="self_link_value",
            status=compute.Zone.Status.DOWN,
        )

        # Wrap the value into a proper Response obj
        json_return_value = compute.Zone.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.Zone)
    assert response.available_cpu_platforms == [
        "available_cpu_platforms_value"
    ]
    assert response.creation_timestamp == "creation_timestamp_value"
    assert response.deprecated == compute.DeprecationStatus(
        deleted="deleted_value")
    assert response.description == "description_value"
    assert response.id == "id_value"
    assert response.kind == "kind_value"
    assert response.name == "name_value"
    assert response.region == "region_value"
    assert response.self_link == "self_link_value"
    assert response.status == compute.Zone.Status.DOWN
def test_list_rest_pager(transport: str = "rest"):
    client = ZonesClient(
        credentials=ga_credentials.AnonymousCredentials(),
        transport=transport,
    )

    # Mock the http request call within the method and fake a response.
    with mock.patch.object(Session, "request") as req:
        # TODO(kbandes): remove this mock unless there's a good reason for it.
        # with mock.patch.object(path_template, 'transcode') as transcode:
        # Set the response as a series of pages
        response = (
            compute.ZoneList(
                items=[
                    compute.Zone(),
                    compute.Zone(),
                    compute.Zone(),
                ],
                next_page_token="abc",
            ),
            compute.ZoneList(
                items=[],
                next_page_token="def",
            ),
            compute.ZoneList(
                items=[
                    compute.Zone(),
                ],
                next_page_token="ghi",
            ),
            compute.ZoneList(items=[
                compute.Zone(),
                compute.Zone(),
            ], ),
        )
        # Two responses for two calls
        response = response + response

        # Wrap the values into proper Response objs
        response = tuple(compute.ZoneList.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

        sample_request = {"project": "sample1"}

        pager = client.list(request=sample_request)

        results = list(pager)
        assert len(results) == 6
        assert all(isinstance(i, compute.Zone) for i in results)

        pages = list(client.list(request=sample_request).pages)
        for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
            assert page_.raw_page.next_page_token == token
def test_get_rest(request_type):
    client = ZonesClient(
        credentials=ga_credentials.AnonymousCredentials(),
        transport="rest",
    )

    # send a request that will satisfy transcoding
    request_init = {"project": "sample1", "zone": "sample2"}
    request = request_type(request_init)

    # Mock the http request call within the method and fake a response.
    with mock.patch.object(type(client.transport._session), "request") as req:
        # Designate an appropriate value for the returned response.
        return_value = compute.Zone(
            available_cpu_platforms=["available_cpu_platforms_value"],
            creation_timestamp="creation_timestamp_value",
            description="description_value",
            id=205,
            kind="kind_value",
            name="name_value",
            region="region_value",
            self_link="self_link_value",
            status="status_value",
            supports_pzs=True,
        )

        # Wrap the value into a proper Response obj
        response_value = Response()
        response_value.status_code = 200
        json_return_value = compute.Zone.to_json(return_value)
        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.Zone)
    assert response.available_cpu_platforms == [
        "available_cpu_platforms_value"
    ]
    assert response.creation_timestamp == "creation_timestamp_value"
    assert response.description == "description_value"
    assert response.id == 205
    assert response.kind == "kind_value"
    assert response.name == "name_value"
    assert response.region == "region_value"
    assert response.self_link == "self_link_value"
    assert response.status == "status_value"
    assert response.supports_pzs is True
def test_list_pager():
    client = ZonesClient(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.ZoneList(
                items=[
                    compute.Zone(),
                    compute.Zone(),
                    compute.Zone(),
                ],
                next_page_token="abc",
            ),
            compute.ZoneList(
                items=[],
                next_page_token="def",
            ),
            compute.ZoneList(
                items=[
                    compute.Zone(),
                ],
                next_page_token="ghi",
            ),
            compute.ZoneList(items=[
                compute.Zone(),
                compute.Zone(),
            ], ),
        )
        # Two responses for two calls
        response = response + response

        # Wrap the values into proper Response objs
        response = tuple(compute.ZoneList.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.Zone) 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 test_get_rest_flattened():
    client = ZonesClient(
        credentials=ga_credentials.AnonymousCredentials(),
        transport="rest",
    )

    # Mock the http request call within the method and fake a response.
    with mock.patch.object(type(client.transport._session), "request") as req:
        # Designate an appropriate value for the returned response.
        return_value = compute.Zone()

        # Wrap the value into a proper Response obj
        response_value = Response()
        response_value.status_code = 200
        json_return_value = compute.Zone.to_json(return_value)

        response_value._content = json_return_value.encode("UTF-8")
        req.return_value = response_value

        # get arguments that satisfy an http rule for this method
        sample_request = {"project": "sample1", "zone": "sample2"}

        # get truthy value for each flattened field
        mock_args = dict(
            project="project_value",
            zone="zone_value",
        )
        mock_args.update(sample_request)
        client.get(**mock_args)

        # Establish that the underlying call was made with the expected
        # request object values.
        assert len(req.mock_calls) == 1
        _, args, _ = req.mock_calls[0]
        assert path_template.validate(
            "https://%s/compute/v1/projects/{project}/zones/{zone}" %
            client.transport._host,
            args[1],
        )
def test_get_rest_required_fields(request_type=compute.GetZoneRequest):
    transport_class = transports.ZonesRestTransport

    request_init = {}
    request_init["project"] = ""
    request_init["zone"] = ""
    request = request_type(request_init)
    jsonified_request = json.loads(
        request_type.to_json(request,
                             including_default_value_fields=False,
                             use_integers_for_enums=False))

    # verify fields with default values are dropped

    unset_fields = transport_class(
        credentials=ga_credentials.AnonymousCredentials(
        )).get._get_unset_required_fields(jsonified_request)
    jsonified_request.update(unset_fields)

    # verify required fields with default values are now present

    jsonified_request["project"] = "project_value"
    jsonified_request["zone"] = "zone_value"

    unset_fields = transport_class(
        credentials=ga_credentials.AnonymousCredentials(
        )).get._get_unset_required_fields(jsonified_request)
    jsonified_request.update(unset_fields)

    # verify required fields with non-default values are left alone
    assert "project" in jsonified_request
    assert jsonified_request["project"] == "project_value"
    assert "zone" in jsonified_request
    assert jsonified_request["zone"] == "zone_value"

    client = ZonesClient(
        credentials=ga_credentials.AnonymousCredentials(),
        transport="rest",
    )
    request = request_type(request_init)

    # Designate an appropriate value for the returned response.
    return_value = compute.Zone()
    # Mock the http request call within the method and fake a response.
    with mock.patch.object(Session, "request") as req:
        # We need to mock transcode() because providing default values
        # for required fields will fail the real version if the http_options
        # expect actual values for those fields.
        with mock.patch.object(path_template, "transcode") as transcode:
            # A uri without fields and an empty body will force all the
            # request fields to show up in the query_params.
            transcode_result = {
                "uri": "v1/sample_method",
                "method": "get",
                "query_params": request_init,
            }
            transcode.return_value = transcode_result

            response_value = Response()
            response_value.status_code = 200
            json_return_value = compute.Zone.to_json(return_value)
            response_value._content = json_return_value.encode("UTF-8")
            req.return_value = response_value

            response = client.get(request)

            expected_params = []
            actual_params = req.call_args.kwargs["params"]
            assert expected_params == actual_params