`__.
+
+ Attributes:
+ name (str):
+ Full path to the ``AuthorizedDomain`` resource in the API.
+ Example: ``apps/myapp/authorizedDomains/example.com``.
+
+ @OutputOnly
+ id (str):
+ Fully qualified domain name of the domain authorized for
+ use. Example: ``example.com``.
+ """
+
+ name = proto.Field(proto.STRING, number=1)
+
+ id = proto.Field(proto.STRING, number=2)
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/google/cloud/appengine_admin_v1/types/domain_mapping.py b/google/cloud/appengine_admin_v1/types/domain_mapping.py
new file mode 100644
index 0000000..c08953b
--- /dev/null
+++ b/google/cloud/appengine_admin_v1/types/domain_mapping.py
@@ -0,0 +1,139 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import proto # type: ignore
+
+
+__protobuf__ = proto.module(
+ package="google.appengine.v1",
+ manifest={"DomainMapping", "SslSettings", "ResourceRecord",},
+)
+
+
+class DomainMapping(proto.Message):
+ r"""A domain serving an App Engine application.
+
+ Attributes:
+ name (str):
+ Full path to the ``DomainMapping`` resource in the API.
+ Example: ``apps/myapp/domainMapping/example.com``.
+
+ @OutputOnly
+ id (str):
+ Relative name of the domain serving the application.
+ Example: ``example.com``.
+ ssl_settings (google.cloud.appengine_admin_v1.types.SslSettings):
+ SSL configuration for this domain. If
+ unconfigured, this domain will not serve with
+ SSL.
+ resource_records (Sequence[google.cloud.appengine_admin_v1.types.ResourceRecord]):
+ The resource records required to configure
+ this domain mapping. These records must be added
+ to the domain's DNS configuration in order to
+ serve the application via this domain mapping.
+ @OutputOnly
+ """
+
+ name = proto.Field(proto.STRING, number=1)
+
+ id = proto.Field(proto.STRING, number=2)
+
+ ssl_settings = proto.Field(proto.MESSAGE, number=3, message="SslSettings",)
+
+ resource_records = proto.RepeatedField(
+ proto.MESSAGE, number=4, message="ResourceRecord",
+ )
+
+
+class SslSettings(proto.Message):
+ r"""SSL configuration for a ``DomainMapping`` resource.
+
+ Attributes:
+ certificate_id (str):
+ ID of the ``AuthorizedCertificate`` resource configuring SSL
+ for the application. Clearing this field will remove SSL
+ support.
+
+ By default, a managed certificate is automatically created
+ for every domain mapping. To omit SSL support or to
+ configure SSL manually, specify ``SslManagementType.MANUAL``
+ on a ``CREATE`` or ``UPDATE`` request. You must be
+ authorized to administer the ``AuthorizedCertificate``
+ resource to manually map it to a ``DomainMapping`` resource.
+ Example: ``12345``.
+ ssl_management_type (google.cloud.appengine_admin_v1.types.SslSettings.SslManagementType):
+ SSL management type for this domain. If ``AUTOMATIC``, a
+ managed certificate is automatically provisioned. If
+ ``MANUAL``, ``certificate_id`` must be manually specified in
+ order to configure SSL for this domain.
+ pending_managed_certificate_id (str):
+ ID of the managed ``AuthorizedCertificate`` resource
+ currently being provisioned, if applicable. Until the new
+ managed certificate has been successfully provisioned, the
+ previous SSL state will be preserved. Once the provisioning
+ process completes, the ``certificate_id`` field will reflect
+ the new managed certificate and this field will be left
+ empty. To remove SSL support while there is still a pending
+ managed certificate, clear the ``certificate_id`` field with
+ an ``UpdateDomainMappingRequest``.
+
+ @OutputOnly
+ """
+
+ class SslManagementType(proto.Enum):
+ r"""The SSL management type for this domain."""
+ SSL_MANAGEMENT_TYPE_UNSPECIFIED = 0
+ AUTOMATIC = 1
+ MANUAL = 2
+
+ certificate_id = proto.Field(proto.STRING, number=1)
+
+ ssl_management_type = proto.Field(proto.ENUM, number=3, enum=SslManagementType,)
+
+ pending_managed_certificate_id = proto.Field(proto.STRING, number=4)
+
+
+class ResourceRecord(proto.Message):
+ r"""A DNS resource record.
+
+ Attributes:
+ name (str):
+ Relative name of the object affected by this record. Only
+ applicable for ``CNAME`` records. Example: 'www'.
+ rrdata (str):
+ Data for this record. Values vary by record
+ type, as defined in RFC 1035 (section 5) and RFC
+ 1034 (section 3.6.1).
+ type_ (google.cloud.appengine_admin_v1.types.ResourceRecord.RecordType):
+ Resource record type. Example: ``AAAA``.
+ """
+
+ class RecordType(proto.Enum):
+ r"""A resource record type."""
+ RECORD_TYPE_UNSPECIFIED = 0
+ A = 1
+ AAAA = 2
+ CNAME = 3
+
+ name = proto.Field(proto.STRING, number=1)
+
+ rrdata = proto.Field(proto.STRING, number=2)
+
+ type_ = proto.Field(proto.ENUM, number=3, enum=RecordType,)
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/google/cloud/appengine_admin_v1/types/firewall.py b/google/cloud/appengine_admin_v1/types/firewall.py
new file mode 100644
index 0000000..e3b179b
--- /dev/null
+++ b/google/cloud/appengine_admin_v1/types/firewall.py
@@ -0,0 +1,74 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import proto # type: ignore
+
+
+__protobuf__ = proto.module(package="google.appengine.v1", manifest={"FirewallRule",},)
+
+
+class FirewallRule(proto.Message):
+ r"""A single firewall rule that is evaluated against incoming
+ traffic and provides an action to take on matched requests.
+
+ Attributes:
+ priority (int):
+ A positive integer between [1, Int32.MaxValue-1] that
+ defines the order of rule evaluation. Rules with the lowest
+ priority are evaluated first.
+
+ A default rule at priority Int32.MaxValue matches all IPv4
+ and IPv6 traffic when no previous rule matches. Only the
+ action of this rule can be modified by the user.
+ action (google.cloud.appengine_admin_v1.types.FirewallRule.Action):
+ The action to take on matched requests.
+ source_range (str):
+ IP address or range, defined using CIDR notation, of
+ requests that this rule applies to. You can use the wildcard
+ character "*" to match all IPs equivalent to "0/0" and
+ "::/0" together. Examples: ``192.168.1.1`` or
+ ``192.168.0.0/16`` or ``2001:db8::/32`` or
+ ``2001:0db8:0000:0042:0000:8a2e:0370:7334``.
+
+ .. raw:: html
+
+ Truncation will be silently performed on addresses which are not
+ properly truncated. For example, `1.2.3.4/24` is accepted as the same
+ address as `1.2.3.0/24`. Similarly, for IPv6, `2001:db8::1/32` is accepted
+ as the same address as `2001:db8::/32`.
+ description (str):
+ An optional string description of this rule.
+ This field has a maximum length of 100
+ characters.
+ """
+
+ class Action(proto.Enum):
+ r"""Available actions to take on matching requests."""
+ UNSPECIFIED_ACTION = 0
+ ALLOW = 1
+ DENY = 2
+
+ priority = proto.Field(proto.INT32, number=1)
+
+ action = proto.Field(proto.ENUM, number=2, enum=Action,)
+
+ source_range = proto.Field(proto.STRING, number=3)
+
+ description = proto.Field(proto.STRING, number=4)
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/google/cloud/appengine_admin_v1/types/instance.py b/google/cloud/appengine_admin_v1/types/instance.py
new file mode 100644
index 0000000..72422cf
--- /dev/null
+++ b/google/cloud/appengine_admin_v1/types/instance.py
@@ -0,0 +1,145 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import proto # type: ignore
+
+
+from google.protobuf import timestamp_pb2 as timestamp # type: ignore
+
+
+__protobuf__ = proto.module(package="google.appengine.v1", manifest={"Instance",},)
+
+
+class Instance(proto.Message):
+ r"""An Instance resource is the computing unit that App Engine
+ uses to automatically scale an application.
+
+ Attributes:
+ name (str):
+ Output only. Full path to the Instance resource in the API.
+ Example:
+ ``apps/myapp/services/default/versions/v1/instances/instance-1``.
+ id (str):
+ Output only. Relative name of the instance within the
+ version. Example: ``instance-1``.
+ app_engine_release (str):
+ Output only. App Engine release this instance
+ is running on.
+ availability (google.cloud.appengine_admin_v1.types.Instance.Availability):
+ Output only. Availability of the instance.
+ vm_name (str):
+ Output only. Name of the virtual machine
+ where this instance lives. Only applicable for
+ instances in App Engine flexible environment.
+ vm_zone_name (str):
+ Output only. Zone where the virtual machine
+ is located. Only applicable for instances in App
+ Engine flexible environment.
+ vm_id (str):
+ Output only. Virtual machine ID of this
+ instance. Only applicable for instances in App
+ Engine flexible environment.
+ start_time (google.protobuf.timestamp_pb2.Timestamp):
+ Output only. Time that this instance was
+ started.
+ @OutputOnly
+ requests (int):
+ Output only. Number of requests since this
+ instance was started.
+ errors (int):
+ Output only. Number of errors since this
+ instance was started.
+ qps (float):
+ Output only. Average queries per second (QPS)
+ over the last minute.
+ average_latency (int):
+ Output only. Average latency (ms) over the
+ last minute.
+ memory_usage (int):
+ Output only. Total memory in use (bytes).
+ vm_status (str):
+ Output only. Status of the virtual machine
+ where this instance lives. Only applicable for
+ instances in App Engine flexible environment.
+ vm_debug_enabled (bool):
+ Output only. Whether this instance is in
+ debug mode. Only applicable for instances in App
+ Engine flexible environment.
+ vm_ip (str):
+ Output only. The IP address of this instance.
+ Only applicable for instances in App Engine
+ flexible environment.
+ vm_liveness (google.cloud.appengine_admin_v1.types.Instance.Liveness.LivenessState):
+ Output only. The liveness health check of
+ this instance. Only applicable for instances in
+ App Engine flexible environment.
+ """
+
+ class Availability(proto.Enum):
+ r"""Availability of the instance."""
+ UNSPECIFIED = 0
+ RESIDENT = 1
+ DYNAMIC = 2
+
+ class Liveness(proto.Message):
+ r"""Wrapper for LivenessState enum."""
+
+ class LivenessState(proto.Enum):
+ r"""Liveness health check status for Flex instances."""
+ LIVENESS_STATE_UNSPECIFIED = 0
+ UNKNOWN = 1
+ HEALTHY = 2
+ UNHEALTHY = 3
+ DRAINING = 4
+ TIMEOUT = 5
+
+ name = proto.Field(proto.STRING, number=1)
+
+ id = proto.Field(proto.STRING, number=2)
+
+ app_engine_release = proto.Field(proto.STRING, number=3)
+
+ availability = proto.Field(proto.ENUM, number=4, enum=Availability,)
+
+ vm_name = proto.Field(proto.STRING, number=5)
+
+ vm_zone_name = proto.Field(proto.STRING, number=6)
+
+ vm_id = proto.Field(proto.STRING, number=7)
+
+ start_time = proto.Field(proto.MESSAGE, number=8, message=timestamp.Timestamp,)
+
+ requests = proto.Field(proto.INT32, number=9)
+
+ errors = proto.Field(proto.INT32, number=10)
+
+ qps = proto.Field(proto.FLOAT, number=11)
+
+ average_latency = proto.Field(proto.INT32, number=12)
+
+ memory_usage = proto.Field(proto.INT64, number=13)
+
+ vm_status = proto.Field(proto.STRING, number=14)
+
+ vm_debug_enabled = proto.Field(proto.BOOL, number=15)
+
+ vm_ip = proto.Field(proto.STRING, number=16)
+
+ vm_liveness = proto.Field(proto.ENUM, number=17, enum=Liveness.LivenessState,)
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/google/cloud/appengine_admin_v1/types/location.py b/google/cloud/appengine_admin_v1/types/location.py
new file mode 100644
index 0000000..a9a3e3e
--- /dev/null
+++ b/google/cloud/appengine_admin_v1/types/location.py
@@ -0,0 +1,52 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import proto # type: ignore
+
+
+__protobuf__ = proto.module(
+ package="google.appengine.v1", manifest={"LocationMetadata",},
+)
+
+
+class LocationMetadata(proto.Message):
+ r"""Metadata for the given
+ [google.cloud.location.Location][google.cloud.location.Location].
+
+ Attributes:
+ standard_environment_available (bool):
+ App Engine standard environment is available
+ in the given location.
+ @OutputOnly
+ flexible_environment_available (bool):
+ App Engine flexible environment is available
+ in the given location.
+ @OutputOnly
+ search_api_available (bool):
+ Output only. `Search
+ API `__
+ is available in the given location.
+ """
+
+ standard_environment_available = proto.Field(proto.BOOL, number=2)
+
+ flexible_environment_available = proto.Field(proto.BOOL, number=4)
+
+ search_api_available = proto.Field(proto.BOOL, number=6)
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/google/cloud/appengine_admin_v1/types/network_settings.py b/google/cloud/appengine_admin_v1/types/network_settings.py
new file mode 100644
index 0000000..81e51dc
--- /dev/null
+++ b/google/cloud/appengine_admin_v1/types/network_settings.py
@@ -0,0 +1,47 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import proto # type: ignore
+
+
+__protobuf__ = proto.module(
+ package="google.appengine.v1", manifest={"NetworkSettings",},
+)
+
+
+class NetworkSettings(proto.Message):
+ r"""A NetworkSettings resource is a container for ingress
+ settings for a version or service.
+
+ Attributes:
+ ingress_traffic_allowed (google.cloud.appengine_admin_v1.types.NetworkSettings.IngressTrafficAllowed):
+ The ingress settings for version or service.
+ """
+
+ class IngressTrafficAllowed(proto.Enum):
+ r"""If unspecified, INGRESS_TRAFFIC_ALLOWED_ALL will be used."""
+ INGRESS_TRAFFIC_ALLOWED_UNSPECIFIED = 0
+ INGRESS_TRAFFIC_ALLOWED_ALL = 1
+ INGRESS_TRAFFIC_ALLOWED_INTERNAL_ONLY = 2
+ INGRESS_TRAFFIC_ALLOWED_INTERNAL_AND_LB = 3
+
+ ingress_traffic_allowed = proto.Field(
+ proto.ENUM, number=1, enum=IngressTrafficAllowed,
+ )
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/google/cloud/appengine_admin_v1/types/operation.py b/google/cloud/appengine_admin_v1/types/operation.py
new file mode 100644
index 0000000..79619d4
--- /dev/null
+++ b/google/cloud/appengine_admin_v1/types/operation.py
@@ -0,0 +1,101 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import proto # type: ignore
+
+
+from google.protobuf import timestamp_pb2 as timestamp # type: ignore
+
+
+__protobuf__ = proto.module(
+ package="google.appengine.v1",
+ manifest={"OperationMetadataV1", "CreateVersionMetadataV1",},
+)
+
+
+class OperationMetadataV1(proto.Message):
+ r"""Metadata for the given
+ [google.longrunning.Operation][google.longrunning.Operation].
+
+ Attributes:
+ method (str):
+ API method that initiated this operation. Example:
+ ``google.appengine.v1.Versions.CreateVersion``.
+
+ @OutputOnly
+ insert_time (google.protobuf.timestamp_pb2.Timestamp):
+ Time that this operation was created.
+ @OutputOnly
+ end_time (google.protobuf.timestamp_pb2.Timestamp):
+ Time that this operation completed.
+ @OutputOnly
+ user (str):
+ User who requested this operation.
+ @OutputOnly
+ target (str):
+ Name of the resource that this operation is acting on.
+ Example: ``apps/myapp/services/default``.
+
+ @OutputOnly
+ ephemeral_message (str):
+ Ephemeral message that may change every time
+ the operation is polled. @OutputOnly
+ warning (Sequence[str]):
+ Durable messages that persist on every
+ operation poll. @OutputOnly
+ create_version_metadata (google.cloud.appengine_admin_v1.types.CreateVersionMetadataV1):
+
+ """
+
+ method = proto.Field(proto.STRING, number=1)
+
+ insert_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,)
+
+ end_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,)
+
+ user = proto.Field(proto.STRING, number=4)
+
+ target = proto.Field(proto.STRING, number=5)
+
+ ephemeral_message = proto.Field(proto.STRING, number=6)
+
+ warning = proto.RepeatedField(proto.STRING, number=7)
+
+ create_version_metadata = proto.Field(
+ proto.MESSAGE,
+ number=8,
+ oneof="method_metadata",
+ message="CreateVersionMetadataV1",
+ )
+
+
+class CreateVersionMetadataV1(proto.Message):
+ r"""Metadata for the given
+ [google.longrunning.Operation][google.longrunning.Operation] during
+ a
+ [google.appengine.v1.CreateVersionRequest][google.appengine.v1.CreateVersionRequest].
+
+ Attributes:
+ cloud_build_id (str):
+ The Cloud Build ID if one was created as part
+ of the version create. @OutputOnly
+ """
+
+ cloud_build_id = proto.Field(proto.STRING, number=1)
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/google/cloud/appengine_admin_v1/types/service.py b/google/cloud/appengine_admin_v1/types/service.py
new file mode 100644
index 0000000..c44eac5
--- /dev/null
+++ b/google/cloud/appengine_admin_v1/types/service.py
@@ -0,0 +1,107 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import proto # type: ignore
+
+
+from google.cloud.appengine_admin_v1.types import (
+ network_settings as ga_network_settings,
+)
+
+
+__protobuf__ = proto.module(
+ package="google.appengine.v1", manifest={"Service", "TrafficSplit",},
+)
+
+
+class Service(proto.Message):
+ r"""A Service resource is a logical component of an application
+ that can share state and communicate in a secure fashion with
+ other services. For example, an application that handles
+ customer requests might include separate services to handle
+ tasks such as backend data analysis or API requests from mobile
+ devices. Each service has a collection of versions that define a
+ specific set of code used to implement the functionality of that
+ service.
+
+ Attributes:
+ name (str):
+ Full path to the Service resource in the API. Example:
+ ``apps/myapp/services/default``.
+
+ @OutputOnly
+ id (str):
+ Relative name of the service within the application.
+ Example: ``default``.
+
+ @OutputOnly
+ split (google.cloud.appengine_admin_v1.types.TrafficSplit):
+ Mapping that defines fractional HTTP traffic
+ diversion to different versions within the
+ service.
+ network_settings (google.cloud.appengine_admin_v1.types.NetworkSettings):
+ Ingress settings for this service. Will apply
+ to all versions.
+ """
+
+ name = proto.Field(proto.STRING, number=1)
+
+ id = proto.Field(proto.STRING, number=2)
+
+ split = proto.Field(proto.MESSAGE, number=3, message="TrafficSplit",)
+
+ network_settings = proto.Field(
+ proto.MESSAGE, number=6, message=ga_network_settings.NetworkSettings,
+ )
+
+
+class TrafficSplit(proto.Message):
+ r"""Traffic routing configuration for versions within a single
+ service. Traffic splits define how traffic directed to the
+ service is assigned to versions.
+
+ Attributes:
+ shard_by (google.cloud.appengine_admin_v1.types.TrafficSplit.ShardBy):
+ Mechanism used to determine which version a
+ request is sent to. The traffic selection
+ algorithm will be stable for either type until
+ allocations are changed.
+ allocations (Sequence[google.cloud.appengine_admin_v1.types.TrafficSplit.AllocationsEntry]):
+ Mapping from version IDs within the service to fractional
+ (0.000, 1] allocations of traffic for that version. Each
+ version can be specified only once, but some versions in the
+ service may not have any traffic allocation. Services that
+ have traffic allocated cannot be deleted until either the
+ service is deleted or their traffic allocation is removed.
+ Allocations must sum to 1. Up to two decimal place precision
+ is supported for IP-based splits and up to three decimal
+ places is supported for cookie-based splits.
+ """
+
+ class ShardBy(proto.Enum):
+ r"""Available sharding mechanisms."""
+ UNSPECIFIED = 0
+ COOKIE = 1
+ IP = 2
+ RANDOM = 3
+
+ shard_by = proto.Field(proto.ENUM, number=1, enum=ShardBy,)
+
+ allocations = proto.MapField(proto.STRING, proto.DOUBLE, number=2)
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/google/cloud/appengine_admin_v1/types/version.py b/google/cloud/appengine_admin_v1/types/version.py
new file mode 100644
index 0000000..ac2bfac
--- /dev/null
+++ b/google/cloud/appengine_admin_v1/types/version.py
@@ -0,0 +1,784 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import proto # type: ignore
+
+
+from google.cloud.appengine_admin_v1.types import app_yaml
+from google.cloud.appengine_admin_v1.types import deploy
+from google.protobuf import duration_pb2 as duration # type: ignore
+from google.protobuf import timestamp_pb2 as timestamp # type: ignore
+
+
+__protobuf__ = proto.module(
+ package="google.appengine.v1",
+ manifest={
+ "InboundServiceType",
+ "ServingStatus",
+ "Version",
+ "EndpointsApiService",
+ "AutomaticScaling",
+ "BasicScaling",
+ "ManualScaling",
+ "CpuUtilization",
+ "RequestUtilization",
+ "DiskUtilization",
+ "NetworkUtilization",
+ "StandardSchedulerSettings",
+ "Network",
+ "Volume",
+ "Resources",
+ "VpcAccessConnector",
+ "Entrypoint",
+ },
+)
+
+
+class InboundServiceType(proto.Enum):
+ r"""Available inbound services."""
+ INBOUND_SERVICE_UNSPECIFIED = 0
+ INBOUND_SERVICE_MAIL = 1
+ INBOUND_SERVICE_MAIL_BOUNCE = 2
+ INBOUND_SERVICE_XMPP_ERROR = 3
+ INBOUND_SERVICE_XMPP_MESSAGE = 4
+ INBOUND_SERVICE_XMPP_SUBSCRIBE = 5
+ INBOUND_SERVICE_XMPP_PRESENCE = 6
+ INBOUND_SERVICE_CHANNEL_PRESENCE = 7
+ INBOUND_SERVICE_WARMUP = 9
+
+
+class ServingStatus(proto.Enum):
+ r"""Run states of a version."""
+ SERVING_STATUS_UNSPECIFIED = 0
+ SERVING = 1
+ STOPPED = 2
+
+
+class Version(proto.Message):
+ r"""A Version resource is a specific set of source code and
+ configuration files that are deployed into a service.
+
+ Attributes:
+ name (str):
+ Full path to the Version resource in the API. Example:
+ ``apps/myapp/services/default/versions/v1``.
+
+ @OutputOnly
+ id (str):
+ Relative name of the version within the service. Example:
+ ``v1``. Version names can contain only lowercase letters,
+ numbers, or hyphens. Reserved names: "default", "latest",
+ and any name with the prefix "ah-".
+ automatic_scaling (google.cloud.appengine_admin_v1.types.AutomaticScaling):
+ Automatic scaling is based on request rate,
+ response latencies, and other application
+ metrics. Instances are dynamically created and
+ destroyed as needed in order to handle traffic.
+ basic_scaling (google.cloud.appengine_admin_v1.types.BasicScaling):
+ A service with basic scaling will create an
+ instance when the application receives a
+ request. The instance will be turned down when
+ the app becomes idle. Basic scaling is ideal for
+ work that is intermittent or driven by user
+ activity.
+ manual_scaling (google.cloud.appengine_admin_v1.types.ManualScaling):
+ A service with manual scaling runs
+ continuously, allowing you to perform complex
+ initialization and rely on the state of its
+ memory over time. Manually scaled versions are
+ sometimes referred to as "backends".
+ inbound_services (Sequence[google.cloud.appengine_admin_v1.types.InboundServiceType]):
+ Before an application can receive email or
+ XMPP messages, the application must be
+ configured to enable the service.
+ instance_class (str):
+ Instance class that is used to run this version. Valid
+ values are:
+
+ - AutomaticScaling: ``F1``, ``F2``, ``F4``, ``F4_1G``
+ - ManualScaling or BasicScaling: ``B1``, ``B2``, ``B4``,
+ ``B8``, ``B4_1G``
+
+ Defaults to ``F1`` for AutomaticScaling and ``B1`` for
+ ManualScaling or BasicScaling.
+ network (google.cloud.appengine_admin_v1.types.Network):
+ Extra network settings.
+ Only applicable in the App Engine flexible
+ environment.
+ zones (Sequence[str]):
+ The Google Compute Engine zones that are
+ supported by this version in the App Engine
+ flexible environment. Deprecated.
+ resources (google.cloud.appengine_admin_v1.types.Resources):
+ Machine resources for this version.
+ Only applicable in the App Engine flexible
+ environment.
+ runtime (str):
+ Desired runtime. Example: ``python27``.
+ runtime_channel (str):
+ The channel of the runtime to use. Only available for some
+ runtimes. Defaults to the ``default`` channel.
+ threadsafe (bool):
+ Whether multiple requests can be dispatched
+ to this version at once.
+ vm (bool):
+ Whether to deploy this version in a container
+ on a virtual machine.
+ beta_settings (Sequence[google.cloud.appengine_admin_v1.types.Version.BetaSettingsEntry]):
+ Metadata settings that are supplied to this
+ version to enable beta runtime features.
+ env (str):
+ App Engine execution environment for this version.
+
+ Defaults to ``standard``.
+ serving_status (google.cloud.appengine_admin_v1.types.ServingStatus):
+ Current serving status of this version. Only the versions
+ with a ``SERVING`` status create instances and can be
+ billed.
+
+ ``SERVING_STATUS_UNSPECIFIED`` is an invalid value. Defaults
+ to ``SERVING``.
+ created_by (str):
+ Email address of the user who created this
+ version.
+ @OutputOnly
+ create_time (google.protobuf.timestamp_pb2.Timestamp):
+ Time that this version was created.
+ @OutputOnly
+ disk_usage_bytes (int):
+ Total size in bytes of all the files that are
+ included in this version and currently hosted on
+ the App Engine disk.
+ @OutputOnly
+ runtime_api_version (str):
+ The version of the API in the given runtime
+ environment. Please see the app.yaml reference
+ for valid values at
+ https://cloud.google.com/appengine/docs/standard//config/appref
+ runtime_main_executable_path (str):
+ The path or name of the app's main
+ executable.
+ service_account (str):
+ The identity that the deployed version will
+ run as. Admin API will use the App Engine
+ Appspot service account as default if this field
+ is neither provided in app.yaml file nor through
+ CLI flag.
+ handlers (Sequence[google.cloud.appengine_admin_v1.types.UrlMap]):
+ An ordered list of URL-matching patterns that should be
+ applied to incoming requests. The first matching URL handles
+ the request and other request handlers are not attempted.
+
+ Only returned in ``GET`` requests if ``view=FULL`` is set.
+ error_handlers (Sequence[google.cloud.appengine_admin_v1.types.ErrorHandler]):
+ Custom static error pages. Limited to 10KB per page.
+
+ Only returned in ``GET`` requests if ``view=FULL`` is set.
+ libraries (Sequence[google.cloud.appengine_admin_v1.types.Library]):
+ Configuration for third-party Python runtime libraries that
+ are required by the application.
+
+ Only returned in ``GET`` requests if ``view=FULL`` is set.
+ api_config (google.cloud.appengine_admin_v1.types.ApiConfigHandler):
+ Serving configuration for `Google Cloud
+ Endpoints `__.
+
+ Only returned in ``GET`` requests if ``view=FULL`` is set.
+ env_variables (Sequence[google.cloud.appengine_admin_v1.types.Version.EnvVariablesEntry]):
+ Environment variables available to the application.
+
+ Only returned in ``GET`` requests if ``view=FULL`` is set.
+ build_env_variables (Sequence[google.cloud.appengine_admin_v1.types.Version.BuildEnvVariablesEntry]):
+ Environment variables available to the build environment.
+
+ Only returned in ``GET`` requests if ``view=FULL`` is set.
+ default_expiration (google.protobuf.duration_pb2.Duration):
+ Duration that static files should be cached by web proxies
+ and browsers. Only applicable if the corresponding
+ `StaticFilesHandler `__
+ does not specify its own expiration time.
+
+ Only returned in ``GET`` requests if ``view=FULL`` is set.
+ health_check (google.cloud.appengine_admin_v1.types.HealthCheck):
+ Configures health checking for instances. Unhealthy
+ instances are stopped and replaced with new instances. Only
+ applicable in the App Engine flexible environment.
+
+ Only returned in ``GET`` requests if ``view=FULL`` is set.
+ readiness_check (google.cloud.appengine_admin_v1.types.ReadinessCheck):
+ Configures readiness health checking for instances.
+ Unhealthy instances are not put into the backend traffic
+ rotation.
+
+ Only returned in ``GET`` requests if ``view=FULL`` is set.
+ liveness_check (google.cloud.appengine_admin_v1.types.LivenessCheck):
+ Configures liveness health checking for instances. Unhealthy
+ instances are stopped and replaced with new instances
+
+ Only returned in ``GET`` requests if ``view=FULL`` is set.
+ nobuild_files_regex (str):
+ Files that match this pattern will not be built into this
+ version. Only applicable for Go runtimes.
+
+ Only returned in ``GET`` requests if ``view=FULL`` is set.
+ deployment (google.cloud.appengine_admin_v1.types.Deployment):
+ Code and application artifacts that make up this version.
+
+ Only returned in ``GET`` requests if ``view=FULL`` is set.
+ version_url (str):
+ Serving URL for this version. Example:
+ "https://myversion-dot-myservice-dot-
+ myapp.appspot.com"
+ @OutputOnly
+ endpoints_api_service (google.cloud.appengine_admin_v1.types.EndpointsApiService):
+ Cloud Endpoints configuration.
+
+ If endpoints_api_service is set, the Cloud Endpoints
+ Extensible Service Proxy will be provided to serve the API
+ implemented by the app.
+ entrypoint (google.cloud.appengine_admin_v1.types.Entrypoint):
+ The entrypoint for the application.
+ vpc_access_connector (google.cloud.appengine_admin_v1.types.VpcAccessConnector):
+ Enables VPC connectivity for standard apps.
+ """
+
+ name = proto.Field(proto.STRING, number=1)
+
+ id = proto.Field(proto.STRING, number=2)
+
+ automatic_scaling = proto.Field(
+ proto.MESSAGE, number=3, oneof="scaling", message="AutomaticScaling",
+ )
+
+ basic_scaling = proto.Field(
+ proto.MESSAGE, number=4, oneof="scaling", message="BasicScaling",
+ )
+
+ manual_scaling = proto.Field(
+ proto.MESSAGE, number=5, oneof="scaling", message="ManualScaling",
+ )
+
+ inbound_services = proto.RepeatedField(
+ proto.ENUM, number=6, enum="InboundServiceType",
+ )
+
+ instance_class = proto.Field(proto.STRING, number=7)
+
+ network = proto.Field(proto.MESSAGE, number=8, message="Network",)
+
+ zones = proto.RepeatedField(proto.STRING, number=118)
+
+ resources = proto.Field(proto.MESSAGE, number=9, message="Resources",)
+
+ runtime = proto.Field(proto.STRING, number=10)
+
+ runtime_channel = proto.Field(proto.STRING, number=117)
+
+ threadsafe = proto.Field(proto.BOOL, number=11)
+
+ vm = proto.Field(proto.BOOL, number=12)
+
+ beta_settings = proto.MapField(proto.STRING, proto.STRING, number=13)
+
+ env = proto.Field(proto.STRING, number=14)
+
+ serving_status = proto.Field(proto.ENUM, number=15, enum="ServingStatus",)
+
+ created_by = proto.Field(proto.STRING, number=16)
+
+ create_time = proto.Field(proto.MESSAGE, number=17, message=timestamp.Timestamp,)
+
+ disk_usage_bytes = proto.Field(proto.INT64, number=18)
+
+ runtime_api_version = proto.Field(proto.STRING, number=21)
+
+ runtime_main_executable_path = proto.Field(proto.STRING, number=22)
+
+ service_account = proto.Field(proto.STRING, number=127)
+
+ handlers = proto.RepeatedField(proto.MESSAGE, number=100, message=app_yaml.UrlMap,)
+
+ error_handlers = proto.RepeatedField(
+ proto.MESSAGE, number=101, message=app_yaml.ErrorHandler,
+ )
+
+ libraries = proto.RepeatedField(
+ proto.MESSAGE, number=102, message=app_yaml.Library,
+ )
+
+ api_config = proto.Field(
+ proto.MESSAGE, number=103, message=app_yaml.ApiConfigHandler,
+ )
+
+ env_variables = proto.MapField(proto.STRING, proto.STRING, number=104)
+
+ build_env_variables = proto.MapField(proto.STRING, proto.STRING, number=125)
+
+ default_expiration = proto.Field(
+ proto.MESSAGE, number=105, message=duration.Duration,
+ )
+
+ health_check = proto.Field(proto.MESSAGE, number=106, message=app_yaml.HealthCheck,)
+
+ readiness_check = proto.Field(
+ proto.MESSAGE, number=112, message=app_yaml.ReadinessCheck,
+ )
+
+ liveness_check = proto.Field(
+ proto.MESSAGE, number=113, message=app_yaml.LivenessCheck,
+ )
+
+ nobuild_files_regex = proto.Field(proto.STRING, number=107)
+
+ deployment = proto.Field(proto.MESSAGE, number=108, message=deploy.Deployment,)
+
+ version_url = proto.Field(proto.STRING, number=109)
+
+ endpoints_api_service = proto.Field(
+ proto.MESSAGE, number=110, message="EndpointsApiService",
+ )
+
+ entrypoint = proto.Field(proto.MESSAGE, number=122, message="Entrypoint",)
+
+ vpc_access_connector = proto.Field(
+ proto.MESSAGE, number=121, message="VpcAccessConnector",
+ )
+
+
+class EndpointsApiService(proto.Message):
+ r"""`Cloud Endpoints `__
+ configuration. The Endpoints API Service provides tooling for
+ serving Open API and gRPC endpoints via an NGINX proxy. Only valid
+ for App Engine Flexible environment deployments.
+
+ The fields here refer to the name and configuration ID of a
+ "service" resource in the `Service Management
+ API `__.
+
+ Attributes:
+ name (str):
+ Endpoints service name which is the name of
+ the "service" resource in the Service Management
+ API. For example
+ "myapi.endpoints.myproject.cloud.goog".
+ config_id (str):
+ Endpoints service configuration ID as specified by the
+ Service Management API. For example "2016-09-19r1".
+
+ By default, the rollout strategy for Endpoints is
+ ``RolloutStrategy.FIXED``. This means that Endpoints starts
+ up with a particular configuration ID. When a new
+ configuration is rolled out, Endpoints must be given the new
+ configuration ID. The ``config_id`` field is used to give
+ the configuration ID and is required in this case.
+
+ Endpoints also has a rollout strategy called
+ ``RolloutStrategy.MANAGED``. When using this, Endpoints
+ fetches the latest configuration and does not need the
+ configuration ID. In this case, ``config_id`` must be
+ omitted.
+ rollout_strategy (google.cloud.appengine_admin_v1.types.EndpointsApiService.RolloutStrategy):
+ Endpoints rollout strategy. If ``FIXED``, ``config_id`` must
+ be specified. If ``MANAGED``, ``config_id`` must be omitted.
+ disable_trace_sampling (bool):
+ Enable or disable trace sampling. By default,
+ this is set to false for enabled.
+ """
+
+ class RolloutStrategy(proto.Enum):
+ r"""Available rollout strategies."""
+ UNSPECIFIED_ROLLOUT_STRATEGY = 0
+ FIXED = 1
+ MANAGED = 2
+
+ name = proto.Field(proto.STRING, number=1)
+
+ config_id = proto.Field(proto.STRING, number=2)
+
+ rollout_strategy = proto.Field(proto.ENUM, number=3, enum=RolloutStrategy,)
+
+ disable_trace_sampling = proto.Field(proto.BOOL, number=4)
+
+
+class AutomaticScaling(proto.Message):
+ r"""Automatic scaling is based on request rate, response
+ latencies, and other application metrics.
+
+ Attributes:
+ cool_down_period (google.protobuf.duration_pb2.Duration):
+ The time period that the
+ `Autoscaler `__
+ should wait before it starts collecting information from a
+ new instance. This prevents the autoscaler from collecting
+ information when the instance is initializing, during which
+ the collected usage would not be reliable. Only applicable
+ in the App Engine flexible environment.
+ cpu_utilization (google.cloud.appengine_admin_v1.types.CpuUtilization):
+ Target scaling by CPU usage.
+ max_concurrent_requests (int):
+ Number of concurrent requests an automatic
+ scaling instance can accept before the scheduler
+ spawns a new instance.
+ Defaults to a runtime-specific value.
+ max_idle_instances (int):
+ Maximum number of idle instances that should
+ be maintained for this version.
+ max_total_instances (int):
+ Maximum number of instances that should be
+ started to handle requests for this version.
+ max_pending_latency (google.protobuf.duration_pb2.Duration):
+ Maximum amount of time that a request should
+ wait in the pending queue before starting a new
+ instance to handle it.
+ min_idle_instances (int):
+ Minimum number of idle instances that should
+ be maintained for this version. Only applicable
+ for the default version of a service.
+ min_total_instances (int):
+ Minimum number of running instances that
+ should be maintained for this version.
+ min_pending_latency (google.protobuf.duration_pb2.Duration):
+ Minimum amount of time a request should wait
+ in the pending queue before starting a new
+ instance to handle it.
+ request_utilization (google.cloud.appengine_admin_v1.types.RequestUtilization):
+ Target scaling by request utilization.
+ disk_utilization (google.cloud.appengine_admin_v1.types.DiskUtilization):
+ Target scaling by disk usage.
+ network_utilization (google.cloud.appengine_admin_v1.types.NetworkUtilization):
+ Target scaling by network usage.
+ standard_scheduler_settings (google.cloud.appengine_admin_v1.types.StandardSchedulerSettings):
+ Scheduler settings for standard environment.
+ """
+
+ cool_down_period = proto.Field(proto.MESSAGE, number=1, message=duration.Duration,)
+
+ cpu_utilization = proto.Field(proto.MESSAGE, number=2, message="CpuUtilization",)
+
+ max_concurrent_requests = proto.Field(proto.INT32, number=3)
+
+ max_idle_instances = proto.Field(proto.INT32, number=4)
+
+ max_total_instances = proto.Field(proto.INT32, number=5)
+
+ max_pending_latency = proto.Field(
+ proto.MESSAGE, number=6, message=duration.Duration,
+ )
+
+ min_idle_instances = proto.Field(proto.INT32, number=7)
+
+ min_total_instances = proto.Field(proto.INT32, number=8)
+
+ min_pending_latency = proto.Field(
+ proto.MESSAGE, number=9, message=duration.Duration,
+ )
+
+ request_utilization = proto.Field(
+ proto.MESSAGE, number=10, message="RequestUtilization",
+ )
+
+ disk_utilization = proto.Field(proto.MESSAGE, number=11, message="DiskUtilization",)
+
+ network_utilization = proto.Field(
+ proto.MESSAGE, number=12, message="NetworkUtilization",
+ )
+
+ standard_scheduler_settings = proto.Field(
+ proto.MESSAGE, number=20, message="StandardSchedulerSettings",
+ )
+
+
+class BasicScaling(proto.Message):
+ r"""A service with basic scaling will create an instance when the
+ application receives a request. The instance will be turned down
+ when the app becomes idle. Basic scaling is ideal for work that
+ is intermittent or driven by user activity.
+
+ Attributes:
+ idle_timeout (google.protobuf.duration_pb2.Duration):
+ Duration of time after the last request that
+ an instance must wait before the instance is
+ shut down.
+ max_instances (int):
+ Maximum number of instances to create for
+ this version.
+ """
+
+ idle_timeout = proto.Field(proto.MESSAGE, number=1, message=duration.Duration,)
+
+ max_instances = proto.Field(proto.INT32, number=2)
+
+
+class ManualScaling(proto.Message):
+ r"""A service with manual scaling runs continuously, allowing you
+ to perform complex initialization and rely on the state of its
+ memory over time.
+
+ Attributes:
+ instances (int):
+ Number of instances to assign to the service at the start.
+ This number can later be altered by using the `Modules
+ API `__
+ ``set_num_instances()`` function.
+ """
+
+ instances = proto.Field(proto.INT32, number=1)
+
+
+class CpuUtilization(proto.Message):
+ r"""Target scaling by CPU usage.
+
+ Attributes:
+ aggregation_window_length (google.protobuf.duration_pb2.Duration):
+ Period of time over which CPU utilization is
+ calculated.
+ target_utilization (float):
+ Target CPU utilization ratio to maintain when
+ scaling. Must be between 0 and 1.
+ """
+
+ aggregation_window_length = proto.Field(
+ proto.MESSAGE, number=1, message=duration.Duration,
+ )
+
+ target_utilization = proto.Field(proto.DOUBLE, number=2)
+
+
+class RequestUtilization(proto.Message):
+ r"""Target scaling by request utilization.
+ Only applicable in the App Engine flexible environment.
+
+ Attributes:
+ target_request_count_per_second (int):
+ Target requests per second.
+ target_concurrent_requests (int):
+ Target number of concurrent requests.
+ """
+
+ target_request_count_per_second = proto.Field(proto.INT32, number=1)
+
+ target_concurrent_requests = proto.Field(proto.INT32, number=2)
+
+
+class DiskUtilization(proto.Message):
+ r"""Target scaling by disk usage.
+ Only applicable in the App Engine flexible environment.
+
+ Attributes:
+ target_write_bytes_per_second (int):
+ Target bytes written per second.
+ target_write_ops_per_second (int):
+ Target ops written per second.
+ target_read_bytes_per_second (int):
+ Target bytes read per second.
+ target_read_ops_per_second (int):
+ Target ops read per seconds.
+ """
+
+ target_write_bytes_per_second = proto.Field(proto.INT32, number=14)
+
+ target_write_ops_per_second = proto.Field(proto.INT32, number=15)
+
+ target_read_bytes_per_second = proto.Field(proto.INT32, number=16)
+
+ target_read_ops_per_second = proto.Field(proto.INT32, number=17)
+
+
+class NetworkUtilization(proto.Message):
+ r"""Target scaling by network usage.
+ Only applicable in the App Engine flexible environment.
+
+ Attributes:
+ target_sent_bytes_per_second (int):
+ Target bytes sent per second.
+ target_sent_packets_per_second (int):
+ Target packets sent per second.
+ target_received_bytes_per_second (int):
+ Target bytes received per second.
+ target_received_packets_per_second (int):
+ Target packets received per second.
+ """
+
+ target_sent_bytes_per_second = proto.Field(proto.INT32, number=1)
+
+ target_sent_packets_per_second = proto.Field(proto.INT32, number=11)
+
+ target_received_bytes_per_second = proto.Field(proto.INT32, number=12)
+
+ target_received_packets_per_second = proto.Field(proto.INT32, number=13)
+
+
+class StandardSchedulerSettings(proto.Message):
+ r"""Scheduler settings for standard environment.
+
+ Attributes:
+ target_cpu_utilization (float):
+ Target CPU utilization ratio to maintain when
+ scaling.
+ target_throughput_utilization (float):
+ Target throughput utilization ratio to
+ maintain when scaling
+ min_instances (int):
+ Minimum number of instances to run for this version. Set to
+ zero to disable ``min_instances`` configuration.
+ max_instances (int):
+ Maximum number of instances to run for this version. Set to
+ zero to disable ``max_instances`` configuration.
+ """
+
+ target_cpu_utilization = proto.Field(proto.DOUBLE, number=1)
+
+ target_throughput_utilization = proto.Field(proto.DOUBLE, number=2)
+
+ min_instances = proto.Field(proto.INT32, number=3)
+
+ max_instances = proto.Field(proto.INT32, number=4)
+
+
+class Network(proto.Message):
+ r"""Extra network settings.
+ Only applicable in the App Engine flexible environment.
+
+ Attributes:
+ forwarded_ports (Sequence[str]):
+ List of ports, or port pairs, to forward from
+ the virtual machine to the application
+ container. Only applicable in the App Engine
+ flexible environment.
+ instance_tag (str):
+ Tag to apply to the instance during creation.
+ Only applicable in the App Engine flexible
+ environment.
+ name (str):
+ Google Compute Engine network where the virtual machines are
+ created. Specify the short name, not the resource path.
+
+ Defaults to ``default``.
+ subnetwork_name (str):
+ Google Cloud Platform sub-network where the virtual machines
+ are created. Specify the short name, not the resource path.
+
+ If a subnetwork name is specified, a network name will also
+ be required unless it is for the default network.
+
+ - If the network that the instance is being created in is a
+ Legacy network, then the IP address is allocated from the
+ IPv4Range.
+ - If the network that the instance is being created in is
+ an auto Subnet Mode Network, then only network name
+ should be specified (not the subnetwork_name) and the IP
+ address is created from the IPCidrRange of the subnetwork
+ that exists in that zone for that network.
+ - If the network that the instance is being created in is a
+ custom Subnet Mode Network, then the subnetwork_name must
+ be specified and the IP address is created from the
+ IPCidrRange of the subnetwork.
+
+ If specified, the subnetwork must exist in the same region
+ as the App Engine flexible environment application.
+ session_affinity (bool):
+ Enable session affinity.
+ Only applicable in the App Engine flexible
+ environment.
+ """
+
+ forwarded_ports = proto.RepeatedField(proto.STRING, number=1)
+
+ instance_tag = proto.Field(proto.STRING, number=2)
+
+ name = proto.Field(proto.STRING, number=3)
+
+ subnetwork_name = proto.Field(proto.STRING, number=4)
+
+ session_affinity = proto.Field(proto.BOOL, number=5)
+
+
+class Volume(proto.Message):
+ r"""Volumes mounted within the app container.
+ Only applicable in the App Engine flexible environment.
+
+ Attributes:
+ name (str):
+ Unique name for the volume.
+ volume_type (str):
+ Underlying volume type, e.g. 'tmpfs'.
+ size_gb (float):
+ Volume size in gigabytes.
+ """
+
+ name = proto.Field(proto.STRING, number=1)
+
+ volume_type = proto.Field(proto.STRING, number=2)
+
+ size_gb = proto.Field(proto.DOUBLE, number=3)
+
+
+class Resources(proto.Message):
+ r"""Machine resources for a version.
+
+ Attributes:
+ cpu (float):
+ Number of CPU cores needed.
+ disk_gb (float):
+ Disk size (GB) needed.
+ memory_gb (float):
+ Memory (GB) needed.
+ volumes (Sequence[google.cloud.appengine_admin_v1.types.Volume]):
+ User specified volumes.
+ kms_key_reference (str):
+ The name of the encryption key that is stored
+ in Google Cloud KMS. Only should be used by
+ Cloud Composer to encrypt the vm disk
+ """
+
+ cpu = proto.Field(proto.DOUBLE, number=1)
+
+ disk_gb = proto.Field(proto.DOUBLE, number=2)
+
+ memory_gb = proto.Field(proto.DOUBLE, number=3)
+
+ volumes = proto.RepeatedField(proto.MESSAGE, number=4, message="Volume",)
+
+ kms_key_reference = proto.Field(proto.STRING, number=5)
+
+
+class VpcAccessConnector(proto.Message):
+ r"""VPC access connector specification.
+
+ Attributes:
+ name (str):
+ Full Serverless VPC Access Connector name
+ e.g. /projects/my-project/locations/us-
+ central1/connectors/c1.
+ """
+
+ name = proto.Field(proto.STRING, number=1)
+
+
+class Entrypoint(proto.Message):
+ r"""The entrypoint for the application.
+
+ Attributes:
+ shell (str):
+ The format should be a shell command that can be fed to
+ ``bash -c``.
+ """
+
+ shell = proto.Field(proto.STRING, number=1, oneof="command")
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/mypy.ini b/mypy.ini
new file mode 100644
index 0000000..4505b48
--- /dev/null
+++ b/mypy.ini
@@ -0,0 +1,3 @@
+[mypy]
+python_version = 3.6
+namespace_packages = True
diff --git a/noxfile.py b/noxfile.py
new file mode 100644
index 0000000..d6d974c
--- /dev/null
+++ b/noxfile.py
@@ -0,0 +1,235 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright 2018 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Generated by synthtool. DO NOT EDIT!
+
+from __future__ import absolute_import
+import os
+import shutil
+
+import nox
+
+
+BLACK_VERSION = "black==19.10b0"
+BLACK_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"]
+
+DEFAULT_PYTHON_VERSION = "3.8"
+SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"]
+UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8", "3.9"]
+
+# 'docfx' is excluded since it only needs to run in 'docs-presubmit'
+nox.options.sessions = [
+ "unit",
+ "system",
+ "cover",
+ "lint",
+ "lint_setup_py",
+ "blacken",
+ "docs",
+]
+
+# Error if a python version is missing
+nox.options.error_on_missing_interpreters = True
+
+
+@nox.session(python=DEFAULT_PYTHON_VERSION)
+def lint(session):
+ """Run linters.
+
+ Returns a failure if the linters find linting errors or sufficiently
+ serious code quality issues.
+ """
+ session.install("flake8", BLACK_VERSION)
+ session.run(
+ "black", "--check", *BLACK_PATHS,
+ )
+ session.run("flake8", "google", "tests")
+
+
+@nox.session(python="3.6")
+def blacken(session):
+ """Run black.
+
+ Format code to uniform standard.
+
+ This currently uses Python 3.6 due to the automated Kokoro run of synthtool.
+ That run uses an image that doesn't have 3.6 installed. Before updating this
+ check the state of the `gcp_ubuntu_config` we use for that Kokoro run.
+ """
+ session.install(BLACK_VERSION)
+ session.run(
+ "black", *BLACK_PATHS,
+ )
+
+
+@nox.session(python=DEFAULT_PYTHON_VERSION)
+def lint_setup_py(session):
+ """Verify that setup.py is valid (including RST check)."""
+ session.install("docutils", "pygments")
+ session.run("python", "setup.py", "check", "--restructuredtext", "--strict")
+
+
+def default(session):
+ # Install all test dependencies, then install this package in-place.
+ session.install("asyncmock", "pytest-asyncio")
+
+ session.install(
+ "mock", "pytest", "pytest-cov",
+ )
+
+ session.install("-e", ".")
+
+ # Run py.test against the unit tests.
+ session.run(
+ "py.test",
+ "--quiet",
+ f"--junitxml=unit_{session.python}_sponge_log.xml",
+ "--cov=google/cloud",
+ "--cov=tests/unit",
+ "--cov-append",
+ "--cov-config=.coveragerc",
+ "--cov-report=",
+ "--cov-fail-under=0",
+ os.path.join("tests", "unit"),
+ *session.posargs,
+ )
+
+
+@nox.session(python=UNIT_TEST_PYTHON_VERSIONS)
+def unit(session):
+ """Run the unit test suite."""
+ default(session)
+
+
+@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS)
+def system(session):
+ """Run the system test suite."""
+ system_test_path = os.path.join("tests", "system.py")
+ system_test_folder_path = os.path.join("tests", "system")
+
+ # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true.
+ if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false":
+ session.skip("RUN_SYSTEM_TESTS is set to false, skipping")
+ # Sanity check: Only run tests if the environment variable is set.
+ if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""):
+ session.skip("Credentials must be set via environment variable")
+ # Install pyopenssl for mTLS testing.
+ if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true":
+ session.install("pyopenssl")
+
+ system_test_exists = os.path.exists(system_test_path)
+ system_test_folder_exists = os.path.exists(system_test_folder_path)
+ # Sanity check: only run tests if found.
+ if not system_test_exists and not system_test_folder_exists:
+ session.skip("System tests were not found")
+
+ # Use pre-release gRPC for system tests.
+ session.install("--pre", "grpcio")
+
+ # Install all test dependencies, then install this package into the
+ # virtualenv's dist-packages.
+ session.install(
+ "mock", "pytest", "google-cloud-testutils",
+ )
+ session.install("-e", ".")
+
+ # Run py.test against the system tests.
+ if system_test_exists:
+ session.run(
+ "py.test",
+ "--quiet",
+ f"--junitxml=system_{session.python}_sponge_log.xml",
+ system_test_path,
+ *session.posargs,
+ )
+ if system_test_folder_exists:
+ session.run(
+ "py.test",
+ "--quiet",
+ f"--junitxml=system_{session.python}_sponge_log.xml",
+ system_test_folder_path,
+ *session.posargs,
+ )
+
+
+@nox.session(python=DEFAULT_PYTHON_VERSION)
+def cover(session):
+ """Run the final coverage report.
+
+ This outputs the coverage report aggregating coverage from the unit
+ test runs (not system test runs), and then erases coverage data.
+ """
+ session.install("coverage", "pytest-cov")
+ session.run("coverage", "report", "--show-missing", "--fail-under=99")
+
+ session.run("coverage", "erase")
+
+
+@nox.session(python=DEFAULT_PYTHON_VERSION)
+def docs(session):
+ """Build the docs for this library."""
+
+ session.install("-e", ".")
+ session.install("sphinx", "alabaster", "recommonmark")
+
+ shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True)
+ session.run(
+ "sphinx-build",
+ "-W", # warnings as errors
+ "-T", # show full traceback on exception
+ "-N", # no colors
+ "-b",
+ "html",
+ "-d",
+ os.path.join("docs", "_build", "doctrees", ""),
+ os.path.join("docs", ""),
+ os.path.join("docs", "_build", "html", ""),
+ )
+
+
+@nox.session(python=DEFAULT_PYTHON_VERSION)
+def docfx(session):
+ """Build the docfx yaml files for this library."""
+
+ session.install("-e", ".")
+ # sphinx-docfx-yaml supports up to sphinx version 1.5.5.
+ # https://github.com/docascode/sphinx-docfx-yaml/issues/97
+ session.install("sphinx==1.5.5", "alabaster", "recommonmark", "sphinx-docfx-yaml")
+
+ shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True)
+ session.run(
+ "sphinx-build",
+ "-T", # show full traceback on exception
+ "-N", # no colors
+ "-D",
+ (
+ "extensions=sphinx.ext.autodoc,"
+ "sphinx.ext.autosummary,"
+ "docfx_yaml.extension,"
+ "sphinx.ext.intersphinx,"
+ "sphinx.ext.coverage,"
+ "sphinx.ext.napoleon,"
+ "sphinx.ext.todo,"
+ "sphinx.ext.viewcode,"
+ "recommonmark"
+ ),
+ "-b",
+ "html",
+ "-d",
+ os.path.join("docs", "_build", "doctrees", ""),
+ os.path.join("docs", ""),
+ os.path.join("docs", "_build", "html", ""),
+ )
diff --git a/renovate.json b/renovate.json
new file mode 100644
index 0000000..f08bc22
--- /dev/null
+++ b/renovate.json
@@ -0,0 +1,6 @@
+{
+ "extends": [
+ "config:base", ":preserveSemverRanges"
+ ],
+ "ignorePaths": [".pre-commit-config.yaml"]
+}
diff --git a/scripts/decrypt-secrets.sh b/scripts/decrypt-secrets.sh
new file mode 100755
index 0000000..21f6d2a
--- /dev/null
+++ b/scripts/decrypt-secrets.sh
@@ -0,0 +1,46 @@
+#!/bin/bash
+
+# Copyright 2015 Google Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
+ROOT=$( dirname "$DIR" )
+
+# Work from the project root.
+cd $ROOT
+
+# Prevent it from overriding files.
+# We recommend that sample authors use their own service account files and cloud project.
+# In that case, they are supposed to prepare these files by themselves.
+if [[ -f "testing/test-env.sh" ]] || \
+ [[ -f "testing/service-account.json" ]] || \
+ [[ -f "testing/client-secrets.json" ]]; then
+ echo "One or more target files exist, aborting."
+ exit 1
+fi
+
+# Use SECRET_MANAGER_PROJECT if set, fallback to cloud-devrel-kokoro-resources.
+PROJECT_ID="${SECRET_MANAGER_PROJECT:-cloud-devrel-kokoro-resources}"
+
+gcloud secrets versions access latest --secret="python-docs-samples-test-env" \
+ --project="${PROJECT_ID}" \
+ > testing/test-env.sh
+gcloud secrets versions access latest \
+ --secret="python-docs-samples-service-account" \
+ --project="${PROJECT_ID}" \
+ > testing/service-account.json
+gcloud secrets versions access latest \
+ --secret="python-docs-samples-client-secrets" \
+ --project="${PROJECT_ID}" \
+ > testing/client-secrets.json
diff --git a/scripts/fixup_appengine_admin_v1_keywords.py b/scripts/fixup_appengine_admin_v1_keywords.py
new file mode 100644
index 0000000..5c6224a
--- /dev/null
+++ b/scripts/fixup_appengine_admin_v1_keywords.py
@@ -0,0 +1,212 @@
+#! /usr/bin/env python3
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import argparse
+import os
+import libcst as cst
+import pathlib
+import sys
+from typing import (Any, Callable, Dict, List, Sequence, Tuple)
+
+
+def partition(
+ predicate: Callable[[Any], bool],
+ iterator: Sequence[Any]
+) -> Tuple[List[Any], List[Any]]:
+ """A stable, out-of-place partition."""
+ results = ([], [])
+
+ for i in iterator:
+ results[int(predicate(i))].append(i)
+
+ # Returns trueList, falseList
+ return results[1], results[0]
+
+
+class appengine_adminCallTransformer(cst.CSTTransformer):
+ CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata')
+ METHOD_TO_PARAMS: Dict[str, Tuple[str]] = {
+ 'batch_update_ingress_rules': ('name', 'ingress_rules', ),
+ 'create_application': ('application', ),
+ 'create_authorized_certificate': ('parent', 'certificate', ),
+ 'create_domain_mapping': ('parent', 'domain_mapping', 'override_strategy', ),
+ 'create_ingress_rule': ('parent', 'rule', ),
+ 'create_version': ('parent', 'version', ),
+ 'debug_instance': ('name', 'ssh_key', ),
+ 'delete_authorized_certificate': ('name', ),
+ 'delete_domain_mapping': ('name', ),
+ 'delete_ingress_rule': ('name', ),
+ 'delete_instance': ('name', ),
+ 'delete_service': ('name', ),
+ 'delete_version': ('name', ),
+ 'get_application': ('name', ),
+ 'get_authorized_certificate': ('name', 'view', ),
+ 'get_domain_mapping': ('name', ),
+ 'get_ingress_rule': ('name', ),
+ 'get_instance': ('name', ),
+ 'get_service': ('name', ),
+ 'get_version': ('name', 'view', ),
+ 'list_authorized_certificates': ('parent', 'view', 'page_size', 'page_token', ),
+ 'list_authorized_domains': ('parent', 'page_size', 'page_token', ),
+ 'list_domain_mappings': ('parent', 'page_size', 'page_token', ),
+ 'list_ingress_rules': ('parent', 'page_size', 'page_token', 'matching_address', ),
+ 'list_instances': ('parent', 'page_size', 'page_token', ),
+ 'list_services': ('parent', 'page_size', 'page_token', ),
+ 'list_versions': ('parent', 'view', 'page_size', 'page_token', ),
+ 'repair_application': ('name', ),
+ 'update_application': ('name', 'application', 'update_mask', ),
+ 'update_authorized_certificate': ('name', 'certificate', 'update_mask', ),
+ 'update_domain_mapping': ('name', 'domain_mapping', 'update_mask', ),
+ 'update_ingress_rule': ('name', 'rule', 'update_mask', ),
+ 'update_service': ('name', 'service', 'update_mask', 'migrate_traffic', ),
+ 'update_version': ('name', 'version', 'update_mask', ),
+
+ }
+
+ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode:
+ try:
+ key = original.func.attr.value
+ kword_params = self.METHOD_TO_PARAMS[key]
+ except (AttributeError, KeyError):
+ # Either not a method from the API or too convoluted to be sure.
+ return updated
+
+ # If the existing code is valid, keyword args come after positional args.
+ # Therefore, all positional args must map to the first parameters.
+ args, kwargs = partition(lambda a: not bool(a.keyword), updated.args)
+ if any(k.keyword.value == "request" for k in kwargs):
+ # We've already fixed this file, don't fix it again.
+ return updated
+
+ kwargs, ctrl_kwargs = partition(
+ lambda a: not a.keyword.value in self.CTRL_PARAMS,
+ kwargs
+ )
+
+ args, ctrl_args = args[:len(kword_params)], args[len(kword_params):]
+ ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl))
+ for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS))
+
+ request_arg = cst.Arg(
+ value=cst.Dict([
+ cst.DictElement(
+ cst.SimpleString("'{}'".format(name)),
+ cst.Element(value=arg.value)
+ )
+ # Note: the args + kwargs looks silly, but keep in mind that
+ # the control parameters had to be stripped out, and that
+ # those could have been passed positionally or by keyword.
+ for name, arg in zip(kword_params, args + kwargs)]),
+ keyword=cst.Name("request")
+ )
+
+ return updated.with_changes(
+ args=[request_arg] + ctrl_kwargs
+ )
+
+
+def fix_files(
+ in_dir: pathlib.Path,
+ out_dir: pathlib.Path,
+ *,
+ transformer=appengine_adminCallTransformer(),
+):
+ """Duplicate the input dir to the output dir, fixing file method calls.
+
+ Preconditions:
+ * in_dir is a real directory
+ * out_dir is a real, empty directory
+ """
+ pyfile_gen = (
+ pathlib.Path(os.path.join(root, f))
+ for root, _, files in os.walk(in_dir)
+ for f in files if os.path.splitext(f)[1] == ".py"
+ )
+
+ for fpath in pyfile_gen:
+ with open(fpath, 'r') as f:
+ src = f.read()
+
+ # Parse the code and insert method call fixes.
+ tree = cst.parse_module(src)
+ updated = tree.visit(transformer)
+
+ # Create the path and directory structure for the new file.
+ updated_path = out_dir.joinpath(fpath.relative_to(in_dir))
+ updated_path.parent.mkdir(parents=True, exist_ok=True)
+
+ # Generate the updated source file at the corresponding path.
+ with open(updated_path, 'w') as f:
+ f.write(updated.code)
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(
+ description="""Fix up source that uses the appengine_admin client library.
+
+The existing sources are NOT overwritten but are copied to output_dir with changes made.
+
+Note: This tool operates at a best-effort level at converting positional
+ parameters in client method calls to keyword based parameters.
+ Cases where it WILL FAIL include
+ A) * or ** expansion in a method call.
+ B) Calls via function or method alias (includes free function calls)
+ C) Indirect or dispatched calls (e.g. the method is looked up dynamically)
+
+ These all constitute false negatives. The tool will also detect false
+ positives when an API method shares a name with another method.
+""")
+ parser.add_argument(
+ '-d',
+ '--input-directory',
+ required=True,
+ dest='input_dir',
+ help='the input directory to walk for python files to fix up',
+ )
+ parser.add_argument(
+ '-o',
+ '--output-directory',
+ required=True,
+ dest='output_dir',
+ help='the directory to output files fixed via un-flattening',
+ )
+ args = parser.parse_args()
+ input_dir = pathlib.Path(args.input_dir)
+ output_dir = pathlib.Path(args.output_dir)
+ if not input_dir.is_dir():
+ print(
+ f"input directory '{input_dir}' does not exist or is not a directory",
+ file=sys.stderr,
+ )
+ sys.exit(-1)
+
+ if not output_dir.is_dir():
+ print(
+ f"output directory '{output_dir}' does not exist or is not a directory",
+ file=sys.stderr,
+ )
+ sys.exit(-1)
+
+ if os.listdir(output_dir):
+ print(
+ f"output directory '{output_dir}' is not empty",
+ file=sys.stderr,
+ )
+ sys.exit(-1)
+
+ fix_files(input_dir, output_dir)
diff --git a/scripts/readme-gen/readme_gen.py b/scripts/readme-gen/readme_gen.py
new file mode 100644
index 0000000..d309d6e
--- /dev/null
+++ b/scripts/readme-gen/readme_gen.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+
+# Copyright 2016 Google Inc
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Generates READMEs using configuration defined in yaml."""
+
+import argparse
+import io
+import os
+import subprocess
+
+import jinja2
+import yaml
+
+
+jinja_env = jinja2.Environment(
+ trim_blocks=True,
+ loader=jinja2.FileSystemLoader(
+ os.path.abspath(os.path.join(os.path.dirname(__file__), 'templates'))))
+
+README_TMPL = jinja_env.get_template('README.tmpl.rst')
+
+
+def get_help(file):
+ return subprocess.check_output(['python', file, '--help']).decode()
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('source')
+ parser.add_argument('--destination', default='README.rst')
+
+ args = parser.parse_args()
+
+ source = os.path.abspath(args.source)
+ root = os.path.dirname(source)
+ destination = os.path.join(root, args.destination)
+
+ jinja_env.globals['get_help'] = get_help
+
+ with io.open(source, 'r') as f:
+ config = yaml.load(f)
+
+ # This allows get_help to execute in the right directory.
+ os.chdir(root)
+
+ output = README_TMPL.render(config)
+
+ with io.open(destination, 'w') as f:
+ f.write(output)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/scripts/readme-gen/templates/README.tmpl.rst b/scripts/readme-gen/templates/README.tmpl.rst
new file mode 100644
index 0000000..4fd2397
--- /dev/null
+++ b/scripts/readme-gen/templates/README.tmpl.rst
@@ -0,0 +1,87 @@
+{# The following line is a lie. BUT! Once jinja2 is done with it, it will
+ become truth! #}
+.. This file is automatically generated. Do not edit this file directly.
+
+{{product.name}} Python Samples
+===============================================================================
+
+.. image:: https://gstatic.com/cloudssh/images/open-btn.png
+ :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor={{folder}}/README.rst
+
+
+This directory contains samples for {{product.name}}. {{product.description}}
+
+{{description}}
+
+.. _{{product.name}}: {{product.url}}
+
+{% if required_api_url %}
+To run the sample, you need to enable the API at: {{required_api_url}}
+{% endif %}
+
+{% if required_role %}
+To run the sample, you need to have `{{required_role}}` role.
+{% endif %}
+
+{{other_required_steps}}
+
+{% if setup %}
+Setup
+-------------------------------------------------------------------------------
+
+{% for section in setup %}
+
+{% include section + '.tmpl.rst' %}
+
+{% endfor %}
+{% endif %}
+
+{% if samples %}
+Samples
+-------------------------------------------------------------------------------
+
+{% for sample in samples %}
+{{sample.name}}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+
+{% if not sample.hide_cloudshell_button %}
+.. image:: https://gstatic.com/cloudssh/images/open-btn.png
+ :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor={{folder}}/{{sample.file}},{{folder}}/README.rst
+{% endif %}
+
+
+{{sample.description}}
+
+To run this sample:
+
+.. code-block:: bash
+
+ $ python {{sample.file}}
+{% if sample.show_help %}
+
+ {{get_help(sample.file)|indent}}
+{% endif %}
+
+
+{% endfor %}
+{% endif %}
+
+{% if cloud_client_library %}
+
+The client library
+-------------------------------------------------------------------------------
+
+This sample uses the `Google Cloud Client Library for Python`_.
+You can read the documentation for more details on API usage and use GitHub
+to `browse the source`_ and `report issues`_.
+
+.. _Google Cloud Client Library for Python:
+ https://googlecloudplatform.github.io/google-cloud-python/
+.. _browse the source:
+ https://github.com/GoogleCloudPlatform/google-cloud-python
+.. _report issues:
+ https://github.com/GoogleCloudPlatform/google-cloud-python/issues
+
+{% endif %}
+
+.. _Google Cloud SDK: https://cloud.google.com/sdk/
\ No newline at end of file
diff --git a/scripts/readme-gen/templates/auth.tmpl.rst b/scripts/readme-gen/templates/auth.tmpl.rst
new file mode 100644
index 0000000..1446b94
--- /dev/null
+++ b/scripts/readme-gen/templates/auth.tmpl.rst
@@ -0,0 +1,9 @@
+Authentication
+++++++++++++++
+
+This sample requires you to have authentication setup. Refer to the
+`Authentication Getting Started Guide`_ for instructions on setting up
+credentials for applications.
+
+.. _Authentication Getting Started Guide:
+ https://cloud.google.com/docs/authentication/getting-started
diff --git a/scripts/readme-gen/templates/auth_api_key.tmpl.rst b/scripts/readme-gen/templates/auth_api_key.tmpl.rst
new file mode 100644
index 0000000..11957ce
--- /dev/null
+++ b/scripts/readme-gen/templates/auth_api_key.tmpl.rst
@@ -0,0 +1,14 @@
+Authentication
+++++++++++++++
+
+Authentication for this service is done via an `API Key`_. To obtain an API
+Key:
+
+1. Open the `Cloud Platform Console`_
+2. Make sure that billing is enabled for your project.
+3. From the **Credentials** page, create a new **API Key** or use an existing
+ one for your project.
+
+.. _API Key:
+ https://developers.google.com/api-client-library/python/guide/aaa_apikeys
+.. _Cloud Console: https://console.cloud.google.com/project?_
diff --git a/scripts/readme-gen/templates/install_deps.tmpl.rst b/scripts/readme-gen/templates/install_deps.tmpl.rst
new file mode 100644
index 0000000..a0406db
--- /dev/null
+++ b/scripts/readme-gen/templates/install_deps.tmpl.rst
@@ -0,0 +1,29 @@
+Install Dependencies
+++++++++++++++++++++
+
+#. Clone python-docs-samples and change directory to the sample directory you want to use.
+
+ .. code-block:: bash
+
+ $ git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git
+
+#. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions.
+
+ .. _Python Development Environment Setup Guide:
+ https://cloud.google.com/python/setup
+
+#. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+.
+
+ .. code-block:: bash
+
+ $ virtualenv env
+ $ source env/bin/activate
+
+#. Install the dependencies needed to run the samples.
+
+ .. code-block:: bash
+
+ $ pip install -r requirements.txt
+
+.. _pip: https://pip.pypa.io/
+.. _virtualenv: https://virtualenv.pypa.io/
diff --git a/scripts/readme-gen/templates/install_portaudio.tmpl.rst b/scripts/readme-gen/templates/install_portaudio.tmpl.rst
new file mode 100644
index 0000000..5ea33d1
--- /dev/null
+++ b/scripts/readme-gen/templates/install_portaudio.tmpl.rst
@@ -0,0 +1,35 @@
+Install PortAudio
++++++++++++++++++
+
+Install `PortAudio`_. This is required by the `PyAudio`_ library to stream
+audio from your computer's microphone. PyAudio depends on PortAudio for cross-platform compatibility, and is installed differently depending on the
+platform.
+
+* For Mac OS X, you can use `Homebrew`_::
+
+ brew install portaudio
+
+ **Note**: if you encounter an error when running `pip install` that indicates
+ it can't find `portaudio.h`, try running `pip install` with the following
+ flags::
+
+ pip install --global-option='build_ext' \
+ --global-option='-I/usr/local/include' \
+ --global-option='-L/usr/local/lib' \
+ pyaudio
+
+* For Debian / Ubuntu Linux::
+
+ apt-get install portaudio19-dev python-all-dev
+
+* Windows may work without having to install PortAudio explicitly (it will get
+ installed with PyAudio).
+
+For more details, see the `PyAudio installation`_ page.
+
+
+.. _PyAudio: https://people.csail.mit.edu/hubert/pyaudio/
+.. _PortAudio: http://www.portaudio.com/
+.. _PyAudio installation:
+ https://people.csail.mit.edu/hubert/pyaudio/#downloads
+.. _Homebrew: http://brew.sh
diff --git a/setup.cfg b/setup.cfg
new file mode 100644
index 0000000..c3a2b39
--- /dev/null
+++ b/setup.cfg
@@ -0,0 +1,19 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Generated by synthtool. DO NOT EDIT!
+[bdist_wheel]
+universal = 1
diff --git a/setup.py b/setup.py
new file mode 100644
index 0000000..7e371bd
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,67 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import io
+import os
+import setuptools # type: ignore
+
+name = "google-cloud-appengine-admin"
+version = "0.1.0"
+description = "App Engine Admin API client library"
+release_status = "Development Status :: 4 - Beta"
+url = "https://github.com/googleapis/python-appengine-admin"
+dependencies = [
+ "google-api-core[grpc] >= 1.22.2, < 2.0.0dev",
+ "libcst >= 0.2.5",
+ "proto-plus >= 1.18.1",
+ "grpc-google-iam-v1",
+ "six",
+]
+
+package_root = os.path.abspath(os.path.dirname(__file__))
+
+readme_filename = os.path.join(package_root, "README.rst")
+with io.open(readme_filename, encoding="utf-8") as readme_file:
+ readme = readme_file.read()
+
+setuptools.setup(
+ name=name,
+ version=version,
+ description=description,
+ long_description=readme,
+ author="Google LLC",
+ author_email="googleapis-packages@google.com",
+ license="Apache 2.0",
+ url=url,
+ packages=setuptools.PEP420PackageFinder.find(),
+ namespace_packages=("google", "google.cloud"),
+ platforms="Posix; MacOS X; Windows",
+ include_package_data=True,
+ install_requires=dependencies,
+ python_requires=">=3.6",
+ classifiers=[
+ release_status,
+ "Intended Audience :: Developers",
+ "Operating System :: OS Independent",
+ "Programming Language :: Python :: 3.6",
+ "Programming Language :: Python :: 3.7",
+ "Programming Language :: Python :: 3.8",
+ "Topic :: Internet",
+ "Topic :: Software Development :: Libraries :: Python Modules",
+ ],
+ zip_safe=False,
+)
diff --git a/synth.py b/synth.py
new file mode 100644
index 0000000..9e9a262
--- /dev/null
+++ b/synth.py
@@ -0,0 +1,55 @@
+# Copyright 2021 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""This script is used to synthesize generated parts of this library."""
+
+import os
+
+import synthtool as s
+import synthtool.gcp as gcp
+from synthtool.languages import python
+
+gapic = gcp.GAPICBazel()
+common = gcp.CommonTemplates()
+
+versions = [
+ "v1",
+
+] # add new versions at the end of the list
+
+# ----------------------------------------------------------------------------
+# Generate appengine GAPIC layer
+# ----------------------------------------------------------------------------
+for version in versions:
+ library = gapic.py_library(
+ service="appengine",
+ version=version,
+ bazel_target=f"//google/appengine/{version}:google-cloud-appengine-admin-{version}-py",
+ )
+
+ s.move(library, excludes=["setup.py", "README.rst", "docs/index.rst"])
+
+# ----------------------------------------------------------------------------
+# Add templated files
+# ----------------------------------------------------------------------------
+
+templated_files = common.py_library(cov_level=99, microgenerator=True)
+
+# the microgenerator has a good coveragerc file
+excludes = [".coveragerc"]
+s.move(
+ templated_files, excludes=excludes
+)
+
+s.shell.run(["nox", "-s", "blacken"], hide_output=False)
diff --git a/testing/.gitignore b/testing/.gitignore
new file mode 100644
index 0000000..b05fbd6
--- /dev/null
+++ b/testing/.gitignore
@@ -0,0 +1,3 @@
+test-env.sh
+service-account.json
+client-secrets.json
\ No newline at end of file
diff --git a/tests/unit/gapic/appengine_admin_v1/__init__.py b/tests/unit/gapic/appengine_admin_v1/__init__.py
new file mode 100644
index 0000000..42ffdf2
--- /dev/null
+++ b/tests/unit/gapic/appengine_admin_v1/__init__.py
@@ -0,0 +1,16 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
diff --git a/tests/unit/gapic/appengine_admin_v1/test_applications.py b/tests/unit/gapic/appengine_admin_v1/test_applications.py
new file mode 100644
index 0000000..32be11e
--- /dev/null
+++ b/tests/unit/gapic/appengine_admin_v1/test_applications.py
@@ -0,0 +1,1537 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import os
+import mock
+
+import grpc
+from grpc.experimental import aio
+import math
+import pytest
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+
+from google import auth
+from google.api_core import client_options
+from google.api_core import exceptions
+from google.api_core import future
+from google.api_core import gapic_v1
+from google.api_core import grpc_helpers
+from google.api_core import grpc_helpers_async
+from google.api_core import operation_async # type: ignore
+from google.api_core import operations_v1
+from google.auth import credentials
+from google.auth.exceptions import MutualTLSChannelError
+from google.cloud.appengine_admin_v1.services.applications import (
+ ApplicationsAsyncClient,
+)
+from google.cloud.appengine_admin_v1.services.applications import ApplicationsClient
+from google.cloud.appengine_admin_v1.services.applications import transports
+from google.cloud.appengine_admin_v1.types import appengine
+from google.cloud.appengine_admin_v1.types import application
+from google.cloud.appengine_admin_v1.types import operation as ga_operation
+from google.longrunning import operations_pb2
+from google.oauth2 import service_account
+from google.protobuf import duration_pb2 as duration # type: ignore
+from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+
+
+def client_cert_source_callback():
+ return b"cert bytes", b"key bytes"
+
+
+# If default endpoint is localhost, then default mtls endpoint will be the same.
+# This method modifies the default endpoint so the client can produce a different
+# mtls endpoint for endpoint testing purposes.
+def modify_default_endpoint(client):
+ return (
+ "foo.googleapis.com"
+ if ("localhost" in client.DEFAULT_ENDPOINT)
+ else client.DEFAULT_ENDPOINT
+ )
+
+
+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 ApplicationsClient._get_default_mtls_endpoint(None) is None
+ assert (
+ ApplicationsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint
+ )
+ assert (
+ ApplicationsClient._get_default_mtls_endpoint(api_mtls_endpoint)
+ == api_mtls_endpoint
+ )
+ assert (
+ ApplicationsClient._get_default_mtls_endpoint(sandbox_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert (
+ ApplicationsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert ApplicationsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi
+
+
+@pytest.mark.parametrize("client_class", [ApplicationsClient, ApplicationsAsyncClient,])
+def test_applications_client_from_service_account_info(client_class):
+ creds = credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "appengine.googleapis.com:443"
+
+
+@pytest.mark.parametrize("client_class", [ApplicationsClient, ApplicationsAsyncClient,])
+def test_applications_client_from_service_account_file(client_class):
+ creds = credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_file"
+ ) as factory:
+ factory.return_value = creds
+ client = client_class.from_service_account_file("dummy/file/path.json")
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ client = client_class.from_service_account_json("dummy/file/path.json")
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "appengine.googleapis.com:443"
+
+
+def test_applications_client_get_transport_class():
+ transport = ApplicationsClient.get_transport_class()
+ available_transports = [
+ transports.ApplicationsGrpcTransport,
+ ]
+ assert transport in available_transports
+
+ transport = ApplicationsClient.get_transport_class("grpc")
+ assert transport == transports.ApplicationsGrpcTransport
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (ApplicationsClient, transports.ApplicationsGrpcTransport, "grpc"),
+ (
+ ApplicationsAsyncClient,
+ transports.ApplicationsGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+@mock.patch.object(
+ ApplicationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ApplicationsClient)
+)
+@mock.patch.object(
+ ApplicationsAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(ApplicationsAsyncClient),
+)
+def test_applications_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(ApplicationsClient, "get_transport_class") as gtc:
+ transport = transport_class(credentials=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(ApplicationsClient, "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,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,use_client_cert_env",
+ [
+ (ApplicationsClient, transports.ApplicationsGrpcTransport, "grpc", "true"),
+ (
+ ApplicationsAsyncClient,
+ transports.ApplicationsGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "true",
+ ),
+ (ApplicationsClient, transports.ApplicationsGrpcTransport, "grpc", "false"),
+ (
+ ApplicationsAsyncClient,
+ transports.ApplicationsGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "false",
+ ),
+ ],
+)
+@mock.patch.object(
+ ApplicationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ApplicationsClient)
+)
+@mock.patch.object(
+ ApplicationsAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(ApplicationsAsyncClient),
+)
+@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"})
+def test_applications_client_mtls_env_auto(
+ client_class, transport_class, transport_name, use_client_cert_env
+):
+ # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default
+ # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists.
+
+ # Check the case client_cert_source is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ options = client_options.ClientOptions(
+ client_cert_source=client_cert_source_callback
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client.DEFAULT_ENDPOINT
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+ # Check the case ADC client cert is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client.DEFAULT_ENDPOINT
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
+
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ 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,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (ApplicationsClient, transports.ApplicationsGrpcTransport, "grpc"),
+ (
+ ApplicationsAsyncClient,
+ transports.ApplicationsGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_applications_client_client_options_scopes(
+ client_class, transport_class, transport_name
+):
+ # Check the case scopes are provided.
+ options = client_options.ClientOptions(scopes=["1", "2"],)
+ 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=["1", "2"],
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (ApplicationsClient, transports.ApplicationsGrpcTransport, "grpc"),
+ (
+ ApplicationsAsyncClient,
+ transports.ApplicationsGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_applications_client_client_options_credentials_file(
+ client_class, transport_class, transport_name
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+ 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="credentials.json",
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+
+def test_applications_client_client_options_from_dict():
+ with mock.patch(
+ "google.cloud.appengine_admin_v1.services.applications.transports.ApplicationsGrpcTransport.__init__"
+ ) as grpc_transport:
+ grpc_transport.return_value = None
+ client = ApplicationsClient(client_options={"api_endpoint": "squid.clam.whelk"})
+ grpc_transport.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,
+ )
+
+
+def test_get_application(
+ transport: str = "grpc", request_type=appengine.GetApplicationRequest
+):
+ client = ApplicationsClient(
+ credentials=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_application), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = application.Application(
+ name="name_value",
+ id="id_value",
+ auth_domain="auth_domain_value",
+ location_id="location_id_value",
+ code_bucket="code_bucket_value",
+ serving_status=application.Application.ServingStatus.SERVING,
+ default_hostname="default_hostname_value",
+ default_bucket="default_bucket_value",
+ gcr_domain="gcr_domain_value",
+ database_type=application.Application.DatabaseType.CLOUD_DATASTORE,
+ )
+
+ response = client.get_application(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.GetApplicationRequest()
+
+ # Establish that the response is the type that we expect.
+
+ assert isinstance(response, application.Application)
+
+ assert response.name == "name_value"
+
+ assert response.id == "id_value"
+
+ assert response.auth_domain == "auth_domain_value"
+
+ assert response.location_id == "location_id_value"
+
+ assert response.code_bucket == "code_bucket_value"
+
+ assert response.serving_status == application.Application.ServingStatus.SERVING
+
+ assert response.default_hostname == "default_hostname_value"
+
+ assert response.default_bucket == "default_bucket_value"
+
+ assert response.gcr_domain == "gcr_domain_value"
+
+ assert (
+ response.database_type == application.Application.DatabaseType.CLOUD_DATASTORE
+ )
+
+
+def test_get_application_from_dict():
+ test_get_application(request_type=dict)
+
+
+def test_get_application_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ApplicationsClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_application), "__call__") as call:
+ client.get_application()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.GetApplicationRequest()
+
+
+@pytest.mark.asyncio
+async def test_get_application_async(
+ transport: str = "grpc_asyncio", request_type=appengine.GetApplicationRequest
+):
+ client = ApplicationsAsyncClient(
+ credentials=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_application), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ application.Application(
+ name="name_value",
+ id="id_value",
+ auth_domain="auth_domain_value",
+ location_id="location_id_value",
+ code_bucket="code_bucket_value",
+ serving_status=application.Application.ServingStatus.SERVING,
+ default_hostname="default_hostname_value",
+ default_bucket="default_bucket_value",
+ gcr_domain="gcr_domain_value",
+ database_type=application.Application.DatabaseType.CLOUD_DATASTORE,
+ )
+ )
+
+ response = await client.get_application(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.GetApplicationRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, application.Application)
+
+ assert response.name == "name_value"
+
+ assert response.id == "id_value"
+
+ assert response.auth_domain == "auth_domain_value"
+
+ assert response.location_id == "location_id_value"
+
+ assert response.code_bucket == "code_bucket_value"
+
+ assert response.serving_status == application.Application.ServingStatus.SERVING
+
+ assert response.default_hostname == "default_hostname_value"
+
+ assert response.default_bucket == "default_bucket_value"
+
+ assert response.gcr_domain == "gcr_domain_value"
+
+ assert (
+ response.database_type == application.Application.DatabaseType.CLOUD_DATASTORE
+ )
+
+
+@pytest.mark.asyncio
+async def test_get_application_async_from_dict():
+ await test_get_application_async(request_type=dict)
+
+
+def test_get_application_field_headers():
+ client = ApplicationsClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.GetApplicationRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_application), "__call__") as call:
+ call.return_value = application.Application()
+
+ client.get_application(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_get_application_field_headers_async():
+ client = ApplicationsAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.GetApplicationRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_application), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ application.Application()
+ )
+
+ await client.get_application(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_create_application(
+ transport: str = "grpc", request_type=appengine.CreateApplicationRequest
+):
+ client = ApplicationsClient(
+ credentials=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.create_application), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.create_application(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.CreateApplicationRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_create_application_from_dict():
+ test_create_application(request_type=dict)
+
+
+def test_create_application_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ApplicationsClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_application), "__call__"
+ ) as call:
+ client.create_application()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.CreateApplicationRequest()
+
+
+@pytest.mark.asyncio
+async def test_create_application_async(
+ transport: str = "grpc_asyncio", request_type=appengine.CreateApplicationRequest
+):
+ client = ApplicationsAsyncClient(
+ credentials=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.create_application), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/spam")
+ )
+
+ response = await client.create_application(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.CreateApplicationRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_create_application_async_from_dict():
+ await test_create_application_async(request_type=dict)
+
+
+def test_update_application(
+ transport: str = "grpc", request_type=appengine.UpdateApplicationRequest
+):
+ client = ApplicationsClient(
+ credentials=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.update_application), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.update_application(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.UpdateApplicationRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_update_application_from_dict():
+ test_update_application(request_type=dict)
+
+
+def test_update_application_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ApplicationsClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_application), "__call__"
+ ) as call:
+ client.update_application()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.UpdateApplicationRequest()
+
+
+@pytest.mark.asyncio
+async def test_update_application_async(
+ transport: str = "grpc_asyncio", request_type=appengine.UpdateApplicationRequest
+):
+ client = ApplicationsAsyncClient(
+ credentials=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.update_application), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/spam")
+ )
+
+ response = await client.update_application(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.UpdateApplicationRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_update_application_async_from_dict():
+ await test_update_application_async(request_type=dict)
+
+
+def test_update_application_field_headers():
+ client = ApplicationsClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.UpdateApplicationRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_application), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ client.update_application(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_update_application_field_headers_async():
+ client = ApplicationsAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.UpdateApplicationRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_application), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+
+ await client.update_application(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_repair_application(
+ transport: str = "grpc", request_type=appengine.RepairApplicationRequest
+):
+ client = ApplicationsClient(
+ credentials=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.repair_application), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.repair_application(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.RepairApplicationRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_repair_application_from_dict():
+ test_repair_application(request_type=dict)
+
+
+def test_repair_application_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ApplicationsClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.repair_application), "__call__"
+ ) as call:
+ client.repair_application()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.RepairApplicationRequest()
+
+
+@pytest.mark.asyncio
+async def test_repair_application_async(
+ transport: str = "grpc_asyncio", request_type=appengine.RepairApplicationRequest
+):
+ client = ApplicationsAsyncClient(
+ credentials=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.repair_application), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/spam")
+ )
+
+ response = await client.repair_application(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.RepairApplicationRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_repair_application_async_from_dict():
+ await test_repair_application_async(request_type=dict)
+
+
+def test_repair_application_field_headers():
+ client = ApplicationsClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.RepairApplicationRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.repair_application), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ client.repair_application(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_repair_application_field_headers_async():
+ client = ApplicationsAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.RepairApplicationRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.repair_application), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+
+ await client.repair_application(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.ApplicationsGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = ApplicationsClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.ApplicationsGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = ApplicationsClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
+
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.ApplicationsGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = ApplicationsClient(
+ client_options={"scopes": ["1", "2"]}, transport=transport,
+ )
+
+
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.ApplicationsGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ client = ApplicationsClient(transport=transport)
+ assert client.transport is transport
+
+
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.ApplicationsGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+ transport = transports.ApplicationsGrpcAsyncIOTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.ApplicationsGrpcTransport,
+ transports.ApplicationsGrpcAsyncIOTransport,
+ ],
+)
+def test_transport_adc(transport_class):
+ # Test default credentials are used if not provided.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transport_class()
+ adc.assert_called_once()
+
+
+def test_transport_grpc_default():
+ # A client should use the gRPC transport by default.
+ client = ApplicationsClient(credentials=credentials.AnonymousCredentials(),)
+ assert isinstance(client.transport, transports.ApplicationsGrpcTransport,)
+
+
+def test_applications_base_transport_error():
+ # Passing both a credentials object and credentials_file should raise an error
+ with pytest.raises(exceptions.DuplicateCredentialArgs):
+ transport = transports.ApplicationsTransport(
+ credentials=credentials.AnonymousCredentials(),
+ credentials_file="credentials.json",
+ )
+
+
+def test_applications_base_transport():
+ # Instantiate the base transport.
+ with mock.patch(
+ "google.cloud.appengine_admin_v1.services.applications.transports.ApplicationsTransport.__init__"
+ ) as Transport:
+ Transport.return_value = None
+ transport = transports.ApplicationsTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Every method on the transport should just blindly
+ # raise NotImplementedError.
+ methods = (
+ "get_application",
+ "create_application",
+ "update_application",
+ "repair_application",
+ )
+ for method in methods:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, method)(request=object())
+
+ # Additionally, the LRO client (a property) should
+ # also raise NotImplementedError
+ with pytest.raises(NotImplementedError):
+ transport.operations_client
+
+
+def test_applications_base_transport_with_credentials_file():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(
+ auth, "load_credentials_from_file"
+ ) as load_creds, mock.patch(
+ "google.cloud.appengine_admin_v1.services.applications.transports.ApplicationsTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ transport = transports.ApplicationsTransport(
+ credentials_file="credentials.json", quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+def test_applications_base_transport_with_adc():
+ # Test the default credentials are used if credentials and credentials_file are None.
+ with mock.patch.object(auth, "default") as adc, mock.patch(
+ "google.cloud.appengine_admin_v1.services.applications.transports.ApplicationsTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transport = transports.ApplicationsTransport()
+ adc.assert_called_once()
+
+
+def test_applications_auth_adc():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ ApplicationsClient()
+ adc.assert_called_once_with(
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ quota_project_id=None,
+ )
+
+
+def test_applications_transport_auth_adc():
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transports.ApplicationsGrpcTransport(
+ host="squid.clam.whelk", quota_project_id="octopus"
+ )
+ adc.assert_called_once_with(
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.ApplicationsGrpcTransport, transports.ApplicationsGrpcAsyncIOTransport],
+)
+def test_applications_grpc_transport_client_cert_source_for_mtls(transport_class):
+ cred = credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
+def test_applications_host_no_port():
+ client = ApplicationsClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="appengine.googleapis.com"
+ ),
+ )
+ assert client.transport._host == "appengine.googleapis.com:443"
+
+
+def test_applications_host_with_port():
+ client = ApplicationsClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="appengine.googleapis.com:8000"
+ ),
+ )
+ assert client.transport._host == "appengine.googleapis.com:8000"
+
+
+def test_applications_grpc_transport_channel():
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.ApplicationsGrpcTransport(
+ host="squid.clam.whelk", channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+def test_applications_grpc_asyncio_transport_channel():
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.ApplicationsGrpcAsyncIOTransport(
+ host="squid.clam.whelk", channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.ApplicationsGrpcTransport, transports.ApplicationsGrpcAsyncIOTransport],
+)
+def test_applications_transport_channel_mtls_with_client_cert_source(transport_class):
+ with mock.patch(
+ "grpc.ssl_channel_credentials", autospec=True
+ ) as grpc_ssl_channel_cred:
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_ssl_cred = mock.Mock()
+ grpc_ssl_channel_cred.return_value = mock_ssl_cred
+
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ cred = credentials.AnonymousCredentials()
+ with pytest.warns(DeprecationWarning):
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (cred, None)
+ transport = transport_class(
+ host="squid.clam.whelk",
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=client_cert_source_callback,
+ )
+ adc.assert_called_once()
+
+ grpc_ssl_channel_cred.assert_called_once_with(
+ certificate_chain=b"cert bytes", private_key=b"key bytes"
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+ assert transport._ssl_channel_credentials == mock_ssl_cred
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.ApplicationsGrpcTransport, transports.ApplicationsGrpcAsyncIOTransport],
+)
+def test_applications_transport_channel_mtls_with_adc(transport_class):
+ mock_ssl_cred = mock.Mock()
+ with mock.patch.multiple(
+ "google.auth.transport.grpc.SslCredentials",
+ __init__=mock.Mock(return_value=None),
+ ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
+ ):
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+ mock_cred = mock.Mock()
+
+ with pytest.warns(DeprecationWarning):
+ transport = transport_class(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=None,
+ )
+
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+def test_applications_grpc_lro_client():
+ client = ApplicationsClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+ transport = client.transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(transport.operations_client, operations_v1.OperationsClient,)
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_applications_grpc_lro_async_client():
+ client = ApplicationsAsyncClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio",
+ )
+ transport = client.transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(transport.operations_client, operations_v1.OperationsAsyncClient,)
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_common_billing_account_path():
+ billing_account = "squid"
+
+ expected = "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
+ )
+ actual = ApplicationsClient.common_billing_account_path(billing_account)
+ assert expected == actual
+
+
+def test_parse_common_billing_account_path():
+ expected = {
+ "billing_account": "clam",
+ }
+ path = ApplicationsClient.common_billing_account_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ApplicationsClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "whelk"
+
+ expected = "folders/{folder}".format(folder=folder,)
+ actual = ApplicationsClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "octopus",
+ }
+ path = ApplicationsClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ApplicationsClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "oyster"
+
+ expected = "organizations/{organization}".format(organization=organization,)
+ actual = ApplicationsClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "nudibranch",
+ }
+ path = ApplicationsClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ApplicationsClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "cuttlefish"
+
+ expected = "projects/{project}".format(project=project,)
+ actual = ApplicationsClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "mussel",
+ }
+ path = ApplicationsClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ApplicationsClient.parse_common_project_path(path)
+ assert expected == actual
+
+
+def test_common_location_path():
+ project = "winkle"
+ location = "nautilus"
+
+ expected = "projects/{project}/locations/{location}".format(
+ project=project, location=location,
+ )
+ actual = ApplicationsClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "scallop",
+ "location": "abalone",
+ }
+ path = ApplicationsClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ApplicationsClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_withDEFAULT_CLIENT_INFO():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.ApplicationsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = ApplicationsClient(
+ credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.ApplicationsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = ApplicationsClient.get_transport_class()
+ transport = transport_class(
+ credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
diff --git a/tests/unit/gapic/appengine_admin_v1/test_authorized_certificates.py b/tests/unit/gapic/appengine_admin_v1/test_authorized_certificates.py
new file mode 100644
index 0000000..f93792b
--- /dev/null
+++ b/tests/unit/gapic/appengine_admin_v1/test_authorized_certificates.py
@@ -0,0 +1,2022 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import os
+import mock
+
+import grpc
+from grpc.experimental import aio
+import math
+import pytest
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+
+from google import auth
+from google.api_core import client_options
+from google.api_core import exceptions
+from google.api_core import gapic_v1
+from google.api_core import grpc_helpers
+from google.api_core import grpc_helpers_async
+from google.auth import credentials
+from google.auth.exceptions import MutualTLSChannelError
+from google.cloud.appengine_admin_v1.services.authorized_certificates import (
+ AuthorizedCertificatesAsyncClient,
+)
+from google.cloud.appengine_admin_v1.services.authorized_certificates import (
+ AuthorizedCertificatesClient,
+)
+from google.cloud.appengine_admin_v1.services.authorized_certificates import pagers
+from google.cloud.appengine_admin_v1.services.authorized_certificates import transports
+from google.cloud.appengine_admin_v1.types import appengine
+from google.cloud.appengine_admin_v1.types import certificate
+from google.oauth2 import service_account
+from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+from google.protobuf import timestamp_pb2 as timestamp # type: ignore
+
+
+def client_cert_source_callback():
+ return b"cert bytes", b"key bytes"
+
+
+# If default endpoint is localhost, then default mtls endpoint will be the same.
+# This method modifies the default endpoint so the client can produce a different
+# mtls endpoint for endpoint testing purposes.
+def modify_default_endpoint(client):
+ return (
+ "foo.googleapis.com"
+ if ("localhost" in client.DEFAULT_ENDPOINT)
+ else client.DEFAULT_ENDPOINT
+ )
+
+
+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 AuthorizedCertificatesClient._get_default_mtls_endpoint(None) is None
+ assert (
+ AuthorizedCertificatesClient._get_default_mtls_endpoint(api_endpoint)
+ == api_mtls_endpoint
+ )
+ assert (
+ AuthorizedCertificatesClient._get_default_mtls_endpoint(api_mtls_endpoint)
+ == api_mtls_endpoint
+ )
+ assert (
+ AuthorizedCertificatesClient._get_default_mtls_endpoint(sandbox_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert (
+ AuthorizedCertificatesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert (
+ AuthorizedCertificatesClient._get_default_mtls_endpoint(non_googleapi)
+ == non_googleapi
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class", [AuthorizedCertificatesClient, AuthorizedCertificatesAsyncClient,]
+)
+def test_authorized_certificates_client_from_service_account_info(client_class):
+ creds = credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "appengine.googleapis.com:443"
+
+
+@pytest.mark.parametrize(
+ "client_class", [AuthorizedCertificatesClient, AuthorizedCertificatesAsyncClient,]
+)
+def test_authorized_certificates_client_from_service_account_file(client_class):
+ creds = credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_file"
+ ) as factory:
+ factory.return_value = creds
+ client = client_class.from_service_account_file("dummy/file/path.json")
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ client = client_class.from_service_account_json("dummy/file/path.json")
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "appengine.googleapis.com:443"
+
+
+def test_authorized_certificates_client_get_transport_class():
+ transport = AuthorizedCertificatesClient.get_transport_class()
+ available_transports = [
+ transports.AuthorizedCertificatesGrpcTransport,
+ ]
+ assert transport in available_transports
+
+ transport = AuthorizedCertificatesClient.get_transport_class("grpc")
+ assert transport == transports.AuthorizedCertificatesGrpcTransport
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (
+ AuthorizedCertificatesClient,
+ transports.AuthorizedCertificatesGrpcTransport,
+ "grpc",
+ ),
+ (
+ AuthorizedCertificatesAsyncClient,
+ transports.AuthorizedCertificatesGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+@mock.patch.object(
+ AuthorizedCertificatesClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(AuthorizedCertificatesClient),
+)
+@mock.patch.object(
+ AuthorizedCertificatesAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(AuthorizedCertificatesAsyncClient),
+)
+def test_authorized_certificates_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(AuthorizedCertificatesClient, "get_transport_class") as gtc:
+ transport = transport_class(credentials=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(AuthorizedCertificatesClient, "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,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,use_client_cert_env",
+ [
+ (
+ AuthorizedCertificatesClient,
+ transports.AuthorizedCertificatesGrpcTransport,
+ "grpc",
+ "true",
+ ),
+ (
+ AuthorizedCertificatesAsyncClient,
+ transports.AuthorizedCertificatesGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "true",
+ ),
+ (
+ AuthorizedCertificatesClient,
+ transports.AuthorizedCertificatesGrpcTransport,
+ "grpc",
+ "false",
+ ),
+ (
+ AuthorizedCertificatesAsyncClient,
+ transports.AuthorizedCertificatesGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "false",
+ ),
+ ],
+)
+@mock.patch.object(
+ AuthorizedCertificatesClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(AuthorizedCertificatesClient),
+)
+@mock.patch.object(
+ AuthorizedCertificatesAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(AuthorizedCertificatesAsyncClient),
+)
+@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"})
+def test_authorized_certificates_client_mtls_env_auto(
+ client_class, transport_class, transport_name, use_client_cert_env
+):
+ # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default
+ # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists.
+
+ # Check the case client_cert_source is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ options = client_options.ClientOptions(
+ client_cert_source=client_cert_source_callback
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client.DEFAULT_ENDPOINT
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+ # Check the case ADC client cert is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client.DEFAULT_ENDPOINT
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
+
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ 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,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (
+ AuthorizedCertificatesClient,
+ transports.AuthorizedCertificatesGrpcTransport,
+ "grpc",
+ ),
+ (
+ AuthorizedCertificatesAsyncClient,
+ transports.AuthorizedCertificatesGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_authorized_certificates_client_client_options_scopes(
+ client_class, transport_class, transport_name
+):
+ # Check the case scopes are provided.
+ options = client_options.ClientOptions(scopes=["1", "2"],)
+ 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=["1", "2"],
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (
+ AuthorizedCertificatesClient,
+ transports.AuthorizedCertificatesGrpcTransport,
+ "grpc",
+ ),
+ (
+ AuthorizedCertificatesAsyncClient,
+ transports.AuthorizedCertificatesGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_authorized_certificates_client_client_options_credentials_file(
+ client_class, transport_class, transport_name
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+ 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="credentials.json",
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+
+def test_authorized_certificates_client_client_options_from_dict():
+ with mock.patch(
+ "google.cloud.appengine_admin_v1.services.authorized_certificates.transports.AuthorizedCertificatesGrpcTransport.__init__"
+ ) as grpc_transport:
+ grpc_transport.return_value = None
+ client = AuthorizedCertificatesClient(
+ client_options={"api_endpoint": "squid.clam.whelk"}
+ )
+ grpc_transport.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,
+ )
+
+
+def test_list_authorized_certificates(
+ transport: str = "grpc", request_type=appengine.ListAuthorizedCertificatesRequest
+):
+ client = AuthorizedCertificatesClient(
+ credentials=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.list_authorized_certificates), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = appengine.ListAuthorizedCertificatesResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ response = client.list_authorized_certificates(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.ListAuthorizedCertificatesRequest()
+
+ # Establish that the response is the type that we expect.
+
+ assert isinstance(response, pagers.ListAuthorizedCertificatesPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_authorized_certificates_from_dict():
+ test_list_authorized_certificates(request_type=dict)
+
+
+def test_list_authorized_certificates_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = AuthorizedCertificatesClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_authorized_certificates), "__call__"
+ ) as call:
+ client.list_authorized_certificates()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.ListAuthorizedCertificatesRequest()
+
+
+@pytest.mark.asyncio
+async def test_list_authorized_certificates_async(
+ transport: str = "grpc_asyncio",
+ request_type=appengine.ListAuthorizedCertificatesRequest,
+):
+ client = AuthorizedCertificatesAsyncClient(
+ credentials=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.list_authorized_certificates), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ appengine.ListAuthorizedCertificatesResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+
+ response = await client.list_authorized_certificates(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.ListAuthorizedCertificatesRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListAuthorizedCertificatesAsyncPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+
+@pytest.mark.asyncio
+async def test_list_authorized_certificates_async_from_dict():
+ await test_list_authorized_certificates_async(request_type=dict)
+
+
+def test_list_authorized_certificates_field_headers():
+ client = AuthorizedCertificatesClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.ListAuthorizedCertificatesRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_authorized_certificates), "__call__"
+ ) as call:
+ call.return_value = appengine.ListAuthorizedCertificatesResponse()
+
+ client.list_authorized_certificates(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_list_authorized_certificates_field_headers_async():
+ client = AuthorizedCertificatesAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.ListAuthorizedCertificatesRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_authorized_certificates), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ appengine.ListAuthorizedCertificatesResponse()
+ )
+
+ await client.list_authorized_certificates(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"]
+
+
+def test_list_authorized_certificates_pager():
+ client = AuthorizedCertificatesClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_authorized_certificates), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListAuthorizedCertificatesResponse(
+ certificates=[
+ certificate.AuthorizedCertificate(),
+ certificate.AuthorizedCertificate(),
+ certificate.AuthorizedCertificate(),
+ ],
+ next_page_token="abc",
+ ),
+ appengine.ListAuthorizedCertificatesResponse(
+ certificates=[], next_page_token="def",
+ ),
+ appengine.ListAuthorizedCertificatesResponse(
+ certificates=[certificate.AuthorizedCertificate(),],
+ next_page_token="ghi",
+ ),
+ appengine.ListAuthorizedCertificatesResponse(
+ certificates=[
+ certificate.AuthorizedCertificate(),
+ certificate.AuthorizedCertificate(),
+ ],
+ ),
+ RuntimeError,
+ )
+
+ metadata = ()
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
+ )
+ pager = client.list_authorized_certificates(request={})
+
+ assert pager._metadata == metadata
+
+ results = [i for i in pager]
+ assert len(results) == 6
+ assert all(isinstance(i, certificate.AuthorizedCertificate) for i in results)
+
+
+def test_list_authorized_certificates_pages():
+ client = AuthorizedCertificatesClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_authorized_certificates), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListAuthorizedCertificatesResponse(
+ certificates=[
+ certificate.AuthorizedCertificate(),
+ certificate.AuthorizedCertificate(),
+ certificate.AuthorizedCertificate(),
+ ],
+ next_page_token="abc",
+ ),
+ appengine.ListAuthorizedCertificatesResponse(
+ certificates=[], next_page_token="def",
+ ),
+ appengine.ListAuthorizedCertificatesResponse(
+ certificates=[certificate.AuthorizedCertificate(),],
+ next_page_token="ghi",
+ ),
+ appengine.ListAuthorizedCertificatesResponse(
+ certificates=[
+ certificate.AuthorizedCertificate(),
+ certificate.AuthorizedCertificate(),
+ ],
+ ),
+ RuntimeError,
+ )
+ pages = list(client.list_authorized_certificates(request={}).pages)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
+
+
+@pytest.mark.asyncio
+async def test_list_authorized_certificates_async_pager():
+ client = AuthorizedCertificatesAsyncClient(
+ credentials=credentials.AnonymousCredentials,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_authorized_certificates),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListAuthorizedCertificatesResponse(
+ certificates=[
+ certificate.AuthorizedCertificate(),
+ certificate.AuthorizedCertificate(),
+ certificate.AuthorizedCertificate(),
+ ],
+ next_page_token="abc",
+ ),
+ appengine.ListAuthorizedCertificatesResponse(
+ certificates=[], next_page_token="def",
+ ),
+ appengine.ListAuthorizedCertificatesResponse(
+ certificates=[certificate.AuthorizedCertificate(),],
+ next_page_token="ghi",
+ ),
+ appengine.ListAuthorizedCertificatesResponse(
+ certificates=[
+ certificate.AuthorizedCertificate(),
+ certificate.AuthorizedCertificate(),
+ ],
+ ),
+ RuntimeError,
+ )
+ async_pager = await client.list_authorized_certificates(request={},)
+ assert async_pager.next_page_token == "abc"
+ responses = []
+ async for response in async_pager:
+ responses.append(response)
+
+ assert len(responses) == 6
+ assert all(isinstance(i, certificate.AuthorizedCertificate) for i in responses)
+
+
+@pytest.mark.asyncio
+async def test_list_authorized_certificates_async_pages():
+ client = AuthorizedCertificatesAsyncClient(
+ credentials=credentials.AnonymousCredentials,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_authorized_certificates),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListAuthorizedCertificatesResponse(
+ certificates=[
+ certificate.AuthorizedCertificate(),
+ certificate.AuthorizedCertificate(),
+ certificate.AuthorizedCertificate(),
+ ],
+ next_page_token="abc",
+ ),
+ appengine.ListAuthorizedCertificatesResponse(
+ certificates=[], next_page_token="def",
+ ),
+ appengine.ListAuthorizedCertificatesResponse(
+ certificates=[certificate.AuthorizedCertificate(),],
+ next_page_token="ghi",
+ ),
+ appengine.ListAuthorizedCertificatesResponse(
+ certificates=[
+ certificate.AuthorizedCertificate(),
+ certificate.AuthorizedCertificate(),
+ ],
+ ),
+ RuntimeError,
+ )
+ pages = []
+ async for page_ in (
+ await client.list_authorized_certificates(request={})
+ ).pages:
+ pages.append(page_)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
+
+
+def test_get_authorized_certificate(
+ transport: str = "grpc", request_type=appengine.GetAuthorizedCertificateRequest
+):
+ client = AuthorizedCertificatesClient(
+ credentials=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_authorized_certificate), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = certificate.AuthorizedCertificate(
+ name="name_value",
+ id="id_value",
+ display_name="display_name_value",
+ domain_names=["domain_names_value"],
+ visible_domain_mappings=["visible_domain_mappings_value"],
+ domain_mappings_count=2238,
+ )
+
+ response = client.get_authorized_certificate(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.GetAuthorizedCertificateRequest()
+
+ # Establish that the response is the type that we expect.
+
+ assert isinstance(response, certificate.AuthorizedCertificate)
+
+ assert response.name == "name_value"
+
+ assert response.id == "id_value"
+
+ assert response.display_name == "display_name_value"
+
+ assert response.domain_names == ["domain_names_value"]
+
+ assert response.visible_domain_mappings == ["visible_domain_mappings_value"]
+
+ assert response.domain_mappings_count == 2238
+
+
+def test_get_authorized_certificate_from_dict():
+ test_get_authorized_certificate(request_type=dict)
+
+
+def test_get_authorized_certificate_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = AuthorizedCertificatesClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_authorized_certificate), "__call__"
+ ) as call:
+ client.get_authorized_certificate()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.GetAuthorizedCertificateRequest()
+
+
+@pytest.mark.asyncio
+async def test_get_authorized_certificate_async(
+ transport: str = "grpc_asyncio",
+ request_type=appengine.GetAuthorizedCertificateRequest,
+):
+ client = AuthorizedCertificatesAsyncClient(
+ credentials=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_authorized_certificate), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ certificate.AuthorizedCertificate(
+ name="name_value",
+ id="id_value",
+ display_name="display_name_value",
+ domain_names=["domain_names_value"],
+ visible_domain_mappings=["visible_domain_mappings_value"],
+ domain_mappings_count=2238,
+ )
+ )
+
+ response = await client.get_authorized_certificate(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.GetAuthorizedCertificateRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, certificate.AuthorizedCertificate)
+
+ assert response.name == "name_value"
+
+ assert response.id == "id_value"
+
+ assert response.display_name == "display_name_value"
+
+ assert response.domain_names == ["domain_names_value"]
+
+ assert response.visible_domain_mappings == ["visible_domain_mappings_value"]
+
+ assert response.domain_mappings_count == 2238
+
+
+@pytest.mark.asyncio
+async def test_get_authorized_certificate_async_from_dict():
+ await test_get_authorized_certificate_async(request_type=dict)
+
+
+def test_get_authorized_certificate_field_headers():
+ client = AuthorizedCertificatesClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.GetAuthorizedCertificateRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_authorized_certificate), "__call__"
+ ) as call:
+ call.return_value = certificate.AuthorizedCertificate()
+
+ client.get_authorized_certificate(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_get_authorized_certificate_field_headers_async():
+ client = AuthorizedCertificatesAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.GetAuthorizedCertificateRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_authorized_certificate), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ certificate.AuthorizedCertificate()
+ )
+
+ await client.get_authorized_certificate(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_create_authorized_certificate(
+ transport: str = "grpc", request_type=appengine.CreateAuthorizedCertificateRequest
+):
+ client = AuthorizedCertificatesClient(
+ credentials=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.create_authorized_certificate), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = certificate.AuthorizedCertificate(
+ name="name_value",
+ id="id_value",
+ display_name="display_name_value",
+ domain_names=["domain_names_value"],
+ visible_domain_mappings=["visible_domain_mappings_value"],
+ domain_mappings_count=2238,
+ )
+
+ response = client.create_authorized_certificate(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.CreateAuthorizedCertificateRequest()
+
+ # Establish that the response is the type that we expect.
+
+ assert isinstance(response, certificate.AuthorizedCertificate)
+
+ assert response.name == "name_value"
+
+ assert response.id == "id_value"
+
+ assert response.display_name == "display_name_value"
+
+ assert response.domain_names == ["domain_names_value"]
+
+ assert response.visible_domain_mappings == ["visible_domain_mappings_value"]
+
+ assert response.domain_mappings_count == 2238
+
+
+def test_create_authorized_certificate_from_dict():
+ test_create_authorized_certificate(request_type=dict)
+
+
+def test_create_authorized_certificate_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = AuthorizedCertificatesClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_authorized_certificate), "__call__"
+ ) as call:
+ client.create_authorized_certificate()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.CreateAuthorizedCertificateRequest()
+
+
+@pytest.mark.asyncio
+async def test_create_authorized_certificate_async(
+ transport: str = "grpc_asyncio",
+ request_type=appengine.CreateAuthorizedCertificateRequest,
+):
+ client = AuthorizedCertificatesAsyncClient(
+ credentials=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.create_authorized_certificate), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ certificate.AuthorizedCertificate(
+ name="name_value",
+ id="id_value",
+ display_name="display_name_value",
+ domain_names=["domain_names_value"],
+ visible_domain_mappings=["visible_domain_mappings_value"],
+ domain_mappings_count=2238,
+ )
+ )
+
+ response = await client.create_authorized_certificate(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.CreateAuthorizedCertificateRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, certificate.AuthorizedCertificate)
+
+ assert response.name == "name_value"
+
+ assert response.id == "id_value"
+
+ assert response.display_name == "display_name_value"
+
+ assert response.domain_names == ["domain_names_value"]
+
+ assert response.visible_domain_mappings == ["visible_domain_mappings_value"]
+
+ assert response.domain_mappings_count == 2238
+
+
+@pytest.mark.asyncio
+async def test_create_authorized_certificate_async_from_dict():
+ await test_create_authorized_certificate_async(request_type=dict)
+
+
+def test_create_authorized_certificate_field_headers():
+ client = AuthorizedCertificatesClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.CreateAuthorizedCertificateRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_authorized_certificate), "__call__"
+ ) as call:
+ call.return_value = certificate.AuthorizedCertificate()
+
+ client.create_authorized_certificate(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_create_authorized_certificate_field_headers_async():
+ client = AuthorizedCertificatesAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.CreateAuthorizedCertificateRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_authorized_certificate), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ certificate.AuthorizedCertificate()
+ )
+
+ await client.create_authorized_certificate(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"]
+
+
+def test_update_authorized_certificate(
+ transport: str = "grpc", request_type=appengine.UpdateAuthorizedCertificateRequest
+):
+ client = AuthorizedCertificatesClient(
+ credentials=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.update_authorized_certificate), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = certificate.AuthorizedCertificate(
+ name="name_value",
+ id="id_value",
+ display_name="display_name_value",
+ domain_names=["domain_names_value"],
+ visible_domain_mappings=["visible_domain_mappings_value"],
+ domain_mappings_count=2238,
+ )
+
+ response = client.update_authorized_certificate(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.UpdateAuthorizedCertificateRequest()
+
+ # Establish that the response is the type that we expect.
+
+ assert isinstance(response, certificate.AuthorizedCertificate)
+
+ assert response.name == "name_value"
+
+ assert response.id == "id_value"
+
+ assert response.display_name == "display_name_value"
+
+ assert response.domain_names == ["domain_names_value"]
+
+ assert response.visible_domain_mappings == ["visible_domain_mappings_value"]
+
+ assert response.domain_mappings_count == 2238
+
+
+def test_update_authorized_certificate_from_dict():
+ test_update_authorized_certificate(request_type=dict)
+
+
+def test_update_authorized_certificate_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = AuthorizedCertificatesClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_authorized_certificate), "__call__"
+ ) as call:
+ client.update_authorized_certificate()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.UpdateAuthorizedCertificateRequest()
+
+
+@pytest.mark.asyncio
+async def test_update_authorized_certificate_async(
+ transport: str = "grpc_asyncio",
+ request_type=appengine.UpdateAuthorizedCertificateRequest,
+):
+ client = AuthorizedCertificatesAsyncClient(
+ credentials=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.update_authorized_certificate), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ certificate.AuthorizedCertificate(
+ name="name_value",
+ id="id_value",
+ display_name="display_name_value",
+ domain_names=["domain_names_value"],
+ visible_domain_mappings=["visible_domain_mappings_value"],
+ domain_mappings_count=2238,
+ )
+ )
+
+ response = await client.update_authorized_certificate(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.UpdateAuthorizedCertificateRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, certificate.AuthorizedCertificate)
+
+ assert response.name == "name_value"
+
+ assert response.id == "id_value"
+
+ assert response.display_name == "display_name_value"
+
+ assert response.domain_names == ["domain_names_value"]
+
+ assert response.visible_domain_mappings == ["visible_domain_mappings_value"]
+
+ assert response.domain_mappings_count == 2238
+
+
+@pytest.mark.asyncio
+async def test_update_authorized_certificate_async_from_dict():
+ await test_update_authorized_certificate_async(request_type=dict)
+
+
+def test_update_authorized_certificate_field_headers():
+ client = AuthorizedCertificatesClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.UpdateAuthorizedCertificateRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_authorized_certificate), "__call__"
+ ) as call:
+ call.return_value = certificate.AuthorizedCertificate()
+
+ client.update_authorized_certificate(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_update_authorized_certificate_field_headers_async():
+ client = AuthorizedCertificatesAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.UpdateAuthorizedCertificateRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_authorized_certificate), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ certificate.AuthorizedCertificate()
+ )
+
+ await client.update_authorized_certificate(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_delete_authorized_certificate(
+ transport: str = "grpc", request_type=appengine.DeleteAuthorizedCertificateRequest
+):
+ client = AuthorizedCertificatesClient(
+ credentials=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.delete_authorized_certificate), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ response = client.delete_authorized_certificate(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.DeleteAuthorizedCertificateRequest()
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_delete_authorized_certificate_from_dict():
+ test_delete_authorized_certificate(request_type=dict)
+
+
+def test_delete_authorized_certificate_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = AuthorizedCertificatesClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_authorized_certificate), "__call__"
+ ) as call:
+ client.delete_authorized_certificate()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.DeleteAuthorizedCertificateRequest()
+
+
+@pytest.mark.asyncio
+async def test_delete_authorized_certificate_async(
+ transport: str = "grpc_asyncio",
+ request_type=appengine.DeleteAuthorizedCertificateRequest,
+):
+ client = AuthorizedCertificatesAsyncClient(
+ credentials=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.delete_authorized_certificate), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+
+ response = await client.delete_authorized_certificate(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.DeleteAuthorizedCertificateRequest()
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+@pytest.mark.asyncio
+async def test_delete_authorized_certificate_async_from_dict():
+ await test_delete_authorized_certificate_async(request_type=dict)
+
+
+def test_delete_authorized_certificate_field_headers():
+ client = AuthorizedCertificatesClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.DeleteAuthorizedCertificateRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_authorized_certificate), "__call__"
+ ) as call:
+ call.return_value = None
+
+ client.delete_authorized_certificate(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_delete_authorized_certificate_field_headers_async():
+ client = AuthorizedCertificatesAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.DeleteAuthorizedCertificateRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_authorized_certificate), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+
+ await client.delete_authorized_certificate(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.AuthorizedCertificatesGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = AuthorizedCertificatesClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.AuthorizedCertificatesGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = AuthorizedCertificatesClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
+
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.AuthorizedCertificatesGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = AuthorizedCertificatesClient(
+ client_options={"scopes": ["1", "2"]}, transport=transport,
+ )
+
+
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.AuthorizedCertificatesGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ client = AuthorizedCertificatesClient(transport=transport)
+ assert client.transport is transport
+
+
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.AuthorizedCertificatesGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+ transport = transports.AuthorizedCertificatesGrpcAsyncIOTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.AuthorizedCertificatesGrpcTransport,
+ transports.AuthorizedCertificatesGrpcAsyncIOTransport,
+ ],
+)
+def test_transport_adc(transport_class):
+ # Test default credentials are used if not provided.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transport_class()
+ adc.assert_called_once()
+
+
+def test_transport_grpc_default():
+ # A client should use the gRPC transport by default.
+ client = AuthorizedCertificatesClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ assert isinstance(client.transport, transports.AuthorizedCertificatesGrpcTransport,)
+
+
+def test_authorized_certificates_base_transport_error():
+ # Passing both a credentials object and credentials_file should raise an error
+ with pytest.raises(exceptions.DuplicateCredentialArgs):
+ transport = transports.AuthorizedCertificatesTransport(
+ credentials=credentials.AnonymousCredentials(),
+ credentials_file="credentials.json",
+ )
+
+
+def test_authorized_certificates_base_transport():
+ # Instantiate the base transport.
+ with mock.patch(
+ "google.cloud.appengine_admin_v1.services.authorized_certificates.transports.AuthorizedCertificatesTransport.__init__"
+ ) as Transport:
+ Transport.return_value = None
+ transport = transports.AuthorizedCertificatesTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Every method on the transport should just blindly
+ # raise NotImplementedError.
+ methods = (
+ "list_authorized_certificates",
+ "get_authorized_certificate",
+ "create_authorized_certificate",
+ "update_authorized_certificate",
+ "delete_authorized_certificate",
+ )
+ for method in methods:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, method)(request=object())
+
+
+def test_authorized_certificates_base_transport_with_credentials_file():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(
+ auth, "load_credentials_from_file"
+ ) as load_creds, mock.patch(
+ "google.cloud.appengine_admin_v1.services.authorized_certificates.transports.AuthorizedCertificatesTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ transport = transports.AuthorizedCertificatesTransport(
+ credentials_file="credentials.json", quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+def test_authorized_certificates_base_transport_with_adc():
+ # Test the default credentials are used if credentials and credentials_file are None.
+ with mock.patch.object(auth, "default") as adc, mock.patch(
+ "google.cloud.appengine_admin_v1.services.authorized_certificates.transports.AuthorizedCertificatesTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transport = transports.AuthorizedCertificatesTransport()
+ adc.assert_called_once()
+
+
+def test_authorized_certificates_auth_adc():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ AuthorizedCertificatesClient()
+ adc.assert_called_once_with(
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ quota_project_id=None,
+ )
+
+
+def test_authorized_certificates_transport_auth_adc():
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transports.AuthorizedCertificatesGrpcTransport(
+ host="squid.clam.whelk", quota_project_id="octopus"
+ )
+ adc.assert_called_once_with(
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.AuthorizedCertificatesGrpcTransport,
+ transports.AuthorizedCertificatesGrpcAsyncIOTransport,
+ ],
+)
+def test_authorized_certificates_grpc_transport_client_cert_source_for_mtls(
+ transport_class,
+):
+ cred = credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
+def test_authorized_certificates_host_no_port():
+ client = AuthorizedCertificatesClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="appengine.googleapis.com"
+ ),
+ )
+ assert client.transport._host == "appengine.googleapis.com:443"
+
+
+def test_authorized_certificates_host_with_port():
+ client = AuthorizedCertificatesClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="appengine.googleapis.com:8000"
+ ),
+ )
+ assert client.transport._host == "appengine.googleapis.com:8000"
+
+
+def test_authorized_certificates_grpc_transport_channel():
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.AuthorizedCertificatesGrpcTransport(
+ host="squid.clam.whelk", channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+def test_authorized_certificates_grpc_asyncio_transport_channel():
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.AuthorizedCertificatesGrpcAsyncIOTransport(
+ host="squid.clam.whelk", channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.AuthorizedCertificatesGrpcTransport,
+ transports.AuthorizedCertificatesGrpcAsyncIOTransport,
+ ],
+)
+def test_authorized_certificates_transport_channel_mtls_with_client_cert_source(
+ transport_class,
+):
+ with mock.patch(
+ "grpc.ssl_channel_credentials", autospec=True
+ ) as grpc_ssl_channel_cred:
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_ssl_cred = mock.Mock()
+ grpc_ssl_channel_cred.return_value = mock_ssl_cred
+
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ cred = credentials.AnonymousCredentials()
+ with pytest.warns(DeprecationWarning):
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (cred, None)
+ transport = transport_class(
+ host="squid.clam.whelk",
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=client_cert_source_callback,
+ )
+ adc.assert_called_once()
+
+ grpc_ssl_channel_cred.assert_called_once_with(
+ certificate_chain=b"cert bytes", private_key=b"key bytes"
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+ assert transport._ssl_channel_credentials == mock_ssl_cred
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.AuthorizedCertificatesGrpcTransport,
+ transports.AuthorizedCertificatesGrpcAsyncIOTransport,
+ ],
+)
+def test_authorized_certificates_transport_channel_mtls_with_adc(transport_class):
+ mock_ssl_cred = mock.Mock()
+ with mock.patch.multiple(
+ "google.auth.transport.grpc.SslCredentials",
+ __init__=mock.Mock(return_value=None),
+ ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
+ ):
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+ mock_cred = mock.Mock()
+
+ with pytest.warns(DeprecationWarning):
+ transport = transport_class(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=None,
+ )
+
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+def test_common_billing_account_path():
+ billing_account = "squid"
+
+ expected = "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
+ )
+ actual = AuthorizedCertificatesClient.common_billing_account_path(billing_account)
+ assert expected == actual
+
+
+def test_parse_common_billing_account_path():
+ expected = {
+ "billing_account": "clam",
+ }
+ path = AuthorizedCertificatesClient.common_billing_account_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = AuthorizedCertificatesClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "whelk"
+
+ expected = "folders/{folder}".format(folder=folder,)
+ actual = AuthorizedCertificatesClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "octopus",
+ }
+ path = AuthorizedCertificatesClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = AuthorizedCertificatesClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "oyster"
+
+ expected = "organizations/{organization}".format(organization=organization,)
+ actual = AuthorizedCertificatesClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "nudibranch",
+ }
+ path = AuthorizedCertificatesClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = AuthorizedCertificatesClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "cuttlefish"
+
+ expected = "projects/{project}".format(project=project,)
+ actual = AuthorizedCertificatesClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "mussel",
+ }
+ path = AuthorizedCertificatesClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = AuthorizedCertificatesClient.parse_common_project_path(path)
+ assert expected == actual
+
+
+def test_common_location_path():
+ project = "winkle"
+ location = "nautilus"
+
+ expected = "projects/{project}/locations/{location}".format(
+ project=project, location=location,
+ )
+ actual = AuthorizedCertificatesClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "scallop",
+ "location": "abalone",
+ }
+ path = AuthorizedCertificatesClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = AuthorizedCertificatesClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_withDEFAULT_CLIENT_INFO():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.AuthorizedCertificatesTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = AuthorizedCertificatesClient(
+ credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.AuthorizedCertificatesTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = AuthorizedCertificatesClient.get_transport_class()
+ transport = transport_class(
+ credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
diff --git a/tests/unit/gapic/appengine_admin_v1/test_authorized_domains.py b/tests/unit/gapic/appengine_admin_v1/test_authorized_domains.py
new file mode 100644
index 0000000..b40fd88
--- /dev/null
+++ b/tests/unit/gapic/appengine_admin_v1/test_authorized_domains.py
@@ -0,0 +1,1252 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import os
+import mock
+
+import grpc
+from grpc.experimental import aio
+import math
+import pytest
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+
+from google import auth
+from google.api_core import client_options
+from google.api_core import exceptions
+from google.api_core import gapic_v1
+from google.api_core import grpc_helpers
+from google.api_core import grpc_helpers_async
+from google.auth import credentials
+from google.auth.exceptions import MutualTLSChannelError
+from google.cloud.appengine_admin_v1.services.authorized_domains import (
+ AuthorizedDomainsAsyncClient,
+)
+from google.cloud.appengine_admin_v1.services.authorized_domains import (
+ AuthorizedDomainsClient,
+)
+from google.cloud.appengine_admin_v1.services.authorized_domains import pagers
+from google.cloud.appengine_admin_v1.services.authorized_domains import transports
+from google.cloud.appengine_admin_v1.types import appengine
+from google.cloud.appengine_admin_v1.types import domain
+from google.oauth2 import service_account
+
+
+def client_cert_source_callback():
+ return b"cert bytes", b"key bytes"
+
+
+# If default endpoint is localhost, then default mtls endpoint will be the same.
+# This method modifies the default endpoint so the client can produce a different
+# mtls endpoint for endpoint testing purposes.
+def modify_default_endpoint(client):
+ return (
+ "foo.googleapis.com"
+ if ("localhost" in client.DEFAULT_ENDPOINT)
+ else client.DEFAULT_ENDPOINT
+ )
+
+
+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 AuthorizedDomainsClient._get_default_mtls_endpoint(None) is None
+ assert (
+ AuthorizedDomainsClient._get_default_mtls_endpoint(api_endpoint)
+ == api_mtls_endpoint
+ )
+ assert (
+ AuthorizedDomainsClient._get_default_mtls_endpoint(api_mtls_endpoint)
+ == api_mtls_endpoint
+ )
+ assert (
+ AuthorizedDomainsClient._get_default_mtls_endpoint(sandbox_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert (
+ AuthorizedDomainsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert (
+ AuthorizedDomainsClient._get_default_mtls_endpoint(non_googleapi)
+ == non_googleapi
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class", [AuthorizedDomainsClient, AuthorizedDomainsAsyncClient,]
+)
+def test_authorized_domains_client_from_service_account_info(client_class):
+ creds = credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "appengine.googleapis.com:443"
+
+
+@pytest.mark.parametrize(
+ "client_class", [AuthorizedDomainsClient, AuthorizedDomainsAsyncClient,]
+)
+def test_authorized_domains_client_from_service_account_file(client_class):
+ creds = credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_file"
+ ) as factory:
+ factory.return_value = creds
+ client = client_class.from_service_account_file("dummy/file/path.json")
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ client = client_class.from_service_account_json("dummy/file/path.json")
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "appengine.googleapis.com:443"
+
+
+def test_authorized_domains_client_get_transport_class():
+ transport = AuthorizedDomainsClient.get_transport_class()
+ available_transports = [
+ transports.AuthorizedDomainsGrpcTransport,
+ ]
+ assert transport in available_transports
+
+ transport = AuthorizedDomainsClient.get_transport_class("grpc")
+ assert transport == transports.AuthorizedDomainsGrpcTransport
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (AuthorizedDomainsClient, transports.AuthorizedDomainsGrpcTransport, "grpc"),
+ (
+ AuthorizedDomainsAsyncClient,
+ transports.AuthorizedDomainsGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+@mock.patch.object(
+ AuthorizedDomainsClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(AuthorizedDomainsClient),
+)
+@mock.patch.object(
+ AuthorizedDomainsAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(AuthorizedDomainsAsyncClient),
+)
+def test_authorized_domains_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(AuthorizedDomainsClient, "get_transport_class") as gtc:
+ transport = transport_class(credentials=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(AuthorizedDomainsClient, "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,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,use_client_cert_env",
+ [
+ (
+ AuthorizedDomainsClient,
+ transports.AuthorizedDomainsGrpcTransport,
+ "grpc",
+ "true",
+ ),
+ (
+ AuthorizedDomainsAsyncClient,
+ transports.AuthorizedDomainsGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "true",
+ ),
+ (
+ AuthorizedDomainsClient,
+ transports.AuthorizedDomainsGrpcTransport,
+ "grpc",
+ "false",
+ ),
+ (
+ AuthorizedDomainsAsyncClient,
+ transports.AuthorizedDomainsGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "false",
+ ),
+ ],
+)
+@mock.patch.object(
+ AuthorizedDomainsClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(AuthorizedDomainsClient),
+)
+@mock.patch.object(
+ AuthorizedDomainsAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(AuthorizedDomainsAsyncClient),
+)
+@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"})
+def test_authorized_domains_client_mtls_env_auto(
+ client_class, transport_class, transport_name, use_client_cert_env
+):
+ # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default
+ # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists.
+
+ # Check the case client_cert_source is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ options = client_options.ClientOptions(
+ client_cert_source=client_cert_source_callback
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client.DEFAULT_ENDPOINT
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+ # Check the case ADC client cert is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client.DEFAULT_ENDPOINT
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
+
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ 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,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (AuthorizedDomainsClient, transports.AuthorizedDomainsGrpcTransport, "grpc"),
+ (
+ AuthorizedDomainsAsyncClient,
+ transports.AuthorizedDomainsGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_authorized_domains_client_client_options_scopes(
+ client_class, transport_class, transport_name
+):
+ # Check the case scopes are provided.
+ options = client_options.ClientOptions(scopes=["1", "2"],)
+ 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=["1", "2"],
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (AuthorizedDomainsClient, transports.AuthorizedDomainsGrpcTransport, "grpc"),
+ (
+ AuthorizedDomainsAsyncClient,
+ transports.AuthorizedDomainsGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_authorized_domains_client_client_options_credentials_file(
+ client_class, transport_class, transport_name
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+ 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="credentials.json",
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+
+def test_authorized_domains_client_client_options_from_dict():
+ with mock.patch(
+ "google.cloud.appengine_admin_v1.services.authorized_domains.transports.AuthorizedDomainsGrpcTransport.__init__"
+ ) as grpc_transport:
+ grpc_transport.return_value = None
+ client = AuthorizedDomainsClient(
+ client_options={"api_endpoint": "squid.clam.whelk"}
+ )
+ grpc_transport.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,
+ )
+
+
+def test_list_authorized_domains(
+ transport: str = "grpc", request_type=appengine.ListAuthorizedDomainsRequest
+):
+ client = AuthorizedDomainsClient(
+ credentials=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.list_authorized_domains), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = appengine.ListAuthorizedDomainsResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ response = client.list_authorized_domains(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.ListAuthorizedDomainsRequest()
+
+ # Establish that the response is the type that we expect.
+
+ assert isinstance(response, pagers.ListAuthorizedDomainsPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_authorized_domains_from_dict():
+ test_list_authorized_domains(request_type=dict)
+
+
+def test_list_authorized_domains_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = AuthorizedDomainsClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_authorized_domains), "__call__"
+ ) as call:
+ client.list_authorized_domains()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.ListAuthorizedDomainsRequest()
+
+
+@pytest.mark.asyncio
+async def test_list_authorized_domains_async(
+ transport: str = "grpc_asyncio", request_type=appengine.ListAuthorizedDomainsRequest
+):
+ client = AuthorizedDomainsAsyncClient(
+ credentials=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.list_authorized_domains), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ appengine.ListAuthorizedDomainsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+
+ response = await client.list_authorized_domains(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.ListAuthorizedDomainsRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListAuthorizedDomainsAsyncPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+
+@pytest.mark.asyncio
+async def test_list_authorized_domains_async_from_dict():
+ await test_list_authorized_domains_async(request_type=dict)
+
+
+def test_list_authorized_domains_field_headers():
+ client = AuthorizedDomainsClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.ListAuthorizedDomainsRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_authorized_domains), "__call__"
+ ) as call:
+ call.return_value = appengine.ListAuthorizedDomainsResponse()
+
+ client.list_authorized_domains(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_list_authorized_domains_field_headers_async():
+ client = AuthorizedDomainsAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.ListAuthorizedDomainsRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_authorized_domains), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ appengine.ListAuthorizedDomainsResponse()
+ )
+
+ await client.list_authorized_domains(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"]
+
+
+def test_list_authorized_domains_pager():
+ client = AuthorizedDomainsClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_authorized_domains), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListAuthorizedDomainsResponse(
+ domains=[
+ domain.AuthorizedDomain(),
+ domain.AuthorizedDomain(),
+ domain.AuthorizedDomain(),
+ ],
+ next_page_token="abc",
+ ),
+ appengine.ListAuthorizedDomainsResponse(domains=[], next_page_token="def",),
+ appengine.ListAuthorizedDomainsResponse(
+ domains=[domain.AuthorizedDomain(),], next_page_token="ghi",
+ ),
+ appengine.ListAuthorizedDomainsResponse(
+ domains=[domain.AuthorizedDomain(), domain.AuthorizedDomain(),],
+ ),
+ RuntimeError,
+ )
+
+ metadata = ()
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
+ )
+ pager = client.list_authorized_domains(request={})
+
+ assert pager._metadata == metadata
+
+ results = [i for i in pager]
+ assert len(results) == 6
+ assert all(isinstance(i, domain.AuthorizedDomain) for i in results)
+
+
+def test_list_authorized_domains_pages():
+ client = AuthorizedDomainsClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_authorized_domains), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListAuthorizedDomainsResponse(
+ domains=[
+ domain.AuthorizedDomain(),
+ domain.AuthorizedDomain(),
+ domain.AuthorizedDomain(),
+ ],
+ next_page_token="abc",
+ ),
+ appengine.ListAuthorizedDomainsResponse(domains=[], next_page_token="def",),
+ appengine.ListAuthorizedDomainsResponse(
+ domains=[domain.AuthorizedDomain(),], next_page_token="ghi",
+ ),
+ appengine.ListAuthorizedDomainsResponse(
+ domains=[domain.AuthorizedDomain(), domain.AuthorizedDomain(),],
+ ),
+ RuntimeError,
+ )
+ pages = list(client.list_authorized_domains(request={}).pages)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
+
+
+@pytest.mark.asyncio
+async def test_list_authorized_domains_async_pager():
+ client = AuthorizedDomainsAsyncClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_authorized_domains),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListAuthorizedDomainsResponse(
+ domains=[
+ domain.AuthorizedDomain(),
+ domain.AuthorizedDomain(),
+ domain.AuthorizedDomain(),
+ ],
+ next_page_token="abc",
+ ),
+ appengine.ListAuthorizedDomainsResponse(domains=[], next_page_token="def",),
+ appengine.ListAuthorizedDomainsResponse(
+ domains=[domain.AuthorizedDomain(),], next_page_token="ghi",
+ ),
+ appengine.ListAuthorizedDomainsResponse(
+ domains=[domain.AuthorizedDomain(), domain.AuthorizedDomain(),],
+ ),
+ RuntimeError,
+ )
+ async_pager = await client.list_authorized_domains(request={},)
+ assert async_pager.next_page_token == "abc"
+ responses = []
+ async for response in async_pager:
+ responses.append(response)
+
+ assert len(responses) == 6
+ assert all(isinstance(i, domain.AuthorizedDomain) for i in responses)
+
+
+@pytest.mark.asyncio
+async def test_list_authorized_domains_async_pages():
+ client = AuthorizedDomainsAsyncClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_authorized_domains),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListAuthorizedDomainsResponse(
+ domains=[
+ domain.AuthorizedDomain(),
+ domain.AuthorizedDomain(),
+ domain.AuthorizedDomain(),
+ ],
+ next_page_token="abc",
+ ),
+ appengine.ListAuthorizedDomainsResponse(domains=[], next_page_token="def",),
+ appengine.ListAuthorizedDomainsResponse(
+ domains=[domain.AuthorizedDomain(),], next_page_token="ghi",
+ ),
+ appengine.ListAuthorizedDomainsResponse(
+ domains=[domain.AuthorizedDomain(), domain.AuthorizedDomain(),],
+ ),
+ RuntimeError,
+ )
+ pages = []
+ async for page_ in (await client.list_authorized_domains(request={})).pages:
+ pages.append(page_)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
+
+
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.AuthorizedDomainsGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = AuthorizedDomainsClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.AuthorizedDomainsGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = AuthorizedDomainsClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
+
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.AuthorizedDomainsGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = AuthorizedDomainsClient(
+ client_options={"scopes": ["1", "2"]}, transport=transport,
+ )
+
+
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.AuthorizedDomainsGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ client = AuthorizedDomainsClient(transport=transport)
+ assert client.transport is transport
+
+
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.AuthorizedDomainsGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+ transport = transports.AuthorizedDomainsGrpcAsyncIOTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.AuthorizedDomainsGrpcTransport,
+ transports.AuthorizedDomainsGrpcAsyncIOTransport,
+ ],
+)
+def test_transport_adc(transport_class):
+ # Test default credentials are used if not provided.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transport_class()
+ adc.assert_called_once()
+
+
+def test_transport_grpc_default():
+ # A client should use the gRPC transport by default.
+ client = AuthorizedDomainsClient(credentials=credentials.AnonymousCredentials(),)
+ assert isinstance(client.transport, transports.AuthorizedDomainsGrpcTransport,)
+
+
+def test_authorized_domains_base_transport_error():
+ # Passing both a credentials object and credentials_file should raise an error
+ with pytest.raises(exceptions.DuplicateCredentialArgs):
+ transport = transports.AuthorizedDomainsTransport(
+ credentials=credentials.AnonymousCredentials(),
+ credentials_file="credentials.json",
+ )
+
+
+def test_authorized_domains_base_transport():
+ # Instantiate the base transport.
+ with mock.patch(
+ "google.cloud.appengine_admin_v1.services.authorized_domains.transports.AuthorizedDomainsTransport.__init__"
+ ) as Transport:
+ Transport.return_value = None
+ transport = transports.AuthorizedDomainsTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Every method on the transport should just blindly
+ # raise NotImplementedError.
+ methods = ("list_authorized_domains",)
+ for method in methods:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, method)(request=object())
+
+
+def test_authorized_domains_base_transport_with_credentials_file():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(
+ auth, "load_credentials_from_file"
+ ) as load_creds, mock.patch(
+ "google.cloud.appengine_admin_v1.services.authorized_domains.transports.AuthorizedDomainsTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ transport = transports.AuthorizedDomainsTransport(
+ credentials_file="credentials.json", quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+def test_authorized_domains_base_transport_with_adc():
+ # Test the default credentials are used if credentials and credentials_file are None.
+ with mock.patch.object(auth, "default") as adc, mock.patch(
+ "google.cloud.appengine_admin_v1.services.authorized_domains.transports.AuthorizedDomainsTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transport = transports.AuthorizedDomainsTransport()
+ adc.assert_called_once()
+
+
+def test_authorized_domains_auth_adc():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ AuthorizedDomainsClient()
+ adc.assert_called_once_with(
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ quota_project_id=None,
+ )
+
+
+def test_authorized_domains_transport_auth_adc():
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transports.AuthorizedDomainsGrpcTransport(
+ host="squid.clam.whelk", quota_project_id="octopus"
+ )
+ adc.assert_called_once_with(
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.AuthorizedDomainsGrpcTransport,
+ transports.AuthorizedDomainsGrpcAsyncIOTransport,
+ ],
+)
+def test_authorized_domains_grpc_transport_client_cert_source_for_mtls(transport_class):
+ cred = credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
+def test_authorized_domains_host_no_port():
+ client = AuthorizedDomainsClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="appengine.googleapis.com"
+ ),
+ )
+ assert client.transport._host == "appengine.googleapis.com:443"
+
+
+def test_authorized_domains_host_with_port():
+ client = AuthorizedDomainsClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="appengine.googleapis.com:8000"
+ ),
+ )
+ assert client.transport._host == "appengine.googleapis.com:8000"
+
+
+def test_authorized_domains_grpc_transport_channel():
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.AuthorizedDomainsGrpcTransport(
+ host="squid.clam.whelk", channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+def test_authorized_domains_grpc_asyncio_transport_channel():
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.AuthorizedDomainsGrpcAsyncIOTransport(
+ host="squid.clam.whelk", channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.AuthorizedDomainsGrpcTransport,
+ transports.AuthorizedDomainsGrpcAsyncIOTransport,
+ ],
+)
+def test_authorized_domains_transport_channel_mtls_with_client_cert_source(
+ transport_class,
+):
+ with mock.patch(
+ "grpc.ssl_channel_credentials", autospec=True
+ ) as grpc_ssl_channel_cred:
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_ssl_cred = mock.Mock()
+ grpc_ssl_channel_cred.return_value = mock_ssl_cred
+
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ cred = credentials.AnonymousCredentials()
+ with pytest.warns(DeprecationWarning):
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (cred, None)
+ transport = transport_class(
+ host="squid.clam.whelk",
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=client_cert_source_callback,
+ )
+ adc.assert_called_once()
+
+ grpc_ssl_channel_cred.assert_called_once_with(
+ certificate_chain=b"cert bytes", private_key=b"key bytes"
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+ assert transport._ssl_channel_credentials == mock_ssl_cred
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.AuthorizedDomainsGrpcTransport,
+ transports.AuthorizedDomainsGrpcAsyncIOTransport,
+ ],
+)
+def test_authorized_domains_transport_channel_mtls_with_adc(transport_class):
+ mock_ssl_cred = mock.Mock()
+ with mock.patch.multiple(
+ "google.auth.transport.grpc.SslCredentials",
+ __init__=mock.Mock(return_value=None),
+ ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
+ ):
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+ mock_cred = mock.Mock()
+
+ with pytest.warns(DeprecationWarning):
+ transport = transport_class(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=None,
+ )
+
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+def test_common_billing_account_path():
+ billing_account = "squid"
+
+ expected = "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
+ )
+ actual = AuthorizedDomainsClient.common_billing_account_path(billing_account)
+ assert expected == actual
+
+
+def test_parse_common_billing_account_path():
+ expected = {
+ "billing_account": "clam",
+ }
+ path = AuthorizedDomainsClient.common_billing_account_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = AuthorizedDomainsClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "whelk"
+
+ expected = "folders/{folder}".format(folder=folder,)
+ actual = AuthorizedDomainsClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "octopus",
+ }
+ path = AuthorizedDomainsClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = AuthorizedDomainsClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "oyster"
+
+ expected = "organizations/{organization}".format(organization=organization,)
+ actual = AuthorizedDomainsClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "nudibranch",
+ }
+ path = AuthorizedDomainsClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = AuthorizedDomainsClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "cuttlefish"
+
+ expected = "projects/{project}".format(project=project,)
+ actual = AuthorizedDomainsClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "mussel",
+ }
+ path = AuthorizedDomainsClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = AuthorizedDomainsClient.parse_common_project_path(path)
+ assert expected == actual
+
+
+def test_common_location_path():
+ project = "winkle"
+ location = "nautilus"
+
+ expected = "projects/{project}/locations/{location}".format(
+ project=project, location=location,
+ )
+ actual = AuthorizedDomainsClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "scallop",
+ "location": "abalone",
+ }
+ path = AuthorizedDomainsClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = AuthorizedDomainsClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_withDEFAULT_CLIENT_INFO():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.AuthorizedDomainsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = AuthorizedDomainsClient(
+ credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.AuthorizedDomainsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = AuthorizedDomainsClient.get_transport_class()
+ transport = transport_class(
+ credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
diff --git a/tests/unit/gapic/appengine_admin_v1/test_domain_mappings.py b/tests/unit/gapic/appengine_admin_v1/test_domain_mappings.py
new file mode 100644
index 0000000..1a995d8
--- /dev/null
+++ b/tests/unit/gapic/appengine_admin_v1/test_domain_mappings.py
@@ -0,0 +1,1897 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import os
+import mock
+
+import grpc
+from grpc.experimental import aio
+import math
+import pytest
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+
+from google import auth
+from google.api_core import client_options
+from google.api_core import exceptions
+from google.api_core import future
+from google.api_core import gapic_v1
+from google.api_core import grpc_helpers
+from google.api_core import grpc_helpers_async
+from google.api_core import operation_async # type: ignore
+from google.api_core import operations_v1
+from google.auth import credentials
+from google.auth.exceptions import MutualTLSChannelError
+from google.cloud.appengine_admin_v1.services.domain_mappings import (
+ DomainMappingsAsyncClient,
+)
+from google.cloud.appengine_admin_v1.services.domain_mappings import (
+ DomainMappingsClient,
+)
+from google.cloud.appengine_admin_v1.services.domain_mappings import pagers
+from google.cloud.appengine_admin_v1.services.domain_mappings import transports
+from google.cloud.appengine_admin_v1.types import appengine
+from google.cloud.appengine_admin_v1.types import domain_mapping
+from google.cloud.appengine_admin_v1.types import operation as ga_operation
+from google.longrunning import operations_pb2
+from google.oauth2 import service_account
+from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+
+
+def client_cert_source_callback():
+ return b"cert bytes", b"key bytes"
+
+
+# If default endpoint is localhost, then default mtls endpoint will be the same.
+# This method modifies the default endpoint so the client can produce a different
+# mtls endpoint for endpoint testing purposes.
+def modify_default_endpoint(client):
+ return (
+ "foo.googleapis.com"
+ if ("localhost" in client.DEFAULT_ENDPOINT)
+ else client.DEFAULT_ENDPOINT
+ )
+
+
+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 DomainMappingsClient._get_default_mtls_endpoint(None) is None
+ assert (
+ DomainMappingsClient._get_default_mtls_endpoint(api_endpoint)
+ == api_mtls_endpoint
+ )
+ assert (
+ DomainMappingsClient._get_default_mtls_endpoint(api_mtls_endpoint)
+ == api_mtls_endpoint
+ )
+ assert (
+ DomainMappingsClient._get_default_mtls_endpoint(sandbox_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert (
+ DomainMappingsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert (
+ DomainMappingsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class", [DomainMappingsClient, DomainMappingsAsyncClient,]
+)
+def test_domain_mappings_client_from_service_account_info(client_class):
+ creds = credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "appengine.googleapis.com:443"
+
+
+@pytest.mark.parametrize(
+ "client_class", [DomainMappingsClient, DomainMappingsAsyncClient,]
+)
+def test_domain_mappings_client_from_service_account_file(client_class):
+ creds = credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_file"
+ ) as factory:
+ factory.return_value = creds
+ client = client_class.from_service_account_file("dummy/file/path.json")
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ client = client_class.from_service_account_json("dummy/file/path.json")
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "appengine.googleapis.com:443"
+
+
+def test_domain_mappings_client_get_transport_class():
+ transport = DomainMappingsClient.get_transport_class()
+ available_transports = [
+ transports.DomainMappingsGrpcTransport,
+ ]
+ assert transport in available_transports
+
+ transport = DomainMappingsClient.get_transport_class("grpc")
+ assert transport == transports.DomainMappingsGrpcTransport
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (DomainMappingsClient, transports.DomainMappingsGrpcTransport, "grpc"),
+ (
+ DomainMappingsAsyncClient,
+ transports.DomainMappingsGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+@mock.patch.object(
+ DomainMappingsClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(DomainMappingsClient),
+)
+@mock.patch.object(
+ DomainMappingsAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(DomainMappingsAsyncClient),
+)
+def test_domain_mappings_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(DomainMappingsClient, "get_transport_class") as gtc:
+ transport = transport_class(credentials=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(DomainMappingsClient, "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,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,use_client_cert_env",
+ [
+ (DomainMappingsClient, transports.DomainMappingsGrpcTransport, "grpc", "true"),
+ (
+ DomainMappingsAsyncClient,
+ transports.DomainMappingsGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "true",
+ ),
+ (DomainMappingsClient, transports.DomainMappingsGrpcTransport, "grpc", "false"),
+ (
+ DomainMappingsAsyncClient,
+ transports.DomainMappingsGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "false",
+ ),
+ ],
+)
+@mock.patch.object(
+ DomainMappingsClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(DomainMappingsClient),
+)
+@mock.patch.object(
+ DomainMappingsAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(DomainMappingsAsyncClient),
+)
+@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"})
+def test_domain_mappings_client_mtls_env_auto(
+ client_class, transport_class, transport_name, use_client_cert_env
+):
+ # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default
+ # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists.
+
+ # Check the case client_cert_source is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ options = client_options.ClientOptions(
+ client_cert_source=client_cert_source_callback
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client.DEFAULT_ENDPOINT
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+ # Check the case ADC client cert is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client.DEFAULT_ENDPOINT
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
+
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ 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,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (DomainMappingsClient, transports.DomainMappingsGrpcTransport, "grpc"),
+ (
+ DomainMappingsAsyncClient,
+ transports.DomainMappingsGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_domain_mappings_client_client_options_scopes(
+ client_class, transport_class, transport_name
+):
+ # Check the case scopes are provided.
+ options = client_options.ClientOptions(scopes=["1", "2"],)
+ 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=["1", "2"],
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (DomainMappingsClient, transports.DomainMappingsGrpcTransport, "grpc"),
+ (
+ DomainMappingsAsyncClient,
+ transports.DomainMappingsGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_domain_mappings_client_client_options_credentials_file(
+ client_class, transport_class, transport_name
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+ 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="credentials.json",
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+
+def test_domain_mappings_client_client_options_from_dict():
+ with mock.patch(
+ "google.cloud.appengine_admin_v1.services.domain_mappings.transports.DomainMappingsGrpcTransport.__init__"
+ ) as grpc_transport:
+ grpc_transport.return_value = None
+ client = DomainMappingsClient(
+ client_options={"api_endpoint": "squid.clam.whelk"}
+ )
+ grpc_transport.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,
+ )
+
+
+def test_list_domain_mappings(
+ transport: str = "grpc", request_type=appengine.ListDomainMappingsRequest
+):
+ client = DomainMappingsClient(
+ credentials=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.list_domain_mappings), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = appengine.ListDomainMappingsResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ response = client.list_domain_mappings(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.ListDomainMappingsRequest()
+
+ # Establish that the response is the type that we expect.
+
+ assert isinstance(response, pagers.ListDomainMappingsPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_domain_mappings_from_dict():
+ test_list_domain_mappings(request_type=dict)
+
+
+def test_list_domain_mappings_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = DomainMappingsClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_domain_mappings), "__call__"
+ ) as call:
+ client.list_domain_mappings()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.ListDomainMappingsRequest()
+
+
+@pytest.mark.asyncio
+async def test_list_domain_mappings_async(
+ transport: str = "grpc_asyncio", request_type=appengine.ListDomainMappingsRequest
+):
+ client = DomainMappingsAsyncClient(
+ credentials=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.list_domain_mappings), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ appengine.ListDomainMappingsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+
+ response = await client.list_domain_mappings(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.ListDomainMappingsRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListDomainMappingsAsyncPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+
+@pytest.mark.asyncio
+async def test_list_domain_mappings_async_from_dict():
+ await test_list_domain_mappings_async(request_type=dict)
+
+
+def test_list_domain_mappings_field_headers():
+ client = DomainMappingsClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.ListDomainMappingsRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_domain_mappings), "__call__"
+ ) as call:
+ call.return_value = appengine.ListDomainMappingsResponse()
+
+ client.list_domain_mappings(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_list_domain_mappings_field_headers_async():
+ client = DomainMappingsAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.ListDomainMappingsRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_domain_mappings), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ appengine.ListDomainMappingsResponse()
+ )
+
+ await client.list_domain_mappings(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"]
+
+
+def test_list_domain_mappings_pager():
+ client = DomainMappingsClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_domain_mappings), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListDomainMappingsResponse(
+ domain_mappings=[
+ domain_mapping.DomainMapping(),
+ domain_mapping.DomainMapping(),
+ domain_mapping.DomainMapping(),
+ ],
+ next_page_token="abc",
+ ),
+ appengine.ListDomainMappingsResponse(
+ domain_mappings=[], next_page_token="def",
+ ),
+ appengine.ListDomainMappingsResponse(
+ domain_mappings=[domain_mapping.DomainMapping(),],
+ next_page_token="ghi",
+ ),
+ appengine.ListDomainMappingsResponse(
+ domain_mappings=[
+ domain_mapping.DomainMapping(),
+ domain_mapping.DomainMapping(),
+ ],
+ ),
+ RuntimeError,
+ )
+
+ metadata = ()
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
+ )
+ pager = client.list_domain_mappings(request={})
+
+ assert pager._metadata == metadata
+
+ results = [i for i in pager]
+ assert len(results) == 6
+ assert all(isinstance(i, domain_mapping.DomainMapping) for i in results)
+
+
+def test_list_domain_mappings_pages():
+ client = DomainMappingsClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_domain_mappings), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListDomainMappingsResponse(
+ domain_mappings=[
+ domain_mapping.DomainMapping(),
+ domain_mapping.DomainMapping(),
+ domain_mapping.DomainMapping(),
+ ],
+ next_page_token="abc",
+ ),
+ appengine.ListDomainMappingsResponse(
+ domain_mappings=[], next_page_token="def",
+ ),
+ appengine.ListDomainMappingsResponse(
+ domain_mappings=[domain_mapping.DomainMapping(),],
+ next_page_token="ghi",
+ ),
+ appengine.ListDomainMappingsResponse(
+ domain_mappings=[
+ domain_mapping.DomainMapping(),
+ domain_mapping.DomainMapping(),
+ ],
+ ),
+ RuntimeError,
+ )
+ pages = list(client.list_domain_mappings(request={}).pages)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
+
+
+@pytest.mark.asyncio
+async def test_list_domain_mappings_async_pager():
+ client = DomainMappingsAsyncClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_domain_mappings),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListDomainMappingsResponse(
+ domain_mappings=[
+ domain_mapping.DomainMapping(),
+ domain_mapping.DomainMapping(),
+ domain_mapping.DomainMapping(),
+ ],
+ next_page_token="abc",
+ ),
+ appengine.ListDomainMappingsResponse(
+ domain_mappings=[], next_page_token="def",
+ ),
+ appengine.ListDomainMappingsResponse(
+ domain_mappings=[domain_mapping.DomainMapping(),],
+ next_page_token="ghi",
+ ),
+ appengine.ListDomainMappingsResponse(
+ domain_mappings=[
+ domain_mapping.DomainMapping(),
+ domain_mapping.DomainMapping(),
+ ],
+ ),
+ RuntimeError,
+ )
+ async_pager = await client.list_domain_mappings(request={},)
+ assert async_pager.next_page_token == "abc"
+ responses = []
+ async for response in async_pager:
+ responses.append(response)
+
+ assert len(responses) == 6
+ assert all(isinstance(i, domain_mapping.DomainMapping) for i in responses)
+
+
+@pytest.mark.asyncio
+async def test_list_domain_mappings_async_pages():
+ client = DomainMappingsAsyncClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_domain_mappings),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListDomainMappingsResponse(
+ domain_mappings=[
+ domain_mapping.DomainMapping(),
+ domain_mapping.DomainMapping(),
+ domain_mapping.DomainMapping(),
+ ],
+ next_page_token="abc",
+ ),
+ appengine.ListDomainMappingsResponse(
+ domain_mappings=[], next_page_token="def",
+ ),
+ appengine.ListDomainMappingsResponse(
+ domain_mappings=[domain_mapping.DomainMapping(),],
+ next_page_token="ghi",
+ ),
+ appengine.ListDomainMappingsResponse(
+ domain_mappings=[
+ domain_mapping.DomainMapping(),
+ domain_mapping.DomainMapping(),
+ ],
+ ),
+ RuntimeError,
+ )
+ pages = []
+ async for page_ in (await client.list_domain_mappings(request={})).pages:
+ pages.append(page_)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
+
+
+def test_get_domain_mapping(
+ transport: str = "grpc", request_type=appengine.GetDomainMappingRequest
+):
+ client = DomainMappingsClient(
+ credentials=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_domain_mapping), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = domain_mapping.DomainMapping(
+ name="name_value", id="id_value",
+ )
+
+ response = client.get_domain_mapping(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.GetDomainMappingRequest()
+
+ # Establish that the response is the type that we expect.
+
+ assert isinstance(response, domain_mapping.DomainMapping)
+
+ assert response.name == "name_value"
+
+ assert response.id == "id_value"
+
+
+def test_get_domain_mapping_from_dict():
+ test_get_domain_mapping(request_type=dict)
+
+
+def test_get_domain_mapping_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = DomainMappingsClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_domain_mapping), "__call__"
+ ) as call:
+ client.get_domain_mapping()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.GetDomainMappingRequest()
+
+
+@pytest.mark.asyncio
+async def test_get_domain_mapping_async(
+ transport: str = "grpc_asyncio", request_type=appengine.GetDomainMappingRequest
+):
+ client = DomainMappingsAsyncClient(
+ credentials=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_domain_mapping), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ domain_mapping.DomainMapping(name="name_value", id="id_value",)
+ )
+
+ response = await client.get_domain_mapping(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.GetDomainMappingRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, domain_mapping.DomainMapping)
+
+ assert response.name == "name_value"
+
+ assert response.id == "id_value"
+
+
+@pytest.mark.asyncio
+async def test_get_domain_mapping_async_from_dict():
+ await test_get_domain_mapping_async(request_type=dict)
+
+
+def test_get_domain_mapping_field_headers():
+ client = DomainMappingsClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.GetDomainMappingRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_domain_mapping), "__call__"
+ ) as call:
+ call.return_value = domain_mapping.DomainMapping()
+
+ client.get_domain_mapping(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_get_domain_mapping_field_headers_async():
+ client = DomainMappingsAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.GetDomainMappingRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_domain_mapping), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ domain_mapping.DomainMapping()
+ )
+
+ await client.get_domain_mapping(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_create_domain_mapping(
+ transport: str = "grpc", request_type=appengine.CreateDomainMappingRequest
+):
+ client = DomainMappingsClient(
+ credentials=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.create_domain_mapping), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.create_domain_mapping(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.CreateDomainMappingRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_create_domain_mapping_from_dict():
+ test_create_domain_mapping(request_type=dict)
+
+
+def test_create_domain_mapping_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = DomainMappingsClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_domain_mapping), "__call__"
+ ) as call:
+ client.create_domain_mapping()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.CreateDomainMappingRequest()
+
+
+@pytest.mark.asyncio
+async def test_create_domain_mapping_async(
+ transport: str = "grpc_asyncio", request_type=appengine.CreateDomainMappingRequest
+):
+ client = DomainMappingsAsyncClient(
+ credentials=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.create_domain_mapping), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/spam")
+ )
+
+ response = await client.create_domain_mapping(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.CreateDomainMappingRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_create_domain_mapping_async_from_dict():
+ await test_create_domain_mapping_async(request_type=dict)
+
+
+def test_create_domain_mapping_field_headers():
+ client = DomainMappingsClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.CreateDomainMappingRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_domain_mapping), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ client.create_domain_mapping(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_create_domain_mapping_field_headers_async():
+ client = DomainMappingsAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.CreateDomainMappingRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_domain_mapping), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+
+ await client.create_domain_mapping(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"]
+
+
+def test_update_domain_mapping(
+ transport: str = "grpc", request_type=appengine.UpdateDomainMappingRequest
+):
+ client = DomainMappingsClient(
+ credentials=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.update_domain_mapping), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.update_domain_mapping(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.UpdateDomainMappingRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_update_domain_mapping_from_dict():
+ test_update_domain_mapping(request_type=dict)
+
+
+def test_update_domain_mapping_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = DomainMappingsClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_domain_mapping), "__call__"
+ ) as call:
+ client.update_domain_mapping()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.UpdateDomainMappingRequest()
+
+
+@pytest.mark.asyncio
+async def test_update_domain_mapping_async(
+ transport: str = "grpc_asyncio", request_type=appengine.UpdateDomainMappingRequest
+):
+ client = DomainMappingsAsyncClient(
+ credentials=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.update_domain_mapping), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/spam")
+ )
+
+ response = await client.update_domain_mapping(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.UpdateDomainMappingRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_update_domain_mapping_async_from_dict():
+ await test_update_domain_mapping_async(request_type=dict)
+
+
+def test_update_domain_mapping_field_headers():
+ client = DomainMappingsClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.UpdateDomainMappingRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_domain_mapping), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ client.update_domain_mapping(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_update_domain_mapping_field_headers_async():
+ client = DomainMappingsAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.UpdateDomainMappingRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_domain_mapping), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+
+ await client.update_domain_mapping(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_delete_domain_mapping(
+ transport: str = "grpc", request_type=appengine.DeleteDomainMappingRequest
+):
+ client = DomainMappingsClient(
+ credentials=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.delete_domain_mapping), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.delete_domain_mapping(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.DeleteDomainMappingRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_delete_domain_mapping_from_dict():
+ test_delete_domain_mapping(request_type=dict)
+
+
+def test_delete_domain_mapping_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = DomainMappingsClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_domain_mapping), "__call__"
+ ) as call:
+ client.delete_domain_mapping()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.DeleteDomainMappingRequest()
+
+
+@pytest.mark.asyncio
+async def test_delete_domain_mapping_async(
+ transport: str = "grpc_asyncio", request_type=appengine.DeleteDomainMappingRequest
+):
+ client = DomainMappingsAsyncClient(
+ credentials=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.delete_domain_mapping), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/spam")
+ )
+
+ response = await client.delete_domain_mapping(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.DeleteDomainMappingRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_delete_domain_mapping_async_from_dict():
+ await test_delete_domain_mapping_async(request_type=dict)
+
+
+def test_delete_domain_mapping_field_headers():
+ client = DomainMappingsClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.DeleteDomainMappingRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_domain_mapping), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ client.delete_domain_mapping(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_delete_domain_mapping_field_headers_async():
+ client = DomainMappingsAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.DeleteDomainMappingRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_domain_mapping), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+
+ await client.delete_domain_mapping(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.DomainMappingsGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = DomainMappingsClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.DomainMappingsGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = DomainMappingsClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
+
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.DomainMappingsGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = DomainMappingsClient(
+ client_options={"scopes": ["1", "2"]}, transport=transport,
+ )
+
+
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.DomainMappingsGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ client = DomainMappingsClient(transport=transport)
+ assert client.transport is transport
+
+
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.DomainMappingsGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+ transport = transports.DomainMappingsGrpcAsyncIOTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.DomainMappingsGrpcTransport,
+ transports.DomainMappingsGrpcAsyncIOTransport,
+ ],
+)
+def test_transport_adc(transport_class):
+ # Test default credentials are used if not provided.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transport_class()
+ adc.assert_called_once()
+
+
+def test_transport_grpc_default():
+ # A client should use the gRPC transport by default.
+ client = DomainMappingsClient(credentials=credentials.AnonymousCredentials(),)
+ assert isinstance(client.transport, transports.DomainMappingsGrpcTransport,)
+
+
+def test_domain_mappings_base_transport_error():
+ # Passing both a credentials object and credentials_file should raise an error
+ with pytest.raises(exceptions.DuplicateCredentialArgs):
+ transport = transports.DomainMappingsTransport(
+ credentials=credentials.AnonymousCredentials(),
+ credentials_file="credentials.json",
+ )
+
+
+def test_domain_mappings_base_transport():
+ # Instantiate the base transport.
+ with mock.patch(
+ "google.cloud.appengine_admin_v1.services.domain_mappings.transports.DomainMappingsTransport.__init__"
+ ) as Transport:
+ Transport.return_value = None
+ transport = transports.DomainMappingsTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Every method on the transport should just blindly
+ # raise NotImplementedError.
+ methods = (
+ "list_domain_mappings",
+ "get_domain_mapping",
+ "create_domain_mapping",
+ "update_domain_mapping",
+ "delete_domain_mapping",
+ )
+ for method in methods:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, method)(request=object())
+
+ # Additionally, the LRO client (a property) should
+ # also raise NotImplementedError
+ with pytest.raises(NotImplementedError):
+ transport.operations_client
+
+
+def test_domain_mappings_base_transport_with_credentials_file():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(
+ auth, "load_credentials_from_file"
+ ) as load_creds, mock.patch(
+ "google.cloud.appengine_admin_v1.services.domain_mappings.transports.DomainMappingsTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ transport = transports.DomainMappingsTransport(
+ credentials_file="credentials.json", quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+def test_domain_mappings_base_transport_with_adc():
+ # Test the default credentials are used if credentials and credentials_file are None.
+ with mock.patch.object(auth, "default") as adc, mock.patch(
+ "google.cloud.appengine_admin_v1.services.domain_mappings.transports.DomainMappingsTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transport = transports.DomainMappingsTransport()
+ adc.assert_called_once()
+
+
+def test_domain_mappings_auth_adc():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ DomainMappingsClient()
+ adc.assert_called_once_with(
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ quota_project_id=None,
+ )
+
+
+def test_domain_mappings_transport_auth_adc():
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transports.DomainMappingsGrpcTransport(
+ host="squid.clam.whelk", quota_project_id="octopus"
+ )
+ adc.assert_called_once_with(
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.DomainMappingsGrpcTransport,
+ transports.DomainMappingsGrpcAsyncIOTransport,
+ ],
+)
+def test_domain_mappings_grpc_transport_client_cert_source_for_mtls(transport_class):
+ cred = credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
+def test_domain_mappings_host_no_port():
+ client = DomainMappingsClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="appengine.googleapis.com"
+ ),
+ )
+ assert client.transport._host == "appengine.googleapis.com:443"
+
+
+def test_domain_mappings_host_with_port():
+ client = DomainMappingsClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="appengine.googleapis.com:8000"
+ ),
+ )
+ assert client.transport._host == "appengine.googleapis.com:8000"
+
+
+def test_domain_mappings_grpc_transport_channel():
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.DomainMappingsGrpcTransport(
+ host="squid.clam.whelk", channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+def test_domain_mappings_grpc_asyncio_transport_channel():
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.DomainMappingsGrpcAsyncIOTransport(
+ host="squid.clam.whelk", channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.DomainMappingsGrpcTransport,
+ transports.DomainMappingsGrpcAsyncIOTransport,
+ ],
+)
+def test_domain_mappings_transport_channel_mtls_with_client_cert_source(
+ transport_class,
+):
+ with mock.patch(
+ "grpc.ssl_channel_credentials", autospec=True
+ ) as grpc_ssl_channel_cred:
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_ssl_cred = mock.Mock()
+ grpc_ssl_channel_cred.return_value = mock_ssl_cred
+
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ cred = credentials.AnonymousCredentials()
+ with pytest.warns(DeprecationWarning):
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (cred, None)
+ transport = transport_class(
+ host="squid.clam.whelk",
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=client_cert_source_callback,
+ )
+ adc.assert_called_once()
+
+ grpc_ssl_channel_cred.assert_called_once_with(
+ certificate_chain=b"cert bytes", private_key=b"key bytes"
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+ assert transport._ssl_channel_credentials == mock_ssl_cred
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.DomainMappingsGrpcTransport,
+ transports.DomainMappingsGrpcAsyncIOTransport,
+ ],
+)
+def test_domain_mappings_transport_channel_mtls_with_adc(transport_class):
+ mock_ssl_cred = mock.Mock()
+ with mock.patch.multiple(
+ "google.auth.transport.grpc.SslCredentials",
+ __init__=mock.Mock(return_value=None),
+ ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
+ ):
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+ mock_cred = mock.Mock()
+
+ with pytest.warns(DeprecationWarning):
+ transport = transport_class(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=None,
+ )
+
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+def test_domain_mappings_grpc_lro_client():
+ client = DomainMappingsClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+ transport = client.transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(transport.operations_client, operations_v1.OperationsClient,)
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_domain_mappings_grpc_lro_async_client():
+ client = DomainMappingsAsyncClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio",
+ )
+ transport = client.transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(transport.operations_client, operations_v1.OperationsAsyncClient,)
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_common_billing_account_path():
+ billing_account = "squid"
+
+ expected = "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
+ )
+ actual = DomainMappingsClient.common_billing_account_path(billing_account)
+ assert expected == actual
+
+
+def test_parse_common_billing_account_path():
+ expected = {
+ "billing_account": "clam",
+ }
+ path = DomainMappingsClient.common_billing_account_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = DomainMappingsClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "whelk"
+
+ expected = "folders/{folder}".format(folder=folder,)
+ actual = DomainMappingsClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "octopus",
+ }
+ path = DomainMappingsClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = DomainMappingsClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "oyster"
+
+ expected = "organizations/{organization}".format(organization=organization,)
+ actual = DomainMappingsClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "nudibranch",
+ }
+ path = DomainMappingsClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = DomainMappingsClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "cuttlefish"
+
+ expected = "projects/{project}".format(project=project,)
+ actual = DomainMappingsClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "mussel",
+ }
+ path = DomainMappingsClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = DomainMappingsClient.parse_common_project_path(path)
+ assert expected == actual
+
+
+def test_common_location_path():
+ project = "winkle"
+ location = "nautilus"
+
+ expected = "projects/{project}/locations/{location}".format(
+ project=project, location=location,
+ )
+ actual = DomainMappingsClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "scallop",
+ "location": "abalone",
+ }
+ path = DomainMappingsClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = DomainMappingsClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_withDEFAULT_CLIENT_INFO():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.DomainMappingsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = DomainMappingsClient(
+ credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.DomainMappingsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = DomainMappingsClient.get_transport_class()
+ transport = transport_class(
+ credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
diff --git a/tests/unit/gapic/appengine_admin_v1/test_firewall.py b/tests/unit/gapic/appengine_admin_v1/test_firewall.py
new file mode 100644
index 0000000..945a7c3
--- /dev/null
+++ b/tests/unit/gapic/appengine_admin_v1/test_firewall.py
@@ -0,0 +1,2000 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import os
+import mock
+
+import grpc
+from grpc.experimental import aio
+import math
+import pytest
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+
+from google import auth
+from google.api_core import client_options
+from google.api_core import exceptions
+from google.api_core import gapic_v1
+from google.api_core import grpc_helpers
+from google.api_core import grpc_helpers_async
+from google.auth import credentials
+from google.auth.exceptions import MutualTLSChannelError
+from google.cloud.appengine_admin_v1.services.firewall import FirewallAsyncClient
+from google.cloud.appengine_admin_v1.services.firewall import FirewallClient
+from google.cloud.appengine_admin_v1.services.firewall import pagers
+from google.cloud.appengine_admin_v1.services.firewall import transports
+from google.cloud.appengine_admin_v1.types import appengine
+from google.cloud.appengine_admin_v1.types import firewall
+from google.oauth2 import service_account
+from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+
+
+def client_cert_source_callback():
+ return b"cert bytes", b"key bytes"
+
+
+# If default endpoint is localhost, then default mtls endpoint will be the same.
+# This method modifies the default endpoint so the client can produce a different
+# mtls endpoint for endpoint testing purposes.
+def modify_default_endpoint(client):
+ return (
+ "foo.googleapis.com"
+ if ("localhost" in client.DEFAULT_ENDPOINT)
+ else client.DEFAULT_ENDPOINT
+ )
+
+
+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 FirewallClient._get_default_mtls_endpoint(None) is None
+ assert FirewallClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint
+ assert (
+ FirewallClient._get_default_mtls_endpoint(api_mtls_endpoint)
+ == api_mtls_endpoint
+ )
+ assert (
+ FirewallClient._get_default_mtls_endpoint(sandbox_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert (
+ FirewallClient._get_default_mtls_endpoint(sandbox_mtls_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert FirewallClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi
+
+
+@pytest.mark.parametrize("client_class", [FirewallClient, FirewallAsyncClient,])
+def test_firewall_client_from_service_account_info(client_class):
+ creds = credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "appengine.googleapis.com:443"
+
+
+@pytest.mark.parametrize("client_class", [FirewallClient, FirewallAsyncClient,])
+def test_firewall_client_from_service_account_file(client_class):
+ creds = credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_file"
+ ) as factory:
+ factory.return_value = creds
+ client = client_class.from_service_account_file("dummy/file/path.json")
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ client = client_class.from_service_account_json("dummy/file/path.json")
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "appengine.googleapis.com:443"
+
+
+def test_firewall_client_get_transport_class():
+ transport = FirewallClient.get_transport_class()
+ available_transports = [
+ transports.FirewallGrpcTransport,
+ ]
+ assert transport in available_transports
+
+ transport = FirewallClient.get_transport_class("grpc")
+ assert transport == transports.FirewallGrpcTransport
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (FirewallClient, transports.FirewallGrpcTransport, "grpc"),
+ (FirewallAsyncClient, transports.FirewallGrpcAsyncIOTransport, "grpc_asyncio"),
+ ],
+)
+@mock.patch.object(
+ FirewallClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FirewallClient)
+)
+@mock.patch.object(
+ FirewallAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(FirewallAsyncClient),
+)
+def test_firewall_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(FirewallClient, "get_transport_class") as gtc:
+ transport = transport_class(credentials=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(FirewallClient, "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,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,use_client_cert_env",
+ [
+ (FirewallClient, transports.FirewallGrpcTransport, "grpc", "true"),
+ (
+ FirewallAsyncClient,
+ transports.FirewallGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "true",
+ ),
+ (FirewallClient, transports.FirewallGrpcTransport, "grpc", "false"),
+ (
+ FirewallAsyncClient,
+ transports.FirewallGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "false",
+ ),
+ ],
+)
+@mock.patch.object(
+ FirewallClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FirewallClient)
+)
+@mock.patch.object(
+ FirewallAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(FirewallAsyncClient),
+)
+@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"})
+def test_firewall_client_mtls_env_auto(
+ client_class, transport_class, transport_name, use_client_cert_env
+):
+ # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default
+ # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists.
+
+ # Check the case client_cert_source is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ options = client_options.ClientOptions(
+ client_cert_source=client_cert_source_callback
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client.DEFAULT_ENDPOINT
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+ # Check the case ADC client cert is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client.DEFAULT_ENDPOINT
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
+
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ 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,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (FirewallClient, transports.FirewallGrpcTransport, "grpc"),
+ (FirewallAsyncClient, transports.FirewallGrpcAsyncIOTransport, "grpc_asyncio"),
+ ],
+)
+def test_firewall_client_client_options_scopes(
+ client_class, transport_class, transport_name
+):
+ # Check the case scopes are provided.
+ options = client_options.ClientOptions(scopes=["1", "2"],)
+ 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=["1", "2"],
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (FirewallClient, transports.FirewallGrpcTransport, "grpc"),
+ (FirewallAsyncClient, transports.FirewallGrpcAsyncIOTransport, "grpc_asyncio"),
+ ],
+)
+def test_firewall_client_client_options_credentials_file(
+ client_class, transport_class, transport_name
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+ 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="credentials.json",
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+
+def test_firewall_client_client_options_from_dict():
+ with mock.patch(
+ "google.cloud.appengine_admin_v1.services.firewall.transports.FirewallGrpcTransport.__init__"
+ ) as grpc_transport:
+ grpc_transport.return_value = None
+ client = FirewallClient(client_options={"api_endpoint": "squid.clam.whelk"})
+ grpc_transport.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,
+ )
+
+
+def test_list_ingress_rules(
+ transport: str = "grpc", request_type=appengine.ListIngressRulesRequest
+):
+ client = FirewallClient(
+ credentials=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.list_ingress_rules), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = appengine.ListIngressRulesResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ response = client.list_ingress_rules(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.ListIngressRulesRequest()
+
+ # Establish that the response is the type that we expect.
+
+ assert isinstance(response, pagers.ListIngressRulesPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_ingress_rules_from_dict():
+ test_list_ingress_rules(request_type=dict)
+
+
+def test_list_ingress_rules_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = FirewallClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_ingress_rules), "__call__"
+ ) as call:
+ client.list_ingress_rules()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.ListIngressRulesRequest()
+
+
+@pytest.mark.asyncio
+async def test_list_ingress_rules_async(
+ transport: str = "grpc_asyncio", request_type=appengine.ListIngressRulesRequest
+):
+ client = FirewallAsyncClient(
+ credentials=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.list_ingress_rules), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ appengine.ListIngressRulesResponse(next_page_token="next_page_token_value",)
+ )
+
+ response = await client.list_ingress_rules(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.ListIngressRulesRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListIngressRulesAsyncPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+
+@pytest.mark.asyncio
+async def test_list_ingress_rules_async_from_dict():
+ await test_list_ingress_rules_async(request_type=dict)
+
+
+def test_list_ingress_rules_field_headers():
+ client = FirewallClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.ListIngressRulesRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_ingress_rules), "__call__"
+ ) as call:
+ call.return_value = appengine.ListIngressRulesResponse()
+
+ client.list_ingress_rules(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_list_ingress_rules_field_headers_async():
+ client = FirewallAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.ListIngressRulesRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_ingress_rules), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ appengine.ListIngressRulesResponse()
+ )
+
+ await client.list_ingress_rules(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"]
+
+
+def test_list_ingress_rules_pager():
+ client = FirewallClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_ingress_rules), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListIngressRulesResponse(
+ ingress_rules=[
+ firewall.FirewallRule(),
+ firewall.FirewallRule(),
+ firewall.FirewallRule(),
+ ],
+ next_page_token="abc",
+ ),
+ appengine.ListIngressRulesResponse(
+ ingress_rules=[], next_page_token="def",
+ ),
+ appengine.ListIngressRulesResponse(
+ ingress_rules=[firewall.FirewallRule(),], next_page_token="ghi",
+ ),
+ appengine.ListIngressRulesResponse(
+ ingress_rules=[firewall.FirewallRule(), firewall.FirewallRule(),],
+ ),
+ RuntimeError,
+ )
+
+ metadata = ()
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
+ )
+ pager = client.list_ingress_rules(request={})
+
+ assert pager._metadata == metadata
+
+ results = [i for i in pager]
+ assert len(results) == 6
+ assert all(isinstance(i, firewall.FirewallRule) for i in results)
+
+
+def test_list_ingress_rules_pages():
+ client = FirewallClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_ingress_rules), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListIngressRulesResponse(
+ ingress_rules=[
+ firewall.FirewallRule(),
+ firewall.FirewallRule(),
+ firewall.FirewallRule(),
+ ],
+ next_page_token="abc",
+ ),
+ appengine.ListIngressRulesResponse(
+ ingress_rules=[], next_page_token="def",
+ ),
+ appengine.ListIngressRulesResponse(
+ ingress_rules=[firewall.FirewallRule(),], next_page_token="ghi",
+ ),
+ appengine.ListIngressRulesResponse(
+ ingress_rules=[firewall.FirewallRule(), firewall.FirewallRule(),],
+ ),
+ RuntimeError,
+ )
+ pages = list(client.list_ingress_rules(request={}).pages)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
+
+
+@pytest.mark.asyncio
+async def test_list_ingress_rules_async_pager():
+ client = FirewallAsyncClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_ingress_rules),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListIngressRulesResponse(
+ ingress_rules=[
+ firewall.FirewallRule(),
+ firewall.FirewallRule(),
+ firewall.FirewallRule(),
+ ],
+ next_page_token="abc",
+ ),
+ appengine.ListIngressRulesResponse(
+ ingress_rules=[], next_page_token="def",
+ ),
+ appengine.ListIngressRulesResponse(
+ ingress_rules=[firewall.FirewallRule(),], next_page_token="ghi",
+ ),
+ appengine.ListIngressRulesResponse(
+ ingress_rules=[firewall.FirewallRule(), firewall.FirewallRule(),],
+ ),
+ RuntimeError,
+ )
+ async_pager = await client.list_ingress_rules(request={},)
+ assert async_pager.next_page_token == "abc"
+ responses = []
+ async for response in async_pager:
+ responses.append(response)
+
+ assert len(responses) == 6
+ assert all(isinstance(i, firewall.FirewallRule) for i in responses)
+
+
+@pytest.mark.asyncio
+async def test_list_ingress_rules_async_pages():
+ client = FirewallAsyncClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_ingress_rules),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListIngressRulesResponse(
+ ingress_rules=[
+ firewall.FirewallRule(),
+ firewall.FirewallRule(),
+ firewall.FirewallRule(),
+ ],
+ next_page_token="abc",
+ ),
+ appengine.ListIngressRulesResponse(
+ ingress_rules=[], next_page_token="def",
+ ),
+ appengine.ListIngressRulesResponse(
+ ingress_rules=[firewall.FirewallRule(),], next_page_token="ghi",
+ ),
+ appengine.ListIngressRulesResponse(
+ ingress_rules=[firewall.FirewallRule(), firewall.FirewallRule(),],
+ ),
+ RuntimeError,
+ )
+ pages = []
+ async for page_ in (await client.list_ingress_rules(request={})).pages:
+ pages.append(page_)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
+
+
+def test_batch_update_ingress_rules(
+ transport: str = "grpc", request_type=appengine.BatchUpdateIngressRulesRequest
+):
+ client = FirewallClient(
+ credentials=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.batch_update_ingress_rules), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = appengine.BatchUpdateIngressRulesResponse()
+
+ response = client.batch_update_ingress_rules(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.BatchUpdateIngressRulesRequest()
+
+ # Establish that the response is the type that we expect.
+
+ assert isinstance(response, appengine.BatchUpdateIngressRulesResponse)
+
+
+def test_batch_update_ingress_rules_from_dict():
+ test_batch_update_ingress_rules(request_type=dict)
+
+
+def test_batch_update_ingress_rules_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = FirewallClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.batch_update_ingress_rules), "__call__"
+ ) as call:
+ client.batch_update_ingress_rules()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.BatchUpdateIngressRulesRequest()
+
+
+@pytest.mark.asyncio
+async def test_batch_update_ingress_rules_async(
+ transport: str = "grpc_asyncio",
+ request_type=appengine.BatchUpdateIngressRulesRequest,
+):
+ client = FirewallAsyncClient(
+ credentials=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.batch_update_ingress_rules), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ appengine.BatchUpdateIngressRulesResponse()
+ )
+
+ response = await client.batch_update_ingress_rules(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.BatchUpdateIngressRulesRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, appengine.BatchUpdateIngressRulesResponse)
+
+
+@pytest.mark.asyncio
+async def test_batch_update_ingress_rules_async_from_dict():
+ await test_batch_update_ingress_rules_async(request_type=dict)
+
+
+def test_batch_update_ingress_rules_field_headers():
+ client = FirewallClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.BatchUpdateIngressRulesRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.batch_update_ingress_rules), "__call__"
+ ) as call:
+ call.return_value = appengine.BatchUpdateIngressRulesResponse()
+
+ client.batch_update_ingress_rules(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_batch_update_ingress_rules_field_headers_async():
+ client = FirewallAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.BatchUpdateIngressRulesRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.batch_update_ingress_rules), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ appengine.BatchUpdateIngressRulesResponse()
+ )
+
+ await client.batch_update_ingress_rules(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_create_ingress_rule(
+ transport: str = "grpc", request_type=appengine.CreateIngressRuleRequest
+):
+ client = FirewallClient(
+ credentials=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.create_ingress_rule), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = firewall.FirewallRule(
+ priority=898,
+ action=firewall.FirewallRule.Action.ALLOW,
+ source_range="source_range_value",
+ description="description_value",
+ )
+
+ response = client.create_ingress_rule(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.CreateIngressRuleRequest()
+
+ # Establish that the response is the type that we expect.
+
+ assert isinstance(response, firewall.FirewallRule)
+
+ assert response.priority == 898
+
+ assert response.action == firewall.FirewallRule.Action.ALLOW
+
+ assert response.source_range == "source_range_value"
+
+ assert response.description == "description_value"
+
+
+def test_create_ingress_rule_from_dict():
+ test_create_ingress_rule(request_type=dict)
+
+
+def test_create_ingress_rule_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = FirewallClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_ingress_rule), "__call__"
+ ) as call:
+ client.create_ingress_rule()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.CreateIngressRuleRequest()
+
+
+@pytest.mark.asyncio
+async def test_create_ingress_rule_async(
+ transport: str = "grpc_asyncio", request_type=appengine.CreateIngressRuleRequest
+):
+ client = FirewallAsyncClient(
+ credentials=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.create_ingress_rule), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ firewall.FirewallRule(
+ priority=898,
+ action=firewall.FirewallRule.Action.ALLOW,
+ source_range="source_range_value",
+ description="description_value",
+ )
+ )
+
+ response = await client.create_ingress_rule(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.CreateIngressRuleRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, firewall.FirewallRule)
+
+ assert response.priority == 898
+
+ assert response.action == firewall.FirewallRule.Action.ALLOW
+
+ assert response.source_range == "source_range_value"
+
+ assert response.description == "description_value"
+
+
+@pytest.mark.asyncio
+async def test_create_ingress_rule_async_from_dict():
+ await test_create_ingress_rule_async(request_type=dict)
+
+
+def test_create_ingress_rule_field_headers():
+ client = FirewallClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.CreateIngressRuleRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_ingress_rule), "__call__"
+ ) as call:
+ call.return_value = firewall.FirewallRule()
+
+ client.create_ingress_rule(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_create_ingress_rule_field_headers_async():
+ client = FirewallAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.CreateIngressRuleRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_ingress_rule), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ firewall.FirewallRule()
+ )
+
+ await client.create_ingress_rule(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"]
+
+
+def test_get_ingress_rule(
+ transport: str = "grpc", request_type=appengine.GetIngressRuleRequest
+):
+ client = FirewallClient(
+ credentials=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_ingress_rule), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = firewall.FirewallRule(
+ priority=898,
+ action=firewall.FirewallRule.Action.ALLOW,
+ source_range="source_range_value",
+ description="description_value",
+ )
+
+ response = client.get_ingress_rule(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.GetIngressRuleRequest()
+
+ # Establish that the response is the type that we expect.
+
+ assert isinstance(response, firewall.FirewallRule)
+
+ assert response.priority == 898
+
+ assert response.action == firewall.FirewallRule.Action.ALLOW
+
+ assert response.source_range == "source_range_value"
+
+ assert response.description == "description_value"
+
+
+def test_get_ingress_rule_from_dict():
+ test_get_ingress_rule(request_type=dict)
+
+
+def test_get_ingress_rule_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = FirewallClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_ingress_rule), "__call__") as call:
+ client.get_ingress_rule()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.GetIngressRuleRequest()
+
+
+@pytest.mark.asyncio
+async def test_get_ingress_rule_async(
+ transport: str = "grpc_asyncio", request_type=appengine.GetIngressRuleRequest
+):
+ client = FirewallAsyncClient(
+ credentials=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_ingress_rule), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ firewall.FirewallRule(
+ priority=898,
+ action=firewall.FirewallRule.Action.ALLOW,
+ source_range="source_range_value",
+ description="description_value",
+ )
+ )
+
+ response = await client.get_ingress_rule(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.GetIngressRuleRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, firewall.FirewallRule)
+
+ assert response.priority == 898
+
+ assert response.action == firewall.FirewallRule.Action.ALLOW
+
+ assert response.source_range == "source_range_value"
+
+ assert response.description == "description_value"
+
+
+@pytest.mark.asyncio
+async def test_get_ingress_rule_async_from_dict():
+ await test_get_ingress_rule_async(request_type=dict)
+
+
+def test_get_ingress_rule_field_headers():
+ client = FirewallClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.GetIngressRuleRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_ingress_rule), "__call__") as call:
+ call.return_value = firewall.FirewallRule()
+
+ client.get_ingress_rule(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_get_ingress_rule_field_headers_async():
+ client = FirewallAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.GetIngressRuleRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_ingress_rule), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ firewall.FirewallRule()
+ )
+
+ await client.get_ingress_rule(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_update_ingress_rule(
+ transport: str = "grpc", request_type=appengine.UpdateIngressRuleRequest
+):
+ client = FirewallClient(
+ credentials=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.update_ingress_rule), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = firewall.FirewallRule(
+ priority=898,
+ action=firewall.FirewallRule.Action.ALLOW,
+ source_range="source_range_value",
+ description="description_value",
+ )
+
+ response = client.update_ingress_rule(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.UpdateIngressRuleRequest()
+
+ # Establish that the response is the type that we expect.
+
+ assert isinstance(response, firewall.FirewallRule)
+
+ assert response.priority == 898
+
+ assert response.action == firewall.FirewallRule.Action.ALLOW
+
+ assert response.source_range == "source_range_value"
+
+ assert response.description == "description_value"
+
+
+def test_update_ingress_rule_from_dict():
+ test_update_ingress_rule(request_type=dict)
+
+
+def test_update_ingress_rule_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = FirewallClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_ingress_rule), "__call__"
+ ) as call:
+ client.update_ingress_rule()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.UpdateIngressRuleRequest()
+
+
+@pytest.mark.asyncio
+async def test_update_ingress_rule_async(
+ transport: str = "grpc_asyncio", request_type=appengine.UpdateIngressRuleRequest
+):
+ client = FirewallAsyncClient(
+ credentials=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.update_ingress_rule), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ firewall.FirewallRule(
+ priority=898,
+ action=firewall.FirewallRule.Action.ALLOW,
+ source_range="source_range_value",
+ description="description_value",
+ )
+ )
+
+ response = await client.update_ingress_rule(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.UpdateIngressRuleRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, firewall.FirewallRule)
+
+ assert response.priority == 898
+
+ assert response.action == firewall.FirewallRule.Action.ALLOW
+
+ assert response.source_range == "source_range_value"
+
+ assert response.description == "description_value"
+
+
+@pytest.mark.asyncio
+async def test_update_ingress_rule_async_from_dict():
+ await test_update_ingress_rule_async(request_type=dict)
+
+
+def test_update_ingress_rule_field_headers():
+ client = FirewallClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.UpdateIngressRuleRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_ingress_rule), "__call__"
+ ) as call:
+ call.return_value = firewall.FirewallRule()
+
+ client.update_ingress_rule(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_update_ingress_rule_field_headers_async():
+ client = FirewallAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.UpdateIngressRuleRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_ingress_rule), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ firewall.FirewallRule()
+ )
+
+ await client.update_ingress_rule(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_delete_ingress_rule(
+ transport: str = "grpc", request_type=appengine.DeleteIngressRuleRequest
+):
+ client = FirewallClient(
+ credentials=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.delete_ingress_rule), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ response = client.delete_ingress_rule(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.DeleteIngressRuleRequest()
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_delete_ingress_rule_from_dict():
+ test_delete_ingress_rule(request_type=dict)
+
+
+def test_delete_ingress_rule_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = FirewallClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_ingress_rule), "__call__"
+ ) as call:
+ client.delete_ingress_rule()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.DeleteIngressRuleRequest()
+
+
+@pytest.mark.asyncio
+async def test_delete_ingress_rule_async(
+ transport: str = "grpc_asyncio", request_type=appengine.DeleteIngressRuleRequest
+):
+ client = FirewallAsyncClient(
+ credentials=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.delete_ingress_rule), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+
+ response = await client.delete_ingress_rule(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.DeleteIngressRuleRequest()
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+@pytest.mark.asyncio
+async def test_delete_ingress_rule_async_from_dict():
+ await test_delete_ingress_rule_async(request_type=dict)
+
+
+def test_delete_ingress_rule_field_headers():
+ client = FirewallClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.DeleteIngressRuleRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_ingress_rule), "__call__"
+ ) as call:
+ call.return_value = None
+
+ client.delete_ingress_rule(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_delete_ingress_rule_field_headers_async():
+ client = FirewallAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.DeleteIngressRuleRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_ingress_rule), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+
+ await client.delete_ingress_rule(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.FirewallGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = FirewallClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.FirewallGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = FirewallClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
+
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.FirewallGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = FirewallClient(
+ client_options={"scopes": ["1", "2"]}, transport=transport,
+ )
+
+
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.FirewallGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ client = FirewallClient(transport=transport)
+ assert client.transport is transport
+
+
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.FirewallGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+ transport = transports.FirewallGrpcAsyncIOTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.FirewallGrpcTransport, transports.FirewallGrpcAsyncIOTransport,],
+)
+def test_transport_adc(transport_class):
+ # Test default credentials are used if not provided.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transport_class()
+ adc.assert_called_once()
+
+
+def test_transport_grpc_default():
+ # A client should use the gRPC transport by default.
+ client = FirewallClient(credentials=credentials.AnonymousCredentials(),)
+ assert isinstance(client.transport, transports.FirewallGrpcTransport,)
+
+
+def test_firewall_base_transport_error():
+ # Passing both a credentials object and credentials_file should raise an error
+ with pytest.raises(exceptions.DuplicateCredentialArgs):
+ transport = transports.FirewallTransport(
+ credentials=credentials.AnonymousCredentials(),
+ credentials_file="credentials.json",
+ )
+
+
+def test_firewall_base_transport():
+ # Instantiate the base transport.
+ with mock.patch(
+ "google.cloud.appengine_admin_v1.services.firewall.transports.FirewallTransport.__init__"
+ ) as Transport:
+ Transport.return_value = None
+ transport = transports.FirewallTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Every method on the transport should just blindly
+ # raise NotImplementedError.
+ methods = (
+ "list_ingress_rules",
+ "batch_update_ingress_rules",
+ "create_ingress_rule",
+ "get_ingress_rule",
+ "update_ingress_rule",
+ "delete_ingress_rule",
+ )
+ for method in methods:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, method)(request=object())
+
+
+def test_firewall_base_transport_with_credentials_file():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(
+ auth, "load_credentials_from_file"
+ ) as load_creds, mock.patch(
+ "google.cloud.appengine_admin_v1.services.firewall.transports.FirewallTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ transport = transports.FirewallTransport(
+ credentials_file="credentials.json", quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+def test_firewall_base_transport_with_adc():
+ # Test the default credentials are used if credentials and credentials_file are None.
+ with mock.patch.object(auth, "default") as adc, mock.patch(
+ "google.cloud.appengine_admin_v1.services.firewall.transports.FirewallTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transport = transports.FirewallTransport()
+ adc.assert_called_once()
+
+
+def test_firewall_auth_adc():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ FirewallClient()
+ adc.assert_called_once_with(
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ quota_project_id=None,
+ )
+
+
+def test_firewall_transport_auth_adc():
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transports.FirewallGrpcTransport(
+ host="squid.clam.whelk", quota_project_id="octopus"
+ )
+ adc.assert_called_once_with(
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.FirewallGrpcTransport, transports.FirewallGrpcAsyncIOTransport],
+)
+def test_firewall_grpc_transport_client_cert_source_for_mtls(transport_class):
+ cred = credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
+def test_firewall_host_no_port():
+ client = FirewallClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="appengine.googleapis.com"
+ ),
+ )
+ assert client.transport._host == "appengine.googleapis.com:443"
+
+
+def test_firewall_host_with_port():
+ client = FirewallClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="appengine.googleapis.com:8000"
+ ),
+ )
+ assert client.transport._host == "appengine.googleapis.com:8000"
+
+
+def test_firewall_grpc_transport_channel():
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.FirewallGrpcTransport(
+ host="squid.clam.whelk", channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+def test_firewall_grpc_asyncio_transport_channel():
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.FirewallGrpcAsyncIOTransport(
+ host="squid.clam.whelk", channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.FirewallGrpcTransport, transports.FirewallGrpcAsyncIOTransport],
+)
+def test_firewall_transport_channel_mtls_with_client_cert_source(transport_class):
+ with mock.patch(
+ "grpc.ssl_channel_credentials", autospec=True
+ ) as grpc_ssl_channel_cred:
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_ssl_cred = mock.Mock()
+ grpc_ssl_channel_cred.return_value = mock_ssl_cred
+
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ cred = credentials.AnonymousCredentials()
+ with pytest.warns(DeprecationWarning):
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (cred, None)
+ transport = transport_class(
+ host="squid.clam.whelk",
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=client_cert_source_callback,
+ )
+ adc.assert_called_once()
+
+ grpc_ssl_channel_cred.assert_called_once_with(
+ certificate_chain=b"cert bytes", private_key=b"key bytes"
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+ assert transport._ssl_channel_credentials == mock_ssl_cred
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.FirewallGrpcTransport, transports.FirewallGrpcAsyncIOTransport],
+)
+def test_firewall_transport_channel_mtls_with_adc(transport_class):
+ mock_ssl_cred = mock.Mock()
+ with mock.patch.multiple(
+ "google.auth.transport.grpc.SslCredentials",
+ __init__=mock.Mock(return_value=None),
+ ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
+ ):
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+ mock_cred = mock.Mock()
+
+ with pytest.warns(DeprecationWarning):
+ transport = transport_class(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=None,
+ )
+
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+def test_common_billing_account_path():
+ billing_account = "squid"
+
+ expected = "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
+ )
+ actual = FirewallClient.common_billing_account_path(billing_account)
+ assert expected == actual
+
+
+def test_parse_common_billing_account_path():
+ expected = {
+ "billing_account": "clam",
+ }
+ path = FirewallClient.common_billing_account_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = FirewallClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "whelk"
+
+ expected = "folders/{folder}".format(folder=folder,)
+ actual = FirewallClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "octopus",
+ }
+ path = FirewallClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = FirewallClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "oyster"
+
+ expected = "organizations/{organization}".format(organization=organization,)
+ actual = FirewallClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "nudibranch",
+ }
+ path = FirewallClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = FirewallClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "cuttlefish"
+
+ expected = "projects/{project}".format(project=project,)
+ actual = FirewallClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "mussel",
+ }
+ path = FirewallClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = FirewallClient.parse_common_project_path(path)
+ assert expected == actual
+
+
+def test_common_location_path():
+ project = "winkle"
+ location = "nautilus"
+
+ expected = "projects/{project}/locations/{location}".format(
+ project=project, location=location,
+ )
+ actual = FirewallClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "scallop",
+ "location": "abalone",
+ }
+ path = FirewallClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = FirewallClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_withDEFAULT_CLIENT_INFO():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.FirewallTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = FirewallClient(
+ credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.FirewallTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = FirewallClient.get_transport_class()
+ transport = transport_class(
+ credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
diff --git a/tests/unit/gapic/appengine_admin_v1/test_instances.py b/tests/unit/gapic/appengine_admin_v1/test_instances.py
new file mode 100644
index 0000000..9b18ecc
--- /dev/null
+++ b/tests/unit/gapic/appengine_admin_v1/test_instances.py
@@ -0,0 +1,1755 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import os
+import mock
+
+import grpc
+from grpc.experimental import aio
+import math
+import pytest
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+
+from google import auth
+from google.api_core import client_options
+from google.api_core import exceptions
+from google.api_core import future
+from google.api_core import gapic_v1
+from google.api_core import grpc_helpers
+from google.api_core import grpc_helpers_async
+from google.api_core import operation_async # type: ignore
+from google.api_core import operations_v1
+from google.auth import credentials
+from google.auth.exceptions import MutualTLSChannelError
+from google.cloud.appengine_admin_v1.services.instances import InstancesAsyncClient
+from google.cloud.appengine_admin_v1.services.instances import InstancesClient
+from google.cloud.appengine_admin_v1.services.instances import pagers
+from google.cloud.appengine_admin_v1.services.instances import transports
+from google.cloud.appengine_admin_v1.types import appengine
+from google.cloud.appengine_admin_v1.types import instance
+from google.cloud.appengine_admin_v1.types import operation as ga_operation
+from google.longrunning import operations_pb2
+from google.oauth2 import service_account
+from google.protobuf import timestamp_pb2 as timestamp # type: ignore
+
+
+def client_cert_source_callback():
+ return b"cert bytes", b"key bytes"
+
+
+# If default endpoint is localhost, then default mtls endpoint will be the same.
+# This method modifies the default endpoint so the client can produce a different
+# mtls endpoint for endpoint testing purposes.
+def modify_default_endpoint(client):
+ return (
+ "foo.googleapis.com"
+ if ("localhost" in client.DEFAULT_ENDPOINT)
+ else client.DEFAULT_ENDPOINT
+ )
+
+
+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 InstancesClient._get_default_mtls_endpoint(None) is None
+ assert InstancesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint
+ assert (
+ InstancesClient._get_default_mtls_endpoint(api_mtls_endpoint)
+ == api_mtls_endpoint
+ )
+ assert (
+ InstancesClient._get_default_mtls_endpoint(sandbox_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert (
+ InstancesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert InstancesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi
+
+
+@pytest.mark.parametrize("client_class", [InstancesClient, InstancesAsyncClient,])
+def test_instances_client_from_service_account_info(client_class):
+ creds = credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "appengine.googleapis.com:443"
+
+
+@pytest.mark.parametrize("client_class", [InstancesClient, InstancesAsyncClient,])
+def test_instances_client_from_service_account_file(client_class):
+ creds = credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_file"
+ ) as factory:
+ factory.return_value = creds
+ client = client_class.from_service_account_file("dummy/file/path.json")
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ client = client_class.from_service_account_json("dummy/file/path.json")
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "appengine.googleapis.com:443"
+
+
+def test_instances_client_get_transport_class():
+ transport = InstancesClient.get_transport_class()
+ available_transports = [
+ transports.InstancesGrpcTransport,
+ ]
+ assert transport in available_transports
+
+ transport = InstancesClient.get_transport_class("grpc")
+ assert transport == transports.InstancesGrpcTransport
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (InstancesClient, transports.InstancesGrpcTransport, "grpc"),
+ (
+ InstancesAsyncClient,
+ transports.InstancesGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+@mock.patch.object(
+ InstancesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(InstancesClient)
+)
+@mock.patch.object(
+ InstancesAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(InstancesAsyncClient),
+)
+def test_instances_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(InstancesClient, "get_transport_class") as gtc:
+ transport = transport_class(credentials=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(InstancesClient, "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,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,use_client_cert_env",
+ [
+ (InstancesClient, transports.InstancesGrpcTransport, "grpc", "true"),
+ (
+ InstancesAsyncClient,
+ transports.InstancesGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "true",
+ ),
+ (InstancesClient, transports.InstancesGrpcTransport, "grpc", "false"),
+ (
+ InstancesAsyncClient,
+ transports.InstancesGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "false",
+ ),
+ ],
+)
+@mock.patch.object(
+ InstancesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(InstancesClient)
+)
+@mock.patch.object(
+ InstancesAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(InstancesAsyncClient),
+)
+@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"})
+def test_instances_client_mtls_env_auto(
+ client_class, transport_class, transport_name, use_client_cert_env
+):
+ # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default
+ # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists.
+
+ # Check the case client_cert_source is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ options = client_options.ClientOptions(
+ client_cert_source=client_cert_source_callback
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client.DEFAULT_ENDPOINT
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+ # Check the case ADC client cert is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client.DEFAULT_ENDPOINT
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
+
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ 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,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (InstancesClient, transports.InstancesGrpcTransport, "grpc"),
+ (
+ InstancesAsyncClient,
+ transports.InstancesGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_instances_client_client_options_scopes(
+ client_class, transport_class, transport_name
+):
+ # Check the case scopes are provided.
+ options = client_options.ClientOptions(scopes=["1", "2"],)
+ 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=["1", "2"],
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (InstancesClient, transports.InstancesGrpcTransport, "grpc"),
+ (
+ InstancesAsyncClient,
+ transports.InstancesGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_instances_client_client_options_credentials_file(
+ client_class, transport_class, transport_name
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+ 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="credentials.json",
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+
+def test_instances_client_client_options_from_dict():
+ with mock.patch(
+ "google.cloud.appengine_admin_v1.services.instances.transports.InstancesGrpcTransport.__init__"
+ ) as grpc_transport:
+ grpc_transport.return_value = None
+ client = InstancesClient(client_options={"api_endpoint": "squid.clam.whelk"})
+ grpc_transport.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,
+ )
+
+
+def test_list_instances(
+ transport: str = "grpc", request_type=appengine.ListInstancesRequest
+):
+ client = InstancesClient(
+ credentials=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.list_instances), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = appengine.ListInstancesResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ response = client.list_instances(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.ListInstancesRequest()
+
+ # Establish that the response is the type that we expect.
+
+ assert isinstance(response, pagers.ListInstancesPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_instances_from_dict():
+ test_list_instances(request_type=dict)
+
+
+def test_list_instances_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = InstancesClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_instances), "__call__") as call:
+ client.list_instances()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.ListInstancesRequest()
+
+
+@pytest.mark.asyncio
+async def test_list_instances_async(
+ transport: str = "grpc_asyncio", request_type=appengine.ListInstancesRequest
+):
+ client = InstancesAsyncClient(
+ credentials=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.list_instances), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ appengine.ListInstancesResponse(next_page_token="next_page_token_value",)
+ )
+
+ response = await client.list_instances(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.ListInstancesRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListInstancesAsyncPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+
+@pytest.mark.asyncio
+async def test_list_instances_async_from_dict():
+ await test_list_instances_async(request_type=dict)
+
+
+def test_list_instances_field_headers():
+ client = InstancesClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.ListInstancesRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_instances), "__call__") as call:
+ call.return_value = appengine.ListInstancesResponse()
+
+ client.list_instances(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_list_instances_field_headers_async():
+ client = InstancesAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.ListInstancesRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_instances), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ appengine.ListInstancesResponse()
+ )
+
+ await client.list_instances(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"]
+
+
+def test_list_instances_pager():
+ client = InstancesClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_instances), "__call__") as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListInstancesResponse(
+ instances=[
+ instance.Instance(),
+ instance.Instance(),
+ instance.Instance(),
+ ],
+ next_page_token="abc",
+ ),
+ appengine.ListInstancesResponse(instances=[], next_page_token="def",),
+ appengine.ListInstancesResponse(
+ instances=[instance.Instance(),], next_page_token="ghi",
+ ),
+ appengine.ListInstancesResponse(
+ instances=[instance.Instance(), instance.Instance(),],
+ ),
+ RuntimeError,
+ )
+
+ metadata = ()
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
+ )
+ pager = client.list_instances(request={})
+
+ assert pager._metadata == metadata
+
+ results = [i for i in pager]
+ assert len(results) == 6
+ assert all(isinstance(i, instance.Instance) for i in results)
+
+
+def test_list_instances_pages():
+ client = InstancesClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_instances), "__call__") as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListInstancesResponse(
+ instances=[
+ instance.Instance(),
+ instance.Instance(),
+ instance.Instance(),
+ ],
+ next_page_token="abc",
+ ),
+ appengine.ListInstancesResponse(instances=[], next_page_token="def",),
+ appengine.ListInstancesResponse(
+ instances=[instance.Instance(),], next_page_token="ghi",
+ ),
+ appengine.ListInstancesResponse(
+ instances=[instance.Instance(), instance.Instance(),],
+ ),
+ RuntimeError,
+ )
+ pages = list(client.list_instances(request={}).pages)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
+
+
+@pytest.mark.asyncio
+async def test_list_instances_async_pager():
+ client = InstancesAsyncClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_instances), "__call__", new_callable=mock.AsyncMock
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListInstancesResponse(
+ instances=[
+ instance.Instance(),
+ instance.Instance(),
+ instance.Instance(),
+ ],
+ next_page_token="abc",
+ ),
+ appengine.ListInstancesResponse(instances=[], next_page_token="def",),
+ appengine.ListInstancesResponse(
+ instances=[instance.Instance(),], next_page_token="ghi",
+ ),
+ appengine.ListInstancesResponse(
+ instances=[instance.Instance(), instance.Instance(),],
+ ),
+ RuntimeError,
+ )
+ async_pager = await client.list_instances(request={},)
+ assert async_pager.next_page_token == "abc"
+ responses = []
+ async for response in async_pager:
+ responses.append(response)
+
+ assert len(responses) == 6
+ assert all(isinstance(i, instance.Instance) for i in responses)
+
+
+@pytest.mark.asyncio
+async def test_list_instances_async_pages():
+ client = InstancesAsyncClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_instances), "__call__", new_callable=mock.AsyncMock
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListInstancesResponse(
+ instances=[
+ instance.Instance(),
+ instance.Instance(),
+ instance.Instance(),
+ ],
+ next_page_token="abc",
+ ),
+ appengine.ListInstancesResponse(instances=[], next_page_token="def",),
+ appengine.ListInstancesResponse(
+ instances=[instance.Instance(),], next_page_token="ghi",
+ ),
+ appengine.ListInstancesResponse(
+ instances=[instance.Instance(), instance.Instance(),],
+ ),
+ RuntimeError,
+ )
+ pages = []
+ async for page_ in (await client.list_instances(request={})).pages:
+ pages.append(page_)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
+
+
+def test_get_instance(
+ transport: str = "grpc", request_type=appengine.GetInstanceRequest
+):
+ client = InstancesClient(
+ credentials=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_instance), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = instance.Instance(
+ name="name_value",
+ id="id_value",
+ app_engine_release="app_engine_release_value",
+ availability=instance.Instance.Availability.RESIDENT,
+ vm_name="vm_name_value",
+ vm_zone_name="vm_zone_name_value",
+ vm_id="vm_id_value",
+ requests=892,
+ errors=669,
+ qps=0.340,
+ average_latency=1578,
+ memory_usage=1293,
+ vm_status="vm_status_value",
+ vm_debug_enabled=True,
+ vm_ip="vm_ip_value",
+ vm_liveness=instance.Instance.Liveness.LivenessState.UNKNOWN,
+ )
+
+ response = client.get_instance(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.GetInstanceRequest()
+
+ # Establish that the response is the type that we expect.
+
+ assert isinstance(response, instance.Instance)
+
+ assert response.name == "name_value"
+
+ assert response.id == "id_value"
+
+ assert response.app_engine_release == "app_engine_release_value"
+
+ assert response.availability == instance.Instance.Availability.RESIDENT
+
+ assert response.vm_name == "vm_name_value"
+
+ assert response.vm_zone_name == "vm_zone_name_value"
+
+ assert response.vm_id == "vm_id_value"
+
+ assert response.requests == 892
+
+ assert response.errors == 669
+
+ assert math.isclose(response.qps, 0.340, rel_tol=1e-6)
+
+ assert response.average_latency == 1578
+
+ assert response.memory_usage == 1293
+
+ assert response.vm_status == "vm_status_value"
+
+ assert response.vm_debug_enabled is True
+
+ assert response.vm_ip == "vm_ip_value"
+
+ assert response.vm_liveness == instance.Instance.Liveness.LivenessState.UNKNOWN
+
+
+def test_get_instance_from_dict():
+ test_get_instance(request_type=dict)
+
+
+def test_get_instance_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = InstancesClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_instance), "__call__") as call:
+ client.get_instance()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.GetInstanceRequest()
+
+
+@pytest.mark.asyncio
+async def test_get_instance_async(
+ transport: str = "grpc_asyncio", request_type=appengine.GetInstanceRequest
+):
+ client = InstancesAsyncClient(
+ credentials=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_instance), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ instance.Instance(
+ name="name_value",
+ id="id_value",
+ app_engine_release="app_engine_release_value",
+ availability=instance.Instance.Availability.RESIDENT,
+ vm_name="vm_name_value",
+ vm_zone_name="vm_zone_name_value",
+ vm_id="vm_id_value",
+ requests=892,
+ errors=669,
+ qps=0.340,
+ average_latency=1578,
+ memory_usage=1293,
+ vm_status="vm_status_value",
+ vm_debug_enabled=True,
+ vm_ip="vm_ip_value",
+ vm_liveness=instance.Instance.Liveness.LivenessState.UNKNOWN,
+ )
+ )
+
+ response = await client.get_instance(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.GetInstanceRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, instance.Instance)
+
+ assert response.name == "name_value"
+
+ assert response.id == "id_value"
+
+ assert response.app_engine_release == "app_engine_release_value"
+
+ assert response.availability == instance.Instance.Availability.RESIDENT
+
+ assert response.vm_name == "vm_name_value"
+
+ assert response.vm_zone_name == "vm_zone_name_value"
+
+ assert response.vm_id == "vm_id_value"
+
+ assert response.requests == 892
+
+ assert response.errors == 669
+
+ assert math.isclose(response.qps, 0.340, rel_tol=1e-6)
+
+ assert response.average_latency == 1578
+
+ assert response.memory_usage == 1293
+
+ assert response.vm_status == "vm_status_value"
+
+ assert response.vm_debug_enabled is True
+
+ assert response.vm_ip == "vm_ip_value"
+
+ assert response.vm_liveness == instance.Instance.Liveness.LivenessState.UNKNOWN
+
+
+@pytest.mark.asyncio
+async def test_get_instance_async_from_dict():
+ await test_get_instance_async(request_type=dict)
+
+
+def test_get_instance_field_headers():
+ client = InstancesClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.GetInstanceRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_instance), "__call__") as call:
+ call.return_value = instance.Instance()
+
+ client.get_instance(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_get_instance_field_headers_async():
+ client = InstancesAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.GetInstanceRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_instance), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instance.Instance())
+
+ await client.get_instance(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_delete_instance(
+ transport: str = "grpc", request_type=appengine.DeleteInstanceRequest
+):
+ client = InstancesClient(
+ credentials=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.delete_instance), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.delete_instance(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.DeleteInstanceRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_delete_instance_from_dict():
+ test_delete_instance(request_type=dict)
+
+
+def test_delete_instance_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = InstancesClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_instance), "__call__") as call:
+ client.delete_instance()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.DeleteInstanceRequest()
+
+
+@pytest.mark.asyncio
+async def test_delete_instance_async(
+ transport: str = "grpc_asyncio", request_type=appengine.DeleteInstanceRequest
+):
+ client = InstancesAsyncClient(
+ credentials=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.delete_instance), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/spam")
+ )
+
+ response = await client.delete_instance(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.DeleteInstanceRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_delete_instance_async_from_dict():
+ await test_delete_instance_async(request_type=dict)
+
+
+def test_delete_instance_field_headers():
+ client = InstancesClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.DeleteInstanceRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_instance), "__call__") as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ client.delete_instance(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_delete_instance_field_headers_async():
+ client = InstancesAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.DeleteInstanceRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_instance), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+
+ await client.delete_instance(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_debug_instance(
+ transport: str = "grpc", request_type=appengine.DebugInstanceRequest
+):
+ client = InstancesClient(
+ credentials=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.debug_instance), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.debug_instance(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.DebugInstanceRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_debug_instance_from_dict():
+ test_debug_instance(request_type=dict)
+
+
+def test_debug_instance_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = InstancesClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.debug_instance), "__call__") as call:
+ client.debug_instance()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.DebugInstanceRequest()
+
+
+@pytest.mark.asyncio
+async def test_debug_instance_async(
+ transport: str = "grpc_asyncio", request_type=appengine.DebugInstanceRequest
+):
+ client = InstancesAsyncClient(
+ credentials=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.debug_instance), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/spam")
+ )
+
+ response = await client.debug_instance(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.DebugInstanceRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_debug_instance_async_from_dict():
+ await test_debug_instance_async(request_type=dict)
+
+
+def test_debug_instance_field_headers():
+ client = InstancesClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.DebugInstanceRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.debug_instance), "__call__") as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ client.debug_instance(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_debug_instance_field_headers_async():
+ client = InstancesAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.DebugInstanceRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.debug_instance), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+
+ await client.debug_instance(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.InstancesGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = InstancesClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.InstancesGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = InstancesClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
+
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.InstancesGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = InstancesClient(
+ client_options={"scopes": ["1", "2"]}, transport=transport,
+ )
+
+
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.InstancesGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ client = InstancesClient(transport=transport)
+ assert client.transport is transport
+
+
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.InstancesGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+ transport = transports.InstancesGrpcAsyncIOTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.InstancesGrpcTransport, transports.InstancesGrpcAsyncIOTransport,],
+)
+def test_transport_adc(transport_class):
+ # Test default credentials are used if not provided.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transport_class()
+ adc.assert_called_once()
+
+
+def test_transport_grpc_default():
+ # A client should use the gRPC transport by default.
+ client = InstancesClient(credentials=credentials.AnonymousCredentials(),)
+ assert isinstance(client.transport, transports.InstancesGrpcTransport,)
+
+
+def test_instances_base_transport_error():
+ # Passing both a credentials object and credentials_file should raise an error
+ with pytest.raises(exceptions.DuplicateCredentialArgs):
+ transport = transports.InstancesTransport(
+ credentials=credentials.AnonymousCredentials(),
+ credentials_file="credentials.json",
+ )
+
+
+def test_instances_base_transport():
+ # Instantiate the base transport.
+ with mock.patch(
+ "google.cloud.appengine_admin_v1.services.instances.transports.InstancesTransport.__init__"
+ ) as Transport:
+ Transport.return_value = None
+ transport = transports.InstancesTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Every method on the transport should just blindly
+ # raise NotImplementedError.
+ methods = (
+ "list_instances",
+ "get_instance",
+ "delete_instance",
+ "debug_instance",
+ )
+ for method in methods:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, method)(request=object())
+
+ # Additionally, the LRO client (a property) should
+ # also raise NotImplementedError
+ with pytest.raises(NotImplementedError):
+ transport.operations_client
+
+
+def test_instances_base_transport_with_credentials_file():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(
+ auth, "load_credentials_from_file"
+ ) as load_creds, mock.patch(
+ "google.cloud.appengine_admin_v1.services.instances.transports.InstancesTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ transport = transports.InstancesTransport(
+ credentials_file="credentials.json", quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+def test_instances_base_transport_with_adc():
+ # Test the default credentials are used if credentials and credentials_file are None.
+ with mock.patch.object(auth, "default") as adc, mock.patch(
+ "google.cloud.appengine_admin_v1.services.instances.transports.InstancesTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transport = transports.InstancesTransport()
+ adc.assert_called_once()
+
+
+def test_instances_auth_adc():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ InstancesClient()
+ adc.assert_called_once_with(
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ quota_project_id=None,
+ )
+
+
+def test_instances_transport_auth_adc():
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transports.InstancesGrpcTransport(
+ host="squid.clam.whelk", quota_project_id="octopus"
+ )
+ adc.assert_called_once_with(
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.InstancesGrpcTransport, transports.InstancesGrpcAsyncIOTransport],
+)
+def test_instances_grpc_transport_client_cert_source_for_mtls(transport_class):
+ cred = credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
+def test_instances_host_no_port():
+ client = InstancesClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="appengine.googleapis.com"
+ ),
+ )
+ assert client.transport._host == "appengine.googleapis.com:443"
+
+
+def test_instances_host_with_port():
+ client = InstancesClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="appengine.googleapis.com:8000"
+ ),
+ )
+ assert client.transport._host == "appengine.googleapis.com:8000"
+
+
+def test_instances_grpc_transport_channel():
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.InstancesGrpcTransport(
+ host="squid.clam.whelk", channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+def test_instances_grpc_asyncio_transport_channel():
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.InstancesGrpcAsyncIOTransport(
+ host="squid.clam.whelk", channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.InstancesGrpcTransport, transports.InstancesGrpcAsyncIOTransport],
+)
+def test_instances_transport_channel_mtls_with_client_cert_source(transport_class):
+ with mock.patch(
+ "grpc.ssl_channel_credentials", autospec=True
+ ) as grpc_ssl_channel_cred:
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_ssl_cred = mock.Mock()
+ grpc_ssl_channel_cred.return_value = mock_ssl_cred
+
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ cred = credentials.AnonymousCredentials()
+ with pytest.warns(DeprecationWarning):
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (cred, None)
+ transport = transport_class(
+ host="squid.clam.whelk",
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=client_cert_source_callback,
+ )
+ adc.assert_called_once()
+
+ grpc_ssl_channel_cred.assert_called_once_with(
+ certificate_chain=b"cert bytes", private_key=b"key bytes"
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+ assert transport._ssl_channel_credentials == mock_ssl_cred
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.InstancesGrpcTransport, transports.InstancesGrpcAsyncIOTransport],
+)
+def test_instances_transport_channel_mtls_with_adc(transport_class):
+ mock_ssl_cred = mock.Mock()
+ with mock.patch.multiple(
+ "google.auth.transport.grpc.SslCredentials",
+ __init__=mock.Mock(return_value=None),
+ ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
+ ):
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+ mock_cred = mock.Mock()
+
+ with pytest.warns(DeprecationWarning):
+ transport = transport_class(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=None,
+ )
+
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+def test_instances_grpc_lro_client():
+ client = InstancesClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+ transport = client.transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(transport.operations_client, operations_v1.OperationsClient,)
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_instances_grpc_lro_async_client():
+ client = InstancesAsyncClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio",
+ )
+ transport = client.transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(transport.operations_client, operations_v1.OperationsAsyncClient,)
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_instance_path():
+ app = "squid"
+ service = "clam"
+ version = "whelk"
+ instance = "octopus"
+
+ expected = "apps/{app}/services/{service}/versions/{version}/instances/{instance}".format(
+ app=app, service=service, version=version, instance=instance,
+ )
+ actual = InstancesClient.instance_path(app, service, version, instance)
+ assert expected == actual
+
+
+def test_parse_instance_path():
+ expected = {
+ "app": "oyster",
+ "service": "nudibranch",
+ "version": "cuttlefish",
+ "instance": "mussel",
+ }
+ path = InstancesClient.instance_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = InstancesClient.parse_instance_path(path)
+ assert expected == actual
+
+
+def test_common_billing_account_path():
+ billing_account = "winkle"
+
+ expected = "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
+ )
+ actual = InstancesClient.common_billing_account_path(billing_account)
+ assert expected == actual
+
+
+def test_parse_common_billing_account_path():
+ expected = {
+ "billing_account": "nautilus",
+ }
+ path = InstancesClient.common_billing_account_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = InstancesClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "scallop"
+
+ expected = "folders/{folder}".format(folder=folder,)
+ actual = InstancesClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "abalone",
+ }
+ path = InstancesClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = InstancesClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "squid"
+
+ expected = "organizations/{organization}".format(organization=organization,)
+ actual = InstancesClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "clam",
+ }
+ path = InstancesClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = InstancesClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "whelk"
+
+ expected = "projects/{project}".format(project=project,)
+ actual = InstancesClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "octopus",
+ }
+ path = InstancesClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = InstancesClient.parse_common_project_path(path)
+ assert expected == actual
+
+
+def test_common_location_path():
+ project = "oyster"
+ location = "nudibranch"
+
+ expected = "projects/{project}/locations/{location}".format(
+ project=project, location=location,
+ )
+ actual = InstancesClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "cuttlefish",
+ "location": "mussel",
+ }
+ path = InstancesClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = InstancesClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_withDEFAULT_CLIENT_INFO():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.InstancesTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = InstancesClient(
+ credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.InstancesTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = InstancesClient.get_transport_class()
+ transport = transport_class(
+ credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
diff --git a/tests/unit/gapic/appengine_admin_v1/test_services.py b/tests/unit/gapic/appengine_admin_v1/test_services.py
new file mode 100644
index 0000000..69f3818
--- /dev/null
+++ b/tests/unit/gapic/appengine_admin_v1/test_services.py
@@ -0,0 +1,1609 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import os
+import mock
+
+import grpc
+from grpc.experimental import aio
+import math
+import pytest
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+
+from google import auth
+from google.api_core import client_options
+from google.api_core import exceptions
+from google.api_core import future
+from google.api_core import gapic_v1
+from google.api_core import grpc_helpers
+from google.api_core import grpc_helpers_async
+from google.api_core import operation_async # type: ignore
+from google.api_core import operations_v1
+from google.auth import credentials
+from google.auth.exceptions import MutualTLSChannelError
+from google.cloud.appengine_admin_v1.services.services import ServicesAsyncClient
+from google.cloud.appengine_admin_v1.services.services import ServicesClient
+from google.cloud.appengine_admin_v1.services.services import pagers
+from google.cloud.appengine_admin_v1.services.services import transports
+from google.cloud.appengine_admin_v1.types import appengine
+from google.cloud.appengine_admin_v1.types import network_settings
+from google.cloud.appengine_admin_v1.types import operation as ga_operation
+from google.cloud.appengine_admin_v1.types import service
+from google.longrunning import operations_pb2
+from google.oauth2 import service_account
+from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+
+
+def client_cert_source_callback():
+ return b"cert bytes", b"key bytes"
+
+
+# If default endpoint is localhost, then default mtls endpoint will be the same.
+# This method modifies the default endpoint so the client can produce a different
+# mtls endpoint for endpoint testing purposes.
+def modify_default_endpoint(client):
+ return (
+ "foo.googleapis.com"
+ if ("localhost" in client.DEFAULT_ENDPOINT)
+ else client.DEFAULT_ENDPOINT
+ )
+
+
+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 ServicesClient._get_default_mtls_endpoint(None) is None
+ assert ServicesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint
+ assert (
+ ServicesClient._get_default_mtls_endpoint(api_mtls_endpoint)
+ == api_mtls_endpoint
+ )
+ assert (
+ ServicesClient._get_default_mtls_endpoint(sandbox_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert (
+ ServicesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert ServicesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi
+
+
+@pytest.mark.parametrize("client_class", [ServicesClient, ServicesAsyncClient,])
+def test_services_client_from_service_account_info(client_class):
+ creds = credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "appengine.googleapis.com:443"
+
+
+@pytest.mark.parametrize("client_class", [ServicesClient, ServicesAsyncClient,])
+def test_services_client_from_service_account_file(client_class):
+ creds = credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_file"
+ ) as factory:
+ factory.return_value = creds
+ client = client_class.from_service_account_file("dummy/file/path.json")
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ client = client_class.from_service_account_json("dummy/file/path.json")
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "appengine.googleapis.com:443"
+
+
+def test_services_client_get_transport_class():
+ transport = ServicesClient.get_transport_class()
+ available_transports = [
+ transports.ServicesGrpcTransport,
+ ]
+ assert transport in available_transports
+
+ transport = ServicesClient.get_transport_class("grpc")
+ assert transport == transports.ServicesGrpcTransport
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (ServicesClient, transports.ServicesGrpcTransport, "grpc"),
+ (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio"),
+ ],
+)
+@mock.patch.object(
+ ServicesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServicesClient)
+)
+@mock.patch.object(
+ ServicesAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(ServicesAsyncClient),
+)
+def test_services_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(ServicesClient, "get_transport_class") as gtc:
+ transport = transport_class(credentials=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(ServicesClient, "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,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,use_client_cert_env",
+ [
+ (ServicesClient, transports.ServicesGrpcTransport, "grpc", "true"),
+ (
+ ServicesAsyncClient,
+ transports.ServicesGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "true",
+ ),
+ (ServicesClient, transports.ServicesGrpcTransport, "grpc", "false"),
+ (
+ ServicesAsyncClient,
+ transports.ServicesGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "false",
+ ),
+ ],
+)
+@mock.patch.object(
+ ServicesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServicesClient)
+)
+@mock.patch.object(
+ ServicesAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(ServicesAsyncClient),
+)
+@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"})
+def test_services_client_mtls_env_auto(
+ client_class, transport_class, transport_name, use_client_cert_env
+):
+ # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default
+ # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists.
+
+ # Check the case client_cert_source is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ options = client_options.ClientOptions(
+ client_cert_source=client_cert_source_callback
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client.DEFAULT_ENDPOINT
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+ # Check the case ADC client cert is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client.DEFAULT_ENDPOINT
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
+
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ 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,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (ServicesClient, transports.ServicesGrpcTransport, "grpc"),
+ (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio"),
+ ],
+)
+def test_services_client_client_options_scopes(
+ client_class, transport_class, transport_name
+):
+ # Check the case scopes are provided.
+ options = client_options.ClientOptions(scopes=["1", "2"],)
+ 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=["1", "2"],
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (ServicesClient, transports.ServicesGrpcTransport, "grpc"),
+ (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio"),
+ ],
+)
+def test_services_client_client_options_credentials_file(
+ client_class, transport_class, transport_name
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+ 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="credentials.json",
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+
+def test_services_client_client_options_from_dict():
+ with mock.patch(
+ "google.cloud.appengine_admin_v1.services.services.transports.ServicesGrpcTransport.__init__"
+ ) as grpc_transport:
+ grpc_transport.return_value = None
+ client = ServicesClient(client_options={"api_endpoint": "squid.clam.whelk"})
+ grpc_transport.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,
+ )
+
+
+def test_list_services(
+ transport: str = "grpc", request_type=appengine.ListServicesRequest
+):
+ client = ServicesClient(
+ credentials=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.list_services), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = appengine.ListServicesResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ response = client.list_services(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.ListServicesRequest()
+
+ # Establish that the response is the type that we expect.
+
+ assert isinstance(response, pagers.ListServicesPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_services_from_dict():
+ test_list_services(request_type=dict)
+
+
+def test_list_services_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ServicesClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_services), "__call__") as call:
+ client.list_services()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.ListServicesRequest()
+
+
+@pytest.mark.asyncio
+async def test_list_services_async(
+ transport: str = "grpc_asyncio", request_type=appengine.ListServicesRequest
+):
+ client = ServicesAsyncClient(
+ credentials=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.list_services), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ appengine.ListServicesResponse(next_page_token="next_page_token_value",)
+ )
+
+ response = await client.list_services(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.ListServicesRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListServicesAsyncPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+
+@pytest.mark.asyncio
+async def test_list_services_async_from_dict():
+ await test_list_services_async(request_type=dict)
+
+
+def test_list_services_field_headers():
+ client = ServicesClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.ListServicesRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_services), "__call__") as call:
+ call.return_value = appengine.ListServicesResponse()
+
+ client.list_services(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_list_services_field_headers_async():
+ client = ServicesAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.ListServicesRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_services), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ appengine.ListServicesResponse()
+ )
+
+ await client.list_services(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"]
+
+
+def test_list_services_pager():
+ client = ServicesClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_services), "__call__") as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListServicesResponse(
+ services=[service.Service(), service.Service(), service.Service(),],
+ next_page_token="abc",
+ ),
+ appengine.ListServicesResponse(services=[], next_page_token="def",),
+ appengine.ListServicesResponse(
+ services=[service.Service(),], next_page_token="ghi",
+ ),
+ appengine.ListServicesResponse(
+ services=[service.Service(), service.Service(),],
+ ),
+ RuntimeError,
+ )
+
+ metadata = ()
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
+ )
+ pager = client.list_services(request={})
+
+ assert pager._metadata == metadata
+
+ results = [i for i in pager]
+ assert len(results) == 6
+ assert all(isinstance(i, service.Service) for i in results)
+
+
+def test_list_services_pages():
+ client = ServicesClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_services), "__call__") as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListServicesResponse(
+ services=[service.Service(), service.Service(), service.Service(),],
+ next_page_token="abc",
+ ),
+ appengine.ListServicesResponse(services=[], next_page_token="def",),
+ appengine.ListServicesResponse(
+ services=[service.Service(),], next_page_token="ghi",
+ ),
+ appengine.ListServicesResponse(
+ services=[service.Service(), service.Service(),],
+ ),
+ RuntimeError,
+ )
+ pages = list(client.list_services(request={}).pages)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
+
+
+@pytest.mark.asyncio
+async def test_list_services_async_pager():
+ client = ServicesAsyncClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_services), "__call__", new_callable=mock.AsyncMock
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListServicesResponse(
+ services=[service.Service(), service.Service(), service.Service(),],
+ next_page_token="abc",
+ ),
+ appengine.ListServicesResponse(services=[], next_page_token="def",),
+ appengine.ListServicesResponse(
+ services=[service.Service(),], next_page_token="ghi",
+ ),
+ appengine.ListServicesResponse(
+ services=[service.Service(), service.Service(),],
+ ),
+ RuntimeError,
+ )
+ async_pager = await client.list_services(request={},)
+ assert async_pager.next_page_token == "abc"
+ responses = []
+ async for response in async_pager:
+ responses.append(response)
+
+ assert len(responses) == 6
+ assert all(isinstance(i, service.Service) for i in responses)
+
+
+@pytest.mark.asyncio
+async def test_list_services_async_pages():
+ client = ServicesAsyncClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_services), "__call__", new_callable=mock.AsyncMock
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListServicesResponse(
+ services=[service.Service(), service.Service(), service.Service(),],
+ next_page_token="abc",
+ ),
+ appengine.ListServicesResponse(services=[], next_page_token="def",),
+ appengine.ListServicesResponse(
+ services=[service.Service(),], next_page_token="ghi",
+ ),
+ appengine.ListServicesResponse(
+ services=[service.Service(), service.Service(),],
+ ),
+ RuntimeError,
+ )
+ pages = []
+ async for page_ in (await client.list_services(request={})).pages:
+ pages.append(page_)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
+
+
+def test_get_service(transport: str = "grpc", request_type=appengine.GetServiceRequest):
+ client = ServicesClient(
+ credentials=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_service), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = service.Service(name="name_value", id="id_value",)
+
+ response = client.get_service(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.GetServiceRequest()
+
+ # Establish that the response is the type that we expect.
+
+ assert isinstance(response, service.Service)
+
+ assert response.name == "name_value"
+
+ assert response.id == "id_value"
+
+
+def test_get_service_from_dict():
+ test_get_service(request_type=dict)
+
+
+def test_get_service_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ServicesClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_service), "__call__") as call:
+ client.get_service()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.GetServiceRequest()
+
+
+@pytest.mark.asyncio
+async def test_get_service_async(
+ transport: str = "grpc_asyncio", request_type=appengine.GetServiceRequest
+):
+ client = ServicesAsyncClient(
+ credentials=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_service), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ service.Service(name="name_value", id="id_value",)
+ )
+
+ response = await client.get_service(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.GetServiceRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, service.Service)
+
+ assert response.name == "name_value"
+
+ assert response.id == "id_value"
+
+
+@pytest.mark.asyncio
+async def test_get_service_async_from_dict():
+ await test_get_service_async(request_type=dict)
+
+
+def test_get_service_field_headers():
+ client = ServicesClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.GetServiceRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_service), "__call__") as call:
+ call.return_value = service.Service()
+
+ client.get_service(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_get_service_field_headers_async():
+ client = ServicesAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.GetServiceRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_service), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.Service())
+
+ await client.get_service(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_update_service(
+ transport: str = "grpc", request_type=appengine.UpdateServiceRequest
+):
+ client = ServicesClient(
+ credentials=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.update_service), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.update_service(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.UpdateServiceRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_update_service_from_dict():
+ test_update_service(request_type=dict)
+
+
+def test_update_service_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ServicesClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_service), "__call__") as call:
+ client.update_service()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.UpdateServiceRequest()
+
+
+@pytest.mark.asyncio
+async def test_update_service_async(
+ transport: str = "grpc_asyncio", request_type=appengine.UpdateServiceRequest
+):
+ client = ServicesAsyncClient(
+ credentials=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.update_service), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/spam")
+ )
+
+ response = await client.update_service(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.UpdateServiceRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_update_service_async_from_dict():
+ await test_update_service_async(request_type=dict)
+
+
+def test_update_service_field_headers():
+ client = ServicesClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.UpdateServiceRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_service), "__call__") as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ client.update_service(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_update_service_field_headers_async():
+ client = ServicesAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.UpdateServiceRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_service), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+
+ await client.update_service(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_delete_service(
+ transport: str = "grpc", request_type=appengine.DeleteServiceRequest
+):
+ client = ServicesClient(
+ credentials=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.delete_service), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.delete_service(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.DeleteServiceRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_delete_service_from_dict():
+ test_delete_service(request_type=dict)
+
+
+def test_delete_service_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ServicesClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_service), "__call__") as call:
+ client.delete_service()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.DeleteServiceRequest()
+
+
+@pytest.mark.asyncio
+async def test_delete_service_async(
+ transport: str = "grpc_asyncio", request_type=appengine.DeleteServiceRequest
+):
+ client = ServicesAsyncClient(
+ credentials=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.delete_service), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/spam")
+ )
+
+ response = await client.delete_service(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.DeleteServiceRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_delete_service_async_from_dict():
+ await test_delete_service_async(request_type=dict)
+
+
+def test_delete_service_field_headers():
+ client = ServicesClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.DeleteServiceRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_service), "__call__") as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ client.delete_service(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_delete_service_field_headers_async():
+ client = ServicesAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.DeleteServiceRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_service), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+
+ await client.delete_service(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.ServicesGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = ServicesClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.ServicesGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = ServicesClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
+
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.ServicesGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = ServicesClient(
+ client_options={"scopes": ["1", "2"]}, transport=transport,
+ )
+
+
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.ServicesGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ client = ServicesClient(transport=transport)
+ assert client.transport is transport
+
+
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.ServicesGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+ transport = transports.ServicesGrpcAsyncIOTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.ServicesGrpcTransport, transports.ServicesGrpcAsyncIOTransport,],
+)
+def test_transport_adc(transport_class):
+ # Test default credentials are used if not provided.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transport_class()
+ adc.assert_called_once()
+
+
+def test_transport_grpc_default():
+ # A client should use the gRPC transport by default.
+ client = ServicesClient(credentials=credentials.AnonymousCredentials(),)
+ assert isinstance(client.transport, transports.ServicesGrpcTransport,)
+
+
+def test_services_base_transport_error():
+ # Passing both a credentials object and credentials_file should raise an error
+ with pytest.raises(exceptions.DuplicateCredentialArgs):
+ transport = transports.ServicesTransport(
+ credentials=credentials.AnonymousCredentials(),
+ credentials_file="credentials.json",
+ )
+
+
+def test_services_base_transport():
+ # Instantiate the base transport.
+ with mock.patch(
+ "google.cloud.appengine_admin_v1.services.services.transports.ServicesTransport.__init__"
+ ) as Transport:
+ Transport.return_value = None
+ transport = transports.ServicesTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Every method on the transport should just blindly
+ # raise NotImplementedError.
+ methods = (
+ "list_services",
+ "get_service",
+ "update_service",
+ "delete_service",
+ )
+ for method in methods:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, method)(request=object())
+
+ # Additionally, the LRO client (a property) should
+ # also raise NotImplementedError
+ with pytest.raises(NotImplementedError):
+ transport.operations_client
+
+
+def test_services_base_transport_with_credentials_file():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(
+ auth, "load_credentials_from_file"
+ ) as load_creds, mock.patch(
+ "google.cloud.appengine_admin_v1.services.services.transports.ServicesTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ transport = transports.ServicesTransport(
+ credentials_file="credentials.json", quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+def test_services_base_transport_with_adc():
+ # Test the default credentials are used if credentials and credentials_file are None.
+ with mock.patch.object(auth, "default") as adc, mock.patch(
+ "google.cloud.appengine_admin_v1.services.services.transports.ServicesTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transport = transports.ServicesTransport()
+ adc.assert_called_once()
+
+
+def test_services_auth_adc():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ ServicesClient()
+ adc.assert_called_once_with(
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ quota_project_id=None,
+ )
+
+
+def test_services_transport_auth_adc():
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transports.ServicesGrpcTransport(
+ host="squid.clam.whelk", quota_project_id="octopus"
+ )
+ adc.assert_called_once_with(
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.ServicesGrpcTransport, transports.ServicesGrpcAsyncIOTransport],
+)
+def test_services_grpc_transport_client_cert_source_for_mtls(transport_class):
+ cred = credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
+def test_services_host_no_port():
+ client = ServicesClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="appengine.googleapis.com"
+ ),
+ )
+ assert client.transport._host == "appengine.googleapis.com:443"
+
+
+def test_services_host_with_port():
+ client = ServicesClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="appengine.googleapis.com:8000"
+ ),
+ )
+ assert client.transport._host == "appengine.googleapis.com:8000"
+
+
+def test_services_grpc_transport_channel():
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.ServicesGrpcTransport(
+ host="squid.clam.whelk", channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+def test_services_grpc_asyncio_transport_channel():
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.ServicesGrpcAsyncIOTransport(
+ host="squid.clam.whelk", channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.ServicesGrpcTransport, transports.ServicesGrpcAsyncIOTransport],
+)
+def test_services_transport_channel_mtls_with_client_cert_source(transport_class):
+ with mock.patch(
+ "grpc.ssl_channel_credentials", autospec=True
+ ) as grpc_ssl_channel_cred:
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_ssl_cred = mock.Mock()
+ grpc_ssl_channel_cred.return_value = mock_ssl_cred
+
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ cred = credentials.AnonymousCredentials()
+ with pytest.warns(DeprecationWarning):
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (cred, None)
+ transport = transport_class(
+ host="squid.clam.whelk",
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=client_cert_source_callback,
+ )
+ adc.assert_called_once()
+
+ grpc_ssl_channel_cred.assert_called_once_with(
+ certificate_chain=b"cert bytes", private_key=b"key bytes"
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+ assert transport._ssl_channel_credentials == mock_ssl_cred
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.ServicesGrpcTransport, transports.ServicesGrpcAsyncIOTransport],
+)
+def test_services_transport_channel_mtls_with_adc(transport_class):
+ mock_ssl_cred = mock.Mock()
+ with mock.patch.multiple(
+ "google.auth.transport.grpc.SslCredentials",
+ __init__=mock.Mock(return_value=None),
+ ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
+ ):
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+ mock_cred = mock.Mock()
+
+ with pytest.warns(DeprecationWarning):
+ transport = transport_class(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=None,
+ )
+
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+def test_services_grpc_lro_client():
+ client = ServicesClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+ transport = client.transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(transport.operations_client, operations_v1.OperationsClient,)
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_services_grpc_lro_async_client():
+ client = ServicesAsyncClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio",
+ )
+ transport = client.transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(transport.operations_client, operations_v1.OperationsAsyncClient,)
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_common_billing_account_path():
+ billing_account = "squid"
+
+ expected = "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
+ )
+ actual = ServicesClient.common_billing_account_path(billing_account)
+ assert expected == actual
+
+
+def test_parse_common_billing_account_path():
+ expected = {
+ "billing_account": "clam",
+ }
+ path = ServicesClient.common_billing_account_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ServicesClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "whelk"
+
+ expected = "folders/{folder}".format(folder=folder,)
+ actual = ServicesClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "octopus",
+ }
+ path = ServicesClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ServicesClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "oyster"
+
+ expected = "organizations/{organization}".format(organization=organization,)
+ actual = ServicesClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "nudibranch",
+ }
+ path = ServicesClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ServicesClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "cuttlefish"
+
+ expected = "projects/{project}".format(project=project,)
+ actual = ServicesClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "mussel",
+ }
+ path = ServicesClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ServicesClient.parse_common_project_path(path)
+ assert expected == actual
+
+
+def test_common_location_path():
+ project = "winkle"
+ location = "nautilus"
+
+ expected = "projects/{project}/locations/{location}".format(
+ project=project, location=location,
+ )
+ actual = ServicesClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "scallop",
+ "location": "abalone",
+ }
+ path = ServicesClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ServicesClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_withDEFAULT_CLIENT_INFO():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.ServicesTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = ServicesClient(
+ credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.ServicesTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = ServicesClient.get_transport_class()
+ transport = transport_class(
+ credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
diff --git a/tests/unit/gapic/appengine_admin_v1/test_versions.py b/tests/unit/gapic/appengine_admin_v1/test_versions.py
new file mode 100644
index 0000000..ef68c8f
--- /dev/null
+++ b/tests/unit/gapic/appengine_admin_v1/test_versions.py
@@ -0,0 +1,1857 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import os
+import mock
+
+import grpc
+from grpc.experimental import aio
+import math
+import pytest
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+
+from google import auth
+from google.api_core import client_options
+from google.api_core import exceptions
+from google.api_core import future
+from google.api_core import gapic_v1
+from google.api_core import grpc_helpers
+from google.api_core import grpc_helpers_async
+from google.api_core import operation_async # type: ignore
+from google.api_core import operations_v1
+from google.auth import credentials
+from google.auth.exceptions import MutualTLSChannelError
+from google.cloud.appengine_admin_v1.services.versions import VersionsAsyncClient
+from google.cloud.appengine_admin_v1.services.versions import VersionsClient
+from google.cloud.appengine_admin_v1.services.versions import pagers
+from google.cloud.appengine_admin_v1.services.versions import transports
+from google.cloud.appengine_admin_v1.types import app_yaml
+from google.cloud.appengine_admin_v1.types import appengine
+from google.cloud.appengine_admin_v1.types import deploy
+from google.cloud.appengine_admin_v1.types import operation as ga_operation
+from google.cloud.appengine_admin_v1.types import version
+from google.longrunning import operations_pb2
+from google.oauth2 import service_account
+from google.protobuf import duration_pb2 as duration # type: ignore
+from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+from google.protobuf import timestamp_pb2 as timestamp # type: ignore
+
+
+def client_cert_source_callback():
+ return b"cert bytes", b"key bytes"
+
+
+# If default endpoint is localhost, then default mtls endpoint will be the same.
+# This method modifies the default endpoint so the client can produce a different
+# mtls endpoint for endpoint testing purposes.
+def modify_default_endpoint(client):
+ return (
+ "foo.googleapis.com"
+ if ("localhost" in client.DEFAULT_ENDPOINT)
+ else client.DEFAULT_ENDPOINT
+ )
+
+
+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 VersionsClient._get_default_mtls_endpoint(None) is None
+ assert VersionsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint
+ assert (
+ VersionsClient._get_default_mtls_endpoint(api_mtls_endpoint)
+ == api_mtls_endpoint
+ )
+ assert (
+ VersionsClient._get_default_mtls_endpoint(sandbox_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert (
+ VersionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert VersionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi
+
+
+@pytest.mark.parametrize("client_class", [VersionsClient, VersionsAsyncClient,])
+def test_versions_client_from_service_account_info(client_class):
+ creds = credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "appengine.googleapis.com:443"
+
+
+@pytest.mark.parametrize("client_class", [VersionsClient, VersionsAsyncClient,])
+def test_versions_client_from_service_account_file(client_class):
+ creds = credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_file"
+ ) as factory:
+ factory.return_value = creds
+ client = client_class.from_service_account_file("dummy/file/path.json")
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ client = client_class.from_service_account_json("dummy/file/path.json")
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "appengine.googleapis.com:443"
+
+
+def test_versions_client_get_transport_class():
+ transport = VersionsClient.get_transport_class()
+ available_transports = [
+ transports.VersionsGrpcTransport,
+ ]
+ assert transport in available_transports
+
+ transport = VersionsClient.get_transport_class("grpc")
+ assert transport == transports.VersionsGrpcTransport
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (VersionsClient, transports.VersionsGrpcTransport, "grpc"),
+ (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"),
+ ],
+)
+@mock.patch.object(
+ VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient)
+)
+@mock.patch.object(
+ VersionsAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(VersionsAsyncClient),
+)
+def test_versions_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(VersionsClient, "get_transport_class") as gtc:
+ transport = transport_class(credentials=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(VersionsClient, "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,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,use_client_cert_env",
+ [
+ (VersionsClient, transports.VersionsGrpcTransport, "grpc", "true"),
+ (
+ VersionsAsyncClient,
+ transports.VersionsGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "true",
+ ),
+ (VersionsClient, transports.VersionsGrpcTransport, "grpc", "false"),
+ (
+ VersionsAsyncClient,
+ transports.VersionsGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "false",
+ ),
+ ],
+)
+@mock.patch.object(
+ VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient)
+)
+@mock.patch.object(
+ VersionsAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(VersionsAsyncClient),
+)
+@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"})
+def test_versions_client_mtls_env_auto(
+ client_class, transport_class, transport_name, use_client_cert_env
+):
+ # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default
+ # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists.
+
+ # Check the case client_cert_source is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ options = client_options.ClientOptions(
+ client_cert_source=client_cert_source_callback
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client.DEFAULT_ENDPOINT
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+ # Check the case ADC client cert is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client.DEFAULT_ENDPOINT
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
+
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ 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,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (VersionsClient, transports.VersionsGrpcTransport, "grpc"),
+ (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"),
+ ],
+)
+def test_versions_client_client_options_scopes(
+ client_class, transport_class, transport_name
+):
+ # Check the case scopes are provided.
+ options = client_options.ClientOptions(scopes=["1", "2"],)
+ 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=["1", "2"],
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (VersionsClient, transports.VersionsGrpcTransport, "grpc"),
+ (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"),
+ ],
+)
+def test_versions_client_client_options_credentials_file(
+ client_class, transport_class, transport_name
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+ 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="credentials.json",
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+
+def test_versions_client_client_options_from_dict():
+ with mock.patch(
+ "google.cloud.appengine_admin_v1.services.versions.transports.VersionsGrpcTransport.__init__"
+ ) as grpc_transport:
+ grpc_transport.return_value = None
+ client = VersionsClient(client_options={"api_endpoint": "squid.clam.whelk"})
+ grpc_transport.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,
+ )
+
+
+def test_list_versions(
+ transport: str = "grpc", request_type=appengine.ListVersionsRequest
+):
+ client = VersionsClient(
+ credentials=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.list_versions), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = appengine.ListVersionsResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ response = client.list_versions(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.ListVersionsRequest()
+
+ # Establish that the response is the type that we expect.
+
+ assert isinstance(response, pagers.ListVersionsPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_versions_from_dict():
+ test_list_versions(request_type=dict)
+
+
+def test_list_versions_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = VersionsClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_versions), "__call__") as call:
+ client.list_versions()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.ListVersionsRequest()
+
+
+@pytest.mark.asyncio
+async def test_list_versions_async(
+ transport: str = "grpc_asyncio", request_type=appengine.ListVersionsRequest
+):
+ client = VersionsAsyncClient(
+ credentials=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.list_versions), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ appengine.ListVersionsResponse(next_page_token="next_page_token_value",)
+ )
+
+ response = await client.list_versions(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.ListVersionsRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListVersionsAsyncPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+
+@pytest.mark.asyncio
+async def test_list_versions_async_from_dict():
+ await test_list_versions_async(request_type=dict)
+
+
+def test_list_versions_field_headers():
+ client = VersionsClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.ListVersionsRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_versions), "__call__") as call:
+ call.return_value = appengine.ListVersionsResponse()
+
+ client.list_versions(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_list_versions_field_headers_async():
+ client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.ListVersionsRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_versions), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ appengine.ListVersionsResponse()
+ )
+
+ await client.list_versions(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"]
+
+
+def test_list_versions_pager():
+ client = VersionsClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_versions), "__call__") as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListVersionsResponse(
+ versions=[version.Version(), version.Version(), version.Version(),],
+ next_page_token="abc",
+ ),
+ appengine.ListVersionsResponse(versions=[], next_page_token="def",),
+ appengine.ListVersionsResponse(
+ versions=[version.Version(),], next_page_token="ghi",
+ ),
+ appengine.ListVersionsResponse(
+ versions=[version.Version(), version.Version(),],
+ ),
+ RuntimeError,
+ )
+
+ metadata = ()
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
+ )
+ pager = client.list_versions(request={})
+
+ assert pager._metadata == metadata
+
+ results = [i for i in pager]
+ assert len(results) == 6
+ assert all(isinstance(i, version.Version) for i in results)
+
+
+def test_list_versions_pages():
+ client = VersionsClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_versions), "__call__") as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListVersionsResponse(
+ versions=[version.Version(), version.Version(), version.Version(),],
+ next_page_token="abc",
+ ),
+ appengine.ListVersionsResponse(versions=[], next_page_token="def",),
+ appengine.ListVersionsResponse(
+ versions=[version.Version(),], next_page_token="ghi",
+ ),
+ appengine.ListVersionsResponse(
+ versions=[version.Version(), version.Version(),],
+ ),
+ RuntimeError,
+ )
+ pages = list(client.list_versions(request={}).pages)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
+
+
+@pytest.mark.asyncio
+async def test_list_versions_async_pager():
+ client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_versions), "__call__", new_callable=mock.AsyncMock
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListVersionsResponse(
+ versions=[version.Version(), version.Version(), version.Version(),],
+ next_page_token="abc",
+ ),
+ appengine.ListVersionsResponse(versions=[], next_page_token="def",),
+ appengine.ListVersionsResponse(
+ versions=[version.Version(),], next_page_token="ghi",
+ ),
+ appengine.ListVersionsResponse(
+ versions=[version.Version(), version.Version(),],
+ ),
+ RuntimeError,
+ )
+ async_pager = await client.list_versions(request={},)
+ assert async_pager.next_page_token == "abc"
+ responses = []
+ async for response in async_pager:
+ responses.append(response)
+
+ assert len(responses) == 6
+ assert all(isinstance(i, version.Version) for i in responses)
+
+
+@pytest.mark.asyncio
+async def test_list_versions_async_pages():
+ client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_versions), "__call__", new_callable=mock.AsyncMock
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ appengine.ListVersionsResponse(
+ versions=[version.Version(), version.Version(), version.Version(),],
+ next_page_token="abc",
+ ),
+ appengine.ListVersionsResponse(versions=[], next_page_token="def",),
+ appengine.ListVersionsResponse(
+ versions=[version.Version(),], next_page_token="ghi",
+ ),
+ appengine.ListVersionsResponse(
+ versions=[version.Version(), version.Version(),],
+ ),
+ RuntimeError,
+ )
+ pages = []
+ async for page_ in (await client.list_versions(request={})).pages:
+ pages.append(page_)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
+
+
+def test_get_version(transport: str = "grpc", request_type=appengine.GetVersionRequest):
+ client = VersionsClient(
+ credentials=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_version), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = version.Version(
+ name="name_value",
+ id="id_value",
+ inbound_services=[version.InboundServiceType.INBOUND_SERVICE_MAIL],
+ instance_class="instance_class_value",
+ zones=["zones_value"],
+ runtime="runtime_value",
+ runtime_channel="runtime_channel_value",
+ threadsafe=True,
+ vm=True,
+ env="env_value",
+ serving_status=version.ServingStatus.SERVING,
+ created_by="created_by_value",
+ disk_usage_bytes=1701,
+ runtime_api_version="runtime_api_version_value",
+ runtime_main_executable_path="runtime_main_executable_path_value",
+ service_account="service_account_value",
+ nobuild_files_regex="nobuild_files_regex_value",
+ version_url="version_url_value",
+ automatic_scaling=version.AutomaticScaling(
+ cool_down_period=duration.Duration(seconds=751)
+ ),
+ )
+
+ response = client.get_version(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.GetVersionRequest()
+
+ # Establish that the response is the type that we expect.
+
+ assert isinstance(response, version.Version)
+
+ assert response.name == "name_value"
+
+ assert response.id == "id_value"
+
+ assert response.inbound_services == [
+ version.InboundServiceType.INBOUND_SERVICE_MAIL
+ ]
+
+ assert response.instance_class == "instance_class_value"
+
+ assert response.zones == ["zones_value"]
+
+ assert response.runtime == "runtime_value"
+
+ assert response.runtime_channel == "runtime_channel_value"
+
+ assert response.threadsafe is True
+
+ assert response.vm is True
+
+ assert response.env == "env_value"
+
+ assert response.serving_status == version.ServingStatus.SERVING
+
+ assert response.created_by == "created_by_value"
+
+ assert response.disk_usage_bytes == 1701
+
+ assert response.runtime_api_version == "runtime_api_version_value"
+
+ assert response.runtime_main_executable_path == "runtime_main_executable_path_value"
+
+ assert response.service_account == "service_account_value"
+
+ assert response.nobuild_files_regex == "nobuild_files_regex_value"
+
+ assert response.version_url == "version_url_value"
+
+
+def test_get_version_from_dict():
+ test_get_version(request_type=dict)
+
+
+def test_get_version_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = VersionsClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_version), "__call__") as call:
+ client.get_version()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.GetVersionRequest()
+
+
+@pytest.mark.asyncio
+async def test_get_version_async(
+ transport: str = "grpc_asyncio", request_type=appengine.GetVersionRequest
+):
+ client = VersionsAsyncClient(
+ credentials=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_version), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ version.Version(
+ name="name_value",
+ id="id_value",
+ inbound_services=[version.InboundServiceType.INBOUND_SERVICE_MAIL],
+ instance_class="instance_class_value",
+ zones=["zones_value"],
+ runtime="runtime_value",
+ runtime_channel="runtime_channel_value",
+ threadsafe=True,
+ vm=True,
+ env="env_value",
+ serving_status=version.ServingStatus.SERVING,
+ created_by="created_by_value",
+ disk_usage_bytes=1701,
+ runtime_api_version="runtime_api_version_value",
+ runtime_main_executable_path="runtime_main_executable_path_value",
+ service_account="service_account_value",
+ nobuild_files_regex="nobuild_files_regex_value",
+ version_url="version_url_value",
+ )
+ )
+
+ response = await client.get_version(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.GetVersionRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, version.Version)
+
+ assert response.name == "name_value"
+
+ assert response.id == "id_value"
+
+ assert response.inbound_services == [
+ version.InboundServiceType.INBOUND_SERVICE_MAIL
+ ]
+
+ assert response.instance_class == "instance_class_value"
+
+ assert response.zones == ["zones_value"]
+
+ assert response.runtime == "runtime_value"
+
+ assert response.runtime_channel == "runtime_channel_value"
+
+ assert response.threadsafe is True
+
+ assert response.vm is True
+
+ assert response.env == "env_value"
+
+ assert response.serving_status == version.ServingStatus.SERVING
+
+ assert response.created_by == "created_by_value"
+
+ assert response.disk_usage_bytes == 1701
+
+ assert response.runtime_api_version == "runtime_api_version_value"
+
+ assert response.runtime_main_executable_path == "runtime_main_executable_path_value"
+
+ assert response.service_account == "service_account_value"
+
+ assert response.nobuild_files_regex == "nobuild_files_regex_value"
+
+ assert response.version_url == "version_url_value"
+
+
+@pytest.mark.asyncio
+async def test_get_version_async_from_dict():
+ await test_get_version_async(request_type=dict)
+
+
+def test_get_version_field_headers():
+ client = VersionsClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.GetVersionRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_version), "__call__") as call:
+ call.return_value = version.Version()
+
+ client.get_version(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_get_version_field_headers_async():
+ client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.GetVersionRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_version), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(version.Version())
+
+ await client.get_version(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_create_version(
+ transport: str = "grpc", request_type=appengine.CreateVersionRequest
+):
+ client = VersionsClient(
+ credentials=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.create_version), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.create_version(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.CreateVersionRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_create_version_from_dict():
+ test_create_version(request_type=dict)
+
+
+def test_create_version_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = VersionsClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_version), "__call__") as call:
+ client.create_version()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.CreateVersionRequest()
+
+
+@pytest.mark.asyncio
+async def test_create_version_async(
+ transport: str = "grpc_asyncio", request_type=appengine.CreateVersionRequest
+):
+ client = VersionsAsyncClient(
+ credentials=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.create_version), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/spam")
+ )
+
+ response = await client.create_version(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.CreateVersionRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_create_version_async_from_dict():
+ await test_create_version_async(request_type=dict)
+
+
+def test_create_version_field_headers():
+ client = VersionsClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.CreateVersionRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_version), "__call__") as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ client.create_version(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_create_version_field_headers_async():
+ client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.CreateVersionRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_version), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+
+ await client.create_version(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"]
+
+
+def test_update_version(
+ transport: str = "grpc", request_type=appengine.UpdateVersionRequest
+):
+ client = VersionsClient(
+ credentials=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.update_version), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.update_version(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.UpdateVersionRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_update_version_from_dict():
+ test_update_version(request_type=dict)
+
+
+def test_update_version_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = VersionsClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_version), "__call__") as call:
+ client.update_version()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.UpdateVersionRequest()
+
+
+@pytest.mark.asyncio
+async def test_update_version_async(
+ transport: str = "grpc_asyncio", request_type=appengine.UpdateVersionRequest
+):
+ client = VersionsAsyncClient(
+ credentials=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.update_version), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/spam")
+ )
+
+ response = await client.update_version(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.UpdateVersionRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_update_version_async_from_dict():
+ await test_update_version_async(request_type=dict)
+
+
+def test_update_version_field_headers():
+ client = VersionsClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.UpdateVersionRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_version), "__call__") as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ client.update_version(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_update_version_field_headers_async():
+ client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.UpdateVersionRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_version), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+
+ await client.update_version(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_delete_version(
+ transport: str = "grpc", request_type=appengine.DeleteVersionRequest
+):
+ client = VersionsClient(
+ credentials=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.delete_version), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.delete_version(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.DeleteVersionRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_delete_version_from_dict():
+ test_delete_version(request_type=dict)
+
+
+def test_delete_version_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = VersionsClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_version), "__call__") as call:
+ client.delete_version()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.DeleteVersionRequest()
+
+
+@pytest.mark.asyncio
+async def test_delete_version_async(
+ transport: str = "grpc_asyncio", request_type=appengine.DeleteVersionRequest
+):
+ client = VersionsAsyncClient(
+ credentials=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.delete_version), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/spam")
+ )
+
+ response = await client.delete_version(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == appengine.DeleteVersionRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_delete_version_async_from_dict():
+ await test_delete_version_async(request_type=dict)
+
+
+def test_delete_version_field_headers():
+ client = VersionsClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.DeleteVersionRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_version), "__call__") as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ client.delete_version(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_delete_version_field_headers_async():
+ client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = appengine.DeleteVersionRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_version), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+
+ await client.delete_version(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.VersionsGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = VersionsClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.VersionsGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = VersionsClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
+
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.VersionsGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = VersionsClient(
+ client_options={"scopes": ["1", "2"]}, transport=transport,
+ )
+
+
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.VersionsGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ client = VersionsClient(transport=transport)
+ assert client.transport is transport
+
+
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.VersionsGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+ transport = transports.VersionsGrpcAsyncIOTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport,],
+)
+def test_transport_adc(transport_class):
+ # Test default credentials are used if not provided.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transport_class()
+ adc.assert_called_once()
+
+
+def test_transport_grpc_default():
+ # A client should use the gRPC transport by default.
+ client = VersionsClient(credentials=credentials.AnonymousCredentials(),)
+ assert isinstance(client.transport, transports.VersionsGrpcTransport,)
+
+
+def test_versions_base_transport_error():
+ # Passing both a credentials object and credentials_file should raise an error
+ with pytest.raises(exceptions.DuplicateCredentialArgs):
+ transport = transports.VersionsTransport(
+ credentials=credentials.AnonymousCredentials(),
+ credentials_file="credentials.json",
+ )
+
+
+def test_versions_base_transport():
+ # Instantiate the base transport.
+ with mock.patch(
+ "google.cloud.appengine_admin_v1.services.versions.transports.VersionsTransport.__init__"
+ ) as Transport:
+ Transport.return_value = None
+ transport = transports.VersionsTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Every method on the transport should just blindly
+ # raise NotImplementedError.
+ methods = (
+ "list_versions",
+ "get_version",
+ "create_version",
+ "update_version",
+ "delete_version",
+ )
+ for method in methods:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, method)(request=object())
+
+ # Additionally, the LRO client (a property) should
+ # also raise NotImplementedError
+ with pytest.raises(NotImplementedError):
+ transport.operations_client
+
+
+def test_versions_base_transport_with_credentials_file():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(
+ auth, "load_credentials_from_file"
+ ) as load_creds, mock.patch(
+ "google.cloud.appengine_admin_v1.services.versions.transports.VersionsTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ transport = transports.VersionsTransport(
+ credentials_file="credentials.json", quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+def test_versions_base_transport_with_adc():
+ # Test the default credentials are used if credentials and credentials_file are None.
+ with mock.patch.object(auth, "default") as adc, mock.patch(
+ "google.cloud.appengine_admin_v1.services.versions.transports.VersionsTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transport = transports.VersionsTransport()
+ adc.assert_called_once()
+
+
+def test_versions_auth_adc():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ VersionsClient()
+ adc.assert_called_once_with(
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ quota_project_id=None,
+ )
+
+
+def test_versions_transport_auth_adc():
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transports.VersionsGrpcTransport(
+ host="squid.clam.whelk", quota_project_id="octopus"
+ )
+ adc.assert_called_once_with(
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport],
+)
+def test_versions_grpc_transport_client_cert_source_for_mtls(transport_class):
+ cred = credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
+def test_versions_host_no_port():
+ client = VersionsClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="appengine.googleapis.com"
+ ),
+ )
+ assert client.transport._host == "appengine.googleapis.com:443"
+
+
+def test_versions_host_with_port():
+ client = VersionsClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="appengine.googleapis.com:8000"
+ ),
+ )
+ assert client.transport._host == "appengine.googleapis.com:8000"
+
+
+def test_versions_grpc_transport_channel():
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.VersionsGrpcTransport(
+ host="squid.clam.whelk", channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+def test_versions_grpc_asyncio_transport_channel():
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.VersionsGrpcAsyncIOTransport(
+ host="squid.clam.whelk", channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport],
+)
+def test_versions_transport_channel_mtls_with_client_cert_source(transport_class):
+ with mock.patch(
+ "grpc.ssl_channel_credentials", autospec=True
+ ) as grpc_ssl_channel_cred:
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_ssl_cred = mock.Mock()
+ grpc_ssl_channel_cred.return_value = mock_ssl_cred
+
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ cred = credentials.AnonymousCredentials()
+ with pytest.warns(DeprecationWarning):
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (cred, None)
+ transport = transport_class(
+ host="squid.clam.whelk",
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=client_cert_source_callback,
+ )
+ adc.assert_called_once()
+
+ grpc_ssl_channel_cred.assert_called_once_with(
+ certificate_chain=b"cert bytes", private_key=b"key bytes"
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+ assert transport._ssl_channel_credentials == mock_ssl_cred
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport],
+)
+def test_versions_transport_channel_mtls_with_adc(transport_class):
+ mock_ssl_cred = mock.Mock()
+ with mock.patch.multiple(
+ "google.auth.transport.grpc.SslCredentials",
+ __init__=mock.Mock(return_value=None),
+ ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
+ ):
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+ mock_cred = mock.Mock()
+
+ with pytest.warns(DeprecationWarning):
+ transport = transport_class(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=None,
+ )
+
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/appengine.admin",
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ ),
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+def test_versions_grpc_lro_client():
+ client = VersionsClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+ transport = client.transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(transport.operations_client, operations_v1.OperationsClient,)
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_versions_grpc_lro_async_client():
+ client = VersionsAsyncClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio",
+ )
+ transport = client.transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(transport.operations_client, operations_v1.OperationsAsyncClient,)
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_common_billing_account_path():
+ billing_account = "squid"
+
+ expected = "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
+ )
+ actual = VersionsClient.common_billing_account_path(billing_account)
+ assert expected == actual
+
+
+def test_parse_common_billing_account_path():
+ expected = {
+ "billing_account": "clam",
+ }
+ path = VersionsClient.common_billing_account_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = VersionsClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "whelk"
+
+ expected = "folders/{folder}".format(folder=folder,)
+ actual = VersionsClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "octopus",
+ }
+ path = VersionsClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = VersionsClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "oyster"
+
+ expected = "organizations/{organization}".format(organization=organization,)
+ actual = VersionsClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "nudibranch",
+ }
+ path = VersionsClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = VersionsClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "cuttlefish"
+
+ expected = "projects/{project}".format(project=project,)
+ actual = VersionsClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "mussel",
+ }
+ path = VersionsClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = VersionsClient.parse_common_project_path(path)
+ assert expected == actual
+
+
+def test_common_location_path():
+ project = "winkle"
+ location = "nautilus"
+
+ expected = "projects/{project}/locations/{location}".format(
+ project=project, location=location,
+ )
+ actual = VersionsClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "scallop",
+ "location": "abalone",
+ }
+ path = VersionsClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = VersionsClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_withDEFAULT_CLIENT_INFO():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.VersionsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = VersionsClient(
+ credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.VersionsTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = VersionsClient.get_transport_class()
+ transport = transport_class(
+ credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)