Ejemplo n.º 1
0
def test_credentials_transport_error():
    # It is an error to provide credentials and a transport instance.
    transport = transports.RegionsRestTransport(
        credentials=ga_credentials.AnonymousCredentials(),
    )
    with pytest.raises(ValueError):
        client = RegionsClient(
            credentials=ga_credentials.AnonymousCredentials(), transport=transport,
        )

    # It is an error to provide a credentials file and a transport instance.
    transport = transports.RegionsRestTransport(
        credentials=ga_credentials.AnonymousCredentials(),
    )
    with pytest.raises(ValueError):
        client = RegionsClient(
            client_options={"credentials_file": "credentials.json"},
            transport=transport,
        )

    # It is an error to provide scopes and a transport instance.
    transport = transports.RegionsRestTransport(
        credentials=ga_credentials.AnonymousCredentials(),
    )
    with pytest.raises(ValueError):
        client = RegionsClient(
            client_options={"scopes": ["1", "2"]}, transport=transport,
        )
Ejemplo n.º 2
0
def test_list_rest_flattened():
    client = RegionsClient(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.RegionList()

        # Wrap the value into a proper Response obj
        json_return_value = compute.RegionList.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.list(project="project_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)
Ejemplo n.º 3
0
def test_list_rest(request_type):
    client = RegionsClient(
        credentials=ga_credentials.AnonymousCredentials(),
        transport="rest",
    )

    # send a request that will satisfy transcoding
    request_init = {"project": "sample1"}
    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.RegionList(
            id="id_value",
            kind="kind_value",
            next_page_token="next_page_token_value",
            self_link="self_link_value",
        )

        # Wrap the value into a proper Response obj
        response_value = Response()
        response_value.status_code = 200
        json_return_value = compute.RegionList.to_json(return_value)
        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.kind == "kind_value"
    assert response.next_page_token == "next_page_token_value"
    assert response.self_link == "self_link_value"
Ejemplo n.º 4
0
def test_parse_common_billing_account_path():
    expected = {
        "billing_account": "clam",
    }
    path = RegionsClient.common_billing_account_path(**expected)

    # Check that the path construction is reversible.
    actual = RegionsClient.parse_common_billing_account_path(path)
    assert expected == actual
Ejemplo n.º 5
0
def test_list_rest_pager(transport: str = "rest"):
    client = RegionsClient(
        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.RegionList(
                items=[
                    compute.Region(),
                    compute.Region(),
                    compute.Region(),
                ],
                next_page_token="abc",
            ),
            compute.RegionList(
                items=[],
                next_page_token="def",
            ),
            compute.RegionList(
                items=[
                    compute.Region(),
                ],
                next_page_token="ghi",
            ),
            compute.RegionList(items=[
                compute.Region(),
                compute.Region(),
            ], ),
        )
        # Two responses for two calls
        response = response + response

        # Wrap the values into proper Response objs
        response = tuple(compute.RegionList.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.Region) 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
Ejemplo n.º 6
0
def test_parse_common_folder_path():
    expected = {
        "folder": "octopus",
    }
    path = RegionsClient.common_folder_path(**expected)

    # Check that the path construction is reversible.
    actual = RegionsClient.parse_common_folder_path(path)
    assert expected == actual
Ejemplo n.º 7
0
def test_parse_common_organization_path():
    expected = {
        "organization": "nudibranch",
    }
    path = RegionsClient.common_organization_path(**expected)

    # Check that the path construction is reversible.
    actual = RegionsClient.parse_common_organization_path(path)
    assert expected == actual
Ejemplo n.º 8
0
def test_parse_common_project_path():
    expected = {
        "project": "mussel",
    }
    path = RegionsClient.common_project_path(**expected)

    # Check that the path construction is reversible.
    actual = RegionsClient.parse_common_project_path(path)
    assert expected == actual
Ejemplo n.º 9
0
def test_regions_client_get_transport_class():
    transport = RegionsClient.get_transport_class()
    available_transports = [
        transports.RegionsRestTransport,
    ]
    assert transport in available_transports

    transport = RegionsClient.get_transport_class("rest")
    assert transport == transports.RegionsRestTransport
Ejemplo n.º 10
0
def test_list_rest_flattened_error():
    client = RegionsClient(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.list(
            compute.ListRegionsRequest(), project="project_value",
        )
Ejemplo n.º 11
0
def test_parse_common_location_path():
    expected = {
        "project": "scallop",
        "location": "abalone",
    }
    path = RegionsClient.common_location_path(**expected)

    # Check that the path construction is reversible.
    actual = RegionsClient.parse_common_location_path(path)
    assert expected == actual
Ejemplo n.º 12
0
def test_list_pager():
    client = RegionsClient(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.RegionList(
                items=[
                    compute.Region(),
                    compute.Region(),
                    compute.Region(),
                ],
                next_page_token="abc",
            ),
            compute.RegionList(
                items=[],
                next_page_token="def",
            ),
            compute.RegionList(
                items=[
                    compute.Region(),
                ],
                next_page_token="ghi",
            ),
            compute.RegionList(items=[
                compute.Region(),
                compute.Region(),
            ], ),
        )
        # Two responses for two calls
        response = response + response

        # Wrap the values into proper Response objs
        response = tuple(compute.RegionList.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.Region) 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
Ejemplo n.º 13
0
def test_get_rest_flattened_error(transport: str = "rest"):
    client = RegionsClient(
        credentials=ga_credentials.AnonymousCredentials(),
        transport=transport,
    )

    # Attempting to call a method with both a request object and flattened
    # fields is an error.
    with pytest.raises(ValueError):
        client.get(
            compute.GetRegionRequest(),
            project="project_value",
            region="region_value",
        )
Ejemplo n.º 14
0
def test_get_rest(transport: str = "rest",
                  request_type=compute.GetRegionRequest):
    client = RegionsClient(
        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.Region(
            creation_timestamp="creation_timestamp_value",
            deprecated=compute.DeprecationStatus(deleted="deleted_value"),
            description="description_value",
            id="id_value",
            kind="kind_value",
            name="name_value",
            quotas=[compute.Quota(limit=0.543)],
            self_link="self_link_value",
            status=compute.Region.Status.DOWN,
            supports_pzs=True,
            zones=["zones_value"],
        )

        # Wrap the value into a proper Response obj
        json_return_value = compute.Region.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.Region)
    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.quotas == [compute.Quota(limit=0.543)]
    assert response.self_link == "self_link_value"
    assert response.status == compute.Region.Status.DOWN
    assert response.supports_pzs is True
    assert response.zones == ["zones_value"]
Ejemplo n.º 15
0
def test_common_billing_account_path():
    billing_account = "squid"
    expected = "billingAccounts/{billing_account}".format(
        billing_account=billing_account,
    )
    actual = RegionsClient.common_billing_account_path(billing_account)
    assert expected == actual
Ejemplo n.º 16
0
def test_transport_instance():
    # A client may be instantiated with a custom transport instance.
    transport = transports.RegionsRestTransport(
        credentials=ga_credentials.AnonymousCredentials(),
    )
    client = RegionsClient(transport=transport)
    assert client.transport is transport
Ejemplo n.º 17
0
def test_regions_host_with_port():
    client = RegionsClient(
        credentials=ga_credentials.AnonymousCredentials(),
        client_options=client_options.ClientOptions(
            api_endpoint="compute.googleapis.com:8000"),
    )
    assert client.transport._host == "compute.googleapis.com:8000"
Ejemplo n.º 18
0
def test_common_location_path():
    project = "winkle"
    location = "nautilus"
    expected = "projects/{project}/locations/{location}".format(
        project=project, location=location,
    )
    actual = RegionsClient.common_location_path(project, location)
    assert expected == actual
Ejemplo n.º 19
0
def test_get_rest(request_type):
    client = RegionsClient(
        credentials=ga_credentials.AnonymousCredentials(),
        transport="rest",
    )

    # send a request that will satisfy transcoding
    request_init = {"project": "sample1", "region": "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.Region(
            creation_timestamp="creation_timestamp_value",
            description="description_value",
            id=205,
            kind="kind_value",
            name="name_value",
            self_link="self_link_value",
            status="status_value",
            supports_pzs=True,
            zones=["zones_value"],
        )

        # Wrap the value into a proper Response obj
        response_value = Response()
        response_value.status_code = 200
        json_return_value = compute.Region.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.Region)
    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.self_link == "self_link_value"
    assert response.status == "status_value"
    assert response.supports_pzs is True
    assert response.zones == ["zones_value"]
Ejemplo n.º 20
0
def test_list_rest(transport: str = "rest",
                   request_type=compute.ListRegionsRequest):
    client = RegionsClient(
        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.RegionList(
            id="id_value",
            items=[
                compute.Region(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.RegionList.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.Region(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)
Ejemplo n.º 21
0
def test_client_withDEFAULT_CLIENT_INFO():
    client_info = gapic_v1.client_info.ClientInfo()

    with mock.patch.object(
        transports.RegionsTransport, "_prep_wrapped_messages"
    ) as prep:
        client = RegionsClient(
            credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
        )
        prep.assert_called_once_with(client_info)

    with mock.patch.object(
        transports.RegionsTransport, "_prep_wrapped_messages"
    ) as prep:
        transport_class = RegionsClient.get_transport_class()
        transport = transport_class(
            credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
        )
        prep.assert_called_once_with(client_info)
Ejemplo n.º 22
0
def test_list_rest_bad_request(transport: str = "rest",
                               request_type=compute.ListRegionsRequest):
    client = RegionsClient(
        credentials=ga_credentials.AnonymousCredentials(),
        transport=transport,
    )

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

    # Mock the http request call within the method and fake a BadRequest error.
    with mock.patch.object(Session, "request") as req, pytest.raises(
            core_exceptions.BadRequest):
        # Wrap the value into a proper Response obj
        response_value = Response()
        response_value.status_code = 400
        response_value.request = Request()
        req.return_value = response_value
        client.list(request)
Ejemplo n.º 23
0
def test_get_rest_flattened():
    client = RegionsClient(
        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.Region()

        # Wrap the value into a proper Response obj
        response_value = Response()
        response_value.status_code = 200
        json_return_value = compute.Region.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", "region": "sample2"}

        # get truthy value for each flattened field
        mock_args = dict(
            project="project_value",
            region="region_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}/regions/{region}" %
            client.transport._host,
            args[1],
        )
Ejemplo n.º 24
0
def test_regions_auth_adc_old_google_auth():
    # If no credentials are provided, we should use ADC credentials.
    with mock.patch.object(google.auth, "default", autospec=True) as adc:
        adc.return_value = (ga_credentials.AnonymousCredentials(), None)
        RegionsClient()
        adc.assert_called_once_with(
            scopes=(
                "https://www.googleapis.com/auth/compute.readonly",
                "https://www.googleapis.com/auth/compute",
                "https://www.googleapis.com/auth/cloud-platform",
            ),
            quota_project_id=None,
        )
Ejemplo n.º 25
0
def test_client_ctx():
    transports = [
        "rest",
    ]
    for transport in transports:
        client = RegionsClient(
            credentials=ga_credentials.AnonymousCredentials(),
            transport=transport)
        # Test client calls underlying transport.
        with mock.patch.object(type(client.transport), "close") as close:
            close.assert_not_called()
            with client:
                pass
            close.assert_called()
Ejemplo n.º 26
0
def test_transport_close():
    transports = {
        "rest": "_session",
    }

    for transport, close_name in transports.items():
        client = RegionsClient(
            credentials=ga_credentials.AnonymousCredentials(),
            transport=transport)
        with mock.patch.object(type(getattr(client.transport, close_name)),
                               "close") as close:
            with client:
                close.assert_not_called()
            close.assert_called_once()
Ejemplo n.º 27
0
def test__get_default_mtls_endpoint():
    api_endpoint = "example.googleapis.com"
    api_mtls_endpoint = "example.mtls.googleapis.com"
    sandbox_endpoint = "example.sandbox.googleapis.com"
    sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com"
    non_googleapi = "api.example.com"

    assert RegionsClient._get_default_mtls_endpoint(None) is None
    assert RegionsClient._get_default_mtls_endpoint(
        api_endpoint) == api_mtls_endpoint
    assert (RegionsClient._get_default_mtls_endpoint(api_mtls_endpoint) ==
            api_mtls_endpoint)
    assert (RegionsClient._get_default_mtls_endpoint(sandbox_endpoint) ==
            sandbox_mtls_endpoint)
    assert (RegionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) ==
            sandbox_mtls_endpoint)
    assert RegionsClient._get_default_mtls_endpoint(
        non_googleapi) == non_googleapi
Ejemplo n.º 28
0
def test_common_project_path():
    project = "cuttlefish"
    expected = "projects/{project}".format(project=project,)
    actual = RegionsClient.common_project_path(project)
    assert expected == actual
Ejemplo n.º 29
0
def test_common_organization_path():
    organization = "oyster"
    expected = "organizations/{organization}".format(organization=organization,)
    actual = RegionsClient.common_organization_path(organization)
    assert expected == actual
Ejemplo n.º 30
0
def test_common_folder_path():
    folder = "whelk"
    expected = "folders/{folder}".format(folder=folder,)
    actual = RegionsClient.common_folder_path(folder)
    assert expected == actual